@odoo/o-spreadsheet 19.4.3 → 19.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/o_spreadsheet.cjs +51 -19
- package/dist/o_spreadsheet.css +3 -3
- package/dist/o_spreadsheet.esm.js +51 -19
- package/dist/o_spreadsheet.iife.js +51 -19
- package/dist/o_spreadsheet.min.iife.js +6 -6
- package/dist/o_spreadsheet.xml +4 -7
- package/dist/types/components/grid/grid.d.ts +1 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/plugins/ui_core_views/pivot_ui.d.ts +3 -0
- package/dist/types/plugins/ui_feature/collaborative.d.ts +2 -1
- package/package.json +1 -1
|
@@ -80,12 +80,12 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
80
80
|
`+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[se(e)]||this.keyCodeMapping[se(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()?.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()&&!me()||(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(vn(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){let t=this.composerRef();t&&t.scrollHeight>t.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=vn(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=fp(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(`
|
|
81
81
|
`)){let e=r.value.split(`
|
|
82
82
|
`),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(vn(e.currentContent)&&t&&t.type!==`SYMBOL`){let e=t.functionContext,n=e?.parent.toUpperCase();if(e&&n&&n in Uk&&t.type!==`UNKNOWN`){let r=Uk[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 Gc(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=Gc(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=Gc(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 Gk(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 Kk(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 qk(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 Jk(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(fu(e))}catch{n.push(void 0)}}}return e}function Yk(e,t){return Jk(qk(Kk(Gk(Xk($l(e,t))))))}function Xk(e){let t=[];for(;e.length;)t.push(Zk(e)||e.shift());return t}function Zk(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 Qk=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 $k(e,t,n){if(ht(e)){let r=n.decimalSeparator===`,`?`/`:`,`;return`{${os(e).map(e=>e.map(e=>eA(e,t,n)).join(r)).join(`;`)}}`}return eA(e,t,n)}function eA(e,t,n){let r=e.value;switch(typeof r){case`number`:return H(r,{locale:n,format:e.format});case`string`:return Po(r)?r:`"${r}"`;case`boolean`:return r?`TRUE`:`FALSE`}return t}function tA(e,t,n){let r=(t.startsWith(`=`)?Yk(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(bl).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}}function nA(e,t){e=e.toLocaleLowerCase(),t=t.toLocaleLowerCase();let n=0,r=0,i=t.length,a=0;for(let o=0;o<i;o++)t[o]===e[a]?(a++,r+=100+r-o/200):r=0,n+=r;return a===e.length?n:0}function rA(e,t,n){let r=[];return t.forEach(t=>{let i=nA(e,n(t));i>0&&r.push({score:i,elem:t})}),r.sort((e,t)=>t.score-e.score),r.map(e=>e.elem)}let iA=new k;var aA=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}},oA=class extends Vr{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}}},sA=class extends Vr{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 oA(this.get);hasSelectedAProposal=!1;hoveredTokens=[];hoveredContentEvaluation=``;autoCompleteKeepLast=new Qk;notificationStore=this.get(aA);highlightStore=this.get(ME);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=tA(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}=vl(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(``);vn(i)||(i=`=${i}`);let a=J_(i,this.getters.getLocale()),o=this.evaluateCanonicalFormula(a);this.hoveredTokens=r,this.hoveredContentEvaluation=$k(o,`0`,this.getters.getLocale())}evaluateCanonicalFormula(e){return this.getters.evaluateFormulaResult(this.sheetId,e)}getRelatedTokens(e,t){try{let n=fu(e),r;for(let e of mu(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 I)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=O({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(`%`)&&uo(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=O({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&&vn(e)){let t=this.getMissingSymbols(this.currentTokens);e+=Wt(t)}this.confirmEdition(e)}}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=vn(e)?Yk(e,t):[],this.currentTokens.filter(e=>e.type!==`SPACE`).length>1e3&&n&&this.notificationStore.raiseError(P(`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 iA.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}=vl(t.value),a=i||this.getters.getSheetName(this.sheetId);if(!Wu(this.getters.getSheetName(n),a))return!1;let o=this.getFullySpreadRange(n,r);return rr(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}=vl(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 pt.NUMBER;if(n in al.content)return pt.FUNCTION}return[`LEFT_PAREN`,`RIGHT_PAREN`].includes(e.type)&&e.parenthesesCode===``?pt.ORPHAN_RIGHT_PAREN:pt[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=xr(n)===1?this.model.getters.expandZone(e.sheetId,n):n,rr(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(!vn(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(!vn(this.currentContent)||this.editionMode===`inactive`)return[];let e=this.sheetId,t=e=>qf[this.colorIndexByRange[e]%qf.length];return this.getReferencedRanges().map(({type:n,range:r})=>{let i=this.getters.getRangeString(r,e),{numberOfRows:a,numberOfCols:o}=cr(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=vn(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=rA(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(vn(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)||Ol.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}},cA=class extends sA{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?Sl(t,`colrow`):t}getComposerContent(){let e=this.args().defaultRangeSheetId;return{text:X_($l(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(){}getCurrentCanonicalContent(){return Y_(this._currentContent,this.getters.getLocale())}},lA=class extends A{static template=`o-spreadsheet-StandaloneComposer`;static components={Composer:Wk};props=(0,t.useProps)({onConfirm:N.function(),composerContent:N.string().optional(``),defaultRangeSheetId:N.UID(),defaultStatic:N.boolean().optional(!1),contextualAutocomplete:N.AutoCompleteProviderDefinition().optional(),placeholder:N.string().optional(),title:N.string().optional(),class:N.string().optional(),invalid:N.boolean().optional(),autofocus:N.boolean().optional(),getContextualColoredSymbolToken:N.function().optional()});composerFocusStore;standaloneComposerStore;composerInterface;spreadsheetRect=v_();setup(){this.composerFocusStore=j(Ur);let e=Ji(cA,()=>({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})}},uA=class extends A{static template=`o-spreadsheet-GaugeChartDesignPanel`;static components={SidePanelCollapsible:WE,Section:Z,RoundColorPicker:QE,GeneralDesignEditor:$E,ChartAnnotation:GE,ChartErrorSection:BE,StandaloneComposer:lA,ChartHumanizeNumbers:eD,Select:T_};props=(0,t.useProps)(TE);state;setup(){this.state=(0,t.proxy)({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=>L_.Errors[e]||L_.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:P(`Value`),title:P(`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 Bo(e,t)!==void 0;let n=this.env.model.getters.evaluateFormula(this.sheetId,e);return yS(n)?!1:Bo(_S(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:P(`Number`)},{value:`percentage`,label:P(`Percentage`)}]}},dA=class extends A{static template=`o-spreadsheet-GeoChartRegionSelectSection`;static components={Section:Z,Select:T_};props=(0,t.useProps)({chartId:N.UID(),definition:N.GeoChartDefinition(),updateChart:N.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}))}},fA=class extends VE{static template=`o-spreadsheet-GeoChartConfigPanel`;static components={...VE.components,GeoChartRegionSelectSection:dA};getLabelRangeOptions(){return[]}},pA=class extends aD{static template=`o-spreadsheet-GeoChartDesignPanel`;static components={...aD.components,RoundColorPicker:QE,ColorScalePicker:Dk,Select:T_};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:P(`None`)},{value:`top`,label:P(`Top left`)},{value:`right`,label:P(`Top right`)},{value:`bottom`,label:P(`Bottom right`)},{value:`left`,label:P(`Bottom left`)}]}},mA=class extends VE{static template=`o-spreadsheet-HierarchicalChartConfigPanel`;static components={...VE.components}},hA=class extends VE{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`?LD(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})}},gA=class extends oD{static template=`o-spreadsheet-LineChartDesignPanel`;static components={...oD.components,ChartShowDataMarkers:kk}},_A=class extends A{static template=`o-spreadsheet.PieHoleSize`;static components={Section:Z,NumberInput:KE};props=(0,t.useProps)({onValueChange:N.function(),value:N.number()});onChange(e){isNaN(Number(e))||this.props.onValueChange(S(Number(e),0,95))}},vA=class extends A{static template=`o-spreadsheet-PieChartDesignPanel`;static components={GeneralDesignEditor:$E,ChartAnnotation:GE,Section:Z,ChartLegend:tD,ChartShowValues:iD,PieHoleSize:_A,Checkbox:wE,ChartHumanizeNumbers:eD,SidePanelCollapsible:WE,RoundColorPicker:QE,Select:T_};props=(0,t.useProps)(TE);state=(0,t.proxy)({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}))}},yA=class extends A{static template=`o-spreadsheet-RadarChartDesignPanel`;static components={GeneralDesignEditor:$E,ChartAnnotation:GE,SeriesDesignEditor:nD,Section:Z,ChartLegend:tD,ChartShowValues:iD,ChartShowDataMarkers:kk,Checkbox:wE,ChartHumanizeNumbers:eD};props=(0,t.useProps)(TE)},bA=class extends VE{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`?LD(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}},xA=class extends A{static template=`o-spreadsheet-ScorecardChartConfigPanel`;static components={SelectionInput:FE,ChartErrorSection:BE,Section:Z,Select:T_};props=(0,t.useProps)(TE);state=(0,t.proxy)({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=>L_.Errors[e]||L_.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:P(`Absolute value`)},{value:`difference`,label:P(`Value change from key value`)},{value:`percentage`,label:P(`Percentage change from key value`)},{value:`progress`,label:P(`Progress bar`)}]}},SA=class extends A{static template=`o-spreadsheet-ScorecardChartDesignPanel`;static components={GeneralDesignEditor:$E,ChartAnnotation:GE,RoundColorPicker:QE,SidePanelCollapsible:WE,Section:Z,Checkbox:wE,ChartTitle:YE,ChartHumanizeNumbers:eD};props=(0,t.useProps)(TE);get colorsSectionTitle(){return this.props.definition.baselineMode===`progress`?P(`Progress bar colors`):P(`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})}},CA=class extends A{static template=`o-spreadsheet-SunburstChartDesignPanel`;static components={GeneralDesignEditor:$E,ChartAnnotation:GE,Section:Z,SidePanelCollapsible:WE,ChartShowValues:iD,Checkbox:wE,TextStyler:bE,RoundColorPicker:QE,ChartLegend:tD,PieHoleSize:_A,ChartHumanizeNumbers:eD};props=(0,t.useProps)(TE);defaults=OO;get showValues(){return this.props.definition.showValues??OO.showValues}get showLabels(){return this.props.definition.showLabels??OO.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})}},wA=class extends A{static template=`o-spreadsheet-TreeMapCategoryColors`;static components={Checkbox:wE,RoundColorPicker:QE};props=(0,t.useProps)({chartId:N.UID(),definition:N.TreeMapChartDefinition(),onColorChanged:N.function()});get coloringOptions(){let e=this.props.definition.coloringOptions??km.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})}},TA=class extends A{static template=`o-spreadsheet-TreeMapColorScale`;static components={RoundColorPicker:QE};props=(0,t.useProps)({chartId:N.UID(),definition:N.TreeMapChartDefinition(),onColorChanged:N.function()});get coloringOptions(){let e=this.props.definition.coloringOptions??km.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 EA={type:`colorScale`,minColor:`#FFF5EB`,midColor:`#FD8D3C`,maxColor:`#7F2704`},DA={type:`categoryColor`,colors:[],useValueBasedGradient:!0};var OA=class extends A{static template=`o-spreadsheet-TreeMapChartDesignPanel`;static components={GeneralDesignEditor:$E,ChartAnnotation:GE,Section:Z,SidePanelCollapsible:WE,ChartShowValues:iD,Checkbox:wE,TextStyler:bE,RoundColorPicker:QE,BadgeSelection:JE,TreeMapCategoryColors:wA,TreeMapColorScale:TA,ChartHumanizeNumbers:eD};props=(0,t.useProps)(TE);savedColors={categoryColors:DA,colorScale:EA};defaults=km;get showHeaders(){return this.props.definition.showHeaders??km.showHeaders}get showValues(){return this.props.definition.showValues??km.showValues}get showLabels(){return this.props.definition.showLabels??km.showLabels}get coloringOptions(){return this.props.definition.coloringOptions??km.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:P(`Category color`),value:`categoryColor`},{label:P(`Color scale`),value:`colorScale`}]}},kA=class extends A{static template=`o-spreadsheet-WaterfallChartDesignPanel`;static components={GeneralDesignEditor:$E,ChartAnnotation:GE,ChartShowValues:iD,Checkbox:wE,SidePanelCollapsible:WE,Section:Z,RoundColorPicker:QE,AxisDesignEditor:XE,RadioSelection:ZE,ChartLegend:tD,ChartHumanizeNumbers:eD};props=(0,t.useProps)(TE);axisChoices=gm;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:P(`Horizontal axis`)},{id:`y`,name:P(`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 AA=new k;CE.add(`range`,hk),AA.add(`line`,{configuration:hA,design:gA}).add(`scatter`,{configuration:bA,design:aD}).add(`bubble`,{configuration:cD,design:lD}).add(`bar`,{configuration:HE,design:sD}).add(`combo`,{configuration:VE,design:Ak}).add(`pie`,{configuration:VE,design:vA}).add(`gauge`,{configuration:Nk,design:uA}).add(`scorecard`,{configuration:xA,design:SA}).add(`waterfall`,{configuration:VE,design:kA}).add(`pyramid`,{configuration:VE,design:aD}).add(`radar`,{configuration:VE,design:yA}).add(`sunburst`,{configuration:mA,design:CA}).add(`geo`,{configuration:fA,design:pA}).add(`funnel`,{configuration:jk,design:Mk}).add(`treemap`,{configuration:mA,design:OA}).add(`calendar`,{configuration:Ek,design:Ok});let jA={line:P(`Line`),column:P(`Column`),bar:P(`Bar`),area:P(`Area`),pie:P(`Pie`),hierarchical:P(`Hierarchical`),misc:P(`Miscellaneous`)};var MA=class extends A{static template=`o-spreadsheet-ChartTypePicker`;static components={Section:Z,Popover:b_};props=(0,t.useProps)({chartId:N.UID(),chartPanelStore:N.Store()});categories=jA;chartTypeByCategories={};popoverRef=(0,t.signal)(null);selectRef=(0,t.signal)(null);state=(0,t.proxy)({popoverProps:void 0,popoverStyle:``});setup(){Ii(window,`pointerdown`,this.onExternalClick,{capture:!0});let e=this.env.model.getters.getChartDefinition(this.props.chartId),t=this.getSupportedChartTypes(e);for(let e of Hg.getAll())t.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=wb.get(e.dataSource.type);t=new Set(n.supportedChartTypes)}else if(!e.dataSource&&(e.type===`scorecard`||e.type===`gauge`||e.type===`bubble`))t=new Set(AC);else throw Error(`Missing chart data source for a chart type that requires it`);return t}onExternalClick(e){_(this.popoverRef()?.parentElement,e)||_(this.selectRef(),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 Hg.getAll().find(t=>t.matcher?.(e)||!1)||Hg.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}},NA=class extends Vr{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=Hg.get(t),r=this.creationContexts[e],i=Tb.get(n.chartType),a=wb.get(r.dataSource?.type??`range`),o={...i.getDefinitionFromContextCreation(r,a),...n.subtypeDefinition};return gk.deleteInvalidKeys(o)}},PA=class extends A{static template=`o-spreadsheet-ChartPanel`;static components={Section:Z,ChartTypePicker:MA};props=(0,t.useProps)({onCloseSidePanel:N.function(),chartId:N.UID()});store;get chartId(){return this.props.chartId}setup(){this.store=Ji(NA)}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=AA.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 FA(e){let n=(0,t.proxy)({hovered:!1});(0,t.useListener)(e,`mouseenter`,()=>n.hovered=!0),(0,t.useListener)(e,`mouseleave`,()=>n.hovered=!1);let r=new ResizeObserver(()=>{n.hovered=!1});return(0,t.useEffect)(()=>{let t=e();return t&&r.observe(t),()=>{r.disconnect()}}),n}function IA(e,t){let n=FA(e);LA({get highlights(){return n.hovered?t.highlights:[]}})}function LA(e){let n=qi(),r=Ji(ME);(0,t.onMounted)(()=>{r.register(e)});let i=e.highlights;Li(e=>{T(e,i)||(i=e,n.trigger(`store-updated`))},()=>[e.highlights])}function RA(e,t,n){let r={},i=an(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(`,`));t.visible&&!t.visible(a,n)||(a.length&&(e=Gt(()=>t.compute(a,n))),r[t.name]={value:e,format:Gt(()=>t.computeFormat(a,n)??``)})}return r}let zA=[{name:P(`Total rows`),types:Object.values(yd),compute:(e,t)=>e.length,computeFormat:(e,t)=>`0`},{name:P(`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},computeFormat:(e,t)=>`0`},{name:P(`Sum`),types:[`number`],compute:(e,t)=>aS([[e]],t),visible:(e,t)=>e.some(e=>!e.format||!pc(e.format)),computeFormat:(e,t)=>e.find(e=>!e.format||!pc(e.format))?.format??`0.00`},{name:P(`Average`),types:[`number`],compute:(e,t)=>xS([[e]],t),computeFormat:(e,t)=>e[0]?.format??`0.00`},{name:P(`Median`),types:[`number`],compute:(e,t)=>SS([[e]],t)??``,computeFormat:(e,t)=>e[0]?.format??`0.00`},{name:P(`Minimum value`),types:[`number`],compute:(e,t)=>ES([[e]],t).value,computeFormat:(e,t)=>e[0]?.format??`0.00`},{name:P(`Maximum value`),types:[`number`],compute:(e,t)=>TS([[e]],t).value,computeFormat:(e,t)=>e[0]?.format??`0.00`}];function BA(e){let t={};for(let n of e)t[n.name]=void 0;return t}var VA=class extends Vr{mutators=[`updateIgnoredRows`,`selectNextColumn`,`selectPreviousColumn`];statisticFnResults=BA(zA);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((Ed.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=BA(zA),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=RA(zA,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})})}},HA=class extends A{static template=`o-spreadsheet-ColumnStatsPanel`;static components={NumberInput:KE,SidePanelCollapsible:WE,BadgeSelection:JE,Section:Z};props=(0,t.useProps)({onCloseSidePanel:N.function()});state=(0,t.proxy)({currentChart:`count`,currentFrequencyOrder:`descending`,highlightPositions:[]});store;chartCanvasRef=(0,t.signal)(null);chart;setup(){this.store=j(VA),LA(this),(0,t.onWillUnmount)(()=>this.destroyChart()),Li(()=>{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:P(`Column %s`,wn(this.store.selectedColumn))}get charts(){return[{value:`count`,label:P(`Count`),icon:`o-spreadsheet-Icon.COUNT_CHART`},{value:`histogram`,label:P(`Distribution`),icon:`o-spreadsheet-Icon.COUNT_CHART`}]}get frequencyOrders(){return[{value:`descending`,label:P(`Descending`),icon:`o-spreadsheet-Icon.DESCENDING_SORT`},{value:`ascending`,label:P(`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?P(`No numeric values to display.`):this.state.currentChart===`count`&&this.store.values.length===0?P(`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.chartCanvasRef();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:bp,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:bp,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.chartCanvasRef();if(!t)return e;let n=t.getContext(`2d`);return n?Pf(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(),O(e)),color:`#ffeb3b9a`,interactive:!1}))]}highlightFrequencyPositions(e){this.state.highlightPositions=e}clearHighlights(){this.state.highlightPositions=[]}},UA=class extends A{static template=`o-spreadsheet-CellIsRuleEditor`;static components={ColorPickerWidget:_E,Select:T_};props=(0,t.useProps)({store:N.Store()});getTextDecoration=Kg;get rule(){return this.props.store.state.rules.cellIs}},WA=class extends A{props=(0,t.useProps)({criterion:N.object(),onCriterionChanged:N.function(),disableFormulas:N.boolean().optional(),autofocus:N.boolean().optional()});setup(){let e=j(Ur);e.activeComposer.editionMode!==`inactive`&&e.activeComposer.stopEdition()}updateCriterion(e){let t={...this.props.criterion,...e};this.props.onCriterionChanged(t)}};let Q=new k;Q.add(`containsText`,{type:`containsText`,isValueValid:(e,t)=>String(e).toLowerCase().includes(String(t.values[0]).toLowerCase()),getErrorString:e=>P(`The value must be a text that contains "%s"`,String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:U_.CriterionError.notEmptyValue,numberOfValues:()=>1,name:P(`Text contains`),getPreview:e=>P(`Text contains "%s"`,e.values[0])}),Q.add(`notContainsText`,{type:`notContainsText`,isValueValid:(e,t)=>!String(e).toLowerCase().includes(String(t.values[0]).toLowerCase()),getErrorString:e=>P(`The value must be a text that does not contain "%s"`,String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:U_.CriterionError.notEmptyValue,numberOfValues:()=>1,name:P(`Text does not contain`),getPreview:e=>P(`Text does not contain "%s"`,e.values[0])}),Q.add(`isEqualText`,{type:`isEqualText`,isValueValid:(e,t)=>String(e).toLowerCase()===String(t.values[0]).toLowerCase(),getErrorString:e=>P(`The value must be exactly "%s"`,String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:U_.CriterionError.notEmptyValue,numberOfValues:()=>1,name:P(`Text is exactly`),getPreview:e=>P(`Text is exactly "%s"`,e.values[0])});let GA=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/;Q.add(`isEmail`,{type:`isEmail`,isValueValid:(e,t)=>typeof e==`string`&&GA.test(e),getErrorString:()=>P(`The value must be a valid email address`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>0,name:P(`Text is valid email`),getPreview:()=>P(`Text is valid email`)}),Q.add(`isLink`,{type:`isLink`,isValueValid:(e,t)=>qd(e)!==void 0,getErrorString:()=>P(`The value must be a valid link`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>0,name:P(`Text is valid link`),getPreview:()=>P(`Text is valid link`)}),Q.add(`dateIs`,{type:`dateIs`,isValueValid:(e,t)=>{let n=_b(t,V)[0],r=ja(e,V);return r===void 0||n===void 0?!1:[`lastWeek`,`lastMonth`,`lastYear`].includes(t.dateValue)?ro(r,Math.floor(Ka(va.now())),n):no(r,n)},getErrorString:(e,t)=>{let n=t.getLocale();return e.dateValue===`exactDate`?P(`The value must be the date %s`,qA(e,n)[0]):P(`The value must be %s`,U_.DateIs[e.dateValue])},isCriterionValueValid:e=>JA(e),criterionValueErrorString:U_.CriterionError.dateValue,numberOfValues:e=>+(e.dateValue===`exactDate`),name:P(`Date is`),getPreview:(e,t)=>e.dateValue===`exactDate`?P(`Date is %s`,vb(e.values,t.getLocale())[0]):P(`Date is %s`,U_.DateIs[e.dateValue])}),Q.add(`dateIsBefore`,{type:`dateIsBefore`,isValueValid:(e,t)=>{let n=_b(t,V)[0],r=ja(e,V);return r!==void 0&&n!==void 0&&io(r,n)},getErrorString:(e,t)=>{let n=t.getLocale();return e.dateValue===`exactDate`?P(`The value must be a date before %s`,qA(e,n)[0]):P(`The value must be a date before %s`,U_.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>JA(e),criterionValueErrorString:U_.CriterionError.dateValue,numberOfValues:e=>+(e.dateValue===`exactDate`),name:P(`Date is before`),getPreview:(e,t)=>e.dateValue===`exactDate`?P(`Date is before %s`,vb(e.values,t.getLocale())[0]):P(`Date is before %s`,U_.DateIsBefore[e.dateValue])}),Q.add(`dateIsOnOrBefore`,{type:`dateIsOnOrBefore`,isValueValid:(e,t)=>{let n=_b(t,V)[0],r=ja(e,V);return r!==void 0&&n!==void 0&&ao(r,n)},getErrorString:(e,t)=>{let n=t.getLocale();return e.dateValue===`exactDate`?P(`The value must be a date on or before %s`,qA(e,n)[0]):P(`The value must be a date on or before %s`,U_.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>JA(e),criterionValueErrorString:U_.CriterionError.dateValue,numberOfValues:e=>+(e.dateValue===`exactDate`),name:P(`Date is on or before`),getPreview:(e,t)=>e.dateValue===`exactDate`?P(`Date is on or before %s`,vb(e.values,t.getLocale())[0]):P(`Date is on or before %s`,U_.DateIsBefore[e.dateValue])}),Q.add(`dateIsAfter`,{type:`dateIsAfter`,isValueValid:(e,t)=>{let n=_b(t,V)[0],r=ja(e,V);return r!==void 0&&n!==void 0&&oo(r,n)},getErrorString:(e,t)=>{let n=t.getLocale();return e.dateValue===`exactDate`?P(`The value must be a date after %s`,qA(e,n)[0]):P(`The value must be a date after %s`,U_.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>JA(e),criterionValueErrorString:U_.CriterionError.dateValue,numberOfValues:e=>+(e.dateValue===`exactDate`),name:P(`Date is after`),getPreview:(e,t)=>e.dateValue===`exactDate`?P(`Date is after %s`,vb(e.values,t.getLocale())[0]):P(`Date is after %s`,U_.DateIsBefore[e.dateValue])}),Q.add(`dateIsOnOrAfter`,{type:`dateIsOnOrAfter`,isValueValid:(e,t)=>{let n=_b(t,V)[0],r=ja(e,V);return r!==void 0&&n!==void 0&&so(r,n)},getErrorString:(e,t)=>{let n=t.getLocale();return e.dateValue===`exactDate`?P(`The value must be a date on or after %s`,qA(e,n)[0]):P(`The value must be a date on or after %s`,U_.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>JA(e),criterionValueErrorString:U_.CriterionError.dateValue,numberOfValues:e=>+(e.dateValue===`exactDate`),name:P(`Date is on or after`),getPreview:(e,t)=>e.dateValue===`exactDate`?P(`Date is on or after %s`,vb(e.values,t.getLocale())[0]):P(`Date is on or after %s`,U_.DateIsBefore[e.dateValue])}),Q.add(`dateIsBetween`,{type:`dateIsBetween`,isValueValid:(e,t)=>{let n=_b(t,V),r=ja(e,V);return r===void 0||n[0]===void 0||n[1]===void 0?!1:ro(r,n[0],n[1])},getErrorString:(e,t)=>{let n=qA(e,t.getLocale());return P(`The value must be a date between %s and %s`,n[0],n[1])},isCriterionValueValid:e=>JA(e),criterionValueErrorString:U_.CriterionError.dateValue,numberOfValues:()=>2,name:P(`Date is between`),getPreview:(e,t)=>{let n=vb(e.values,t.getLocale());return P(`Date is between %s and %s`,n[0],n[1])}}),Q.add(`dateIsNotBetween`,{type:`dateIsNotBetween`,isValueValid:(e,t)=>{let n=_b(t,V),r=ja(e,V);return r===void 0||n[0]===void 0||n[1]===void 0?!1:!ro(r,n[0],n[1])},getErrorString:(e,t)=>{let n=qA(e,t.getLocale());return P(`The value must be a date not between %s and %s`,n[0],n[1])},isCriterionValueValid:e=>JA(e),criterionValueErrorString:U_.CriterionError.dateValue,numberOfValues:()=>2,name:P(`Date is not between`),getPreview:(e,t)=>{let n=vb(e.values,t.getLocale());return P(`Date is not between %s and %s`,n[0],n[1])}}),Q.add(`dateIsValid`,{type:`dateIsValid`,isValueValid:(e,t)=>ja(e,V)!==void 0,getErrorString:()=>P(`The value must be a valid date`),isCriterionValueValid:e=>JA(e),criterionValueErrorString:``,numberOfValues:()=>0,name:P(`Is valid date`),getPreview:()=>P(`Date is valid`)}),Q.add(`isEqual`,{type:`isEqual`,isValueValid:(e,t)=>e===t.values[0],getErrorString:(e,t)=>P(`The value must be equal to %s`,KA(e,t.getLocale())[0]),isCriterionValueValid:e=>YA(e),criterionValueErrorString:U_.CriterionError.numberValue,numberOfValues:()=>1,name:P(`Is equal to`),getPreview:(e,t)=>P(`Value is equal to %s`,KA(e,t.getLocale())[0])}),Q.add(`isNotEqual`,{type:`isNotEqual`,isValueValid:(e,t)=>e!==t.values[0],getErrorString:(e,t)=>P(`The value must not be equal to %s`,KA(e,t.getLocale())[0]),isCriterionValueValid:e=>YA(e),criterionValueErrorString:U_.CriterionError.numberValue,numberOfValues:()=>1,name:P(`Is not equal to`),getPreview:(e,t)=>P(`Value is not equal to %s`,KA(e,t.getLocale())[0])}),Q.add(`isGreaterThan`,{type:`isGreaterThan`,isValueValid:(e,t)=>{if(typeof e!=`number`)return!1;let n=t.values[0];return typeof n==`number`?e>n:!1},getErrorString:(e,t)=>P(`The value must be greater than %s`,KA(e,t.getLocale())[0]),isCriterionValueValid:e=>YA(e),criterionValueErrorString:U_.CriterionError.numberValue,numberOfValues:()=>1,name:P(`Is greater than`),getPreview:(e,t)=>P(`Value is greater than %s`,KA(e,t.getLocale())[0])}),Q.add(`isGreaterOrEqualTo`,{type:`isGreaterOrEqualTo`,isValueValid:(e,t)=>{if(typeof e!=`number`)return!1;let n=t.values[0];return typeof n==`number`?e>=n:!1},getErrorString:(e,t)=>P(`The value must be greater or equal to %s`,KA(e,t.getLocale())[0]),isCriterionValueValid:e=>YA(e),criterionValueErrorString:U_.CriterionError.numberValue,numberOfValues:()=>1,name:P(`Is greater or equal to`),getPreview:(e,t)=>P(`Value is greater or equal to %s`,KA(e,t.getLocale())[0])}),Q.add(`isLessThan`,{type:`isLessThan`,isValueValid:(e,t)=>{if(typeof e!=`number`)return!1;let n=t.values[0];return typeof n==`number`?e<n:!1},getErrorString:(e,t)=>P(`The value must be less than %s`,KA(e,t.getLocale())[0]),isCriterionValueValid:e=>YA(e),criterionValueErrorString:U_.CriterionError.numberValue,numberOfValues:()=>1,name:P(`Is less than`),getPreview:(e,t)=>P(`Value is less than %s`,KA(e,t.getLocale())[0])}),Q.add(`isLessOrEqualTo`,{type:`isLessOrEqualTo`,isValueValid:(e,t)=>{if(typeof e!=`number`)return!1;let n=t.values[0];return typeof n==`number`?e<=n:!1},getErrorString:(e,t)=>P(`The value must be less or equal to %s`,KA(e,t.getLocale())[0]),isCriterionValueValid:e=>YA(e),criterionValueErrorString:U_.CriterionError.numberValue,numberOfValues:()=>1,name:P(`Is less or equal to`),getPreview:(e,t)=>P(`Value is less or equal to %s`,KA(e,t.getLocale())[0])}),Q.add(`isBetween`,{type:`isBetween`,isValueValid:(e,t)=>typeof e!=`number`||typeof t.values[0]!=`number`||typeof t.values[1]!=`number`?!1:un(e,t.values[0],t.values[1]),getErrorString:(e,t)=>{let n=KA(e,t.getLocale());return P(`The value must be between %s and %s`,n[0],n[1])},isCriterionValueValid:e=>YA(e),criterionValueErrorString:U_.CriterionError.numberValue,numberOfValues:()=>2,name:P(`Is between`),getPreview:(e,t)=>{let n=KA(e,t.getLocale());return P(`Value is between %s and %s`,n[0],n[1])}}),Q.add(`isNotBetween`,{type:`isNotBetween`,isValueValid:(e,t)=>typeof e!=`number`||typeof t.values[0]!=`number`||typeof t.values[1]!=`number`?!1:!un(e,t.values[0],t.values[1]),getErrorString:(e,t)=>{let n=KA(e,t.getLocale());return P(`The value must not be between %s and %s`,n[0],n[1])},isCriterionValueValid:e=>YA(e),criterionValueErrorString:U_.CriterionError.numberValue,numberOfValues:()=>2,name:P(`Is not between`),getPreview:(e,t)=>{let n=KA(e,t.getLocale());return P(`Value is not between %s and %s`,n[0],n[1])}}),Q.add(`isBoolean`,{type:`isBoolean`,isValueValid:(e,t)=>e===``||typeof e==`boolean`,getErrorString:()=>P(`The value must be a boolean`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>0,name:P(`Checkbox`),getPreview:()=>P(`Checkbox`)}),Q.add(`isValueInList`,{type:`isValueInList`,isValueValid:(e,t)=>e===null?!1:t.values.map(e=>String(e).toLowerCase()).includes(e.toString().toLowerCase()),getErrorString:e=>P(`The value must be one of: %s`,e.values.join(`, `)),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>void 0,allowedValues:`onlyLiterals`,name:P(`Value in list`),getPreview:e=>P(`Value one of: %s`,e.values.join(`, `))}),Q.add(`isValueInRange`,{type:`isValueInRange`,preComputeCriterion:(e,t,n)=>{if(t.length===0)return new Set;let r=t[0].sheetId,i=n.getDataValidationRangeValues(r,e);return new Set(i.map(e=>e.value.toString().toLowerCase()))},isValueValid:(e,t,n)=>e?n.has(e.toString().toLowerCase()):!1,getErrorString:e=>P(`The value must be a value in the range %s`,String(e.values[0])),isCriterionValueValid:e=>fl.test(e),criterionValueErrorString:U_.CriterionError.validRange,numberOfValues:()=>1,allowedValues:`onlyLiterals`,name:P(`Value in range`),getPreview:e=>P(`Value in range %s`,e.values[0])}),Q.add(`customFormula`,{type:`customFormula`,isValueValid:(e,t)=>{let n=t.values[0];return typeof n==`number`||typeof n==`boolean`?!!n:!1},getErrorString:()=>P(`The value does not match the custom formula data validation rule`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>1,allowedValues:`onlyFormulas`,name:P(`Custom formula`),getPreview:e=>P(`Custom formula %s`,e.values[0])}),Q.add(`beginsWithText`,{type:`beginsWithText`,isValueValid:(e,t)=>String(e).toLowerCase().startsWith(String(t.values[0]).toLowerCase()),getErrorString:e=>P(`The value must be a text that begins with "%s"`,String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:U_.CriterionError.notEmptyValue,numberOfValues:()=>1,name:P(`Text begins with`),getPreview:e=>P(`Text begins with "%s"`,e.values[0])}),Q.add(`endsWithText`,{type:`endsWithText`,isValueValid:(e,t)=>String(e).toLowerCase().endsWith(String(t.values[0]).toLowerCase()),getErrorString:e=>P(`The value must be a text that ends with "%s"`,String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:U_.CriterionError.notEmptyValue,numberOfValues:()=>1,name:P(`Text ends with`),getPreview:e=>P(`Text ends with "%s"`,e.values[0])}),Q.add(`isEmpty`,{type:`isEmpty`,isValueValid:(e,t)=>(e??``).toString().trim()===``,getErrorString:()=>P(`The value must be empty`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>0,name:P(`Is empty`),getPreview:()=>P(`Is empty`)}),Q.add(`isNotEmpty`,{type:`isNotEmpty`,isValueValid:(e,t)=>(e??``).toString().trim()!==``,getErrorString:()=>P(`The value must not be empty`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>0,name:P(`Is not empty`),getPreview:()=>P(`Is not empty`)}),Q.add(`top10`,{type:`top10`,preComputeCriterion:(e,t,n)=>{let r=Bo(e.values[0],V);if(r===void 0||r<=0)return;let i=[];for(let e of t)for(let{value:t}of n.getVisibleRangeValues(e))typeof t==`number`&&i.push(t);let a=i.sort((e,t)=>e-t);e.isPercent&&(r=S(r,1,100));let o=0;return o=e.isBottom&&!e.isPercent?r-1:e.isBottom&&e.isPercent?Math.floor(a.length*r/100)-1:!e.isBottom&&e.isPercent?a.length-Math.floor(a.length*r/100):a.length-r,o=S(o,0,a.length-1),a[o]},isValueValid:(e,t,n)=>typeof e!=`number`||n===void 0?!1:t.isBottom?e<=n:e>=n,getErrorString:e=>{let t={value:String(e.values[0]),percentSymbol:e.isPercent?`%`:``};return e.isBottom?P(`The value must be in bottom %(value)s%(percentSymbol)s`,t):P(`The value must be in top %(value)s%(percentSymbol)s`,t)},isCriterionValueValid:e=>XA(e),criterionValueErrorString:U_.CriterionError.positiveNumber,numberOfValues:()=>1,name:P(`Is in Top/Bottom ranking`),getPreview:e=>{let t={value:e.values[0],percentSymbol:e.isPercent?`%`:``};return e.isBottom?P(`Value is in bottom %(value)s%(percentSymbol)s`,t):P(`Value is in top %(value)s%(percentSymbol)s`,t)}}),Q.add(`uniqueValues`,{type:`uniqueValues`,preComputeCriterion:(e,t,n)=>{let r=ZA(t,n);return new Set(Object.keys(r).filter(e=>r[e]===1))},isValueValid:(e,t,n)=>e===null||n===void 0?!1:n.has(String(e).toLowerCase()),getErrorString:()=>P(`The value must be unique`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>0,name:P(`Is value unique`),getPreview:()=>P(`Value is unique`)}),Q.add(`duplicateValues`,{type:`duplicateValues`,preComputeCriterion:(e,t,n)=>{let r=ZA(t,n);return new Set(Object.keys(r).filter(e=>r[e]!==1))},isValueValid:(e,t,n)=>e===null||n===void 0?!1:n.has(String(e).toLowerCase()),getErrorString:()=>P(`The value must not be unique`),isCriterionValueValid:()=>!0,criterionValueErrorString:``,numberOfValues:()=>0,name:P(`Is value duplicate`),getPreview:()=>P(`Value is duplicate`)});function KA(e,t){return e.values.map(e=>e===void 0?F.InvalidReference:X_(String(e),t))}function qA(e,t){return _b(e,V).map(e=>e===void 0?F.InvalidReference:H(e,{locale:t,format:t.dateFormat}))}function JA(e){return ja(e,V)!==void 0}function YA(e){return Bo(e,V)!==void 0}function XA(e){let t=Bo(e,V);return t!==void 0&&t>0}function ZA(e,t){let n={};for(let r of e)for(let e of t.getVisibleRangeValues(r)){let t=R(e).toLowerCase();t&&(n[t]=(n[t]||0)+1)}return n}var QA=class extends A{static template=`o-spreadsheet-CriterionInput`;static components={StandaloneComposer:lA};props=(0,t.useProps)({value:N.string().optional(``),criterionType:N.DataValidationCriterionType(),onValueChanged:N.function(),onKeyDown:N.function().optional(()=>()=>{}),focused:N.boolean().optional(!1),onBlur:N.function().optional(()=>()=>{}),onFocus:N.function().optional(),disableFormulas:N.boolean().optional()});inputRef=t.signal.ref(HTMLInputElement);setup(){Li(()=>{let e=this.inputRef();this.props.focused&&e&&e.focus()},()=>[this.props.focused,this.inputRef()]),(0,t.onWillUpdateProps)(e=>{e.value!==this.props.value&&(this.state.textInput=X_(e.value,this.env.model.getters.getLocale()))})}state=(0,t.proxy)({shouldDisplayError:!!this.props.value,textInput:X_(this.props.value,this.env.model.getters.getLocale())});get placeholder(){return this.allowedValues===`onlyFormulas`?P(`Formula`):this.allowedValues===`onlyLiterals`?P(`Value`):P(`Value or formula`)}get allowedValues(){let e=Q.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.state.textInput=e.target.value}onInputValueConfirmed(){let e=this.env.model.getters.getLocale(),t=Y_(this.state.textInput,e);this.props.onValueChanged(t)}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,Y_(this.state.textInput,this.env.model.getters.getLocale()))}};let $A={today:P(`today`),yesterday:P(`yesterday`),tomorrow:P(`tomorrow`),lastWeek:P(`in the past week`),lastMonth:P(`in the past month`),lastYear:P(`in the past year`),exactDate:P(`exact date`)};var ej=class extends WA{static template=`o-spreadsheet-DataValidationDateCriterion`;static components={CriterionInput:QA,Select:T_};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($A).map(e=>({value:e,label:$A[e]}))}},tj=class extends WA{static template=`o-spreadsheet-DoubleInputCriterionForm`;static components={CriterionInput:QA};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]})}},nj=class extends WA{static template=`o-spreadsheet-SingleInputCriterionForm`;static components={CriterionInput:QA};onValueChanged(e){let t=x(this.props.criterion);t.values[0]=e,this.updateCriterion(t)}},rj=class extends WA{static template=`o-spreadsheet-Top10CriterionForm`;static components={CriterionInput:QA,Select:T_};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:P(`Top`)},{value:`bottom`,label:P(`Bottom`)}]}get isPercentSelectOptions(){return[{value:`values`,label:P(`Values`)},{value:`percent`,label:P(`Percent`)}]}},ij=class extends WA{static template=`o-spreadsheet-ListCriterionForm`;static components={CriterionInput:QA,RoundColorPicker:QE,Select:T_};state=(0,t.proxy)({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:P(`Chip`)},{value:`arrow`,label:P(`Arrow`)},{value:`plainText`,label:P(`Plain text`)}]}},aj=class extends WA{static template=`o-spreadsheet-ValueInRangeCriterionForm`;static components={RoundColorPicker:QE,SelectionInput:FE,Select:T_};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:P(`Chip`)},{value:`arrow`,label:P(`Arrow`)},{value:`plainText`,label:P(`Plain text`)}]}};let oj={list:10,text:20,number:30,date:40,relative:45,misc:50},sj=new k;sj.add(`containsText`,{type:`containsText`,component:nj,category:`text`,sequence:10}),sj.add(`notContainsText`,{type:`notContainsText`,component:nj,category:`text`,sequence:20}),sj.add(`beginsWithText`,{type:`beginsWithText`,component:nj,category:`text`,sequence:25}),sj.add(`endsWithText`,{type:`endsWithText`,component:nj,category:`text`,sequence:26}),sj.add(`isEqualText`,{type:`isEqualText`,component:nj,category:`text`,sequence:30}),sj.add(`isEmail`,{type:`isEmail`,component:void 0,category:`text`,sequence:40}),sj.add(`isLink`,{type:`isLink`,component:void 0,category:`text`,sequence:50}),sj.add(`dateIs`,{type:`dateIs`,component:ej,category:`date`,sequence:20}),sj.add(`dateIsBefore`,{type:`dateIsBefore`,component:ej,category:`date`,sequence:30}),sj.add(`dateIsOnOrBefore`,{type:`dateIsOnOrBefore`,component:ej,category:`date`,sequence:40}),sj.add(`dateIsAfter`,{type:`dateIsAfter`,component:ej,category:`date`,sequence:50}),sj.add(`dateIsOnOrAfter`,{type:`dateIsOnOrAfter`,component:ej,category:`date`,sequence:60}),sj.add(`dateIsBetween`,{type:`dateIsBetween`,component:tj,category:`date`,sequence:70}),sj.add(`dateIsNotBetween`,{type:`dateIsNotBetween`,component:tj,category:`date`,sequence:80}),sj.add(`dateIsValid`,{type:`dateIsValid`,component:void 0,category:`date`,sequence:10}),sj.add(`isEqual`,{type:`isEqual`,component:nj,category:`number`,sequence:10}),sj.add(`isNotEqual`,{type:`isNotEqual`,component:nj,category:`number`,sequence:20}),sj.add(`isGreaterThan`,{type:`isGreaterThan`,component:nj,category:`number`,sequence:50}),sj.add(`isGreaterOrEqualTo`,{type:`isGreaterOrEqualTo`,component:nj,category:`number`,sequence:60}),sj.add(`isLessThan`,{type:`isLessThan`,component:nj,category:`number`,sequence:30}),sj.add(`isLessOrEqualTo`,{type:`isLessOrEqualTo`,component:nj,category:`number`,sequence:40}),sj.add(`isBetween`,{type:`isBetween`,component:tj,category:`number`,sequence:70}),sj.add(`isNotBetween`,{type:`isNotBetween`,component:tj,category:`number`,sequence:80}),sj.add(`isBoolean`,{type:`isBoolean`,component:void 0,category:`misc`,sequence:10}),sj.add(`isValueInList`,{type:`isValueInList`,component:ij,category:`list`,sequence:10}),sj.add(`isValueInRange`,{type:`isValueInRange`,component:aj,category:`list`,sequence:20}),sj.add(`customFormula`,{type:`customFormula`,component:nj,category:`misc`,sequence:20}),sj.add(`isEmpty`,{type:`isEmpty`,component:void 0,category:`misc`,sequence:5}),sj.add(`isNotEmpty`,{type:`isNotEmpty`,component:void 0,category:`misc`,sequence:6}),sj.add(`top10`,{type:`top10`,component:rj,category:`relative`,sequence:7}),sj.add(`uniqueValues`,{type:`uniqueValues`,component:void 0,category:`relative`,sequence:8}),sj.add(`duplicateValues`,{type:`duplicateValues`,component:void 0,category:`relative`,sequence:9});function cj(e){let t=sj.getAll().filter(t=>e.has(t.type)).sort((e,t)=>e.category===t.category?e.sequence-t.sequence:oj[e.category]-oj[t.category]);return t.map((e,n)=>({label:Q.get(e.type).name,value:e.type,separator:e.category!==t[n+1]?.category}))}let lj=new Set([`containsText`,`notContainsText`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`beginsWithText`,`endsWithText`,`isNotEmpty`,`isEmpty`,`isNotEqual`,`isEqual`,`customFormula`,`dateIs`,`dateIsBefore`,`dateIsAfter`,`dateIsOnOrBefore`,`dateIsOnOrAfter`,`top10`,`uniqueValues`,`duplicateValues`]);var uj=class extends Vr{mutators=[`updateConditionalFormat`,`closeMenus`];icons=Fy;iconSets=Iy;state;cfId;constructor(e,n,r){switch(super(e),this.cfId=n.id,this.state=(0,t.proxy)({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(fl))){e.suppressErrors||(this.state.errors=[`InvalidRange`]);return}let n=this.model.getters.getActiveSheetId(),r=e.rule||this.getEditedRule(this.state.currentCFType),i=this.model.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:this.cfId,rule:r},ranges:t.map(e=>this.model.getters.getRangeDataFromXc(n,e)),sheetId:n});i.isSuccessful&&(this.state.hasEditedCf=!0);let a=i.reasons.filter(e=>e!==`NoChanges`);e.suppressErrors||(this.state.errors=a)}get isRangeValid(){return this.state.errors.includes(`EmptyRange`)}get errorMessages(){return this.state.errors.map(e=>I_.Errors[e]||I_.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 cj(lj)}get criterionComponent(){return sj.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=Jf(e.minimum.color),n=Jf(e.midpoint?.color||11982760),r=Jf(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:ke,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){let n=Y_(t,this.model.getters.getLocale());this.state.rules.colorScale[e].value=n,this.updateConditionalFormat({rule:this.state.rules.colorScale})}setColorScaleColor(e,t){if(!Zf(t))return;let n=this.state.rules.colorScale[e];n&&(n.color=Yf(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){let n=Y_(t,this.model.getters.getLocale());this.state.rules.iconSet[e].value=n,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){Zf(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:Jy(`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}}}},dj=class extends A{static template=`o-spreadsheet-ColorScaleRuleEditorThreshold`;static components={RoundColorPicker:QE,StandaloneComposer:lA,Select:T_};props=(0,t.useProps)({store:N.Store(),thresholdType:N.or([N.literal(`minimum`),N.literal(`midpoint`),N.literal(`maximum`)])});get rule(){return this.props.store.state.rules.colorScale}get threshold(){return this.rule[this.props.thresholdType]}getThresholdColor(e){return Jf(e?e.color:ke)}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:P(`Formula`),defaultStatic:!0,invalid:t,class:`o-sidePanel-composer`,defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getThresholdTypeSelectOptions(){let e=[{value:`number`,label:P(`Number`)},{value:`percentage`,label:P(`Percentage`)},{value:`percentile`,label:P(`Percentile`)},{value:`formula`,label:P(`Formula`)}];return this.props.thresholdType===`midpoint`?[{value:`none`,label:P(`None`)},...e]:[{value:`value`,label:P(`Cell values`)},...e]}localizeValue(e){let t=this.env.model.getters.getLocale();return e?X_(e,t):``}},fj=class extends A{static template=`o-spreadsheet-ColorScaleRuleEditor`;static components={ColorScaleRuleEditorThreshold:dj};props=(0,t.useProps)({store:N.Store()})},pj=class extends A{static template=`o-spreadsheet-DataBarRuleEditor`;static components={SelectionInput:FE,RoundColorPicker:QE};props=(0,t.useProps)({store:N.Store()});get rule(){return this.props.store.state.rules.dataBar}colorNumberToHex=Jf},mj=class extends A{static template=`o-spreadsheet-IconPicker`;props=(0,t.useProps)({onIconPicked:N.function()});onIconClick(e){e&&this.props.onIconPicked(e)}getIconName(e,t){return Iy[e][t]}getIconTemplate(e){return`o-spreadsheet-Icon.${Fy[e].template}`}},hj=class extends A{static template=`o-spreadsheet-IconSetRuleEditor`;static components={IconPicker:mj,StandaloneComposer:lA,Select:T_};props=(0,t.useProps)({store:N.Store()});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:P(`Formula`),defaultStatic:!0,invalid:n,class:`o-sidePanel-composer`,defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getThresholdTypeSelectOptions(){return[{value:`number`,label:P(`Number`)},{value:`percentage`,label:P(`Percentage`)},{value:`percentile`,label:P(`Percentile`)},{value:`formula`,label:P(`Formula`)}]}getIconSetOperatorSelectOptions(){return[{value:`gt`,label:`>`},{value:`ge`,label:`>=`}]}localizeValue(e){let t=this.env.model.getters.getLocale();return e?X_(e,t):``}},gj=class extends A{static template=`o-spreadsheet-ConditionalFormattingEditor`;static components={SelectionInput:FE,Section:Z,BadgeSelection:JE,ValidationMessages:zE,CellIsRuleEditor:UA,ColorScaleRuleEditor:fj,IconSetRuleEditor:hj,DataBarRuleEditor:pj};props=(0,t.useProps)({cf:N.ConditionalFormat(),isNewCf:N.boolean(),onCloseSidePanel:N.function()});activeSheetId;store;setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId(),this.store=Ji(uj,x(this.props.cf),this.props.isNewCf),Li((e,t)=>{(this.activeSheetId!==e||t)&&this.env.replaceSidePanel(`ConditionalFormatting`,`ConditionalFormattingEditor_${this.props.cf.id}`)},()=>[this.env.model.getters.getActiveSheetId(),this.isEditedCfRemoved]),Ii(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:P(`Single color`)},{value:`ColorScaleRule`,label:P(`Color scale`)},{value:`IconSetRule`,label:P(`Icon set`)},{value:`DataBarRule`,label:P(`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}`)}},_j=class extends A{static template=`o-spreadsheet-ConditionalFormatPreview`;props=(0,t.useProps)({conditionalFormat:N.ConditionalFormat(),onMouseDown:N.function(),class:N.string()});icons=Fy;cfPreviewRef=(0,t.signal)(null);setup(){IA(this.cfPreviewRef,this)}get previewImageStyle(){let e=this.props.conditionalFormat.rule;if(e.type===`CellIsRule`)return W(qg(e.style));if(e.type===`ColorScaleRule`){let t=Jf(e.minimum.color),n=e.midpoint?Jf(e.midpoint.color):null,r=Jf(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, ${Jf(e.color)} 50%, white 50%)`}; color: ${Le};`;return``}get description(){let e=this.props.conditionalFormat;switch(e.rule.type){case`CellIsRule`:return Q.get(e.rule.operator).getPreview({...e.rule,type:e.rule.operator},this.env.model.getters);case`ColorScaleRule`:return I_.ColorScale;case`IconSetRule`:return I_.IconSet;case`DataBarRule`:return I_.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:De,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()})}},vj=class extends A{static template=`o-spreadsheet-ConditionalFormatPreviewList`;static components={ConditionalFormatPreview:_j};props=(0,t.useProps)({onCloseSidePanel:N.function()});dragAndDrop=oE();cfListRef=(0,t.signal)(null);get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId())}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[e.id]||``}onPreviewMouseDown(e,t){if(t.button!==0)return;let n=this.cfListRef();if(!n)return;let r=Array.from(n.children).map(e=>b(e)),i=this.conditionalFormats.map((e,t)=>({id:e.id,size:r[t].height,position:r[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:i,scrollableContainerEl:n,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onAddConditionalFormat(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones(),n={id:G.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=>Yn(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()})}},yj=class extends A{static template=`o-spreadsheet-DataValidationPreview`;props=(0,t.useProps)({rule:N.DataValidationRule()});dvPreviewRef=(0,t.signal)(null);setup(){IA(this.dvPreviewRef,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:De,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 Q.get(this.props.rule.criterion.type).getPreview(this.props.rule.criterion,this.env.model.getters)}},bj=class extends A{static template=`o-spreadsheet-DataValidationPanel`;static components={DataValidationPreview:yj};props=(0,t.useProps)({onCloseSidePanel:N.function()});addDataValidationRule(){this.env.replaceSidePanel(`DataValidationEditor`,`DataValidation`,{ruleId:G.smallUuid()})}get validationRules(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getDataValidationRules(e)}};let xj=new Set([`containsText`,`notContainsText`,`isEqualText`,`isEmail`,`isLink`,`dateIs`,`dateIsBefore`,`dateIsOnOrBefore`,`dateIsAfter`,`dateIsOnOrAfter`,`dateIsBetween`,`dateIsNotBetween`,`dateIsValid`,`isEqual`,`isNotEqual`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`isBoolean`,`isValueInList`,`isValueInRange`,`customFormula`]);var Sj=class extends A{static template=`o-spreadsheet-DataValidationEditor`;static components={SelectionInput:FE,Select:T_,Section:Z,ValidationMessages:zE};props=(0,t.useProps)({ruleId:N.UID(),onCancel:N.function().optional(),onCloseSidePanel:N.function()});state=(0,t.proxy)({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);e&&(this.state.rule={...e,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=e.criterion,n=Q.get(t.type),r=t.values.slice(0,n.numberOfValues(t)).filter(e=>e&&e.trim()!==``);return e.criterion={...t,values:r},{sheetId:this.editingSheetId,ranges:this.state.rule.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.editingSheetId,e)),rule:e}}get dvCriterionOptions(){return cj(xj)}get defaultDataValidationRule(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones().map(t=>Yn(this.env.model.getters.getUnboundedZone(e,t)));return{id:this.props.ruleId,criterion:{type:`containsText`,values:[``]},ranges:t}}get criterionComponent(){return sj.get(this.state.rule.criterion.type).component}get errorMessages(){return this.state.errors.map(e=>U_.Errors[e]||U_.Errors.Unexpected)}get isRuleBlockingSelectOptions(){return[{value:`false`,label:P(`Show a warning`)},{value:`true`,label:P(`Reject the input`)}]}};let Cj=`#8B008B`;var wj=class extends Vr{mutators=[`updateSearchOptions`,`updateSearchContent`,`searchFormulas`,`selectPreviousMatch`,`selectNextMatch`,`replace`];allSheetsMatches=[];activeSheetMatches=[];specificRangeMatches=[];selectedMatchPosition=null;allSheetsHiddenMatches=[];activeSheetHiddenMatches=[];specificRangeHiddenMatches=[];hiddenSheetsWithMatches=[];currentSearchRegex=null;initialShowFormulaState;irreplaceableMatchCount=0;isSearchDirty=!1;shouldFinalizeUpdateSelection=!1;notificationStore=this.get(aA);selectedMatchIndex=null;toSearch=``;toReplace=``;searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1,includeHidden:!1,searchScope:`activeSheet`,specificRange:void 0};constructor(e){super(e),this.initialShowFormulaState=this.model.getters.shouldShowFormulas(),this.searchOptions.searchFormulas=this.initialShowFormulaState;let t=e(ME);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 allSheetsMatchesCount(){return this.allSheetsMatches.length}get activeSheetMatchesCount(){return this.activeSheetMatches.length}get specificRangeMatchesCount(){return this.specificRangeMatches.length}get allSheetsHiddenMatchesCount(){return this.allSheetsHiddenMatches.length}get activeSheetHiddenMatchesCount(){return this.activeSheetHiddenMatches.length}get specificRangeHiddenMatchesCount(){return this.specificRangeHiddenMatches.length}_updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null,this.selectedMatchPosition=null),this.toSearch=e,this.currentSearchRegex=dn(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=[],t=[];if(this.toSearch){for(let t of this.getters.getVisibleSheetIds())e.push(...this.findMatchesInSheet(t));if(this.searchOptions.includeHidden)for(let n of this.getters.getInvisibleSheetIds()){let r=this.findMatchesInSheet(n);e.push(...r),r.length&&t.push(n)}}if(this.allSheetsMatches=e,this.activeSheetMatches=e.filter(e=>e.sheetId===this.getters.getActiveSheetId()),this.allSheetsHiddenMatches=e.filter(e=>{let t=this.getters.getInvisibleSheetIds().includes(e.sheetId),n=this.getters.isColHidden(e.sheetId,e.col),r=this.getters.isRowHidden(e.sheetId,e.row);return t||n||r}),this.activeSheetHiddenMatches=this.allSheetsHiddenMatches.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&&or(e.col,e.row,n)),this.specificRangeHiddenMatches=this.allSheetsHiddenMatches.filter(e=>e.sheetId===t&&or(e.col,e.row,n))}else this.specificRangeMatches=[],this.specificRangeHiddenMatches=[];this.hiddenSheetsWithMatches=t}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.getInvisibleSheetIds().includes(e),r=this.getters.isColHidden(e,i),a=this.getters.isRowHidden(e,o);if(!this.searchOptions.includeHidden&&(n||r||a))continue;let s={sheetId:e,col:i,row:o};if(this.currentSearchRegex?.test(this.getSearchableString(s))){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,{allowsHiddenSelection:!0})}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:P(`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:P(`%(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=dn(t,r),o=new RegExp(a.source,a.flags+`g`),s=J_(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=O(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:Cj,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:Cj,noFill:!0,thinLine:!0})}return e}},Tj=class extends A{static template=`o-spreadsheet-FindAndReplacePanel`;static components={SelectionInput:FE,Section:Z,Checkbox:wE,ValidationMessages:zE,Select:T_};props=(0,t.useProps)({onCloseSidePanel:N.function()});searchInputRef=t.signal.ref(HTMLInputElement);store;state;updateSearchContent;get hasSearchResult(){return this.store.selectedMatchIndex!==null}get searchOptions(){return this.store.searchOptions}get allSheetsMatchesCount(){let{allSheetsMatchesCount:e,allSheetsHiddenMatchesCount:t,searchOptions:n}=this.store,r=e===1?P(`1 match in all sheets`):P(`%(count)s matches in all sheets`,{count:e});return n.includeHidden&&(r+=this.hiddenLabel(t)),r}get currentSheetMatchesCount(){let{activeSheetMatchesCount:e,activeSheetHiddenMatchesCount:t,searchOptions:n}=this.store,r=this.env.model.getters.getSheetName(this.env.model.getters.getActiveSheetId()),i=e===1?P(`1 match in %(sheetName)s`,{sheetName:r}):P(`%(count)s matches in %(sheetName)s`,{count:e,sheetName:r});return n.includeHidden&&(i+=this.hiddenLabel(t)),i}get specificRangeMatchesCount(){let e=this.searchOptions.specificRange;if(!e)return``;let{specificRangeMatchesCount:t,specificRangeHiddenMatchesCount:n,searchOptions:r}=this.store,{sheetId:i,zone:a}=e,o=t===1?P(`1 match in range %(range)s of %(sheetName)s`,{range:Yn(a),sheetName:this.env.model.getters.getSheetName(i)}):P(`%(count)s matches in range %(range)s of %(sheetName)s`,{count:t,range:Yn(a),sheetName:this.env.model.getters.getSheetName(i)});return r.includeHidden&&(o+=this.hiddenLabel(n)),o}hiddenLabel(e){return e===1?` (${P(`1 is hidden`)})`:` (${P(`%(hidden)s are hidden`,{hidden:e})})`}get searchInfo(){return this.store.toSearch?[this.specificRangeMatchesCount,this.currentSheetMatchesCount,this.allSheetsMatchesCount].filter(Boolean):[]}get hiddenSheetsWithMatchesInfo(){return this.store.hiddenSheetsWithMatches.map(e=>this.env.model.getters.getSheetName(e))}setup(){this.store=Ji(wj),this.state=(0,t.proxy)({dataRange:``}),(0,t.onMounted)(()=>this.searchInputRef()?.focus()),(0,t.onWillUnmount)(()=>this.updateSearchContent.stopDebounce()),this.updateSearchContent=Vt(this.store.updateSearchContent,200),Ii(window,`keydown`,e=>{let t=se(e);(t===`Ctrl+F`||t===`Ctrl+H`)&&(this.searchInputRef()?.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})}searchIncludeHidden(e){this.store.updateSearchOptions({includeHidden: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:P(`All sheets`)},{value:`activeSheet`,label:P(`Current sheet`)},{value:`specificRange`,label:P(`Specific range`)}]}};let Ej=new k;function Dj({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=>Pw(e,r(e)),isActive:e=>wM(e,r(e)),format:t}}let Oj={name:P(`Automatic`),execute:e=>Pw(e,``),isActive:e=>CM(e)},kj={name:P(`Plain text`),execute:e=>Pw(e,`@`),isActive:e=>wM(e,`@`)},Aj=Dj({name:P(`Number`),descriptionValue:1000.12,format:`#,##0.00`}),jj={name:P(`Format as percent`),execute:lT,icon:`o-spreadsheet-Icon.PERCENT`},Mj=Dj({name:P(`Percent`),descriptionValue:.1012,format:`0.00%`}),Nj=Dj({name:P(`Scientific`),descriptionValue:.1012,format:`0.00e`}),Pj=Dj({name:P(`Currency`),descriptionValue:1000.12,format:e=>bc(e.model.config.defaultCurrency||lt)}),Fj={...Dj({name:P(`Currency rounded`),descriptionValue:1e3,format:e=>wc(bc(e.model.config.defaultCurrency||lt))}),isVisible:e=>{let t=bc(e.model.config.defaultCurrency||lt);return t!==wc(t)}},Ij=Dj({name:P(`Accounting`),descriptionValue:-1000.12,format:e=>xc(e.model.config.defaultCurrency||lt)}),Lj=$d(`2023/09/26 10:43:00 PM`,V),Rj={name:P(`Custom currency`),isVisible:e=>e.loadCurrencies!==void 0&&!e.isSmall,execute:e=>e.openSidePanel(`MoreFormats`,{category:`currency`})},zj=Dj({name:P(`Date`),descriptionValue:Lj,format:e=>e.model.getters.getLocale().dateFormat}),Bj=Dj({name:P(`Time`),descriptionValue:Lj,format:e=>e.model.getters.getLocale().timeFormat}),Vj=Dj({name:P(`Date time`),descriptionValue:Lj,format:e=>av(e.model.getters.getLocale())}),Hj=Dj({name:P(`Duration`),descriptionValue:`27:51:38`,format:`hhhh:mm:ss`}),Uj={name:P(`Custom date and time`),isVisible:e=>!e.isSmall,execute:e=>e.openSidePanel(`MoreFormats`,{category:`date`})},Wj={name:P(`Custom number format`),isVisible:e=>!e.isSmall,execute:e=>e.openSidePanel(`MoreFormats`,{category:`number`})};Dj({name:P(`Full date time`),format:`dddd d mmmm yyyy hh:mm:ss a`,descriptionValue:Lj});let Gj={name:P(`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})},Kj={name:P(`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})},qj={name:P(`Bold`),shortcut:`Ctrl+B`,execute:e=>Fw(e,{bold:!e.model.getters.getCurrentStyle().bold}),icon:`o-spreadsheet-Icon.BOLD`,isActive:e=>!!e.model.getters.getCurrentStyle().bold},Jj={name:P(`Italic`),shortcut:`Ctrl+I`,execute:e=>Fw(e,{italic:!e.model.getters.getCurrentStyle().italic}),icon:`o-spreadsheet-Icon.ITALIC`,isActive:e=>!!e.model.getters.getCurrentStyle().italic},Yj={name:P(`Underline`),shortcut:`Ctrl+U`,execute:e=>Fw(e,{underline:!e.model.getters.getCurrentStyle().underline}),icon:`o-spreadsheet-Icon.UNDERLINE`,isActive:e=>!!e.model.getters.getCurrentStyle().underline},Xj={name:P(`Rotation`),icon:e=>MM(e)};function Zj(e,t){t=Math.trunc(t/We)*We,Fw(e,{rotation:t})}function Qj(e,t){let n=e.model.getters.getCurrentStyle().rotation;return n===void 0?t===0:Math.abs(n-t)<We}let $j={name:P(`No rotation`),execute:e=>Fw(e,{rotation:0}),icon:`o-spreadsheet-Icon.ROTATION-0`,isActive:e=>Qj(e,0)},eM={name:P(`45° rotation`),execute:e=>Zj(e,Math.PI/4),icon:`o-spreadsheet-Icon.ROTATION-45`,isActive:e=>Qj(e,Math.PI/4)},tM={name:P(`90° rotation`),execute:e=>Zj(e,Math.PI/2),icon:`o-spreadsheet-Icon.ROTATION-90`,isActive:e=>Qj(e,Math.PI/2)},nM={name:P(`-90° rotation`),execute:e=>Zj(e,-Math.PI/2),icon:`o-spreadsheet-Icon.ROTATION-270`,isActive:e=>Qj(e,-Math.PI/2)},rM={name:P(`-45° rotation`),execute:e=>Zj(e,-Math.PI/4),icon:`o-spreadsheet-Icon.ROTATION-315`,isActive:e=>Qj(e,-Math.PI/4)},iM={name:P(`Strikethrough`),execute:e=>Fw(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),icon:`o-spreadsheet-Icon.STRIKE`,isActive:e=>!!e.model.getters.getCurrentStyle().strikethrough},aM={name:P(`Font size`),children:SM(),icon:`o-spreadsheet-Icon.FONT_SIZE`},oM={name:P(`Alignment`),icon:`o-spreadsheet-Icon.ALIGN_LEFT`},sM={name:P(`Horizontal align`),icon:e=>kM(e)},cM={name:P(`Left`),shortcut:`Ctrl+Shift+L`,execute:e=>Fw(e,{align:`left`}),isActive:e=>EM(e)===`left`,icon:`o-spreadsheet-Icon.ALIGN_LEFT`},lM={name:P(`Center`),shortcut:`Ctrl+Shift+E`,execute:e=>Fw(e,{align:`center`}),isActive:e=>EM(e)===`center`,icon:`o-spreadsheet-Icon.ALIGN_CENTER`},uM={name:P(`Right`),shortcut:`Ctrl+Shift+R`,execute:e=>Fw(e,{align:`right`}),isActive:e=>EM(e)===`right`,icon:`o-spreadsheet-Icon.ALIGN_RIGHT`},dM={name:P(`Vertical align`),icon:e=>AM(e)},fM={name:P(`Top`),execute:e=>Fw(e,{verticalAlign:`top`}),isActive:e=>DM(e)===`top`,icon:`o-spreadsheet-Icon.ALIGN_TOP`},pM={name:P(`Middle`),execute:e=>Fw(e,{verticalAlign:`middle`}),isActive:e=>DM(e)===`middle`,icon:`o-spreadsheet-Icon.ALIGN_MIDDLE`},mM={name:P(`Bottom`),execute:e=>Fw(e,{verticalAlign:`bottom`}),isActive:e=>DM(e)===`bottom`,icon:`o-spreadsheet-Icon.ALIGN_BOTTOM`},hM={name:P(`Wrapping`),icon:`o-spreadsheet-Icon.WRAPPING_OVERFLOW`},gM={name:P(`Wrapping`),icon:e=>jM(e)},_M={name:P(`Overflow`),execute:e=>Fw(e,{wrapping:`overflow`}),isActive:e=>OM(e)===`overflow`,icon:`o-spreadsheet-Icon.WRAPPING_OVERFLOW`},vM={name:P(`Wrap`),execute:e=>Fw(e,{wrapping:`wrap`}),isActive:e=>OM(e)===`wrap`,icon:`o-spreadsheet-Icon.WRAPPING_WRAP`},yM={name:P(`Clip`),execute:e=>Fw(e,{wrapping:`clip`}),isActive:e=>OM(e)===`clip`,icon:`o-spreadsheet-Icon.WRAPPING_CLIP`};P(`Text Color`),P(`Fill Color`);let bM={name:P(`Conditional formatting`),execute:uT,isEnabled:e=>!e.isSmall,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.CONDITIONAL_FORMAT`},xM={name:P(`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 SM(){return ot.map(e=>({name:e.toString(),sequence:e,id:`font_size_${e}`,execute:t=>Fw(t,{fontSize:e}),isActive:t=>TM(t,e)}))}function CM(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 wM(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 TM(e,t){return(e.model.getters.getCurrentStyle().fontSize||qe)===t}function EM(e){let t=e.model.getters.getCurrentStyle();return t.align&&t.align!=="default"?t.align:e.model.getters.getActiveCell().defaultAlign}function DM(e){let t=e.model.getters.getCurrentStyle();return t.verticalAlign?t.verticalAlign:Ge}function OM(e){let t=e.model.getters.getCurrentStyle();return t.wrapping?t.wrapping:Ke}function kM(e){switch(EM(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 AM(e){switch(DM(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 jM(e){switch(OM(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 MM(e){return Qj(e,Math.PI/2)?`o-spreadsheet-Icon.ROTATION-90`:Qj(e,-Math.PI/2)?`o-spreadsheet-Icon.ROTATION-270`:Qj(e,Math.PI/4)?`o-spreadsheet-Icon.ROTATION-45`:Qj(e,-Math.PI/4)?`o-spreadsheet-Icon.ROTATION-315`:`o-spreadsheet-Icon.ROTATION-0`}let NM={name:R_.Custom,code:``,symbol:``,decimalPlaces:2,position:`after`};var PM=class extends Vr{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=[NM,...Ej.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=!Lc(e||``),this.category=this.detectFormatCategory(e)}get categories(){return[{label:P(`Number`),value:`number`},{label:P(`Date`),value:`date`},{label:P(`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?pc(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:P(`Automatic`),format:void 0},{label:P(`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(Lj,{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?xc(e):bc(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||!Lc(e))return[];if(this.category===`date`)return[{label:P(`Sample:`),value:H(Lj,{format:e,locale:t})}];{let n=Rc(e),r=[{label:P(`Positive:`),value:H(1234.56,{format:e,locale:t})},{label:P(`Negative:`),value:H(-1234.56,{format:e,locale:t})},{label:P(`Zero:`),value:H(0,{format:e,locale:t})}];return n===4&&r.push({label:P(`Text:`),value:H(`Text`,{format:e,locale:t})}),r}}updateAvailableCurrencies(){this.availableCurrencies=[NM,...Ej.getAll()]}updateFormat(e){this.currentFormat=e,this.invalidFormat=!Lc(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?P(`The format entered is not valid.`):void 0}},FM=class extends A{static template=`o-spreadsheet-MoreFormatsPanel`;static components={BadgeSelection:JE,Section:Z,TextInput:mE,Checkbox:wE,Select:T_};props=(0,t.useProps)({onCloseSidePanel:N.function(),category:N.or([N.literal(`number`),N.literal(`date`),N.literal(`currency`)]).optional()});store;setup(){this.store=Ji(PM,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(){Ej.getAll().length===0&&((await(this.env.loadCurrencies?.()??Promise.resolve([]))).forEach((e,t)=>{Ej.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 IM(e,t){RM(e,e.model.dispatch(`CREATE_NAMED_RANGE`,t))}function LM(e,t){RM(e,e.model.dispatch(`UPDATE_NAMED_RANGE`,t))}function RM(e,t){t.isSuccessful||(t.isCancelledBecause(`NamedRangeNameAlreadyExists`)?e.raiseError(P(`A named range with this name already exists.`)):t.isCancelledBecause(`NamedRangeInvalidName`)?e.raiseError(P(`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(P(`A named range name cannot resemble a cell reference.`)):t.isCancelledBecause(`NamedRangeNotFound`)&&e.raiseError(P(`The named range to update was not found.`)))}var zM=class extends A{static template=`o-spreadsheet-NamedRangePreview`;static components={SelectionInput:FE,TextInput:mE};props=(0,t.useProps)({namedRange:N.NamedRange()});state=(0,t.proxy)({});namedRangePreviewRef=(0,t.signal)(null);setup(){IA(this.namedRangePreviewRef,this)}get highlights(){return this.state.isSelectionInputFocused?[]:[{range:this.props.namedRange.range,color:De,noFill:!0}]}deleteNamedRange(){this.env.model.dispatch(`DELETE_NAMED_RANGE`,{name:this.props.namedRange.name})}updateNamedRangeName(e){e=e.replace(/ /g,`_`),LM(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;LM(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())}},BM=class extends A{static template=`o-spreadsheet-NamedRangesPanel`;static components={NamedRangePreview:zM,SelectionInput:FE,TextInput:mE};props=(0,t.useProps)({onCloseSidePanel:N.function()});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:_n(P(`Named_Range`),e,{compute:(e,t)=>`${e}${t}`}),ranges:[this.env.model.getters.getRangeDataFromZone(t,n)]})}},VM=class extends A{static template=`o-spreadsheet-PerfProfilePanel`;static components={Section:Z};props=(0,t.useProps)({onCloseSidePanel:N.function()});state=(0,t.proxy)({selectedIndex:void 0,lastProfiledTime:0});setup(){LA(this)}get perfProfile(){return this.env.model.getters.getPerfProfile()}get highlights(){let e=this.state.selectedIndex;if(e===void 0)return[];let t=this.perfProfile?.entries[e];return t?[{range:t.range,color:`#e28f08`,noFill:!0}]:[]}stringifyRange({range:e}){return this.env.model.getters.getRangeString(e,`forceSheetReference`)}startProfiling(e){e.timeStamp-this.state.lastProfiledTime<50||(this.state.selectedIndex=void 0,this.env.model.dispatch(`EVALUATE_CELLS`,{profiling:!0}),this.state.lastProfiledTime=performance.now())}isSelected(e){return this.state.selectedIndex===e}selectEntry(e){this.state.selectedIndex=e;let t=this.perfProfile?.entries[e];if(!t||!this.env.model.getters.tryGetSheet(t.range.sheetId))return;let n=this.env.model.getters.getActiveSheetId();t.range.sheetId!==n&&this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:t.range.sheetId});let r=t.range.zone;this.env.model.selection.selectCell(r.right,r.bottom),this.env.model.selection.selectCell(r.left,r.top)}formatTime(e){let t=this.env.model.getters.getLocale();return e>=1e3?P(`%(seconds)s s`,{seconds:H(e/1e3,{format:`0.00`,locale:t})}):P(`%(milliseconds)s ms`,{milliseconds:H(e,{format:`0.00`,locale:t})})}humanize(e){let t=this.env.model.getters.getLocale();return Ec({value:e},t)}formatPercent(e){let t=this.perfProfile?.totalTime;return t?H(e/t,{format:`0.0%`,locale:this.env.model.getters.getLocale()}):`0.0%`}barWidth(e){let t=this.perfProfile?.totalTime??0;return t?e.time/t*100:0}},HM=class extends Vr{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=P_),{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:_C(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:P_,label:P(`(previous)`)},{value:F_,label:P(`(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})}},UM=class extends A{static template=`o-spreadsheet-PivotMeasureDisplayPanel`;props=(0,t.useProps)({onCloseSidePanel:N.function(),pivotId:N.UID(),measure:N.PivotCoreMeasure()});static components={Section:Z,Checkbox:wE,RadioSelection:ZE,Select:T_};measureDisplayTypeLabels=G_.labels;measureDisplayDescription=G_.documentation;store;setup(){this.store=Ji(HM,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 WM(e,t){let n=e.getActiveSheetId();return Ar(GM(e,t).map(O)).map(t=>({range:e.getRangeFromZone(n,t),noFill:!0,color:De}))}function GM(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 KM=class extends A{static template=`o-spreadsheet-PivotDeferUpdate`;props=(0,t.useProps)({deferUpdate:N.boolean(),isDirty:N.boolean(),toggleDeferUpdate:N.function(),discard:N.function(),apply:N.function()});static components={Section:Z,Checkbox:wE};get deferUpdatesLabel(){return P(`Defer updates`)}get deferUpdatesTooltip(){return P(`Changing the pivot definition requires to reload the data. It may take some time.`)}},qM=class{measures;columns;rows;filters;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.filters=(e.filters??[]).map(e=>this.createPivotFilter(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 I(P(`Dimension %s does not exist`,e));return t}getMeasure(e){let t=this.measures.find(t=>t.id===e);if(!t)throw new I(P(`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:P(`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&&sC(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}}createPivotFilter(e,t){let n=e[t.fieldName];return{...t,displayName:n?.name??t.fieldName,isValid:!!n}}},JM=class extends qM{range;constructor(e,t,n){if(super(e,t),e.dataSet){let{sheetId:t,zone:r}=e.dataSet;this.range=n.getRangeFromZone(t,r)}}};let YM=new Set([`containsText`,`notContainsText`,`isEqualText`,`dateIs`,`dateIsBefore`,`dateIsOnOrBefore`,`dateIsAfter`,`dateIsOnOrAfter`,`dateIsBetween`,`dateIsNotBetween`,`isEqual`,`isNotEqual`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`customFormula`,`beginsWithText`,`endsWithText`,`isNotEmpty`,`isEmpty`]),XM=[`containsText`,`notContainsText`,`isEqualText`,`isEmpty`,`isNotEmpty`,`beginsWithText`,`endsWithText`],ZM=[`isEqual`,`isNotEqual`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`isEmpty`,`isNotEmpty`],QM=[`dateIs`,`dateIsBefore`,`dateIsOnOrBefore`,`dateIsAfter`,`dateIsOnOrAfter`,`dateIsBetween`,`dateIsNotBetween`,`isEmpty`,`isNotEmpty`];var $M=class extends A{static template=`o-spreadsheet-FilterMenuCriterion`;static components={Select:T_};props=(0,t.useProps)({criterion:N.CriterionFilter(),criterionOperators:N.array(N.GenericCriterionType()),onCriterionChanged:N.function()});state;setup(){(0,t.onWillUpdateProps)(e=>{T(e.criterion,this.props.criterion)||(this.state.criterion=e.criterion)}),this.state=(0,t.proxy)({criterion:this.props.criterion})}get criterionOptions(){return[{label:P(`None`),value:`none`},...cj(new Set(this.props.criterionOperators))]}get criterionComponent(){return this.state.criterion.type===`none`?void 0:sj.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)}},eN=class extends A{static template=`o-spreadsheet-FilterMenuValueItem`;static components={Checkbox:wE};props=(0,t.useProps)({value:N.string(),isChecked:N.boolean(),isSelected:N.boolean(),onMouseMove:N.function(),onClick:N.function(),scrolledTo:N.or([N.literal(`top`),N.literal(`bottom`)]).optional()});itemRef=(0,t.signal)(null);setup(){(0,t.onWillPatch)(()=>{this.props.scrolledTo&&this.scrollListToSelectedValue()})}scrollListToSelectedValue(){let e=this.itemRef();e&&e.scrollIntoView?.({block:`nearest`})}},tN=class extends A{static template=`o-spreadsheet-FilterMenuValueList`;static components={FilterMenuValueItem:eN};props=(0,t.useProps)({values:N.array(N.object({checked:N.boolean(),string:N.string(),scrolledTo:N.or([N.literal(`top`),N.literal(`bottom`)]).optional()})),onUpdateHiddenValues:N.function()});state=(0,t.proxy)({displayedValues:[],textFilter:``,selectedValue:void 0,numberOfDisplayedValues:50,hasMoreValues:!1});searchBarRef=t.signal.ref(HTMLInputElement);setup(){(0,t.onWillUpdateProps)(e=>{T(e.values,this.props.values)||this.computeDisplayedValues(e)}),this.computeDisplayedValues(this.props)}checkValue(e){this.state.selectedValue=e.string,e.checked=!e.checked,this.searchBarRef()?.focus(),this.updateHiddenValues()}onMouseMove(e){this.state.selectedValue=e.string}getSearchedValues(e){return this.state.textFilter?rA(this.state.textFilter,e.values,e=>e.string):e.values}setAllChecked(e){let t=new Set(this.getSearchedValues(this.props));for(let n of this.props.values)t.has(n)&&(n.checked=e);this.updateHiddenValues()}selectAll(){this.setAllChecked(!0)}clearAll(){this.setAllChecked(!1)}updateHiddenValues(){let e=this.props.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(this.props)}computeDisplayedValues(e){let t=this.getSearchedValues(e);this.state.displayedValues=t.slice(0,this.state.numberOfDisplayedValues),this.state.hasMoreValues=t.length>this.state.numberOfDisplayedValues}loadMoreValues(){this.state.numberOfDisplayedValues+=100,this.computeDisplayedValues(this.props)}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.props.values.forEach(e=>e.scrolledTo=void 0)}scrollListToSelectedValue(e){this.clearScrolledToValue();let t=this.props.values.find(e=>e.string===this.state.selectedValue);t&&(t.scrolledTo=e===`ArrowUp`?`top`:`bottom`)}},nN=class extends A{static template=`o-spreadsheet-PivotFilterMenu`;static components={FilterMenuValueList:tN,SidePanelCollapsible:WE,FilterMenuCriterion:$M};criterionCategory=`char`;updatedCriterionValue;props=(0,t.useProps)({pivotId:N.UID(),definition:N.instanceOf(JM),filter:N.PivotFilter(),values:N.array(N.object({checked:N.boolean(),string:N.string(),scrolledTo:N.or([N.literal(`top`),N.literal(`bottom`)]).optional()})),onClosed:N.function().optional(),onConfirmed:N.function()});setup(){(0,t.onWillUpdateProps)(e=>{T(e.definition,this.props.definition)||(this.updatedCriterionValue=void 0,this.criterionCategory=this.getCriterionCategory())}),this.criterionCategory=this.getCriterionCategory()}getCriterionCategory(){return this.env.model.getters.getPivot(this.props.pivotId).getFields()[this.props.filter.fieldName]?.type||`char`}onUpdateHiddenValues(e){this.updatedCriterionValue={filterType:`values`,hiddenValues:e}}onCriterionChanged(e){this.updatedCriterionValue=e}confirm(){if(!this.updatedCriterionValue){this.props.onClosed?.();return}this.props.onConfirmed(this.updatedCriterionValue),this.props.onClosed?.()}get criterionOperators(){return this.criterionCategory===`datetime`?QM:this.criterionCategory===`integer`?ZM:XM}cancel(){this.props.onClosed?.()}getFilterCriterionValue(){let e=this.props.filter;return e.filterType===`criterion`?x(e):{filterType:`criterion`,type:`none`,values:[]}}},rN=class extends A{static template=`o-spreadsheet-PivotDimension`;props=(0,t.useProps)({dimension:N.or([N.PivotDimension(),N.PivotMeasure(),N.PivotFilter()]),onRemoved:N.function().optional(),onNameUpdated:N.function().optional(),type:N.or([N.literal(`row`),N.literal(`col`),N.literal(`measure`),N.literal(`filter`)]).optional()});static components={CogWheelMenu:xE,TextInput:mE};updateName(e){this.props.onNameUpdated?.(this.props.dimension,e===``||e.startsWith(`=`)?void 0:e)}get dimensionDisplayName(){let e=this.props.dimension.displayName;return OC(e)}},iN=class extends A{static template=`o-spreadsheet-PivotFilterEditor`;static components={PivotDimension:rN,Popover:b_,PivotFilterMenu:nN};props=(0,t.useProps)({pivotId:N.UID(),definition:N.instanceOf(JM),filter:N.PivotFilter(),onFiltersUpdated:N.function()});state;buttonFilter=(0,t.signal)(null);popover;setup(){Ii(window,`click`,e=>{_(this.buttonFilter(),e)||(this.popover.isOpen=!1)}),(0,t.onWillUpdateProps)(e=>{T(e.definition,this.props.definition)||(this.state.values=this.getFilterHiddenValues(e))}),this.popover=(0,t.proxy)({isOpen:!1}),this.state=(0,t.proxy)({values:this.getFilterHiddenValues(this.props)})}filterCaption(){if(this.props.filter.filterType===`criterion`)return this.props.filter.type===`none`?P(`showing all items`):Q.get(this.props.filter.type).getPreview(this.props.filter,this.env.model.getters);let e=this.props.filter.hiddenValues.length,t=this.state.values.length-e;return e===0?P(`showing all items`):t===1?P(`showing 1 item`):P(`showing %s items`,t)}getFilterHiddenValues(e){let t=this.env.model.getters.getPivot(e.pivotId);if(t.type!==`SPREADSHEET`)throw Error(`Filters are only available on spreadsheet pivot table`);let n=t.getDataEntries(),r=e.filter.fieldName,i=new Set,a=[];for(let t of n){let n=t[r]?t[r].formattedValue.toString():``;i.has(n)||(a.push({string:n,checked:e.filter.filterType===`criterion`?!0:!e.filter.hiddenValues.includes(n),normalizedValue:jf(n)}),i.add(n))}return a.sort((e,t)=>e.normalizedValue.localeCompare(t.normalizedValue,void 0,{numeric:!0,sensitivity:`base`}))}get popoverProps(){let{x:e,y:t,width:n,height:r}=this.buttonFilter()?.getBoundingClientRect()??{x:0,y:0,width:0,height:0};return{anchorRect:{x:e,y:t,width:n,height:r},positioning:`bottom-left`}}getCell(e){return this.env.model.getters.getCell(e)}removeFilter(e){let{filters:t}=this.props.definition;this.props.onFiltersUpdated({filters:(t??[]).filter(t=>t.fieldName!==e.fieldName)})}openMenuFilter(){this.popover.isOpen=!this.popover.isOpen}closeMenuFilter(){this.popover.isOpen=!1}isActive(){let e=this.props.filter;return e.filterType===`criterion`?e.type!==`none`:e.hiddenValues.length>0}updateFilterData(e){let{filters:t}=this.props.definition,n=this.props.filter,r=(t??[]).map(t=>t.fieldName===n.fieldName?{...t,...e}:t);this.props.onFiltersUpdated({filters:r})}};function aN(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 oN=class extends A{static template=`o-spreadsheet-AddDimensionButton`;static components={Popover:b_,TextValueProvider:Pk};props=(0,t.useProps)({onFieldPicked:N.function(),fields:N.array()});buttonRef=(0,t.signal)(null);popover=(0,t.proxy)({isOpen:!1});search=(0,t.proxy)({input:``});autoComplete;autofocusRef=(0,t.signal)(null);setup(){this.autoComplete=Ji(oA),this.autoComplete.useProvider(this.getProvider()),Ii(window,`click`,e=>{e.target!==this.buttonRef()&&(this.popover.isOpen=!1)}),dE(this.autofocusRef)}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?rA(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:aN(this.search.input,t,Me,`o-semi-bold`)}})}get popoverProps(){let e=this.buttonRef(),{x:t,y:n,width:r,height:i}=e?e.getBoundingClientRect():{x:0,y:0,width:0,height:0};return{anchorRect:{x:t,y:n,width:r,height:i},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}}},sN=class extends A{static template=`o-spreadsheet-PivotCustomGroupsCollapsible`;props=(0,t.useProps)({pivotId:N.UID(),customField:N.PivotCustomGroupedField(),onCustomFieldUpdated:N.function()});static components={SidePanelCollapsible:WE,TextInput:mE,Checkbox:wE};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:bC(P(`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=bC(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}})}},cN=class extends A{static template=`o-spreadsheet-PivotDimensionGranularity`;props=(0,t.useProps)({dimension:N.PivotDimension(),onUpdated:N.function(),availableGranularities:N.SetOf(),allGranularities:N.array()});static components={Select:T_};periods=iC;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]}))}},lN=class extends A{static template=`o-spreadsheet-PivotDimensionOrder`;props=(0,t.useProps)({dimension:N.PivotDimension(),onUpdated:N.function(),isMeasureSorted:N.boolean().optional()});static components={Select:T_};get orderSelectOptions(){let e=[{value:`asc`,label:P(`Ascending`)},{value:`desc`,label:P(`Descending`)}];return this.props.isMeasureSorted&&e.unshift({value:`measures`,label:P(`Sorted by measure`)}),this.props.dimension.type===`date`?e:[{value:``,label:P(`Unsorted`)},...e]}get selectedValue(){return this.props.isMeasureSorted?`measures`:this.props.dimension.order||``}};function uN(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:Be}],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:Be}],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 dN=class extends A{static template=`o-spreadsheet-PivotMeasureEditor`;static components={PivotDimension:rN,StandaloneComposer:lA,Select:T_};props=(0,t.useProps)({pivotId:N.string(),definition:N.PivotRuntimeDefinition(),measure:N.PivotMeasure(),onMeasureUpdated:N.function(),onRemoved:N.function(),generateMeasureId:N.function(),aggregators:N.object({})});getMeasureAutocomplete(){return uN(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=wt(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 Be}get isCalculatedMeasureInvalid(){return fd.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:P(`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?_C(r):``,a=t.value?.toString()||``;return G_.descriptions[t.type](i,a)}},fN=class extends A{static template=`o-spreadsheet-PivotSortSection`;static components={Section:Z};props=(0,t.useProps)({definition:N.PivotRuntimeDefinition(),pivotId:N.UID()});get hasValidSort(){let e=this.env.model.getters.getPivot(this.props.pivotId);return!!this.props.definition.sortedColumn&&yC(this.props.definition.sortedColumn,e)}get sortDescription(){return P(`Sorted on column (%(ascOrDesc)s):`,{ascOrDesc:this.props.definition.sortedColumn?.order===`asc`?P(`ascending`):P(`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:_C(c),value:s})}e.domain.length===0&&i.push({value:P(`Total`)});let a=t.getMeasure(e.measure).displayName;return i.push({value:a,field:P(`Measure`)}),i}},pN=class extends A{static template=`o-spreadsheet-PivotLayoutConfigurator`;static components={AddDimensionButton:oN,PivotDimension:rN,PivotDimensionOrder:lN,PivotDimensionGranularity:cN,PivotMeasureEditor:dN,PivotSortSection:fN,PivotCustomGroupsCollapsible:sN,SidePanelCollapsible:WE};props=(0,t.useProps)({definition:N.instanceOf(qM),onDimensionsUpdated:N.function(),onFiltersUpdated:N.function(),unusedGroupableFields:N.array(N.PivotField()),measureFields:N.array(N.PivotField()),unusedGranularities:N.RecordOf(),dateGranularities:N.array(N.string()),datetimeGranularities:N.array(N.string()),getScrollableContainerEl:N.function().optional(),pivotId:N.UID()});dimensionsRef=(0,t.signal)(null);dragAndDrop=oE();AGGREGATORS=tC;composerFocus;isDateOrDatetimeField=sC;setup(){this.composerFocus=j(Ur)}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(),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 sC(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(),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().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:kC(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,sortedColumn:i}=this.props.definition,a=n.some(t=>t.nameWithGranularity===e.nameWithGranularity);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),sortedColumn:a?void 0:i})}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?P(`This dimension contains a lot of values (%s), and might slow down the pivot table.`,t.length):void 0}get hasSortedColumn(){return!!this.props.definition.sortedColumn}},mN=class extends A{static template=`o-spreadsheet-PivotTitleSection`;static components={CogWheelMenu:xE,Section:Z,TextInput:mE};props=(0,t.useProps)({pivotId:N.UID(),flipAxis:N.function()});get cogWheelMenuItems(){return[{name:P(`Flip axes`),icon:`o-spreadsheet-Icon.EXCHANGE`,execute:this.props.flipAxis,isEnabledOnLockedSheet:!0},{name:P(`Duplicate`),icon:`o-spreadsheet-Icon.COPY`,execute:()=>this.duplicatePivot(),isEnabledOnLockedSheet:!0},{name:P(`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=G.smallUuid(),t=G.smallUuid(),n=this.env.model.dispatch(`DUPLICATE_PIVOT_IN_NEW_SHEET`,{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t}),r;r=n.isSuccessful?P(`Pivot duplicated.`):n.isCancelledBecause(`PivotInError`)?P(`Cannot duplicate a pivot in error.`):P(`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(P(`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}})}};function hN(e,t,n,r,i){if(r.filterType===`values`){let e=r.hiddenValues?.map(jf);if(!e)return!1;if(new Set(e).has(jf(n.formattedValue)))return!0}else{if(r.type===`none`)return!1;let a=Q.get(r.type),o=r.values.map(n=>n.startsWith(`=`)?e.evaluateFormula(t,n)??``:$d(n,V));if(o.some(yS))return!1;let s={type:r.type,values:o.map(_S),dateValue:r.dateValue};if(!a.isValueValid(n.value,s,i))return!0}return!1}function gN(e,t){let{colDomain:n,rowDomain:r}=vN(e,t);return[...n,...r.slice(0,r.length-1)]}function _N(e,t){let{colDomain:n,rowDomain:r}=vN(e,t);return[...n.slice(0,n.length-1),...r]}function vN(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 yN(e,t,n){return t===`column`?vN(e,n).colDomain:vN(e,n).rowDomain}function bN(e,t){return t.find(t=>t.field===e)?.value}function xN(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}=vN(e,t);return SN(n,e.getExpandedTableStructure().getRowTree())&&SN(r,e.getExpandedTableStructure().getColTree())}function SN(e,t){return CN(e,t)!==void 0}function CN(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 wN(e,t,n){let{rowDomain:r,colDomain:i}=vN(e,n);if(DN(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 TN(e,t,n){e=x(e);let r=e.find(e=>e.field===t);return r&&(r.value=n),e}function EN(e,t){return t.some(t=>t.field===e)}function DN(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 ON(e,t,n,r){let i=DN(e,n),a=i===`row`?e.getExpandedTableStructure().getRowTree():e.getExpandedTableStructure().getColTree(),o=CN(yN(e,i,t),a,n)?.map(e=>e.value)??[],s=bN(n,t);if(s===void 0)return;let c=o.indexOf(s);if(!(s===void 0||c===-1))return TN(t,n,o[S(c+(r===`(previous)`?-1:1),0,o.length-1)])}function kN(e){return e?e.map(AN).join(`, `):``}function AN(e){return e?`${e.field}=${e.value}`:``}function jN(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 kN(i.field===t?r:[...r,i])}function MN(e,t){let n=e.findIndex(e=>e.field===t);return n===-1?``:kN([...e.slice(0,n),...e.slice(n+1)])}function NN(e,t,n){let r=[...e],i=[...t];r.sort((e,t)=>n([...i,e],[...i,t]));for(let t of e)t.children=NN(t.children,[...i,t],n);return r}function PN(e,t){return e.length>t.length&&t.every((t,n)=>T(t,e[n]))}var FN=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=Gt(()=>this.buildRowsTree()),this.colTree=Gt(()=>this.buildColumnsTree())}removeCollapsedColumns(e,t,n){let r=(n,r)=>{let i=this.getDomain(n),a=e[r],o=a.findIndex(e=>PN(this.getDomain(e),i)),s=a.findLastIndex(e=>PN(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=>PN(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=ZS){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?IN:{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 IN;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`}:IN}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)?IN:{type:`VALUE`,domain:[...this.getDomain(this.rows[a]),...this.getColDomain(o)],measure:this.getColMeasure(o)}}return IN}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:dC({displayName:`measure`,type:`char`},e.values[n])};{let{fieldName:r,granularity:i}=oC(t),a=this.fieldsType[r]||`char`;return{type:a,field:t,value:dC({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}=oC(a),c=dC({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}=oC(r),o=dC({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=NN(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=Gt(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 IN={type:`EMPTY`};function LN(e,t,n){let r=t.measures.filter(e=>!e.isHidden).map(e=>e.id),i=zN(e,t.columns,0);BN(i,r.length);let a=VN(i,t),o=RN(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 FN(a,o,r,s,n===`collapsed`?t.collapsedDomains:void 0)}function RN(e,t,n,r,i){if(t>=n.length)return[];let a=n[t],o=a.nameWithGranularity,s=HN(e,a),c=WN(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(...RN(a,t+1,n,u,r))}return l}function zN(e,t,n){if(n>=t.length)return[];let r=t[n],i=t[n].nameWithGranularity,a=HN(e,r);return WN(a,t[n]).map(e=>({value:a[e]?.[0]?.[r.nameWithGranularity]?.value??null,field:i,children:zN(a[e]||[],t,n+1),type:r.type,width:0}))}function BN(e,t){for(let n in e){let r=e[n];r.children.length===0?r.width=t:(BN(r.children,t),r.width=r.children.reduce((e,t)=>e+t.width,0))}}function VN(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 HN(e,t){return Object.groupBy(e,UN(t))}function UN(e){let t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}function WN(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?GN(t,e,i):0)}function GN(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`?L(t,V)-L(n,V):L(n,V)-L(t,V):e.order===`asc`?t.localeCompare(n):n.localeCompare(t)}var KN=class{type=`SPREADSHEET`;getters;_definition;coreDefinition;metaData={fields:{},fieldKeys:[]};unfilteredDataEntries=[];filteredDataEntries=[];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.unfilteredDataEntries=this.loadDataEntries(),this.filteredDataEntries=this.loadFilteredDataEntries(this.unfilteredDataEntries)),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;for(let e of this.definition.filters??[])if(!e.isValid)return!1;return!0}assertIsValid({throwOnError:e}){if(!this.isValid()){if(e)throw this.invalidRangeError?this.invalidRangeError:new I(P(`At least one measure/dimension and/or filter is not correct.`));return{value:F.GenericError,message:this.invalidRangeError?.message??P(`At least one measure/dimension and/or filter is not correct.`)}}}areDomainArgsFieldsValid(e){let t=e.filter((e,t)=>t%2==0).map(R);return t.length&&t.at(-1)===`measure`&&(t=t.slice(0,-1)),lC(t,this.definition)}parseArgsToPivotDomain(e){let t=[];for(let n=0;n<e.length-1;n+=2){let r=R(e[n]),i=this.getTypeOfDimension(r),a=r===`measure`?R(e[n+1]):dC(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:P(`Total`)};let n=this.getDimension(t.field),r=this.filterDataEntriesFromDomain(this.filteredDataEntries,e)[0]?.[n.nameWithGranularity];return n.type===`datetime`?RS(n.granularity||`month`).toValueAndFormat(t.value,this.getters.getLocale()):r?r.value===null?{value:P(`(Undefined)`)}:r:{value:``}}getPivotCellValueAndFormat(e,t){let n=this.filterDataEntriesFromDomain(this.filteredDataEntries,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=nC[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 $c(e,o.toUpperCase())}}getDataEntries(){return this.unfilteredDataEntries}getPossibleFieldValues(e){let t=[],n=HN(this.filteredDataEntries,e),r=WN(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||=LN(this.filteredDataEntries,this.definition,`collapsed`),this.collapsedTable)}getExpandedTableStructure(){if(!this.isValid())throw Error(`Pivot is not valid !`);return this.expandedTable||=LN(this.filteredDataEntries,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=SC(this.coreDefinition,e.fields);return{...e,fields:{...e.fields,...t}}}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}else return this.invalidRangeError=new I(P(`The pivot cannot be created because the dataset is missing.`)),{fields:{},fieldKeys:[]}}loadRuntimeDefinition(){return new JM(this.coreDefinition,this.fields,this.getters)}loadDataEntries(){let e=this._definition?.range;return this.isValid()&&e?this.extractDataEntriesFromRange(e):[]}loadFilteredDataEntries(e){let t=this._definition?.range?.sheetId;return t?(this._definition&&this._definition.filters&&(e=e.filter(e=>{let n=!0;for(let r of this._definition?.filters??[]){let i=e[r.fieldName];if(i&&hN(this.getters,t,i,r)){n=!1;break}}return n})),e):[]}getTypeOfDimension(e){if(e===`measure`)return`char`;let{fieldName:t}=oC(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&&pc(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 I(P(`The pivot cannot be created because cell %s contains an error`,E(e,t)));if(n.type===`empty`||n.value===``)throw new I(P(`The pivot cannot be created because cell %s is empty`,E(e,t)));if(n.value===`__count`)throw new I(P(`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=xC(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={},o=!0;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,t.type!==`empty`&&(o=!1))}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}}o||(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=fD(t,r[t.fieldName]?.value||null,this.getters.getLocale()),{format:i,value:a}=RS(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 qN=new k,JN=[`year`,`quarter_number`,`month_number`,`month`,`iso_week_number`,`day_of_month`,`day`,`day_of_week`],YN=[...JN,`hour_number`,`minute_number`,`second_number`];qN.add(`SPREADSHEET`,{ui:KN,definition:JM,dateGranularities:[...JN],isMeasureCandidate:e=>e.type!==`boolean`,datetimeGranularities:[...YN],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=XN(a,n);if(o===a)return t;let s=o&&{sheetId:o.sheetId,zone:o.zone};return{...t,dataSet:s}}});function XN(e,t){if(!e)return;let n=t(e);switch(n.changeType){case`REMOVE`:return;default:return n.range}}let ZN=[`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`];function QN(e,t){return e.getFunctionsFromTokens(ZN,t)[0]}function $N(e,t){return e.getFunctionsFromTokens(ZN,t)}function eP(e,t){return e.getFunctionsFromTokens(ZN,t).length}function tP(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:pt.STRING}],fuzzySearchKey:r}}function nP(e){let t=`"${e.id}"`,n=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:pt.STRING}],fuzzySearchKey:n}}function rP(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 iP(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 aP(e){let t=e.functionContext?.args[0];if(!(!t||![`STRING`,`NUMBER`].includes(t.type)))return t.value}var oP=class extends Vr{pivotId;updateMode;mutators=[`reset`,`deferUpdates`,`applyUpdate`,`discardPendingUpdate`,`update`];_updatesAreDeferred;draft=null;notification=this.get(aA);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=qN.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:P(`Count`),type:`integer`,aggregator:`sum`}],t=this.fields;for(let n in t){let r=t[n];r&&qN.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&&qN.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=>sC(e)?!a.includes(e.name)||o[e.name].size>0:!a.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get unusedFilterFields(){let e=Object.values(this.fields).filter(e=>e!==void 0),{filters:t}=this.definition,n=(t??[]).map(e=>e.fieldName);return e.filter(e=>!n.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return qN.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return qN.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:P(`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:K_(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})),filters:(n.filters??[]).map(e=>e.filterType===`values`?{fieldName:e.fieldName,filterType:e.filterType,hiddenValues:e.hiddenValues}:{fieldName:e.fieldName,filterType:e.filterType,type:e.type,values:e.values,dateValue:e.dateValue}),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=QN(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}},sP=class extends A{static template=`o-spreadsheet-PivotSpreadsheetSidePanel`;static components={PivotLayoutConfigurator:pN,Section:Z,SelectionInput:FE,Checkbox:wE,PivotDeferUpdate:KM,PivotTitleSection:mN,AddDimensionButton:oN,PivotFilterEditor:iN};props=(0,t.useProps)({pivotId:N.UID(),onCloseSidePanel:N.function()});store;state;pivotSidePanelRef=(0,t.signal)(null);setup(){this.store=Ji(oP,this.props.pivotId),this.state=(0,t.proxy)({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()}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)}onFiltersUpdated(e){this.store.update(e)}addFilter(e){let{filters:t}=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.onFiltersUpdated({filters:(t??[]).concat([{fieldName:e,filterType:`values`,hiddenValues:[]}])})}};let cP=new k;cP.add(`SPREADSHEET`,{editor:sP});let lP=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`}}}}),uP=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`}}}}),dP=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:K.black.light}},secondColumnStripe:{style:{fillColor:K.black.light},border:{left:{color:K.black.medium,style:`thin`},right:{color:K.black.medium,style:`thin`}}}}),fP=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:K.black.medium,style:`thin`},bottom:{color:K.black.medium,style:`thin`}}},secondColumnStripe:{style:{fillColor:e.light}}}),pP=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`}}}}),mP=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`}}}}),hP=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`}}}}),gP=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}}}),_P=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`}}}}),vP=e=>({category:`dark`,templateName:`pivotDarkWithGrayHeader`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.light}},headerRow:{style:{bold:!0,fillColor:K.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:K.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`}}}}),yP=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`}}}}),bP=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}}}),xP={None:{category:`light`,templateName:`none`,primaryColor:``,displayName:P(`None`)}},SP=[K.black,K.lightBlue,K.red,K.lightGreen,K.purple,K.gray,K.orange];function CP(e,t){let n=1;for(let r of t)for(let t of SP){let i=e+n++;xP[i]={...r(t),displayName:wP(t.name,e,n-1)}}}function wP(e,t,n){let r=``;return t.includes(`Light`)?r=tx.light:t.includes(`Medium`)?r=tx.medium:t.includes(`Dark`)&&(r=tx.dark),`${r} ${e} ${n}`}CP(`PivotTableStyleLight`,[lP,uP,dP,fP]),CP(`PivotTableStyleMedium`,[pP,mP,hP,gP]),CP(`PivotTableStyleDark`,[_P,vP,yP,bP]),xP.PivotTableStyleDark1={...xP.PivotTableStyleDark1,..._P({...K.black,mediumBorder:vp(K.black.medium,.1)})},xP.PivotTableStyleDark15={...xP.PivotTableStyleDark15,...yP({...K.black,highlight:K.gray.dark,mediumBorder:K.black.medium})},xP.PivotTableStyleDark22={...xP.PivotTableStyleDark22,...bP({...K.black,highlight:K.gray.dark,mediumBorder:K.black.medium})};function TP(e){let t=xP[e];return t&&Object.keys(hx).find(e=>{let n=hx[e];return n.category===t.category&&n.primaryColor===t.primaryColor})||`None`}let EP=[`wholeTable`,`firstColumnStripe`,`secondColumnStripe`,`firstRowStripe`,`secondRowStripe`,`firstColumn`,`lastColumn`,`headerRow`,`measureHeader`,`firstAlternatingSubHeaderRow`,`secondAlternatingSubHeaderRow`,`mainSubHeaderRow`,`totalRow`];function DP(e,t){let n=t.numberOfHeaders,r={...e,top:e.top+n};return r.top<=r.bottom?r:void 0}function OP(e){let t=e.range;return{row:t.zone.top,col:t.zone.left,sheetId:t.sheetId}}function kP(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 AP(e){return e.type===`static`||e.type===`forceStatic`}function jP(e,t,n){return{borders:MP(e,t,n),styles:PP(e,t,n)}}function MP(e,t,n){let{numberOfCols:r,numberOfRows:i}=n,a=rs(r,i,()=>({}));for(let o of EP){let s=t[o]?.border;if(!s)continue;let c=FP(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?NP(a,`top`,s.top,n,c,r,i):c!==t.top&&!l&&s?.horizontal!==void 0&&NP(a,`top`,s.horizontal,n,c,r,i),c===t.bottom&&s?.bottom!==void 0&&NP(a,`bottom`,s.bottom,n,c,r,i),n===t.left&&s?.left!==void 0&&NP(a,`left`,s.left,n,c,r,i),n===t.right&&s?.right!==void 0?NP(a,`right`,s.right,n,c,r,i):n!==t.right&&!l&&s?.vertical!==void 0&&NP(a,`right`,s.vertical,n,c,r,i)}}return a}function NP(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 PP(e,t,n){let{numberOfCols:r,numberOfRows:i}=n,a=rs(r,i,()=>({}));for(let r of EP){let i=t[r];if(!i)continue;let o=FP(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 FP(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 IP(e,t){return e.model.getters.isTableStyleEditable(t)?_e([{id:`editTableStyle`,name:P(`Edit table style`),execute:e=>e.openSidePanel(`TableStyleEditorPanel`,{styleId:t}),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.EDIT`},{id:`deleteTableStyle`,name:P(`Delete table style`),execute:e=>e.model.dispatch(`REMOVE_TABLE_STYLE`,{tableStyleId:t}),icon:`o-spreadsheet-Icon.TRASH`}]):[]}function LP(e,t,n){e.resetTransform(),RP(e,t,n),zP(e,t,n),BP(e,t,n)}function RP(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++){let c=t.styles[n][s].fillColor;if(!c)continue;e.fillStyle=c;let l=n===a-1?r+1:r,u=s===o-1?i+1:i;e.fillRect(n*r,s*i,l,u)}e.restore()}function zP(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 BP(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 VP=class extends A{static template=`o-spreadsheet-TableStylePreview`;static components={MenuPopover:w_};props=(0,t.useProps)({tableConfig:N.TableConfig(),tableStyle:N.TableStyle(),type:N.or([N.literal(`table`),N.literal(`pivot`)]),styleId:N.string().optional(),selected:N.boolean().optional(),onClick:N.function().optional()});canvasRef=(0,t.signal)(null);menu=(0,t.proxy)({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)(()=>{let t=this.canvasRef();if(t)return e.observe(t),()=>{e.disconnect()}})}drawTable(e){let t=this.canvasRef();if(!t)return;let n=t.getContext(`2d`),{width:r,height:i}=t.getBoundingClientRect();if(!r||!i)return;t.width=r,t.height=i;let a;a=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])},LP(n,jP(e.tableConfig,e.tableStyle,a),{...a,colWidth:(r-1)/a.numberOfCols,rowHeight:(i-1)/a.numberOfRows})}onContextMenu(e){this.props.styleId&&(this.menu.menuItems=IP(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})}},HP=class extends A{static template=`o-spreadsheet-TableStylesPopover`;static components={Popover:b_,TableStylePreview:VP};props=(0,t.useProps)({tableConfig:N.object(),popoverProps:N.object().optional(),closePopover:N.function(),onStylePicked:N.function(),selectedStyleId:N.string().optional(),tableStyles:N.RecordOf(),type:N.or([N.literal(`table`),N.literal(`pivot`)])});tableStyleListRef=(0,t.signal)(null);state=(0,t.proxy)({selectedCategory:this.initialSelectedCategory});setup(){Ii(window,`click`,this.onExternalClick,{capture:!0})}onExternalClick(e){let t=this.tableStyleListRef();t&&!_(t,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`?{...tx,custom:P(`Custom`)}:tx}newTableStyle(){this.props.closePopover(),this.env.openSidePanel(`TableStyleEditorPanel`,{onStylePicked:this.props.onStylePicked})}},UP=class extends A{static template=`o-spreadsheet-TableStylePicker`;static components={TableStylesPopover:HP,TableStylePreview:VP};props=(0,t.useProps)({tableConfig:N.TableConfig(),onStylePicked:N.function(),tableStyles:N.RecordOf(),type:N.or([N.literal(`table`),N.literal(`pivot`)])});state=(0,t.proxy)({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}},WP=class extends A{static template=`o-spreadsheet-PivotDesignPanel`;static components={Section:Z,Checkbox:wE,NumberInput:KE,TableStylePicker:UP};props=(0,t.useProps)({pivotId:N.UID()});store;setup(){this.store=Ji(oP,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 ZS}get tableConfig(){let e=(this.pivotStyle.displayMeasuresRow??ZS.displayMeasuresRow)||(this.pivotStyle.displayColumnHeaders??ZS.displayColumnHeaders);return{hasFilters:!1,totalRow:this.pivotStyle.displayTotals??ZS.displayTotals,firstColumn:!0,lastColumn:!1,styleId:this.pivotStyle.tableStyleId??ZS.tableStyleId,bandedRows:this.pivotStyle.bandedRows??ZS.bandedRows,bandedColumns:this.pivotStyle.bandedColumns??ZS.bandedColumns,numberOfHeaders:+!!e}}onStylePicked(e){this.updatePivotStyleProperty(`tableStyleId`,e)}get tableStyles(){return xP}},GP=class extends A{static template=`o-spreadsheet-PivotSidePanel`;static components={PivotLayoutConfigurator:pN,Section:Z,PivotDesignPanel:WP};props=(0,t.useProps)({pivotId:N.UID(),onCloseSidePanel:N.function(),openTab:N.or([N.literal(`configuration`),N.literal(`design`)]).optional(`configuration`)});state=(0,t.proxy)({panel:this.props.openTab||`configuration`});setup(){LA(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 cP.get(e.type).editor}get highlights(){return this.state.panel===`configuration`?WM(this.env.model.getters,this.props.pivotId):[]}switchPanel(e){this.state.panel=e}},KP=class extends A{static template=`o-spreadsheet-RemoveDuplicatesPanel`;static components={ValidationMessages:zE,Section:Z,Checkbox:wE};props=(0,t.useProps)({onCloseSidePanel:N.function()});state=(0,t.proxy)({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=P(`Column %s`,wn(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(H_.Errors[n]||H_.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){let e=cr(this.env.model.getters.getSelectedZone());return P(`%(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))}},qP=class extends A{static template=`o-spreadsheet-SettingsPanel`;static components={Section:Z,ValidationMessages:zE,BadgeSelection:JE,Select:T_};props=(0,t.useProps)({onCloseSidePanel:N.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=q_(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:av(e),locale:e})}get firstDayOfWeek(){return Qs[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 JP={SplitIsDestructive:P(`This will overwrite data in the subsequent columns. Split anyway?`)};function YP(e,t,n){let r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n});return r.isCancelledBecause(`SplitWillOverwriteContent`)&&e.askConfirmation(JP.SplitIsDestructive,()=>{r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n,force:!0})}),r}let XP=[{label:P(`Detect automatically`),value:`auto`},{label:P(`Custom separator`),value:`custom`},{label:P(`Space`),value:` `},{label:P(`Comma`),value:`,`},{label:P(`Semicolon`),value:`;`},{label:P(`Line Break`),value:`
|
|
83
|
-
`}];var ZP=class extends A{static template=`o-spreadsheet-SplitIntoColumnsPanel`;static components={ValidationMessages:zE,Section:Z,Checkbox:wE,Select:T_};props=(0,t.useProps)({onCloseSidePanel:N.function()});state=(0,t.proxy)({separatorValue:`auto`,addNewColumns:!1,customSeparator:``});setup(){let e=j(Ur);Li(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(){YP(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(V_.Errors[n]||V_.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(V_.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 XP}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}},QP=class extends A{static template=`o-spreadsheet-TablePanel`;static components={TableStylePicker:UP,SelectionInput:FE,ValidationMessages:zE,Checkbox:wE,Section:Z,NumberInput:KE};props=(0,t.useProps)({onCloseSidePanel:N.function(),table:N.CoreTable()});state;setup(){let e=this.env.model.getters.getActiveSheetId();this.state=(0,t.proxy)({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(OP(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(OP(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(xr(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=OP(s);this.env.model.selection.selectZone({zone:O(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=>W_.Errors[e]||W_.Errors.Unexpected)}getCheckboxLabel(e){return W_.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:W_.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 W_.Tooltips.isDynamic}};let $P=`#3C78D8`;var eF=class extends A{static template=`o-spreadsheet-TableStyleEditorPanel`;static components={Section:Z,RoundColorPicker:QE,TableStylePreview:VP};props=(0,t.useProps)({onCloseSidePanel:N.function(),onStylePicked:N.function().optional(),styleId:N.string().optional()});state=(0,t.proxy)(this.getInitialState());setup(){Ii(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||$P,selectedTemplateName:e?.templateName||`lightColoredText`,styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=Zf(e)?e:$P,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){let e=this.props.styleId||G.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(gx).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 _x(this.state.styleName,e,this.state.primaryColor)}};let tF=new k;tF.add(`ConditionalFormatting`,{title:P(`Conditional formatting`),Body:vj}),tF.add(`ConditionalFormattingEditor`,{title:P(`Conditional formatting`),Body:gj,computeState:(e,t)=>({isOpen:!0,props:t,key:`ConditionalFormattingEditor_${t.cf.id}`})}),tF.add(`ChartPanel`,{title:P(`Chart`),Body:PA,computeState:(e,t)=>{let n=e.getSelectedFigureIds();if(n.length>1)return{isOpen:!1};let r=n.length&&n[0],i=r&&e.getFigureSheetId(r),a=i?e.isSheetLocked(i):!1,o=r?e.getChartIdFromFigureId(r):t.chartId;return!o||!e.isChartDefined(o)||a?{isOpen:!1}:{isOpen:!0,props:{chartId:o}}}}),tF.add(`FindAndReplace`,{title:P(`Find and Replace`),Body:Tj}),tF.add(`SplitToColumns`,{title:P(`Split text into columns`),Body:ZP}),tF.add(`Settings`,{title:P(`Spreadsheet settings`),Body:qP}),tF.add(`RemoveDuplicates`,{title:P(`Remove duplicates`),Body:KP}),tF.add(`DataValidation`,{title:P(`Data validation`),Body:bj}),tF.add(`DataValidationEditor`,{title:P(`Data validation`),Body:Sj,computeState:(e,t)=>({isOpen:!0,props:t,key:`DataValidationEditor_${t.ruleId}`})}),tF.add(`MoreFormats`,{title:P(`More formats`),Body:FM}),tF.add(`ColumnStats`,{title:P(`Column statistics`),Body:HA}),tF.add(`TableSidePanel`,{title:P(`Edit table`),Body:QP,computeState:e=>{let t=e.getFirstTableInSelection();return!t||t.isPivotTable?{isOpen:!1}:{isOpen:!0,props:{table:e.getCoreTable(OP(t))},key:t.id}}}),tF.add(`TableStyleEditorPanel`,{title:P(`Create custom table style`),Body:eF,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??`new`})}),tF.add(`PivotSidePanel`,{title:(e,t)=>P(`Pivot #%s`,e.model.getters.getPivotFormulaId(t.pivotId)),Body:GP,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),tF.add(`PivotMeasureDisplayPanel`,{title:(e,t)=>P(`Measure "%s" options`,e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id).displayName),Body:UM,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}}}}),tF.add(`CarouselPanel`,{title:P(`Carousel`),Body:SE,computeState:(e,t)=>{let n=t.figureId||e.getSelectedFigureIds().length&&e.getSelectedFigureIds()[0],r=n&&e.getFigureSheetId(n),i=r?e.isSheetLocked(r):!1;return!n||!e.doesCarouselExist(n)||i?{isOpen:!1}:{isOpen:!0,props:{figureId:n}}}}),tF.add(`NamedRangesPanel`,{title:P(`Named Ranges`),Body:BM}),tF.add(`PerfProfile`,{title:P(`Performance`),Body:VM});var nF=class{mutators=[`setSmallThreshhold`];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}},rF=class extends Vr{mutators=[`open`,`replace`,`toggle`,`close`,`changePanelSize`,`resetPanelSize`,`togglePinPanel`,`closeMainPanel`,`changeSpreadsheetWidth`,`toggleCollapsePanel`];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(nF);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(aA).notifyUser({sticky:!1,type:`warning`,text:P(`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=tF.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 iF(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(z_)}var aF=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]]}}},oF=class extends cv{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}},sF=class extends oF{static getters=[`getCellFingerprint`];getCellFingerprint(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=Su(e)&&!e.unboundedZone.hasHeader,l=xu(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=pr({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 cF(o)+s}getLiteralFingerprint(e){switch(this.getters.getEvaluatedCell(e).type){case`number`:case`boolean`:return lF;case`text`:case`empty`:case`error`:return}}};function cF(e){return Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t).join(`,`)}let lF=`DATA_FINGERPRINT`;var uF=class extends Vr{mutators=[`enable`,`disable`];isInvalidated=!1;fingerprintColors={[lF]:`#D9D9D9`};isEnabled=!1;colors=new aF;handle(e){switch(Fd(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 aF}computeFingerprints(){this.colors=new aF;let e=new aF,t=new Set,n=this.getters.getActiveSheetId(),r=this.getters.getCells(n);for(let n in r){let i=r[n],a=this.getters.getCellFingerprint(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 Mp(e.size);Object.keys(this.fingerprintColors).forEach(()=>t.next());for(let n of e)this.fingerprintColors[n]||(this.fingerprintColors[n]=fp(t.next(),.8))}};let dF={name:tT,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:Xw,icon:`o-spreadsheet-Icon.HIDE_COL`},fF={name:P(`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`},pF={name:P(`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`},mF={name:nT,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:Jw,icon:`o-spreadsheet-Icon.HIDE_ROW`},hF={name:P(`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`},gF={name:P(`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`},_F={name:P(`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`},vF={name:P(`Freeze`),icon:`o-spreadsheet-Icon.FREEZE`},yF={name:P(`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},bF={name:P(`1 row`),execute:e=>iF(e,`ROW`,1)},xF={name:P(`2 rows`),execute:e=>iF(e,`ROW`,2)},SF={name:P(`Up to current row`),execute:e=>{let{bottom:t}=e.model.getters.getSelectedZone();iF(e,`ROW`,t+1)}},CF={name:P(`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},wF={name:P(`1 column`),execute:e=>iF(e,`COL`,1)},TF={name:P(`2 columns`),execute:e=>iF(e,`COL`,2)},EF={name:P(`Up to current column`),execute:e=>{let{right:t}=e.model.getters.getSelectedZone();iF(e,`COL`,t+1)}},DF={name:P(`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)}},OF={name:P(`Irregularity map`),execute:e=>{let t=e.getStore(uF);t.isEnabled?t.disable():t.enable()},isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.IRREGULARITY_MAP`};function kF(e){return{name:P(`%(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 AF={name:P(`Formulas`),isActive:e=>e.model.getters.shouldShowFormulas(),execute:e=>e.model.dispatch(`SET_FORMULA_VISIBILITY`,{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0},jF={name:e=>{let t=e.model.getters.getSelectedZone();return t.left===t.right?P(`Group column %s`,wn(t.left)):P(`Group columns %s - %s`,wn(t.left),wn(t.right))},execute:e=>FF(e,`COL`),isVisible:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZone(),r=e.model.getters.getHeaderGroupsInZone(t,`COL`,n);return bT(e)&&!r.some(e=>e.start===n.left&&e.end===n.right)},icon:`o-spreadsheet-Icon.GROUP_COLUMNS`},MF={name:e=>{let t=e.model.getters.getSelectedZone();return t.top===t.bottom?P(`Group row %s`,String(t.top+1)):P(`Group rows %s - %s`,String(t.top+1),String(t.bottom+1))},execute:e=>FF(e,`ROW`),isVisible:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZone(),r=e.model.getters.getHeaderGroupsInZone(t,`ROW`,n);return bT(e)&&!r.some(e=>e.start===n.top&&e.end===n.bottom)},icon:`o-spreadsheet-Icon.GROUP_ROWS`},NF={name:e=>{let t=e.model.getters.getSelectedZone();return t.left===t.right?P(`Ungroup column %s`,wn(t.left)):P(`Ungroup columns %s - %s`,wn(t.left),wn(t.right))},execute:e=>IF(e,`COL`),icon:`o-spreadsheet-Icon.UNGROUP_COLUMNS`},PF={name:e=>{let t=e.model.getters.getSelectedZone();return t.top===t.bottom?P(`Ungroup row %s`,String(t.top+1)):P(`Ungroup rows %s - %s`,String(t.top+1),String(t.bottom+1))},execute:e=>IF(e,`ROW`),icon:`o-spreadsheet-Icon.UNGROUP_ROWS`};function FF(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 IF(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 LF(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 RF={name:e=>{let t=e.getStore(rF);return t.mainPanel&&t.mainPanel.isPinned?P(`Unpin the side panel`):P(`Pin the side panel`)},isVisible:e=>e.getStore(rF).isMainPanelOpen,execute:e=>{e.getStore(rF).togglePinPanel()},icon:`o-spreadsheet-Icon.THUMB_TACK`};function zF(e){let t=e.model.dispatch(`CUT`);t.isSuccessful||t.isCancelledBecause(`WrongCutSelection`)&&e.raiseError(P(`This operation is not allowed with multiple selections.`))}var BF=class extends k{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 _e(this.getAll())}};let VF={MergeIsDestructive:P(`Merging these cells will only preserve the top-leftmost value. Merge anyway?`),MergeInFilter:P(`You can't merge cells inside of an existing filter.`)};function HF(e,t,n){let r=e.model.dispatch(`ADD_MERGE`,{sheetId:t,target:n});r.isCancelledBecause(`MergeInTable`)?e.raiseError(VF.MergeInFilter):r.isCancelledBecause(`MergeIsDestructive`)&&e.askConfirmation(VF.MergeIsDestructive,()=>{e.model.dispatch(`ADD_MERGE`,{sheetId:t,target:n,force:!0})})}let UF={name:P(`Undo`),shortcut:`Ctrl+Z`,execute:e=>e.model.dispatch(`REQUEST_UNDO`),isEnabled:e=>e.model.getters.canUndo(),isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.UNDO`},WF={name:P(`Redo`),shortcut:`Ctrl+Y`,execute:e=>e.model.dispatch(`REQUEST_REDO`),isEnabled:e=>e.model.getters.canRedo(),isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.REDO`},GF={name:P(`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`},KF={name:P(`Cut`),shortcut:`Ctrl+X`,execute:async e=>{zF(e),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},icon:`o-spreadsheet-Icon.CUT`},qF={name:P(`Paste`),shortcut:`Ctrl+V`,execute:Iw,icon:`o-spreadsheet-Icon.PASTE`},JF={name:P(`Paste special`),isVisible:e=>!e.model.getters.isCutOperation(),icon:`o-spreadsheet-Icon.PASTE`},YF={name:P(`Paste as value`),shortcut:`Ctrl+Shift+V`,execute:Lw},XF={name:P(`Paste format only`),execute:zw},ZF={name:P(`Find and replace`),shortcut:`Ctrl+H`,isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,execute:e=>{e.openSidePanel(`FindAndReplace`,{})},isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.SEARCH`},QF={name:P(`Delete values`),execute:e=>e.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},$F={name:Ww,execute:Gw,isVisible:e=>Kw(`ROW`,e)},eI={...$F,isVisible:bT},tI={name:Bw,execute:Vw},nI={name:qw,execute:Yw,isVisible:e=>Kw(`COL`,e)},rI={...nI,isVisible:bT},iI={name:Hw,execute:Uw},aI={name:P(`Delete cells`),isVisible:bT},oI={name:P(`Delete cell and shift up`),execute:e=>{let t=e.model.getters.getSelectedZone();aw(e,e.model.dispatch(`DELETE_CELL`,{zone:t,shiftDimension:`ROW`}))}},sI={name:P(`Delete cell and shift left`),execute:e=>{let t=e.model.getters.getSelectedZone();aw(e,e.model.dispatch(`DELETE_CELL`,{zone:t,shiftDimension:`COL`}))}},cI={name:P(`Merge cells`),isEnabled:e=>!dI(e),isActive:e=>fI(e),execute:e=>pI(e),icon:`o-spreadsheet-Icon.MERGE_CELL`},lI={name:()=>P(`Edit table`),execute:e=>e.openSidePanel(`TableSidePanel`,{}),icon:`o-spreadsheet-Icon.EDIT_TABLE`},uI={name:()=>P(`Delete table`),execute:yT,icon:`o-spreadsheet-Icon.DELETE_TABLE`};function dI(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=>xr(e)===1)||Cr(t,r,i)||ar(t)}function fI(e){if(dI(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 pI(e){if(dI(e))return;let t=e.model.getters.getSelectedZones(),n=e.model.getters.getActiveSheetId();if(fI(e)){let r=t.flatMap(t=>e.model.getters.getMergesInZone(n,t));e.model.dispatch(`REMOVE_MERGE`,{sheetId:n,target:r})}else HF(e,n,t)}let mI={name:P(`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`},hI={name:P(`Ascending`),execute:e=>DI(e,e.model.getters.getActivePosition(),`asc`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`asc`},gI={name:P(`Descending`),execute:e=>DI(e,e.model.getters.getActivePosition(),`desc`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`desc`},_I={name:P(`No sorting`),execute:e=>DI(e,e.model.getters.getActivePosition(),`none`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`none`},vI={name:P(`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`},yI={name:P(`Group pivot dimensions`),execute:e=>{let t=OI(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)kI(o,r,i,a.getFields());else{let e=(o.customFields||{})[i.name];if(!e)return;AI(e,r)}e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:o})},isVisible:e=>{let t=OI(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||qN.get(a.type).canHaveCustomGroup(i))}},bI={name:P(`Group all remaining dimensions`),execute:e=>{let t=OI(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]:TC(a,r,i.getFields());o&&(o.groups.push({name:bC(P(`Others`),o),values:[],isOtherGroup:!0}),wC(a,r.name,o.name),e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:a}))},isVisible:e=>{let t=OI(e);if(!t)return!1;let{pivotId:n,field:r,values:i}=t;return NI(e,n,i,r)}},xI={name:P(`Ungroup pivot dimensions`),execute:e=>{let t=OI(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));jI(o,r,i,a.getFields()),e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:o})},isVisible:e=>{let t=OI(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=TC(o,i,a.getFields());if(![...o.rows,...o.columns].some(t=>t.fieldName===e.name))return!1}return MI(o,r,i,a.getFields())}},SI={name:e=>{let t=e.model.getters.getActivePosition(),n=TI(e.model.getters,t);return n.isPivotGroup?n.isCollapsed?P(`Expand`):P(`Collapse`):``},execute(e){EC(e.model.getters.getActivePosition(),e)},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=TI(e.model.getters,t),r=e.model.getters.getPivotStyleAtPosition(t);return n.isPivotGroup&&!r?.pivotStyle.tabularForm}},CI={name:P(`Collapse all`),execute(e){let t=e.model.getters.getActivePosition(),n=TI(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=TI(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)))}},wI={name:P(`Expand all`),execute(e){let t=e.model.getters.getActivePosition(),n=TI(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=TI(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 TI(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 EI(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 DI(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=vN(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 OI(e){let t,n,r=[];for(let i of e.model.getters.getSelectedZones()){let a=e.model.getters.getActiveSheetId();for(let o of fr(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 kI(e,t,n,r){let i=TC(e,n,r);CC(t,i);let a={name:bC(P(`Group`),i),values:t};i.groups.push(a),e.customFields||={},e.customFields[i.name]=i,wC(e,n.name,i.name)}function AI(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:bC(P(`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 jI(e,t,n,r){let i;if(!n.isCustomField)i=TC(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)),CC(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)&&(PI(e,i.name),delete e.customFields?.[i.name])}function MI(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 TC(e,n,r).groups.some(e=>e.isOtherGroup||t.some(t=>e.values.includes(t)))}function NI(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||MI(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 PI(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 FI=new BF;FI.add(`cut`,{...KF,sequence:10}).add(`copy`,{...GF,sequence:20}).add(`paste`,{...qF,sequence:30}).add(`paste_special`,{...JF,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...YF,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...XF,sequence:20}).add(`add_row_before`,{...ET,sequence:70}).add(`add_column_before`,{...MT,sequence:90}).add(`insert_cell`,{...FT,sequence:100,separator:!0}).addChild(`insert_cell_down`,[`insert_cell`],{...IT,name:P(`Shift down`),sequence:10}).addChild(`insert_cell_right`,[`insert_cell`],{...LT,name:P(`Shift right`),sequence:20}).add(`delete_row`,{...eI,sequence:110,icon:`o-spreadsheet-Icon.TRASH`}).add(`delete_column`,{...rI,sequence:120,icon:`o-spreadsheet-Icon.TRASH`}).add(`delete_cell`,{...aI,sequence:130,separator:!0,icon:`o-spreadsheet-Icon.TRASH`}).addChild(`delete_cell_up`,[`delete_cell`],{...oI,name:P(`Shift up`),sequence:10,icon:`o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP`}).addChild(`delete_cell_left`,[`delete_cell`],{...sI,name:P(`Shift left`),sequence:20,icon:`o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT`}).add(`edit_table`,{...lI,isVisible:mT,isEnabled:e=>!e.isSmall,sequence:140}).add(`delete_table`,{...uI,isVisible:mT,sequence:145,separator:!0}).add(`insert_link`,{...QT,name:fT,sequence:150,separator:!0}).add(`pivot_headers_group`,{sequence:155,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,...yI}).add(`pivot_group_remaining`,{sequence:155,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,...bI}).add(`pivot_headers_ungroup`,{sequence:155,icon:`o-spreadsheet-Icon.MINUS_IN_BOX`,...xI}).add(`collapse_pivot`,{sequence:156,name:P(`Expand/Collapse`),icon:`o-spreadsheet-Icon.COLLAPSE`}).addChild(`toggle_collapse_pivot_cell`,[`collapse_pivot`],{sequence:10,...SI}).addChild(`collapse_all_pivot`,[`collapse_pivot`],{sequence:20,...CI}).addChild(`expand_all_pivot`,[`collapse_pivot`],{sequence:30,...wI}).add(`pivot_sorting`,{name:P(`Sort pivot`),sequence:155,icon:`o-spreadsheet-Icon.SORT_RANGE`,isVisible:e=>{let t=e.model.getters.getActivePosition();return EI(e.model.getters,t)}}).add(`pivot_fix_formulas`,{...vI,sequence:160}).add(`pivot_properties`,{...mI,sequence:170,separator:!0}).addChild(`pivot_sorting_asc`,[`pivot_sorting`],{...hI,sequence:10}).addChild(`pivot_sorting_desc`,[`pivot_sorting`],{...gI,sequence:20}).addChild(`pivot_sorting_none`,[`pivot_sorting`],{..._I,sequence:30});function II(e,t,n,r,i){let a=r.right>r.left;if(e.model.getters.doesIntersectMerge(t,r)){a=!1;let n;for(let i=r.top;i<=r.bottom;i++){n=[];for(let a=r.left;a<=r.right;a++){let r=e.model.getters.getMerge({sheetId:t,col:a,row:i});r&&!n.includes(r.id.toString())&&n.push(r.id.toString())}if(n.length>=2){a=!0;break}}}if(a){LI(e,t,n,r,i);return}let o=e.model.getters.getContiguousZone(t,r);rr(o,r)?LI(e,t,n,r,i):e.askConfirmation(P(`We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?`),()=>LI(e,t,n,o,i),()=>LI(e,t,n,r,i))}function LI(e,t,n,r,i,a){let o=e.model.dispatch(`SORT_CELLS`,{sheetId:t,col:n.col,row:n.row,zone:r,sortDirection:i,sortOptions:a});if(o.isCancelledBecause(`InvalidSortZone`)){let{col:t,row:i}=n;e.model.selection.selectZone({cell:{col:t,row:i},zone:r}),e.raiseError(P(`Cannot sort. To sort, select only cells or only merges that have the same size.`))}if(o.isCancelledBecause(`SortZoneWithArrayFormulas`)){let{col:t,row:i}=n;e.model.selection.selectZone({cell:{col:t,row:i},zone:r}),e.raiseError(P(`Cannot sort a zone with array formulas.`))}}let RI={name:P(`Sort range`),isVisible:bT,icon:`o-spreadsheet-Icon.SORT_RANGE`},zI={name:P(`Ascending (A ⟶ Z)`),execute:e=>{let{anchor:t,zones:n}=e.model.getters.getSelection();II(e,e.model.getters.getActiveSheetId(),t.cell,n[0],`asc`)},icon:`o-spreadsheet-Icon.SORT_ASCENDING`},BI={name:P(`Data cleanup`),icon:`o-spreadsheet-Icon.DATA_CLEANUP`},VI={name:P(`Remove duplicates`),execute:e=>{xr(e.model.getters.getSelectedZone())===1&&e.model.selection.selectTableAroundSelection(),e.openSidePanel(`RemoveDuplicates`,{})},isEnabled:e=>!e.isSmall},HI={name:P(`Trim whitespace`),execute:e=>{e.model.dispatch(`TRIM_WHITESPACE`)}},UI={name:P(`Descending (Z ⟶ A)`),execute:e=>{let{anchor:t,zones:n}=e.model.getters.getSelection();II(e,e.model.getters.getActiveSheetId(),t.cell,n[0],`desc`)},icon:`o-spreadsheet-Icon.SORT_DESCENDING`},WI={...ST},GI={...ST,isActive:e=>pT(e)},KI={name:P(`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`},qI={name:P(`Column statistics`),execute:e=>e.openSidePanel(`ColumnStats`,{}),icon:`o-spreadsheet-Icon.COLUMN_STATS`},JI={id:`reinsert_dynamic_pivot`,name:P(`Re-insert dynamic pivot`),sequence:60,icon:`o-spreadsheet-Icon.INSERT_PIVOT`,children:[oT],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())},YI={id:`reinsert_static_pivot`,name:P(`Re-insert static pivot`),sequence:70,icon:`o-spreadsheet-Icon.INSERT_PIVOT`,children:[sT],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())},XI={name:P(`Calculation`),icon:`o-spreadsheet-Icon.CALCULATOR`},ZI={name:P(`Automatic`),execute:e=>e.model.dispatch(`SET_AUTOMATIC_EVALUATION`,{enabled:!0}),isActive:e=>e.model.getters.isAutomaticEvaluationEnabled()},QI={name:P(`Manual`),execute:e=>e.model.dispatch(`SET_AUTOMATIC_EVALUATION`,{enabled:!1}),isActive:e=>!e.model.getters.isAutomaticEvaluationEnabled()},$I=new BF;$I.add(`cut`,{...KF,sequence:10}).add(`copy`,{...GF,sequence:20}).add(`paste`,{...qF,sequence:30}).add(`paste_special`,{...JF,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...YF,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...XF,sequence:20}).add(`sort_columns`,{...RI,name:e=>e.model.getters.getActiveCols().size>1?P(`Sort columns`):P(`Sort column`),sequence:50,separator:!0}).addChild(`sort_ascending`,[`sort_columns`],{...zI,sequence:10}).addChild(`sort_descending`,[`sort_columns`],{...UI,sequence:20}).add(`column_statistics`,{...qI,sequence:60,separator:!0}).add(`add_column_before`,{...AT,sequence:70}).add(`add_column_after`,{...NT,sequence:80}).add(`delete_column`,{...nI,sequence:90,icon:`o-spreadsheet-Icon.TRASH`}).add(`clear_column`,{...iI,sequence:100,icon:`o-spreadsheet-Icon.CLEAR`}).add(`hide_columns`,{...dF,sequence:105,separator:!0}).add(`unhide_columns`,{...fF,sequence:106,separator:!0}).add(`conditional_formatting`,{...bM,sequence:110,separator:!0}).add(`edit_table`,{...lI,isVisible:mT,sequence:120}).add(`delete_table`,{...uI,isVisible:mT,sequence:125,separator:!0}).add(`group_columns`,{sequence:150,...jF}).add(`ungroup_columns`,{sequence:155,...NF,isVisible:e=>LF(e,`COL`)});let eL={CannotHideAllRows:P(`Cannot hide all the rows of a sheet.`),CannotHideAllColumns:P(`Cannot hide all the columns of a sheet.`)};function tL(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`?eL.CannotHideAllRows:eL.CannotHideAllColumns;e.raiseError(t)}}function nL(e,t){return _e([{id:`unfold_all`,name:P(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:P(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 rL(e,t,n,r){return[..._e([{id:`toggle_group`,name:e=>{let i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,n,r)?P(t===`ROW`?`Expand row group`:`Expand column group`):P(t===`ROW`?`Collapse row group`:`Collapse column group`)},execute:e=>{tL(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:P(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}]),...nL(e,t)]}let iL=new BF;iL.add(`group_columns`,{sequence:10,...jF,isVisible:()=>!0,isEnabled:jF.isVisible}).add(`group_rows`,{sequence:20,...MF,isVisible:()=>!0,isEnabled:MF.isVisible});let aL=new BF;aL.add(`ungroup_columns`,{sequence:10,...NF,isEnabled:e=>LF(e,`COL`)}).add(`ungroup_rows`,{sequence:20,...PF,isEnabled:e=>LF(e,`ROW`)});let oL=new BF;oL.add(`cut`,{...KF,sequence:10}).add(`copy`,{...GF,sequence:20}).add(`paste`,{...qF,sequence:30}).add(`paste_special`,{...JF,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...YF,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...XF,sequence:20}).add(`add_row_before`,{...wT,sequence:50}).add(`add_row_after`,{...DT,sequence:60}).add(`delete_row`,{...$F,sequence:70,icon:`o-spreadsheet-Icon.TRASH`}).add(`clear_row`,{...tI,sequence:80,icon:`o-spreadsheet-Icon.CLEAR`}).add(`hide_rows`,{...mF,sequence:85,separator:!0}).add(`unhide_rows`,{...hF,sequence:86,separator:!0}).add(`conditional_formatting`,{...bM,sequence:90,separator:!0}).add(`group_rows`,{sequence:100,...MF}).add(`ungroup_rows`,{sequence:110,...PF,isVisible:e=>LF(e,`ROW`)});var sL=class extends Vr{highlightStore=this.get(ME);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}]}},cL=class extends Vr{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 lL(e){return 20+120*Math.exp(-.035*(e-1))}function uL(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=v(e.model.getters.getViewportZoomLevel()),d=tg(e,r,u),{x:f,y:m}=c.getMainViewportCoordinates(),{top:g,left:_,bottom:ee,right:y}=c.getActiveMainViewport(),{scrollX:b,scrollY:te}=c.getActiveSheetScrollInfo(),{xSplit:ne,ySplit:re}=c.getPaneDivisions(l),ie=!1,ae=140,oe=d.clientX-u.x,se=c.getColIndex(oe);if(s!==`vertical`){let t=i.clientX-u.x,n=c.getEdgeScrollCol(oe,t,a);if(n.canEdgeScroll){ie=!0,ae=Math.min(ae,n.delay);let t=se;switch(n.direction){case`reset`:se=t=ne;break;case 1:se=y,t=_+1;break;case-1:for(se=_-1;e.model.getters.isColHidden(l,se);)se--;t=se;break}b=c.getColDimensions(l,t).start-f}}let ce=d.clientY-u.y,le=c.getRowIndex(ce);if(s!==`horizontal`){let t=i.clientY-u.y,n=c.getEdgeScrollRow(ce,t,o);if(n.canEdgeScroll){ie=!0,ae=Math.min(ae,n.delay);let t=le;switch(n.direction){case`reset`:le=t=re;break;case 1:le=ee,t=g+1;break;case-1:for(le=g-1;e.model.getters.isRowHidden(l,le);)le--;t=le;break}te=e.model.getters.getRowDimensions(l,t).start-m}}ie||(se=dL(se,oe,c.getNumberCols(l)-1),le=dL(le,ce,c.getNumberRows(l)-1)),p?.(se,le,r),ie&&(e.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:b,offsetY:te}),n=setTimeout(()=>{n=null,h(r)},Math.round(ae))),i={clientX:d.clientX,clientY:d.clientY}},g=()=>{m?.(),f()};return(0,t.onWillUnmount)(()=>{f()}),Li(()=>{f()},()=>[c.getActiveSheetId()]),{start:(t,n,r,c=`all`)=>{f();let _=v(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(aE(h,g),u)}}}function dL(e,t,n){return e===-1?t<0?0:n:e}var fL=class extends A{static template=`o-spreadsheet-Autofill`;props=(0,t.useProps)({position:N.DOMCoordinates(),isVisible:N.boolean()});state=(0,t.proxy)({position:{x:0,y:0},handler:!1});dragNDropGrid=uL(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=pL),e}onMouseDown(e){this.state.handler=!0;let t=tg(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`)}},pL=class extends A{props=(0,t.useProps)({content:N.string()});static template=t.xml`
|
|
83
|
+
`}];var ZP=class extends A{static template=`o-spreadsheet-SplitIntoColumnsPanel`;static components={ValidationMessages:zE,Section:Z,Checkbox:wE,Select:T_};props=(0,t.useProps)({onCloseSidePanel:N.function()});state=(0,t.proxy)({separatorValue:`auto`,addNewColumns:!1,customSeparator:``});setup(){let e=j(Ur);Li(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(){YP(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(V_.Errors[n]||V_.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(V_.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 XP}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}},QP=class extends A{static template=`o-spreadsheet-TablePanel`;static components={TableStylePicker:UP,SelectionInput:FE,ValidationMessages:zE,Checkbox:wE,Section:Z,NumberInput:KE};props=(0,t.useProps)({onCloseSidePanel:N.function(),table:N.CoreTable()});state;setup(){let e=this.env.model.getters.getActiveSheetId();this.state=(0,t.proxy)({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(OP(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(OP(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(xr(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=OP(s);this.env.model.selection.selectZone({zone:O(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=>W_.Errors[e]||W_.Errors.Unexpected)}getCheckboxLabel(e){return W_.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:W_.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 W_.Tooltips.isDynamic}};let $P=`#3C78D8`;var eF=class extends A{static template=`o-spreadsheet-TableStyleEditorPanel`;static components={Section:Z,RoundColorPicker:QE,TableStylePreview:VP};props=(0,t.useProps)({onCloseSidePanel:N.function(),onStylePicked:N.function().optional(),styleId:N.string().optional()});state=(0,t.proxy)(this.getInitialState());setup(){Ii(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||$P,selectedTemplateName:e?.templateName||`lightColoredText`,styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=Zf(e)?e:$P,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){let e=this.props.styleId||G.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(gx).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 _x(this.state.styleName,e,this.state.primaryColor)}};let tF=new k;tF.add(`ConditionalFormatting`,{title:P(`Conditional formatting`),Body:vj}),tF.add(`ConditionalFormattingEditor`,{title:P(`Conditional formatting`),Body:gj,computeState:(e,t)=>({isOpen:!0,props:t,key:`ConditionalFormattingEditor_${t.cf.id}`})}),tF.add(`ChartPanel`,{title:P(`Chart`),Body:PA,computeState:(e,t)=>{let n=e.getSelectedFigureIds();if(n.length>1)return{isOpen:!1};let r=n.length&&n[0],i=r&&e.getFigureSheetId(r),a=i?e.isSheetLocked(i):!1,o=r?e.getChartIdFromFigureId(r):t.chartId;return!o||!e.isChartDefined(o)||a?{isOpen:!1}:{isOpen:!0,props:{chartId:o}}}}),tF.add(`FindAndReplace`,{title:P(`Find and Replace`),Body:Tj}),tF.add(`SplitToColumns`,{title:P(`Split text into columns`),Body:ZP}),tF.add(`Settings`,{title:P(`Spreadsheet settings`),Body:qP}),tF.add(`RemoveDuplicates`,{title:P(`Remove duplicates`),Body:KP}),tF.add(`DataValidation`,{title:P(`Data validation`),Body:bj}),tF.add(`DataValidationEditor`,{title:P(`Data validation`),Body:Sj,computeState:(e,t)=>({isOpen:!0,props:t,key:`DataValidationEditor_${t.ruleId}`})}),tF.add(`MoreFormats`,{title:P(`More formats`),Body:FM}),tF.add(`ColumnStats`,{title:P(`Column statistics`),Body:HA}),tF.add(`TableSidePanel`,{title:P(`Edit table`),Body:QP,computeState:e=>{let t=e.getFirstTableInSelection();return!t||t.isPivotTable?{isOpen:!1}:{isOpen:!0,props:{table:e.getCoreTable(OP(t))},key:t.id}}}),tF.add(`TableStyleEditorPanel`,{title:P(`Create custom table style`),Body:eF,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??`new`})}),tF.add(`PivotSidePanel`,{title:(e,t)=>P(`Pivot #%s`,e.model.getters.getPivotFormulaId(t.pivotId)),Body:GP,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),tF.add(`PivotMeasureDisplayPanel`,{title:(e,t)=>P(`Measure "%s" options`,e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id).displayName),Body:UM,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}}}}),tF.add(`CarouselPanel`,{title:P(`Carousel`),Body:SE,computeState:(e,t)=>{let n=t.figureId||e.getSelectedFigureIds().length&&e.getSelectedFigureIds()[0],r=n&&e.getFigureSheetId(n),i=r?e.isSheetLocked(r):!1;return!n||!e.doesCarouselExist(n)||i?{isOpen:!1}:{isOpen:!0,props:{figureId:n}}}}),tF.add(`NamedRangesPanel`,{title:P(`Named Ranges`),Body:BM}),tF.add(`PerfProfile`,{title:P(`Performance`),Body:VM});var nF=class{mutators=[`setSmallThreshhold`];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}},rF=class extends Vr{mutators=[`open`,`replace`,`toggle`,`close`,`changePanelSize`,`resetPanelSize`,`togglePinPanel`,`closeMainPanel`,`changeSpreadsheetWidth`,`toggleCollapsePanel`];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(nF);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(aA).notifyUser({sticky:!1,type:`warning`,text:P(`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=tF.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 iF(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(z_)}var aF=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]]}}},oF=class extends cv{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}},sF=class extends oF{static getters=[`getCellFingerprint`];getCellFingerprint(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=Su(e)&&!e.unboundedZone.hasHeader,l=xu(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=pr({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 cF(o)+s}getLiteralFingerprint(e){switch(this.getters.getEvaluatedCell(e).type){case`number`:case`boolean`:return lF;case`text`:case`empty`:case`error`:return}}};function cF(e){return Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t).join(`,`)}let lF=`DATA_FINGERPRINT`;var uF=class extends Vr{mutators=[`enable`,`disable`];isInvalidated=!1;fingerprintColors={[lF]:`#D9D9D9`};isEnabled=!1;colors=new aF;handle(e){switch(Fd(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 aF}computeFingerprints(){this.colors=new aF;let e=new aF,t=new Set,n=this.getters.getActiveSheetId(),r=this.getters.getCells(n);for(let n in r){let i=r[n],a=this.getters.getCellFingerprint(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 Mp(e.size);Object.keys(this.fingerprintColors).forEach(()=>t.next());for(let n of e)this.fingerprintColors[n]||(this.fingerprintColors[n]=fp(t.next(),.8))}};let dF={name:tT,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:Xw,icon:`o-spreadsheet-Icon.HIDE_COL`},fF={name:P(`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`},pF={name:P(`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`},mF={name:nT,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:Jw,icon:`o-spreadsheet-Icon.HIDE_ROW`},hF={name:P(`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`},gF={name:P(`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`},_F={name:P(`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`},vF={name:P(`Freeze`),icon:`o-spreadsheet-Icon.FREEZE`},yF={name:P(`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},bF={name:P(`1 row`),execute:e=>iF(e,`ROW`,1)},xF={name:P(`2 rows`),execute:e=>iF(e,`ROW`,2)},SF={name:P(`Up to current row`),execute:e=>{let{bottom:t}=e.model.getters.getSelectedZone();iF(e,`ROW`,t+1)}},CF={name:P(`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},wF={name:P(`1 column`),execute:e=>iF(e,`COL`,1)},TF={name:P(`2 columns`),execute:e=>iF(e,`COL`,2)},EF={name:P(`Up to current column`),execute:e=>{let{right:t}=e.model.getters.getSelectedZone();iF(e,`COL`,t+1)}},DF={name:P(`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)}},OF={name:P(`Irregularity map`),execute:e=>{let t=e.getStore(uF);t.isEnabled?t.disable():t.enable()},isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.IRREGULARITY_MAP`};function kF(e){return{name:P(`%(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 AF={name:P(`Formulas`),isActive:e=>e.model.getters.shouldShowFormulas(),execute:e=>e.model.dispatch(`SET_FORMULA_VISIBILITY`,{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0},jF={name:e=>{let t=e.model.getters.getSelectedZone();return t.left===t.right?P(`Group column %s`,wn(t.left)):P(`Group columns %s - %s`,wn(t.left),wn(t.right))},execute:e=>FF(e,`COL`),isVisible:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZone(),r=e.model.getters.getHeaderGroupsInZone(t,`COL`,n);return bT(e)&&!r.some(e=>e.start===n.left&&e.end===n.right)},icon:`o-spreadsheet-Icon.GROUP_COLUMNS`},MF={name:e=>{let t=e.model.getters.getSelectedZone();return t.top===t.bottom?P(`Group row %s`,String(t.top+1)):P(`Group rows %s - %s`,String(t.top+1),String(t.bottom+1))},execute:e=>FF(e,`ROW`),isVisible:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZone(),r=e.model.getters.getHeaderGroupsInZone(t,`ROW`,n);return bT(e)&&!r.some(e=>e.start===n.top&&e.end===n.bottom)},icon:`o-spreadsheet-Icon.GROUP_ROWS`},NF={name:e=>{let t=e.model.getters.getSelectedZone();return t.left===t.right?P(`Ungroup column %s`,wn(t.left)):P(`Ungroup columns %s - %s`,wn(t.left),wn(t.right))},execute:e=>IF(e,`COL`),icon:`o-spreadsheet-Icon.UNGROUP_COLUMNS`},PF={name:e=>{let t=e.model.getters.getSelectedZone();return t.top===t.bottom?P(`Ungroup row %s`,String(t.top+1)):P(`Ungroup rows %s - %s`,String(t.top+1),String(t.bottom+1))},execute:e=>IF(e,`ROW`),icon:`o-spreadsheet-Icon.UNGROUP_ROWS`};function FF(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 IF(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 LF(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 RF={name:e=>{let t=e.getStore(rF);return t.mainPanel&&t.mainPanel.isPinned?P(`Unpin the side panel`):P(`Pin the side panel`)},isVisible:e=>e.getStore(rF).isMainPanelOpen,execute:e=>{e.getStore(rF).togglePinPanel()},icon:`o-spreadsheet-Icon.THUMB_TACK`};function zF(e){let t=e.model.dispatch(`CUT`);t.isSuccessful||t.isCancelledBecause(`WrongCutSelection`)&&e.raiseError(P(`This operation is not allowed with multiple selections.`))}var BF=class extends k{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 _e(this.getAll())}};let VF={MergeIsDestructive:P(`Merging these cells will only preserve the top-leftmost value. Merge anyway?`),MergeInFilter:P(`You can't merge cells inside of an existing filter.`)};function HF(e,t,n){let r=e.model.dispatch(`ADD_MERGE`,{sheetId:t,target:n});r.isCancelledBecause(`MergeInTable`)?e.raiseError(VF.MergeInFilter):r.isCancelledBecause(`MergeIsDestructive`)&&e.askConfirmation(VF.MergeIsDestructive,()=>{e.model.dispatch(`ADD_MERGE`,{sheetId:t,target:n,force:!0})})}let UF={name:P(`Undo`),shortcut:`Ctrl+Z`,execute:e=>e.model.dispatch(`REQUEST_UNDO`),isEnabled:e=>e.model.getters.canUndo(),isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.UNDO`},WF={name:P(`Redo`),shortcut:`Ctrl+Y`,execute:e=>e.model.dispatch(`REQUEST_REDO`),isEnabled:e=>e.model.getters.canRedo(),isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.REDO`},GF={name:P(`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`},KF={name:P(`Cut`),shortcut:`Ctrl+X`,execute:async e=>{zF(e),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},icon:`o-spreadsheet-Icon.CUT`},qF={name:P(`Paste`),shortcut:`Ctrl+V`,execute:Iw,icon:`o-spreadsheet-Icon.PASTE`},JF={name:P(`Paste special`),isVisible:e=>!e.model.getters.isCutOperation(),icon:`o-spreadsheet-Icon.PASTE`},YF={name:P(`Paste as value`),shortcut:`Ctrl+Shift+V`,execute:Lw},XF={name:P(`Paste format only`),execute:zw},ZF={name:P(`Find and replace`),shortcut:`Ctrl+H`,isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,execute:e=>{e.openSidePanel(`FindAndReplace`,{})},isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.SEARCH`},QF={name:P(`Delete values`),execute:e=>e.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},$F={name:Ww,execute:Gw,isVisible:e=>Kw(`ROW`,e)},eI={...$F,isVisible:bT},tI={name:Bw,execute:Vw},nI={name:qw,execute:Yw,isVisible:e=>Kw(`COL`,e)},rI={...nI,isVisible:bT},iI={name:Hw,execute:Uw},aI={name:P(`Delete cells`),isVisible:bT},oI={name:P(`Delete cell and shift up`),execute:e=>{let t=e.model.getters.getSelectedZone();aw(e,e.model.dispatch(`DELETE_CELL`,{zone:t,shiftDimension:`ROW`}))}},sI={name:P(`Delete cell and shift left`),execute:e=>{let t=e.model.getters.getSelectedZone();aw(e,e.model.dispatch(`DELETE_CELL`,{zone:t,shiftDimension:`COL`}))}},cI={name:P(`Merge cells`),isEnabled:e=>!dI(e),isActive:e=>fI(e),execute:e=>pI(e),icon:`o-spreadsheet-Icon.MERGE_CELL`},lI={name:()=>P(`Edit table`),execute:e=>e.openSidePanel(`TableSidePanel`,{}),icon:`o-spreadsheet-Icon.EDIT_TABLE`},uI={name:()=>P(`Delete table`),execute:yT,icon:`o-spreadsheet-Icon.DELETE_TABLE`};function dI(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=>xr(e)===1)||Cr(t,r,i)||ar(t)}function fI(e){if(dI(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 pI(e){if(dI(e))return;let t=e.model.getters.getSelectedZones(),n=e.model.getters.getActiveSheetId();if(fI(e)){let r=t.flatMap(t=>e.model.getters.getMergesInZone(n,t));e.model.dispatch(`REMOVE_MERGE`,{sheetId:n,target:r})}else HF(e,n,t)}let mI={name:P(`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`},hI={name:P(`Ascending`),execute:e=>DI(e,e.model.getters.getActivePosition(),`asc`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`asc`},gI={name:P(`Descending`),execute:e=>DI(e,e.model.getters.getActivePosition(),`desc`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`desc`},_I={name:P(`No sorting`),execute:e=>DI(e,e.model.getters.getActivePosition(),`none`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`none`},vI={name:P(`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`},yI={name:P(`Group pivot dimensions`),execute:e=>{let t=OI(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)kI(o,r,i,a.getFields());else{let e=(o.customFields||{})[i.name];if(!e)return;AI(e,r)}e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:o})},isVisible:e=>{let t=OI(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||qN.get(a.type).canHaveCustomGroup(i))}},bI={name:P(`Group all remaining dimensions`),execute:e=>{let t=OI(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]:TC(a,r,i.getFields());o&&(o.groups.push({name:bC(P(`Others`),o),values:[],isOtherGroup:!0}),wC(a,r.name,o.name),e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:a}))},isVisible:e=>{let t=OI(e);if(!t)return!1;let{pivotId:n,field:r,values:i}=t;return NI(e,n,i,r)}},xI={name:P(`Ungroup pivot dimensions`),execute:e=>{let t=OI(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));jI(o,r,i,a.getFields()),e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:o})},isVisible:e=>{let t=OI(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=TC(o,i,a.getFields());if(![...o.rows,...o.columns].some(t=>t.fieldName===e.name))return!1}return MI(o,r,i,a.getFields())}},SI={name:e=>{let t=e.model.getters.getActivePosition(),n=TI(e.model.getters,t);return n.isPivotGroup?n.isCollapsed?P(`Expand`):P(`Collapse`):``},execute(e){EC(e.model.getters.getActivePosition(),e)},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=TI(e.model.getters,t),r=e.model.getters.getPivotStyleAtPosition(t);return n.isPivotGroup&&!r?.pivotStyle.tabularForm}},CI={name:P(`Collapse all`),execute(e){let t=e.model.getters.getActivePosition(),n=TI(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=TI(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)))}},wI={name:P(`Expand all`),execute(e){let t=e.model.getters.getActivePosition(),n=TI(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=TI(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 TI(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 EI(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 DI(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=vN(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 OI(e){let t,n,r=[];for(let i of e.model.getters.getSelectedZones()){let a=e.model.getters.getActiveSheetId();for(let o of fr(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 kI(e,t,n,r){let i=TC(e,n,r);CC(t,i);let a={name:bC(P(`Group`),i),values:t};i.groups.push(a),e.customFields||={},e.customFields[i.name]=i,wC(e,n.name,i.name)}function AI(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:bC(P(`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 jI(e,t,n,r){let i;if(!n.isCustomField)i=TC(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)),CC(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)&&(PI(e,i.name),delete e.customFields?.[i.name])}function MI(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 TC(e,n,r).groups.some(e=>e.isOtherGroup||t.some(t=>e.values.includes(t)))}function NI(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||MI(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 PI(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 FI=new BF;FI.add(`cut`,{...KF,sequence:10}).add(`copy`,{...GF,sequence:20}).add(`paste`,{...qF,sequence:30}).add(`paste_special`,{...JF,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...YF,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...XF,sequence:20}).add(`add_row_before`,{...ET,sequence:70}).add(`add_column_before`,{...MT,sequence:90}).add(`insert_cell`,{...FT,sequence:100,separator:!0}).addChild(`insert_cell_down`,[`insert_cell`],{...IT,name:P(`Shift down`),sequence:10}).addChild(`insert_cell_right`,[`insert_cell`],{...LT,name:P(`Shift right`),sequence:20}).add(`delete_row`,{...eI,sequence:110,icon:`o-spreadsheet-Icon.TRASH`}).add(`delete_column`,{...rI,sequence:120,icon:`o-spreadsheet-Icon.TRASH`}).add(`delete_cell`,{...aI,sequence:130,separator:!0,icon:`o-spreadsheet-Icon.TRASH`}).addChild(`delete_cell_up`,[`delete_cell`],{...oI,name:P(`Shift up`),sequence:10,icon:`o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP`}).addChild(`delete_cell_left`,[`delete_cell`],{...sI,name:P(`Shift left`),sequence:20,icon:`o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT`}).add(`edit_table`,{...lI,isVisible:mT,isEnabled:e=>!e.isSmall,sequence:140}).add(`delete_table`,{...uI,isVisible:mT,sequence:145,separator:!0}).add(`insert_link`,{...QT,name:fT,sequence:150,separator:!0}).add(`pivot_headers_group`,{sequence:155,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,...yI}).add(`pivot_group_remaining`,{sequence:155,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,...bI}).add(`pivot_headers_ungroup`,{sequence:155,icon:`o-spreadsheet-Icon.MINUS_IN_BOX`,...xI}).add(`collapse_pivot`,{sequence:156,name:P(`Expand/Collapse`),icon:`o-spreadsheet-Icon.COLLAPSE`}).addChild(`toggle_collapse_pivot_cell`,[`collapse_pivot`],{sequence:10,...SI}).addChild(`collapse_all_pivot`,[`collapse_pivot`],{sequence:20,...CI}).addChild(`expand_all_pivot`,[`collapse_pivot`],{sequence:30,...wI}).add(`pivot_sorting`,{name:P(`Sort pivot`),sequence:155,icon:`o-spreadsheet-Icon.SORT_RANGE`,isVisible:e=>{let t=e.model.getters.getActivePosition();return EI(e.model.getters,t)}}).add(`pivot_fix_formulas`,{...vI,sequence:160}).add(`pivot_properties`,{...mI,sequence:170,separator:!0}).addChild(`pivot_sorting_asc`,[`pivot_sorting`],{...hI,sequence:10}).addChild(`pivot_sorting_desc`,[`pivot_sorting`],{...gI,sequence:20}).addChild(`pivot_sorting_none`,[`pivot_sorting`],{..._I,sequence:30});function II(e,t,n,r,i){let a=r.right>r.left;if(e.model.getters.doesIntersectMerge(t,r)){a=!1;let n;for(let i=r.top;i<=r.bottom;i++){n=[];for(let a=r.left;a<=r.right;a++){let r=e.model.getters.getMerge({sheetId:t,col:a,row:i});r&&!n.includes(r.id.toString())&&n.push(r.id.toString())}if(n.length>=2){a=!0;break}}}if(a){LI(e,t,n,r,i);return}let o=e.model.getters.getContiguousZone(t,r);rr(o,r)?LI(e,t,n,r,i):e.askConfirmation(P(`We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?`),()=>LI(e,t,n,o,i),()=>LI(e,t,n,r,i))}function LI(e,t,n,r,i,a){let o=e.model.dispatch(`SORT_CELLS`,{sheetId:t,col:n.col,row:n.row,zone:r,sortDirection:i,sortOptions:a});if(o.isCancelledBecause(`InvalidSortZone`)){let{col:t,row:i}=n;e.model.selection.selectZone({cell:{col:t,row:i},zone:r}),e.raiseError(P(`Cannot sort. To sort, select only cells or only merges that have the same size.`))}if(o.isCancelledBecause(`SortZoneWithArrayFormulas`)){let{col:t,row:i}=n;e.model.selection.selectZone({cell:{col:t,row:i},zone:r}),e.raiseError(P(`Cannot sort a zone with array formulas.`))}}let RI={name:P(`Sort range`),isVisible:bT,icon:`o-spreadsheet-Icon.SORT_RANGE`},zI={name:P(`Ascending (A ⟶ Z)`),execute:e=>{let{anchor:t,zones:n}=e.model.getters.getSelection();II(e,e.model.getters.getActiveSheetId(),t.cell,n[0],`asc`)},icon:`o-spreadsheet-Icon.SORT_ASCENDING`},BI={name:P(`Data cleanup`),icon:`o-spreadsheet-Icon.DATA_CLEANUP`},VI={name:P(`Remove duplicates`),execute:e=>{xr(e.model.getters.getSelectedZone())===1&&e.model.selection.selectTableAroundSelection(),e.openSidePanel(`RemoveDuplicates`,{})},isEnabled:e=>!e.isSmall},HI={name:P(`Trim whitespace`),execute:e=>{e.model.dispatch(`TRIM_WHITESPACE`)}},UI={name:P(`Descending (Z ⟶ A)`),execute:e=>{let{anchor:t,zones:n}=e.model.getters.getSelection();II(e,e.model.getters.getActiveSheetId(),t.cell,n[0],`desc`)},icon:`o-spreadsheet-Icon.SORT_DESCENDING`},WI={...ST},GI={...ST,isActive:e=>pT(e)},KI={name:P(`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`},qI={name:P(`Column statistics`),execute:e=>e.openSidePanel(`ColumnStats`,{}),icon:`o-spreadsheet-Icon.COLUMN_STATS`},JI={id:`reinsert_dynamic_pivot`,name:P(`Re-insert dynamic pivot`),sequence:60,icon:`o-spreadsheet-Icon.INSERT_PIVOT`,children:[oT],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())},YI={id:`reinsert_static_pivot`,name:P(`Re-insert static pivot`),sequence:70,icon:`o-spreadsheet-Icon.INSERT_PIVOT`,children:[sT],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())},XI={name:P(`Calculation`),icon:`o-spreadsheet-Icon.CALCULATOR`},ZI={name:P(`Automatic`),execute:e=>e.model.dispatch(`SET_AUTOMATIC_EVALUATION`,{enabled:!0}),isActive:e=>e.model.getters.isAutomaticEvaluationEnabled()},QI={name:P(`Manual`),execute:e=>e.model.dispatch(`SET_AUTOMATIC_EVALUATION`,{enabled:!1}),isActive:e=>!e.model.getters.isAutomaticEvaluationEnabled()},$I=new BF;$I.add(`cut`,{...KF,sequence:10}).add(`copy`,{...GF,sequence:20}).add(`paste`,{...qF,sequence:30}).add(`paste_special`,{...JF,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...YF,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...XF,sequence:20}).add(`sort_columns`,{...RI,name:e=>e.model.getters.getActiveCols().size>1?P(`Sort columns`):P(`Sort column`),sequence:50,separator:!0}).addChild(`sort_ascending`,[`sort_columns`],{...zI,sequence:10}).addChild(`sort_descending`,[`sort_columns`],{...UI,sequence:20}).add(`column_statistics`,{...qI,sequence:60,separator:!0}).add(`add_column_before`,{...AT,sequence:70}).add(`add_column_after`,{...NT,sequence:80}).add(`delete_column`,{...nI,sequence:90,icon:`o-spreadsheet-Icon.TRASH`}).add(`clear_column`,{...iI,sequence:100,icon:`o-spreadsheet-Icon.CLEAR`}).add(`hide_columns`,{...dF,sequence:105,separator:!0}).add(`unhide_columns`,{...fF,sequence:106,separator:!0}).add(`conditional_formatting`,{...bM,sequence:110,separator:!0}).add(`edit_table`,{...lI,isVisible:mT,sequence:120}).add(`delete_table`,{...uI,isVisible:mT,sequence:125,separator:!0}).add(`group_columns`,{sequence:150,...jF}).add(`ungroup_columns`,{sequence:155,...NF,isVisible:e=>LF(e,`COL`)});let eL={CannotHideAllRows:P(`Cannot hide all the rows of a sheet.`),CannotHideAllColumns:P(`Cannot hide all the columns of a sheet.`)};function tL(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`?eL.CannotHideAllRows:eL.CannotHideAllColumns;e.raiseError(t)}}function nL(e,t){return _e([{id:`unfold_all`,name:P(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:P(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 rL(e,t,n,r){return[..._e([{id:`toggle_group`,name:e=>{let i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,n,r)?P(t===`ROW`?`Expand row group`:`Expand column group`):P(t===`ROW`?`Collapse row group`:`Collapse column group`)},execute:e=>{tL(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:P(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}]),...nL(e,t)]}let iL=new BF;iL.add(`group_columns`,{sequence:10,...jF,isVisible:()=>!0,isEnabled:jF.isVisible}).add(`group_rows`,{sequence:20,...MF,isVisible:()=>!0,isEnabled:MF.isVisible});let aL=new BF;aL.add(`ungroup_columns`,{sequence:10,...NF,isEnabled:e=>LF(e,`COL`)}).add(`ungroup_rows`,{sequence:20,...PF,isEnabled:e=>LF(e,`ROW`)});let oL=new BF;oL.add(`cut`,{...KF,sequence:10}).add(`copy`,{...GF,sequence:20}).add(`paste`,{...qF,sequence:30}).add(`paste_special`,{...JF,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...YF,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...XF,sequence:20}).add(`add_row_before`,{...wT,sequence:50}).add(`add_row_after`,{...DT,sequence:60}).add(`delete_row`,{...$F,sequence:70,icon:`o-spreadsheet-Icon.TRASH`}).add(`clear_row`,{...tI,sequence:80,icon:`o-spreadsheet-Icon.CLEAR`}).add(`hide_rows`,{...mF,sequence:85,separator:!0}).add(`unhide_rows`,{...hF,sequence:86,separator:!0}).add(`conditional_formatting`,{...bM,sequence:90,separator:!0}).add(`group_rows`,{sequence:100,...MF}).add(`ungroup_rows`,{sequence:110,...PF,isVisible:e=>LF(e,`ROW`)});var sL=class extends Vr{highlightStore=this.get(ME);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}]}},cL=class extends Vr{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 lL(e){return 20+120*Math.exp(-.035*(e-1))}function uL(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=v(e.model.getters.getViewportZoomLevel()),d=tg(e,r,u),{x:f,y:m}=c.getMainViewportCoordinates(),{top:g,left:_,bottom:ee,right:y}=c.getActiveMainViewport(),{scrollX:b,scrollY:te}=c.getActiveSheetScrollInfo(),{xSplit:ne,ySplit:re}=c.getPaneDivisions(l),ie=!1,ae=140,oe=d.clientX-u.x,se=c.getColIndex(oe);if(s!==`vertical`){let t=i.clientX-u.x,n=c.getEdgeScrollCol(oe,t,a);if(n.canEdgeScroll){ie=!0,ae=Math.min(ae,n.delay);let t=se;switch(n.direction){case`reset`:se=t=ne;break;case 1:se=y,t=_+1;break;case-1:for(se=_-1;e.model.getters.isColHidden(l,se);)se--;t=se;break}b=c.getColDimensions(l,t).start-f}}let ce=d.clientY-u.y,le=c.getRowIndex(ce);if(s!==`horizontal`){let t=i.clientY-u.y,n=c.getEdgeScrollRow(ce,t,o);if(n.canEdgeScroll){ie=!0,ae=Math.min(ae,n.delay);let t=le;switch(n.direction){case`reset`:le=t=re;break;case 1:le=ee,t=g+1;break;case-1:for(le=g-1;e.model.getters.isRowHidden(l,le);)le--;t=le;break}te=e.model.getters.getRowDimensions(l,t).start-m}}ie||(se=dL(se,oe,c.getNumberCols(l)-1),le=dL(le,ce,c.getNumberRows(l)-1)),p?.(se,le,r),ie&&(e.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:b,offsetY:te}),n=setTimeout(()=>{n=null,h(r)},Math.round(ae))),i={clientX:d.clientX,clientY:d.clientY}},g=()=>{m?.(),f()};return(0,t.onWillUnmount)(()=>{f()}),Li(()=>{f()},()=>[c.getActiveSheetId()]),{start:(t,n,r,c=`all`)=>{f();let _=v(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(aE(h,g),u)}}}function dL(e,t,n){return e===-1?t<0?0:n:e}var fL=class extends A{static template=`o-spreadsheet-Autofill`;props=(0,t.useProps)({position:N.DOMCoordinates(),isVisible:N.boolean()});state=(0,t.proxy)({position:{x:0,y:0},handler:!1});dragNDropGrid=uL(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=pL),e}onMouseDown(e){this.state.handler=!0;let t=tg(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`)}},pL=class extends A{props=(0,t.useProps)({content:N.string()});static template=t.xml`
|
|
84
84
|
<div t-out="this.props.content"/>
|
|
85
85
|
`},mL=class extends A{static template=`o-spreadsheet-ClientTag`;props=(0,t.useProps)({active:N.boolean(),name:N.string(),color:N.Color(),col:N.HeaderIndex(),row:N.HeaderIndex()});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 hL=[`*`,`+`,`&`];function gL(e,t=60){return`=`+wL(kL(e),t-1)}function _L(){return{type:`insertLine`}}function vL(e,t){return{type:`nest`,indentLevel:e,doc:t}}function yL(e){return{type:`concat`,docs:e}}function bL(e){return xL(SL(e),e)}function xL(e,t){return{type:`chooseBetween`,doc1:e,doc2:t}}function SL(e){return typeof e==`string`?e:e.type===`chooseBetween`?SL(e.doc1):e.type===`concat`?yL(e.docs.map(SL)):e.type===`nest`?{type:`nest`,indentLevel:e.indentLevel,doc:SL(e.doc)}:e.type===`insertLine`?``:e}let CL=an(function(e){return`
|
|
86
86
|
`+` `.repeat(e)});function wL(e,t){return TL(EL(t,e))}function TL(e){let t=``;for(;e;)t+=e.subString,e=e.next;return t}function EL(e,t){return DL(e,0,{indentLevel:0,doc:t,next:null})}function DL(e,t,n){if(n===null)return null;let{indentLevel:r,doc:i,next:a}=n;if(typeof i==`string`)return{subString:i,next:DL(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 DL(e,t,n)}if(i.type===`nest`)return DL(e,t,{indentLevel:r+i.indentLevel,doc:i.doc,next:a});if(i.type===`insertLine`)return{subString:CL(r),next:DL(e,r,a)};if(i.type===`chooseBetween`){let n=DL(e,t,{indentLevel:r,doc:i.doc1,next:a});return OL(e-t,n)?n:DL(e,t,{indentLevel:r,doc:i.doc2,next:a})}return null}function OL(e,t){for(;t;){if(t.subString[0]===`
|
|
87
87
|
`)return!0;if(e-=t.subString.length,e<0)return!1;t=t.next}return!0}function kL(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=al.get(e.value.toUpperCase()),r=Gc(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=>kL(e));i.push(bL(yL(AL(t)))),a+=n.nbrArgRepeating}else i.push(kL(e.args[a])),a++;return jL(yL(AL(i)),t+e.value);case`ARRAY`:return ML(yL(e.value.map(e=>yL(e.map((e,t)=>t===0?kL(e):yL([`, `,_L(),kL(e)])))).map((e,t)=>t===0?bL(e):yL([`; `,_L(),bL(e)]))));case`UNARY_OPERATION`:let o=kL(e.operand),s=(e.postfix?PL(e):FL(e))?jL(o):o;return e.postfix?yL([s,t+e.value]):yL([t+e.value,s]);case`BIN_OPERATION`:{let n=kL(e.left),r=PL(e)?jL(n):n,i=kL(e.right),a=FL(e)?jL(i):i;return bL(yL([r,`${t}${e.value}`,vL(1,yL([_L(),a]))]))}default:return t+e.value}}function AL(e){let t=e.length?[e[0]]:[];for(let n=1;n<e.length;n++)t.push(`, `,_L()),t.push(e[n]);return t}function jL(e,t=void 0){let n=[`(`,vL(1,yL([_L(),e])),_L(),`)`];return t&&n.unshift(t),bL(yL(n))}function ML(e){return bL(yL([`{`,vL(1,yL([_L(),e])),_L(),`}`]))}function NL(e){let t=e.debug?`?`:``;switch(e.type){case`FUNCALL`:let n=e.args.map(e=>NL(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(PL(e)?`(${NL(e.operand)})`:NL(e.operand))+t+e.value;let r=FL(e)?`(${NL(e.operand)})`:NL(e.operand);return t+e.value+r;case`ARRAY`:return`{`+t+e.value.map(e=>e.map(e=>NL(e)).join(`,`)).join(`;`)+`}`;case`BIN_OPERATION`:let i=PL(e)?`(${NL(e.left)})`:NL(e.left),a=FL(e)?`(${NL(e.right)})`:NL(e.right);return i+t+e.value+a;default:return t+e.value}}function PL(e){let t=e.value,n=`left`in e?e.left:e.operand,r=n.value;return n.type===`BIN_OPERATION`&&iu[r]<iu[t]}function FL(e){let t=e.value,n=`right`in e?e.right:e.operand,r=iu[n.value],i=iu[t];return n.type===`BIN_OPERATION`?r<i?!0:r===i&&!hL.includes(t):!1}let IL=P(`The cell you are trying to edit has been deleted.`);var LL=class extends sA{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)):OE(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=Q.get(r.criterion.type).getErrorString(r.criterion,this.getters,t.sheetId);this.notificationStore.raiseError(P(`The data you entered in %s violates the data validation rule set on the cell:
|
|
88
|
-
%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(vn(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,O({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(IL));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(IL);return}let{top:t,left:n}=Qn({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(IL);return}let{top:t,left:n}=Qn({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}=Zn({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&&!vn(e)&&(e=Pt(e,r.link.url));let i=this.getters.getCell(n)?.format,a=i===`@`||i&&pc(i)?void 0:vc(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!==`
|
|
88
|
+
%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(vn(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,O({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(IL));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(IL);return}let{top:t,left:n}=Qn({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(IL);return}let{top:t,left:n}=Qn({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}=Zn({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&&!vn(e)&&(e=Pt(e,r.link.url));let i=this.getters.getCell(n)?.format,a=i===`@`||i&&pc(i)?void 0:vc(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
89
|
`&&t!==` `&&r++}return n}let a=t;return t&&(a={start:i(t.start),end:i(t.end)}),{text:$_(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&&pc(i)?Pa(s,n)===null?{text:H(a,{locale:n,format:Number.isInteger(a)?n.dateFormat:av(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 gL(e.compiledFormula.getAst(this.getters),t)}numberComposerContent(e,t,n){return t?.includes(`%`)?`${fc(e*100,n.decimalSeparator)}%`:fc(e,n.decimalSeparator)}addHeadersForSpreadingFormula(e){let t=xn(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=vn(t)?this.getters.evaluateFormula(this.sheetId,t):$d(t,this.getters.getLocale());if(yS(n))return!0;let r=this.getters.getValidationResultForCellValue(_S(n),e);return!(!r.isValid&&r.rule.isBlocking)}startEdition(e,t){return this.getters.isCurrentSheetLocked()?(this.model.trigger(`command-rejected`,{result:new Ld(`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})}getCurrentCanonicalContent(){return J_(this._currentContent,this.getters.getLocale())}};let RL=3*.4*globalThis.devicePixelRatio||1;var zL=class extends A{static template=`o-spreadsheet-GridComposer`;static components={Composer:Wk};props=(0,t.useProps)({gridDims:N.DOMDimension(),onInputContextMenu:N.function()});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=j(LL);this.composerStore=e,this.composerFocusStore=j(Ur),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 yl(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-RL}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*RL;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=vn(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`:Kg(r),m=`left`;e||(m=r.align==="default"||!r.align?t.defaultAlign:r.align);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:`${RL}px solid ${Oe}`,"min-width":`${v}px`,"min-height":`${_}px`,"max-width":`${g}px`,"max-height":`${h}px`,background:c,color:l,"font-size":`${Tf(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,O(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=O(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 BL({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=t-r+u-c;for(let e of i)d=S(d,-e.x,a-e.x-e.width),f=S(f,-e.y,o-e.y-e.height);return i.map(e=>({...e,x:e.x+d,y:e.y+f}))}function VL(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 HL(e,t,n){let r=m_(...t),i=KL(e,r,[`hCenter`,`right`,`left`],n,[`hCenter`,`right`,`left`]),a=KL(e,r,[`vCenter`,`bottom`,`top`],n,[`vCenter`,`bottom`,`top`]),{y:o,x:s}=e.getMainViewportCoordinates(),{scrollY:c,scrollX:l}=e.getActiveSheetScrollInfo();for(let e of t){if(a){e.y-=a.snapOffset;let t=e.y<o,n=e.y<o;t&&!n?e.y+=c:!t&&n&&(e.y-=c)}if(i){e.x-=i.snapOffset;let t=e.x<s,n=e.x<s;t&&!n?e.x+=l:!t&&n&&(e.x-=l)}}return{snappedFigures:t,verticalSnapLine:i,horizontalSnapLine:a}}function UL(e,t,n,r,i){let a=KL(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=KL(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),{snappedFigures:[r],verticalSnapLine:a,horizontalSnapLine:o}}function WL(e,t,n){return n.map(n=>JL(e,t,!1,n)).filter(n=>GL(e,t,n))}function GL(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 KL(e,t,n,r,i){let a=n.map(n=>JL(e,t,!0,n)),o;for(let t of r){let n=WL(e,t,i);for(let e of a)for(let r of n){if(!qL(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 qL(e,t){return Math.abs(e-t)<=5}function JL(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 YL=class extends A{static template=`o-spreadsheet-FiguresContainer`;static components={FigureComponent:M_};dnd=(0,t.proxy)({draggedFigure:void 0,selectedFigures:void 0,selectedRect: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.draggedFigure=void 0,this.dnd.selectedFigures=void 0,this.dnd.selectedRect=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();for(let t of this.dnd.selectedFigures||[])e.some(e=>e.id===t.id)||e.push(t);return 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.selectedFigures&&t.push({type:`dnd`,figures:this.dnd.selectedFigures,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}}get selectedRectStyle(){return this.dnd.selectedRect?this.rectToCss(this.dnd.selectedRect):``}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 this.dnd.selectedFigures?.some(t=>t.id===e.id)?`dnd`:e.x<t&&e.y<n?`topLeft`:e.x<t?`bottomLeft`:e.y<n?`topRight`:`bottomRight`}getDndFigureRect(){if(this.dnd.selectedFigures&&this.dnd.selectedFigures.length>1)return m_(...this.dnd.selectedFigures)}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}isMenuClick(e){let t=e.target;return t&&t instanceof Element?!!t.closest(`.o-figure-menu`):!1}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly()||this.isMenuClick(t))return;let n=this.env.model.getters.getSelectedFigureIds().includes(e.id);if(!n&&!this.env.model.dispatch(`SELECT_FIGURE`,{figureId:e.id,selectMultiple:t.shiftKey||le(t)}).isSuccessful||this.env.isMobile()||this.env.model.getters.isCurrentSheetLocked())return;let r=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getViewportZoomLevel(),a={x:t.clientX/i,y:t.clientY/i},o=this.env.model.getters.getActiveSheetScrollInfo(),s=this.env.model.getters.getSelectedFigureIds().map(e=>this.env.model.getters.getFigure(r,e)).filter(w).map(e=>this.env.model.getters.getFigureUI(r,e)).map(this.toBottomRightViewport.bind(this)),c=e.id,l={maxX:this.env.model.getters.getColDimensions(r,this.env.model.getters.getNumberCols(r)-1).end,maxY:this.env.model.getters.getRowDimensions(r,this.env.model.getters.getNumberRows(r)-1).end},u=!1,d=e=>{let t=this.env.model.getters,n={x:e.clientX/i,y:e.clientY/i},r=Math.abs(n.x-a.x),d=Math.abs(n.y-a.y);if(!u&&r<5&&d<5)return;u=!0;let f=BL(n,a,s,l,o,t.getActiveSheetScrollInfo()),p=f.find(e=>e.id===c),m,h=this.getOtherFigures(f.map(e=>e.id));if(p&&!f.find(e=>e.tag!==`chart`)&&(m=this.getCarouselOverlappingChart(p,h)),this.dnd.overlappingCarousel=m,m)this.dnd.draggedFigure=p,this.dnd.selectedFigures=f,this.dnd.selectedRect=this.getDndFigureRect(),this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0;else{let e=HL(t,f,h);this.dnd.selectedFigures=e.snappedFigures,this.dnd.selectedRect=this.getDndFigureRect(),this.dnd.draggedFigure=f.find(e=>e.id===c),this.dnd.horizontalSnap=this.getSnap(e.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(e.verticalSnapLine)}},f=t=>{if(!this.dnd.draggedFigure){n&&(t.shiftKey||le(t)?this.env.model.dispatch(`UNSELECT_FIGURE`,{figureId:e.id}):this.env.model.dispatch(`SELECT_FIGURE`,{figureId:e.id}));return}if(this.dnd.overlappingCarousel){let e=this.dnd.overlappingCarousel.id,t=this.dnd.selectedFigures?.map(e=>e.id)||[];this.env.model.dispatch(`ADD_FIGURES_CHART_TO_CAROUSEL`,{sheetId:r,carouselFigureId:e,chartFigureIds:t})}else{let e=this.dnd.selectedFigures?.map(e=>({sheetId:r,figureId:e.id,...this.env.model.getters.getPositionAnchorOffset(e)}))||[];this.env.model.dispatch(`MOVE_FIGURES`,{figures:e})}this.dnd.draggedFigure=void 0,this.dnd.selectedFigures=void 0,this.dnd.selectedRect=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0};this.dnd.cancelDnd=aE(d,f)}startResize(e,t,n,r){r.stopPropagation();let i=this.env.model.getters.getActiveSheetScrollInfo(),a=j_.get(e.tag).keepRatio||!1,o=j_.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=VL(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=UL(this.env.model.getters,t,n,c,d);this.dnd.draggedFigure=f.snappedFigures[0],this.dnd.selectedFigures=[this.dnd.draggedFigure],this.dnd.selectedRect=void 0,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.selectedFigures=void 0,this.dnd.selectedRect=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0};this.dnd.cancelDnd=aE(d,f)}getOtherFigures(e){return this.getVisibleFigures().filter(t=>!e.includes(t.id))}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=m_({...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}},XL=class extends A{static template=`o-spreadsheet-GridAddRowsFooter`;static components={ValidationMessages:zE};DOMFocusableElementStore;inputRef=t.signal.ref(HTMLInputElement);state=(0,t.proxy)({inputValue:`100`,errorFlag:!1});setup(){this.DOMFocusableElementStore=j(l_),Ii(window,`click`,this.onExternalClick,{capture:!0})}get addRowsPosition(){let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo(),{y:t,height:n}=this.env.model.getters.getMainViewportRect();return W({top:`${t+n-e-46}px`,height:`46px`})}get errorMessages(){return[P(`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){let t=this.inputRef();t!==document.activeElement||e.target===t||this.focusDefaultElement()}focusDefaultElement(){document.activeElement===this.inputRef()&&this.DOMFocusableElementStore.focus()}};let ZL={figureHandlers:new k,cellHandlers:new k},QL=[`cell`,`border`,`table`,`conditionalFormat`,`merge`];var $L=class extends Vr{mutators=[`activate`,`cancel`,`pasteFormat`];highlightStore=this.get(ME);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 QL.map(e=>({handlerName:e,handler:new(ZL.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(fw(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}=yw(e,t,this.copiedData,this.clipboardHandlers,n);vw(this.clipboardHandlers,this.copiedData,r,n),bw(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:Oe,dashed:!0,sheetId:e.sheetId,noFill:!0,thinLine:!0,interactive:!1})):[]}},eR=class extends Vr{mutators=[`clear`,`hover`];col;row;overlayColors=new aF;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 aF;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`)}},tR=class extends Vr{mutators=[`setHoveredIcon`];hoveredIcon=void 0;setHoveredIcon(e){this.hoveredIcon=e}};function nR(e,n){let r=j(N_),i=j(eR),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=y(n());return{x:e.clientX-t.x,y:e.clientY-t.y}}let{pause:f,resume:p}=u_(m,200);function m(){let{col:e,row:t}=u(),n=o.now()-l;if(n>300&&(e!==a.col||t!==a.row)&&b(void 0,void 0),n>300){if(e<0||t<0)return;b(e,t)}}function h(e){_(n(),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)&&b(void 0,void 0)}function v(t){let r=tg(e,t),{x:i,y:a}=d(r),o=y(n());return a<0||a>o.height||i<0||i>o.width?h(r):f()}(0,t.useListener)(n,`pointermove`,t=>!e.isMobile()&&h(tg(e,t))),(0,t.useListener)(n,`mouseleave`,v),(0,t.useListener)(n,`mouseenter`,p),(0,t.useListener)(n,`pointerdown`,g),(0,t.useListener)(n,`pointerdown`,t=>e.isMobile()&&h(tg(e,t))),Ii(window,`click`,ee);function ee(e){let t=e.target,r=n();r&&!r.contains(t)&&b(void 0,void 0)}function b(e,t){(e!==a.col||t!==a.row)&&(a.col=e,a.row=t,r.hover({col:e,row:t}))}return a}var rR=class extends A{static template=`o-spreadsheet-GridOverlay`;static components={FiguresContainer:YL,GridAddRowsFooter:XL};props=(0,t.useProps)({onCellDoubleClicked:N.function().optional(()=>()=>{}),onCellClicked:N.function().optional(()=>()=>{}),onCellRightClicked:N.function().optional(()=>()=>{}),onGridResized:N.function().optional(()=>()=>{}),gridOverlayDimensions:N.string()});gridOverlayRef=(0,t.signal)(null);cellPopovers;paintFormatStore;hoveredIconStore;setup(){nR(this.env,this.gridOverlayRef);let e=new ResizeObserver(()=>{this.props.onGridResized()});(0,t.onMounted)(()=>{e.observe(this.gridOverlayEl)}),(0,t.onWillUnmount)(()=>{e.disconnect()}),this.cellPopovers=j(lw),this.paintFormatStore=j($L),this.hoveredIconStore=j(tR)}get gridOverlayEl(){let e=this.gridOverlayRef();if(!e)throw Error(`GridOverlay el is not defined.`);return e}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(tg(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(tg(this.env,e))}onClick(e){e.button>0||!this.env.isMobile()||this.onCellClicked(tg(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:le(e.ev)},e),i?.onClick&&i.onClick(i.position,this.env),e.ev.target===this.gridOverlayRef()&&this.cellPopovers.isOpen&&T(t,this.cellPopovers.persistentCellPopover)){this.cellPopovers.close();return}}onDoubleClick(e){let t=tg(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(tg(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=y(this.gridOverlayRef()),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)||O(c),n=this.env.model.getters.getRect(t);return __(r,i,this.env.model.getters.getCellIconRect(e,n))});return u?.onClick?u:void 0}},iR=class extends A{static template=`o-spreadsheet-GridPopover`;static components={Popover:b_};props=(0,t.useProps)({onClosePopover:N.function(),onMouseWheel:N.function(),gridRect:N.Rect()});cellPopovers;setup(){this.cellPopovers=j(lw)}get cellPopover(){let e=this.cellPopovers.cellPopover;if(!e.isOpen)return{isOpen:!1};let t=rg(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}}}},aR=class extends A{static template=`o-spreadsheet-UnhideRowHeaders`;props=(0,t.useProps)({headersGroups:N.array(),headerRange:N.object({start:N.HeaderIndex(),end:N.HeaderIndex()}),offset:N.number().optional(0)});get sheetId(){return this.env.model.getters.getActiveSheetId()}getUnhidePreviousButtonStyle(e){let t=this.env.model.getters.getRect(O({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(O({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}},oR=class extends A{static template=`o-spreadsheet-UnhideColumnHeaders`;props=(0,t.useProps)({headersGroups:N.array(),headerRange:N.object({start:N.HeaderIndex(),end:N.HeaderIndex()}),offset:N.number().optional(0)});get sheetId(){return this.env.model.getters.getActiveSheetId()}getUnhidePreviousButtonStyle(e){let t=this.env.model.getters.getRect(O({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(O({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}};let sR={onOpenContextMenu:N.function()};var cR=class extends A{props=(0,t.useProps)(sR);composerFocusStore;PADDING=0;MAX_SIZE_MARGIN=0;MIN_ELEMENT_SIZE=0;lastSelectedElementIndex=null;state=(0,t.proxy)({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=uL(this.env);setup(){this.composerFocusStore=j(Ur)}_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(le(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=tg(this.env,e);this._computeHandleDisplay(t),this._computeGrabDisplay(t)}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(e){let t=tg(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=tg(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();aE(e=>{this.state.delta=this._getClientPosition(tg(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=tg(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=tg(this.env,e),n=this._getElementIndex(this._getEvOffset(t));if(!(n<0)){if(this.env.model.getters.isReadonly()){this._selectElement(n,!1);return}if(!le(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=tg(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=tg(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,le(e)),this.lastSelectedElementIndex=t;let n=tg(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(tg(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)}},lR=class extends cR{static template=`o-spreadsheet-ColResizer`;static components={UnhideColumnHeaders:oR};colResizerRef=(0,t.signal)(null);setup(){super.setup(),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()?.clientWidth??0}_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(z_)}_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}},uR=class extends cR{static template=`o-spreadsheet-RowResizer`;static components={UnhideRowHeaders:aR};rowResizerRef=(0,t.signal)(null);setup(){super.setup(),this.PADDING=5,this.MAX_SIZE_MARGIN=60,this.MIN_ELEMENT_SIZE=10}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()?.clientHeight??0}_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(z_):r.reasons.includes(`CannotMoveTableHeader`)&&this.env.raiseError(B_))}_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}},dR=class extends A{static template=`o-spreadsheet-HeadersOverlay`;props=(0,t.useProps)(sR);static components={ColResizer:lR,RowResizer:uR};selectAll(){this.env.model.selection.selectAll()}},fR=class extends Fr{renderer;fingerprints;hoveredTables;hoveredIcon;lastRenderSheetId=void 0;lastRenderBoxes=new Map;preventNewAnimationsInNextFrame=!1;zonesWithPreventedAnimationsInNextFrame={};animations=new Map;getters;constructor(e,t=e(Br)){super(e),this.renderer=t;let n=e(Ir);this.getters=n.getters,this.fingerprints=e(uF),this.hoveredTables=e(eR),this.hoveredIcon=e(tR),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]=D(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=this.getBackgroundColor(e),t.fillRect(0,0,r+Ee,i+Ee)}drawBackground(e,t){let{ctx:n,thinLineWidth:r}=e,i=!e.hideGridLines&&this.getters.getGridLinesVisibility(e.sheetId),a=i?.1*r:0;if(i){let i=this.getters.getSpreadsheetTheme(),o=this.getBackgroundColor(e);n.strokeStyle=fp(lp(i.gridBorderColor+`aa`,o+`50`),1),n.lineWidth=r;for(let e of t)e.style.hideGridLines||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 r of t){let t=r.style;if(t.fillColor&&Xf(t.fillColor)!==Xf(this.getBackgroundColor(e))&&(n.fillStyle=Xf(t.fillColor),n.fillRect(r.x-Ee,r.y-Ee,r.width+Ee*2,r.height+Ee*2)),r.dataBarFill){n.fillStyle=r.dataBarFill.color;let e=r.dataBarFill.percentage,t=r.width*(e/100);n.fillRect(r.x,r.y,t,r.height)}if(r.overlayColor&&(n.fillStyle=lp(t.fillColor||this.getBackgroundColor(e),r.overlayColor),n.fillRect(r.x-Ee,r.y-Ee,r.width+Ee*2,r.height+Ee*2)),r?.chip){n.save(),n.beginPath(),n.rect(r.x,r.y,r.width,r.height),n.clip();let e=r.chip;n.fillStyle=r.overlayColor?lp(e.color,r.overlayColor):e.color,n.beginPath(),n.roundRect(e.x,e.y,e.width,e.height,10),n.fill(),n.restore()}r.isError&&(n.fillStyle=`red`,n.beginPath(),n.moveTo(r.x+r.width-5,r.y),n.lineTo(r.x+r.width,r.y),n.lineTo(r.x+r.width,r.y+5),n.fill())}}drawOverflowingCellBackground(e,t){let{ctx:n,thinLineWidth:r}=e;for(let i of t)if(i.content&&i.isOverflow){let t=i.content.align||`left`,a,o,s=i.y+r/2,c=i.height-r,l=Math.min(i.clipRect?.width||1/0,i.content.width);t===`left`?(a=i.x+r/2,o=l-2*r):t===`right`?(a=i.x+i.width-r/2,o=-l+2*r):(a=(i.clipRect?.x||i.x+i.width/2-i.content.width/2)+r/2,o=l-2*r),n.fillStyle=this.getBackgroundColor(e),n.fillRect(a,s,o,c)}}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=Ef(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}=Lf(e.content,a));for(let t of e.content.textLines)Ff(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(Ry(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=Er(d),p=Or(d),m=this.getters.getNumberCols(i),h=this.getters.getNumberRows(i),g=e.activeCols,_=e.activeRows,v=this.getters.getSpreadsheetTheme();t.font=`400 11px ${Je}`,t.textAlign=`center`,t.textBaseline=`middle`,t.lineWidth=n,t.strokeStyle=v.headerTextColor,t.fillStyle=this.getters.getSpreadsheetTheme().backgroundColor,t.fillRect(0,0,48,u),t.fillRect(0,0,l,26);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=v.headerActiveBackgroundColor:c?t.fillStyle=v.headerSelectedBackgroundColor:t.fillStyle=v.headerBackgroundColor,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=v.headerActiveBackgroundColor:c?t.fillStyle=v.headerSelectedBackgroundColor:t.fillStyle=v.headerBackgroundColor,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=v.headerBorderColor,t.stroke();for(let e of a){let n=wn(e);t.fillStyle=g.has(e)?`#fff`:v.headerTextColor;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`:v.headerTextColor;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=this.getters.getSpreadsheetTheme().frozenPaneHeaderBorderColor,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=this.getters.getSpreadsheetTheme().frozenPaneBorderColor,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&&Ic(r.value,r.format)?`left`:t&&r.type===`number`?n===`center`?n:`left`:!n||n==="default"?r.defaultAlign:n}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),ee={left:v.find(e=>e?.horizontalAlign===`left`),right:v.find(e=>e?.horizontalAlign===`right`),center:v.find(e=>e?.horizontalAlign===`center`)},y={id:Yn(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:ee,disabledAnimation:this.zonesWithPreventedAnimationsInNextFrame[t]?.some(e=>sr(n,e)||ir(n,e))},b=Df(y.style);if(l.type===`empty`||y.icons.center)return y;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=(y.icons.left?y.icons.left.size+y.icons.left.margin:0)+ue,fe=(y.icons.right?y.icons.right.size+y.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(y,b,g.verticalAlign,he)),_e=y.x;me===`left`?_e+=4+de:me===`right`?_e+=y.width-4-fe:_e+=y.width/2,_e=Math.round(_e);let ve=mf(b,he);if(y.content={textLines:oe,width:te===`overflow`?ce:p,textHeight:ve,textWidth:ce,align:me,x:_e,y:ge,fontSizePx:b},h?.fillColor){let e=de;y.chip={color:h.fillColor,width:y.width-e-5,height:ve+2,x:y.x+e,y:ge-2}}let ye=pe>p||le.height>m;if(y.icons.left||y.icons.right||y.chip)y.clipRect={x:y.x+de,y:y.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=y.border?.right?n.right:this.findNextEmptyCol(t,o,a,s),l=y.border?.left?n.left:this.findPreviousEmptyCol(t,o,i,s),y.isOverflow=!0),me){case`left`:{let i=O({col:r,row:s}),{x:a,y:o,width:c,height:l}=e.getVisibleRect(t,er(n,i));(c<pe||b>l||oe.length>1)&&(y.clipRect={x:a,y:o,width:c,height:l});break}case`right`:{let r=O({col:l,row:s}),{x:i,y:a,width:o,height:c}=e.getVisibleRect(t,er(n,r));(o<pe||b>c||oe.length>1)&&(y.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=y.x+y.width/2;if(a+c<d+u||a>d-u||b>s||oe.length>1){let e=a>d-u?a:d-u;y.clipRect={x:e,y:o,width:a+c-e,height:s}}break}}}else(te===`clip`||te===`wrap`||oe.length>1)&&(y.clipRect={x:y.x,y:y.y,width:p,height:m});return y}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,O(i),c))}for(let n of this.getters.getMerges(t))if(!this.getters.isMergeHidden(t,n)&&ir(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=e_.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 e_.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)}}getBackgroundColor(e){return this.getters.getSheet(e.sheetId).backgroundColor||this.getters.getSpreadsheetTheme().backgroundColor}};function pR({canvasRef:e,renderingCtx:t,rendererStore:n,changeCanvasSizeOnZoom:r}){Li(a);let i=n||j(Br);Ji(fR,i);function a(){let n=e(),a=n.getContext(`2d`,{alpha:!1}),o={ctx:a,thinLineWidth:.4,...t()},s=o.dpr,c=o.viewports.getZoomLevel();r||(c=Math.max(c,1));let{width:l,height:u}=o.viewports.getSheetViewDimensionWithHeaders();n.width=l*s*c,n.height=u*s*c;let d=W({width:r?`${l*c}px`:`${l}px`,height:r?`${u*c}px`:`${u}px`});n.setAttribute(`style`,d),!(l===0||u===0)&&(a.translate(-.5,-.5),a.scale(s*c,s*c),i.draw(o))}}let mR=.95;function hR(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;(0,t.useListener)(e,`touchstart`,_,{capture:!1}),(0,t.useListener)(e,`touchmove`,v,{capture:!1}),(0,t.useListener)(e,`touchend`,ee,{capture:!1}),(0,t.useListener)(e,`pointerdown`,b,{passive:!1,capture:!1}),(0,t.useListener)(e,`pointermove`,ne,{passive:!1,capture:!1}),Ii(window,`pointerup`,te,{passive:!1,capture:!0}),(0,t.useListener)(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 ee(e){d=!1,s=c=0,p&&clearTimeout(p),l*=1.2,u*=1.2,requestAnimationFrame(y)}function y(){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*=mR,u*=mR,requestAnimationFrame(y)}function b(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=gR(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=gR(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 gR(e,t){let n=e.clientX-t.clientX,r=e.clientY-t.clientY;return Math.sqrt(n*n+r*r)}function _R(e){function t(e,t){return e*(t===0?1:23)}return n=>{e(t(n.shiftKey&&!ce()?n.deltaY:n.deltaX,n.deltaMode),t(n.shiftKey&&!ce()?n.deltaX:n.deltaY,n.deltaMode))}}var vR=class extends A{static template=`o-spreadsheet-Border`;props=(0,t.useProps)({zone:N.Zone(),orientation:N.or([N.literal(`n`),N.literal(`s`),N.literal(`w`),N.literal(`e`)]),isMoving:N.boolean(),onMoveHighlight:N.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)}},yR=class extends A{static template=`o-spreadsheet-Corner`;props=(0,t.useProps)({zone:N.Zone(),color:N.Color(),orientation:N.or([N.literal(`nw`),N.literal(`ne`),N.literal(`sw`),N.literal(`se`),N.literal(`n`),N.literal(`s`),N.literal(`e`),N.literal(`w`)]),isResizing:N.boolean(),onResizeHighlight:N.function()});dirX;dirY;setup(){let{dirX:e,dirY:t}=bR(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 bR(e){return{dirX:e.includes(`w`)?-1:+!!e.includes(`e`),dirY:e.includes(`n`)?-1:+!!e.includes(`s`)}}var xR=class extends A{static template=`o-spreadsheet-Highlight`;static components={Corner:yR,Border:vR};props=(0,t.useProps)({range:N.Range(),color:N.Color()});highlightState=(0,t.proxy)({shiftingMode:`none`});dragNDropGrid=uL(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=tg(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};rr(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=v(this.env.model.getters.getViewportZoomLevel()),r=tg(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};rr(m,d)||(this.env.model.selection.selectZone({cell:{col:m.left,row:m.top},zone:m},{unbounded:!0}),d=m)}},()=>{this.highlightState.shiftingMode=`none`})}},SR=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}},CR=class extends A{static template=t.xml`
|
|
90
90
|
<div
|
|
91
91
|
t-attf-class="o-scrollbar {{this.props.direction}}"
|
|
@@ -110,10 +110,10 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
110
110
|
offset="this.offset"
|
|
111
111
|
direction="'vertical'"
|
|
112
112
|
onScroll.bind="(offset) => this.onScroll(offset)"
|
|
113
|
-
/>`;props=(0,t.useProps)({topOffset:N.number().optional(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:`${t}px`}}onScroll(e){let{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:t,offsetY:e})}},ER=class extends A{static template=`o-spreadsheet-Selection`;static components={Highlight:xR};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:Oe}}},DR=class extends A{static template=`o-spreadsheet-TableResizer`;props=(0,t.useProps)({table:N.Table()});state=(0,t.proxy)({highlightZone:void 0});dragNDropGrid=uL(this.env);setup(){LA(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=tg(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 OR={ROW:oL,COL:$I,CELL:FI,GROUP_HEADERS:iL,UNGROUP_HEADERS:aL};var kR=class extends A{static template=`o-spreadsheet-Grid`;static components={GridComposer:zL,GridOverlay:rR,GridPopover:iR,HeadersOverlay:dR,MenuPopover:w_,Autofill:fL,ClientTag:mL,Highlight:xR,Popover:b_,VerticalScrollBar:TR,HorizontalScrollBar:wR,TableResizer:DR,Selection:ER};props=(0,t.useProps)({exposeFocus:N.function(),getGridSize:N.function()});HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef=(0,t.signal)(null);canvasRef=(0,t.signal)(null);highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=uL(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=j(ME),this.menuState=(0,t.proxy)({isOpen:!1,anchorRect:null,menuItems:[]}),this.hoveredCell=j(N_),this.composerFocusStore=j(Ur),this.DOMFocusableElementStore=j(l_),this.sidePanel=j(rF),this.paintFormatStore=j($L),this.clientFocusStore=j(cL),j(sL),Hi({getPopoverContainerRect:()=>this.getGridRect()}),Ii(document.body,`cut`,this.copy.bind(this,!0)),Ii(document.body,`copy`,this.copy.bind(this,!1)),Ii(document.body,`paste`,this.paste),(0,t.onMounted)(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),pR({canvasRef:this.canvasRef,renderingCtx:()=>({dpr:window.devicePixelRatio||1,viewports:this.env.model.getters.getViewportCollection(),...this.env.model.getters.getSelectionState()})}),this.onMouseWheel=_R((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=j(lw),Li((e,t)=>{!e&&!t&&this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),hR(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`),F9:()=>this.env.model.dispatch(`EVALUATE_CELLS`),"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":()=>cT(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&&Kd(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":()=>{rw(this.env,{type:`COPY_PASTE_CELLS_ABOVE`})},"Ctrl+R":()=>{rw(this.env,{type:`COPY_PASTE_CELLS_ON_LEFT`})},"Ctrl+Enter":()=>{rw(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":()=>Lw(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?$w(this.env):i&&!r&&Zw(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":()=>{tE.execute?.(this.env)},"Alt+T":()=>{HT.execute?.(this.env)},PageDown:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_DOWN`),PageUp:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_UP`),"Ctrl+Shift+K":()=>{this.closeMenu(),dT(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}OE(this.env.model.getters,this.env.model.selection,e)}moveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.env.model.selection.moveAnchorCell(e,1);return}OE(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.getSelectedFigureIds().length&&this.composerFocusStore.activeComposer.editionMode===`inactive`&&this.DOMFocusableElementStore.focus()}get gridEl(){let e=this.gridRef();if(!e)throw Error(`Grid el is not defined.`);return e}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{...y(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(),DE(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=se(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`;or(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=OR[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?zF(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=>dw.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()===gw(r.content[`text/html`]))ow(this.env,i);else{let e=hw(r.content);await sw(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(!LF(this.env,`COL`)&&!LF(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(AP)}get displaySelectionHandler(){return this.env.isMobile()&&this.composerFocusStore.activeComposer.editionMode===`inactive`}};let AR=new k;AR.add(`SPREADSHEET`,!1);var jR=class extends A{static template=`o-spreadsheet-ClickableCellSortIcon`;props=(0,t.useProps)({position:N.CellPosition(),sortDirection:N.or([N.SortDirection,N.literal(`none`)])});hoveredTableStore;setup(){this.hoveredTableStore=j(eR)}get style(){let e=this.env.model.getters.getCellComputedStyle(this.props.position),t=Df(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?lp(e.fillColor||`#FFFFFF`,t):e.fillColor||`#FFFFFF`}},MR=class extends A{static template=`o-spreadsheet-FullScreenFigure`;static components={ChartFigure:k_};fullScreenFigureStore;fullScreenFigureRef=(0,t.signal)(null);spreadsheetRect=v_();figureRegistry=j_;setup(){this.fullScreenFigureStore=j(c_);let e=j(ha),n;(0,t.onWillUpdateProps)(()=>{n!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+`-fullscreen`),n=this.figureUI?.id}),(0,t.useEffect)(()=>this.fullScreenFigureRef()?.focus())}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 j_.get(this.figureUI.tag).Component}},NR=class extends A{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:wE};props=(0,t.useProps)({pivotId:N.UID(),onCellClicked:N.function()});pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.proxy)({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(R(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${cC(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(${cC(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(${cC(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=R(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(${cC(e,o,a).join(`,`)})`,value:H(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},PR=l({GHOST_SUNBURST_VALUE:()=>nh,canChartParseLabels:()=>LD,getBarChartData:()=>_D,getBarChartDatasets:()=>rh,getBarChartLegend:()=>pO,getBarChartScales:()=>Lm,getBarChartTooltip:()=>zO,getBubbleChartData:()=>OD,getBubbleChartDatasets:()=>lh,getBubbleChartLegend:()=>vO,getBubbleChartScales:()=>Wm,getBubbleChartTooltip:()=>HO,getCalendarChartData:()=>bD,getCalendarChartDatasetAndLabels:()=>ah,getCalendarChartLayout:()=>eO,getCalendarChartScales:()=>Rm,getCalendarChartShowValues:()=>AO,getCalendarChartTooltip:()=>BO,getCalendarColorScale:()=>zm,getChartColorsGenerator:()=>Eh,getChartLabelFormat:()=>YD,getChartLayout:()=>$D,getChartShowValues:()=>kO,getChartTitle:()=>FO,getComboChartDatasets:()=>fh,getComboChartLegend:()=>yO,getFunnelChartData:()=>ED,getFunnelChartDatasets:()=>hh,getFunnelChartScales:()=>Ym,getFunnelChartTooltip:()=>JO,getFunnelLabelColors:()=>gh,getGeoChartData:()=>TD,getGeoChartDatasets:()=>mh,getGeoChartScales:()=>Jm,getGeoChartTooltip:()=>qO,getHierarchalChartData:()=>DD,getLineChartData:()=>SD,getLineChartDatasets:()=>sh,getLineChartLegend:()=>hO,getLineChartScales:()=>Bm,getLineChartTooltip:()=>VO,getPieChartData:()=>CD,getPieChartDatasets:()=>dh,getPieChartLegend:()=>gO,getPieChartTooltip:()=>UO,getPyramidChartData:()=>xD,getPyramidChartLegend:()=>mO,getPyramidChartScales:()=>Km,getPyramidChartShowValues:()=>MO,getPyramidChartTooltip:()=>GO,getRadarChartData:()=>wD,getRadarChartDatasets:()=>ph,getRadarChartLegend:()=>xO,getRadarChartScales:()=>qm,getRadarChartTooltip:()=>KO,getRuntimeColorScale:()=>$m,getScatterChartDatasets:()=>ch,getScatterChartLegend:()=>_O,getScatterChartScales:()=>Um,getSunburstChartDatasets:()=>_h,getSunburstChartLegend:()=>SO,getSunburstChartTooltip:()=>YO,getSunburstShowValues:()=>jO,getTopPaddingForDashboard:()=>QD,getTreeMapChartDatasets:()=>Sh,getTreeMapChartTooltip:()=>XO,getTrendDatasetForBarChart:()=>AD,getTrendDatasetForLineChart:()=>jD,getWaterfallChartLegend:()=>bO,getWaterfallChartScales:()=>Gm,getWaterfallChartShowValues:()=>NO,getWaterfallChartTooltip:()=>WO,getWaterfallDatasetAndLabels:()=>oh,makeDatasetsCumulative:()=>ZD}),FR=class extends lv{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||Ye.style,color:e.border.color||Ye.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 Dt(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 D(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 D(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 _v(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,Wn(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=hv(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=gv(e)}e.borders=t}exportForExcel(e){this.export(e)}},IR=class extends lv{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]})}}},LR=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=fd.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=Yd(this.getters,-1,e.content,e.format??void 0,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=Nn(n[i]),o=0;for(o=0;o+i+1<n.length;o++){let t=Nn(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),Cu(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),Cu(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),Cu(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)}`:Cu(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 RR(e){return[Nn(e)]}function*zR(e,t){let n=Nn(e),r=Nn(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 BR=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=zR(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:Nn(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?RR(a):zR(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=fd.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:fd.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:fd.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=Xd(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 fd.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}}}},VR=class extends lv{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`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`;default:return`Success`}}handle(e){switch(e.type){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:null});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 D(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})}}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:null})}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 aF,i=new BR;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 _v(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 LR(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=E(l.col,l.row);if(c.style&&Object.keys(c.style).length){let e=hv(c.style,n);a[e]??=[],a[e].push(l)}if(c.format){let e=hv(c.format,r);o[e]??=[],o[e].push(l)}c.isFormula?s[u]=t?e.squish(c,i.id):c.compiledFormula.toFormulaString(this.getters):c.content&&(s[u]=t?e.squish(c,i.id):c.content)}i.styles=gv(a),i.formats=gv(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?Qd(a,i,r,n):Yd(this.getters,a,t||``,r,n,e,{avoidAutomaticDateFormat:!0})}exportForExcel(e){this.export(e,!1);let t=[];for(let n in e.formats||[])Pc(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}getCells(e){return 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 fd.CopyWithDependencies(t,e,n).toFormulaString(this.getters,{useBoundedReference:r})}getTranslatedCellFormula(e,t,n,r){r instanceof fd||(r=fd.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 fd.CopyWithDependencies(t,e,n).toFormulaString(this.getters)}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}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={sheetId:e,col:t,row:n},a=this.getters.getCell(i),o=r.content!==void 0||`formula`in r,s;s=o?nn(r?.content):a?.isFormula?a.compiledFormula.toFormulaString(this.getters):a?.content||``;let c;if(r.style!==void 0){let e=Object.fromEntries(Object.entries(r.style??{}).filter(([e,t])=>t!==this.getters.getCellDefaultStyleValue(i,e)));c=Bt(e)?void 0:e}else c=a?.style;let l;if(r.format!==void 0){let e=this.getters.getCellDefaultFormat(i);l=r.format===null?void 0:r.format,(l??``)===(e??``)&&(l=void 0)}else l=a?.format;if((o&&!s&&!r.formula||!o&&(!a||!a.isFormula&&a.content===``))&&!c&&l===void 0){a&&(this.history.update(`cells`,e,a.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let u=a?.id||this.getNextCellId(),d=Yd(this.getters,u,s,l,c,e);this.history.update(`cells`,e,d.id,d),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:d.id,col:t,row:n,sheetId:e})}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?or(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`}},HR=class extends lv{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=gk.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=gk.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=gk.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=gk.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 gk.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 UR(e){return e===``?NaN:Number(e)}var WR=class extends lv{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)or(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(Un));let s=D(o,r);return D([...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 lj.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=Q.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(fd.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&&UR(t)>=UR(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&&UR(t)>=UR(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&&UR(t)>=UR(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&fd.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)}},GR=class extends lv{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=>wu(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=D(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(or(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 Eu(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:!e?.style?.align||e.style.align==="default"?`center`:e.style.align,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 Q.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=Q.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=Q.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||fd.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`}},KR=class extends lv{static getters=[`getCellStyle`,`getDefaultStyle`,`getCellDefaultStyleValue`,`getCellFormat`,`getCellDefaultFormat`,`getDefaultFormat`,`getDefaultStyleColors`];style={};format={};allowDispatch(e){return e.type===`SET_FORMATTING`?this.checkUselessSetFormatting(e):`Success`}handle(e){switch(e.type){case`SET_FORMATTING`:e.style!==void 0&&this.setStyle(e.sheetId,e.target,e.style),e.format!==void 0&&this.setFormat(e.sheetId,e.target,e.format);break;case`CLEAR_FORMATTING`:this.setStyle(e.sheetId,e.target,Ue),this.setFormat(e.sheetId,e.target,null);break;case`ADD_COLUMNS_ROWS`:let t=e.position===`before`?e.base:e.base+1;this.moveColRows(e.sheetId,e.dimension,t,e.quantity);let n=e.position===`before`?e.base+e.quantity:e.base;for(let r=t;r<t+e.quantity;r++)this.copyColRow(e.sheetId,e.dimension,n,r);break;case`REMOVE_COLUMNS_ROWS`:for(let t of Dt(e.elements).toReversed()){for(let n of t)this.clearColRows(e.sheetId,e.dimension,n);this.moveColRows(e.sheetId,e.dimension,t[0],-t.length)}break;case`DUPLICATE_SHEET`:this.history.update(`style`,e.sheetIdTo,x(this.style[e.sheetId])),this.history.update(`format`,e.sheetIdTo,x(this.format[e.sheetId]));break}}clearColRows(e,t,n){let r=t===`COL`?`colDefault`:`rowDefault`;for(let t in this.style[e])this.history.update(`style`,e,t,r,n,void 0);this.history.update(`format`,e,r,n,void 0)}moveColRows(e,t,n,r){let i=t===`COL`?`colDefault`:`rowDefault`;for(let t in this.style[e]){let a=Object.entries(this.style[e][t]?.[i]??[]);r>0&&a.reverse();for(let[o,s]of a){let a=parseInt(o);a<n||(this.history.update(`style`,e,t,i,a+r,s),this.history.update(`style`,e,t,i,a,void 0))}}let a=Object.entries(this.format[e]?.[i]??[]);r>0&&a.reverse();for(let[t,o]of a){let a=parseInt(t);a<n||(this.history.update(`format`,e,i,a+r,o),this.history.update(`format`,e,i,a,void 0))}}copyColRow(e,t,n,r){let i=t===`COL`?`colDefault`:`rowDefault`;for(let t in this.style[e]){let a=this.style[e][t]?.[i]?.[n];this.history.update(`style`,e,t,i,r,a)}this.history.update(`format`,e,i,r,this.format[e]?.[i]?.[n])}setFormat(e,t,n){t=D(t);let{numberOfCols:r,numberOfRows:i}=this.getters.getSheetSize(e),a=r*i;for(let o of t){let t=o.bottom-o.top+1>i/2,s=o.right-o.left+1>r/2;s&&t&&xr(o)>a/2?this.setSheetFormat(e,o,n):t?this.setColsFormat(e,o,n??``):s?this.setRowsFormat(e,o,n??``):this.updateCellsFormat(e,o,n??``)}}setSheetFormat(e,t,n){this.updateCellsFormat(e,t,null);let r=this.getters.getSheetZone(e),i=this.getters.getRowsZone(e,t.top,t.bottom),a=D([i],[t]),o=this.getDefaultFormatInCell(e,a,{shouldUseDefaultSheet:!0,shouldUseDefaultRow:!0}),s=this.getters.getColsZone(e,t.left,t.right),c=D([s],[t]);o.push(...this.getDefaultFormatInCell(e,c,{shouldUseDefaultSheet:!0,shouldUseDefaultCol:!0}));let l=D([r],[i,s]);o.push(...this.getDefaultFormatInCell(e,l,{shouldUseDefaultSheet:!0})),this.history.update(`format`,e,`sheetDefault`,n??void 0);let u=Object.keys(this.format[e]?.rowDefault??{});for(let n of u){let r=parseInt(n);t.top<=r&&r<=t.bottom&&this.history.update(`format`,e,`rowDefault`,r,void 0)}let d=Object.keys(this.format[e]?.colDefault??{});for(let n of d){let r=parseInt(n);t.left<=r&&r<=t.right&&this.history.update(`format`,e,`colDefault`,r,void 0)}for(let[e,t]of o)this.updateCellFormat(e,t)}setColsFormat(e,t,n){this.updateCellsFormat(e,t,null);let r=D([this.getters.getColsZone(e,t.left,t.right)],[t]),i=this.getDefaultFormatInCell(e,r,{shouldUseDefaultSheet:!0,shouldUseDefaultCol:!0}),a=Object.keys(this.format[e]?.rowDefault??{}),o=n===(this.format[e]?.sheetDefault??``)?void 0:n;for(let r=t.left;r<=t.right;r++){this.history.update(`format`,e,`colDefault`,r,o);for(let i of a){let a=parseInt(i);t.top<=a&&a<=t.bottom&&this.updateCellFormat({col:r,row:a,sheetId:e},n)}}for(let[e,t]of i)this.updateCellFormat(e,t)}setRowsFormat(e,t,n){this.updateCellsFormat(e,t,null);let r=D([this.getters.getRowsZone(e,t.top,t.bottom)],[t]),i=this.getDefaultFormatInCell(e,r,{shouldUseDefaultSheet:!0,shouldUseDefaultCol:!0,shouldUseDefaultRow:!0});for(let r=t.top;r<=t.bottom;r++)this.history.update(`format`,e,`rowDefault`,r,n);for(let[e,t]of i)this.updateCellFormat(e,t)}updateCellsFormat(e,t,n){for(let r=t.left;r<=t.right;r++)for(let i=t.top;i<=t.bottom;i++)this.updateCellFormat({sheetId:e,col:r,row:i},n)}updateCellFormat(e,t){(t??``)===(this.getCellDefaultFormat(e)??``)?this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,format:null}):this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,format:t})}getDefaultFormatInCell(e,t,n){let r=[];for(let i of t.flatMap(t=>fr(e,t))){if(this.getters.getCell(i)?.format)continue;let t=this.format[e]?.rowDefault?.[i.row];if(t){n.shouldUseDefaultRow&&r.push([i,t]);continue}let a=this.format[e]?.colDefault?.[i.col];if(a){n.shouldUseDefaultCol&&r.push([i,a]);continue}let o=this.format[e]?.sheetDefault;if(o){n.shouldUseDefaultSheet&&r.push([i,o]);continue}}return r}setStyle(e,t,n){t=D(t);let{numberOfCols:r,numberOfRows:i}=this.getters.getSheetSize(e),a=r*i;for(let o of t){let t=o.bottom-o.top+1>i/2,s=o.right-o.left+1>r/2;s&&t&&xr(o)>a/2?this.setSheetStyle(e,o,n):t?this.setColsStyle(e,o,n):s?this.setRowsStyle(e,o,n):this.updateCellsStyle(e,o,n)}}setSheetStyle(e,t,n){this.clearCellStyle(e,t,n);let r=this.getters.getSheetZone(e),i=this.getters.getRowsZone(e,t.top,t.bottom),a=D([i],[t]),o=this.getPartialDefaultStyleInCell(e,a,n,{shouldUseDefaultSheet:!0,shouldUseDefaultRow:!0}),s=this.getters.getColsZone(e,t.left,t.right),c=D([s],[t]);o.push(...this.getPartialDefaultStyleInCell(e,c,n,{shouldUseDefaultSheet:!0,shouldUseDefaultCol:!0}));let l=D([r],[i,s]);o.push(...this.getPartialDefaultStyleInCell(e,l,n,{shouldUseDefaultSheet:!0}));for(let r in n){n[r]===Ue[r]?this.history.update(`style`,e,r,`sheetDefault`,void 0):this.history.update(`style`,e,r,`sheetDefault`,n[r]);let i=Object.keys(this.style[e]?.[r]?.rowDefault??{});for(let n of i){let i=parseInt(n);t.top<=i&&i<=t.bottom&&this.history.update(`style`,e,r,`rowDefault`,i,void 0)}let a=Object.keys(this.style[e]?.[r]?.colDefault??{});for(let n of a){let i=parseInt(n);t.left<=i&&i<=t.right&&this.history.update(`style`,e,r,`colDefault`,i,void 0)}}for(let[e,t]of o)this.updateCellStyle(e,t)}setColsStyle(e,t,n){this.clearCellStyle(e,t,n);let r=D([this.getters.getColsZone(e,t.left,t.right)],[t]),i=this.getPartialDefaultStyleInCell(e,r,n,{shouldUseDefaultSheet:!0,shouldUseDefaultCol:!0}),a=new aF;for(let r in n){let i=Object.keys(this.style[e]?.[r]?.rowDefault??{}),o=n[r]===(this.style[e]?.[r]?.sheetDefault??Ue[r])?void 0:n[r];for(let s=t.left;s<=t.right;s++){this.history.update(`style`,e,r,`colDefault`,s,o);for(let o of i){let i=parseInt(o);if(t.top<=i&&i<=t.bottom){let t={col:s,row:i,sheetId:e},o=a.get(t);if(o)o[r]=n[r];else{let e={};e[r]=n[r],a.set(t,e)}}}}}for(let[e,t]of a.entries())this.updateCellStyle(e,t);for(let[e,t]of i)this.updateCellStyle(e,t)}setRowsStyle(e,t,n){this.clearCellStyle(e,t,n);let r=D([this.getters.getRowsZone(e,t.top,t.bottom)],[t]),i=this.getPartialDefaultStyleInCell(e,r,n,{shouldUseDefaultSheet:!0,shouldUseDefaultCol:!0,shouldUseDefaultRow:!0});for(let r in n){let i=Object.keys(this.style[e]?.[r]?.colDefault??{}).length!==0;for(let a=t.top;a<=t.bottom;a++)i||n[r]!==(this.style[e]?.[r]?.sheetDefault??Ue[r])?this.history.update(`style`,e,r,`rowDefault`,a,n[r]):this.history.update(`style`,e,r,`rowDefault`,a,void 0)}for(let[e,t]of i)this.updateCellStyle(e,t)}updateCellsStyle(e,t,n,r){for(let i=t.left;i<=t.right;i++)for(let a=t.top;a<=t.bottom;a++)this.updateCellStyle({sheetId:e,col:i,row:a},n,r)}updateCellStyle(e,t,n){let r=this.getters.getCell(e),i=n?.cellPriority?{...t,...r?.style}:{...r?.style,...t};this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,style:i})}clearCellStyle(e,t,n){for(let r=t.top;r<=t.bottom;r++)for(let i of this.getters.getRowCellIds(e,r)){let a=this.getters.getCellPosition(i).col;if(a<t.left||t.right<a)continue;let o=this.getters.getCellById(i)?.style;if(!o)continue;o={...o};let s=!1;for(let e in n)o[e]!==void 0&&(s=!0,delete o[e]);s&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:r,style:Object.keys(o).length===0?null:o})}}getPartialDefaultStyleInCell(e,t,n,r){let i=[];for(let a of t.flatMap(t=>fr(e,t))){let e=this.getters.getCell(a)?.style??{},t={},o=!1,s=this.style[a.sheetId];for(let i in n){if(i in e)continue;let c=s?.[i];if(!c){n[i]!==Ue[i]&&(t[i]=Ue[i],o=!0);continue}let l=c.rowDefault?.[a.row];if(l!==void 0){r.shouldUseDefaultRow&&(t[i]=l,o=!0);continue}let u=c.colDefault?.[a.col];if(u!==void 0){r.shouldUseDefaultCol&&(t[i]=u,o=!0);continue}let d=c.sheetDefault;if(d!==void 0){r.shouldUseDefaultSheet&&(t[i]=d,o=!0);continue}n[i]!==Ue[i]&&(t[i]=Ue[i],o=!0)}o&&i.push([a,t])}return i}getCellStyle(e){let t=this.getters.getCell(e),n=this.style[e.sheetId];if(!n)return t?.style??{};let r={...t?.style};for(let t in n)if(!(t in r)){let i=n[t];if(!i)continue;let a=i.rowDefault?.[e.row]??i.colDefault?.[e.col]??i.sheetDefault;a!==void 0&&(r[t]=a)}return r}getCellDefaultStyleValue(e,t){let n=this.style[e.sheetId]?.[t];return n?.rowDefault?.[e.row]??n?.colDefault?.[e.col]??n?.sheetDefault??Ue[t]}getCellFormat(e){let t=this.getters.getCell(e);return t?.format===void 0?this.getCellDefaultFormat(e):t?.format}getCellDefaultFormat(e){let t=this.format[e.sheetId];return t?.rowDefault?.[e.row]??t?.colDefault?.[e.col]??t?.sheetDefault}getDefaultStyle(e,t,n,r){return n===`SHEET`?this.style[e]?.[t]?.sheetDefault:n===`COL`?this.style[e]?.[t]?.colDefault?.[r]:this.style[e]?.[t]?.rowDefault?.[r]}getDefaultStyleColors(){let e=new Set;for(let t in this.style){let n=this.style[t];if(n)for(let t of[`fillColor`,`textColor`]){let r=n[t];if(r){r.sheetDefault&&e.add(r.sheetDefault);for(let t of Object.values(r.colDefault??[]))t&&e.add(t);for(let t of Object.values(r.rowDefault??[]))t&&e.add(t)}}}return[...e]}getDefaultFormat(e,t,n){return t===`SHEET`?this.format[e]?.sheetDefault:t===`COL`?this.format[e]?.colDefault?.[n]:this.format[e]?.rowDefault?.[n]}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 D(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};if(r&&!T(this.getCellStyle(a),e.style)||i&&this.getCellFormat(a)!==e.format)return`Success`}return`NoChanges`}mapToId(e,t){let n={colDefault:{},rowDefault:{}};e.sheetDefault&&(n.sheetDefault=hv(e.sheetDefault,t));for(let r in e.colDefault)n.colDefault[r]=hv(e.colDefault[r],t);for(let r in e.rowDefault)n.rowDefault[r]=hv(e.rowDefault[r],t);return n}mapToValue(e,t){let n={colDefault:[],rowDefault:[]};e.sheetDefault&&(n.sheetDefault=t[e.sheetDefault]);for(let r in e.colDefault)n.colDefault[r]=t[e.colDefault[r]];for(let r in e.rowDefault)n.rowDefault[r]=t[e.rowDefault[r]];return n}mapStyleToId(e,t){let n=Sn({}),r=Sn({}),i={};for(let t in e){let a=e[t];a.sheetDefault&&(i[t]=a.sheetDefault);for(let e in a.colDefault)n.get(e)[t]=a.colDefault[e];for(let e in a.rowDefault)r.get(e)[t]=a.rowDefault[e]}let a=[];for(let[e,t]of Object.entries(n.state))a[e]=t;let o=[];for(let[e,t]of Object.entries(r.state))o[e]=t;return this.mapToId({colDefault:a,rowDefault:o,sheetDefault:i},t)}export(e){for(let t of e.sheets){let n=this.format[t.id];t.defaultFormat=n&&!Bt(n)?this.mapToId(n,e.formats):void 0;let r=this.style[t.id];t.defaultStyle=r&&!Bt(r)?this.mapStyleToId(r,e.styles):void 0}}import(e){for(let t of e.sheets)if(this.history.update(`format`,t.id,t.defaultFormat&&this.mapToValue(t.defaultFormat,e.formats)),t.defaultStyle){let n=this.mapToValue(t.defaultStyle,e.styles);for(let e in n.sheetDefault)this.history.update(`style`,t.id,e,`sheetDefault`,n.sheetDefault[e]);for(let e in n.colDefault??[]){let r=parseInt(e),i=n.colDefault?.[e];for(let e in i)this.history.update(`style`,t.id,e,`colDefault`,r,i[e])}for(let e in n.rowDefault??[]){let r=parseInt(e),i=n.rowDefault?.[e];for(let e in i)this.history.update(`style`,t.id,e,`rowDefault`,r,i[e])}}}exportForExcel(e){this.export(e)}},qR=class extends lv{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)}},JR=class extends lv{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=qt(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&&rn([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]=zu(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=Bu(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=Hy(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=Hy(t,e,n.end+1);r.collapsed=!0}}}}}},YR=class extends lv{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=on(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=qt(e.position,e.base),r=t[e.base],i=sn(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)})}}},XR=class extends lv{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`:pn(e.elements)<0||fn(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=qt(e.position,e.base),n=sn([...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 Xt(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])}}},ZR=class extends lv{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]}}},QR=class extends lv{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(ir(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&&ir(n,o)&&(o=er(n,o))}return rr(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:rr(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 rr(t,n);let{numberOfCols:r,numberOfRows:i}=cr(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:ez(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&&ir(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 Cr(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||!rr(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.getCellStyle({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,Yn({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:null,format: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)}o&&this.dispatch(`SET_FORMATTING`,{sheetId:e,target:[t],style:o});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||!rr(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}=cr(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 dr(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,Wn(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...$R(e))}}exportForExcel(e){this.export(e)}};function $R(e){return Object.entries(e).map(([e,t])=>t?ez(parseInt(e,10),t):void 0).filter(w).map(e=>E(e.left,e.top)+`:`+E(e.right,e.bottom))}function ez(e,t){return{...t.zone,id:e}}var tz=class extends lv{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 FN(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=qN.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=fd.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:uC(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||rC(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}},nz=class extends lv{static getters=[`getLocale`];locale=V;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return q_(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===av(e)&&(n=av(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}}},rz=class extends lv{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.getInvisibleSheetIds.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`:case`SET_SHEET_BACKGROUND_COLOR`:return!e.color||Zf(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=pn(e.elements),n=fn(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`,Uu(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`SET_SHEET_BACKGROUND_COLOR`:this.history.update(`sheets`,e.sheetId,`backgroundColor`,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[Uu(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:Ru(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,backgroundColor:t.backgroundColor,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,backgroundColor:t.backgroundColor};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[Uu(e)]}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}getInvisibleSheetIds(){return this.orderedSheetIds.filter(e=>!this.isSheetVisible(e))}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 Vu(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?Xt(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(qn))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>sr(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:Ru(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=>Wu(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:nt.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[Uu(n)],r[Uu(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[Uu(r.name)]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return Hu(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[Uu(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 Dt(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(Wn),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 Cd(e)&&e.ranges.length===0?`EmptyRange`:`sheetId`in e?`ranges`in e&&e.ranges.some(e=>e._sheetId!==``&&!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:Sd(e)&&e.target.length===0?`EmptyTarget`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},iz=class extends lv{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||!qn(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},az=class extends lv{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(!gx[e.templateName])return`InvalidTableStyle`;try{Xf(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=_x(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:ex.styleId}});break}}getTableStyle(e){if(xP[e])return xP[e];if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return _n(P(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!hx[e]&&!xP[e]}import(e){for(let e in hx)this.styles[e]=hx[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=_x(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)hx[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},oz=class extends lv{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 Tr(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(ir(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||ex,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=>!nr(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=>sr(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=>or(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>ir(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,[O(r)]).length)return`none`}return o}isPivotFormula(e,t){return e.startsWith(`=`)?QN(fd.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=vr(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,vr(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 kP(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 kP(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=kP(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<cr(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||ex,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:Yn(e.range.zone),type:e.type};T(e.config,ex)||(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=Yn(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}};let sz=al.mapping;function cz(e,t,n){return new lz(e,t,n).getParameters()}var lz=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(sz),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=nr(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(!qn(e.zone))return new Eo;if(e.invalidSheetName)return new Eo(P(`Invalid sheet name: %s`,e.invalidSheetName))}},uz=class{interval;left;right;max;constructor(e,t=null,n=null){this.interval=e,this.left=t,this.right=n,this.max=e.bottom}},dz=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(fz),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;)fz(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 uz(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 fz(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 pz=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){Pn(this.profilesStartingPosition,this.profiles,[e])}delete(e){Pn(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return Fn(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 zn(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}},mz=class e{setsBySheetId={};constructor(e=[]){for(let t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new pz),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(let t of e)this.add(t)}addPosition(e){this.add(Ou(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(Ou(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(Ou(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]()}},hz=class{forest={};removeAllDependencies(e){}addDependencies(e,t){let n={zone:O(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 mz){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 mz;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 dz,this.forest[e][t]=n),n}},gz=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=_z(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 _z(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var vz=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]=gz.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)}},yz=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),bz=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 xz,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new xz),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)}},xz=class extends yz.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}},Sz=class{resultsToArrayFormulas=new bz;arrayFormulasToResults=new aF;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||Cz}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 Cz=[],wz=new k;wz.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let Tz=Object.freeze(ef({value:null})),Ez={};for(let[e,t]of Object.entries(cd))Ez[t]=e;for(let[e,t]of Object.entries(ld))Ez[t]=e;var Dz=class{context;getters;compilationParams;evaluatedCells=new aF;formulaDependencies=Gt(new hz);blockedArrayFormulas=new vz({});spreadingRelations=new Sz;perfProfile;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=cz(this.context,this.getters,this.computeAndSave.bind(this))}getPerfProfile(){return this.perfProfile}getEvaluatedCell(e){return this.evaluatedCells.get(e)||Tz}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===F.SpilledBlocked)?O(e):er(O(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,O(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=cz(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(e){this.compilationParams=cz(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.__timingEntries=e,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 vz(e)}evaluateCells(e){let t=performance.now(),n=new mz;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`)}evaluateCellsWithoutCascade(e){let t=new mz;t.addManyPositions(e),this.evaluate(t)}getArrayFormulasImpactedByChangesOf(e){let t=new mz;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 Sz,this.formulaDependencies=Gt(()=>{let e=new hz;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(e){let t=performance.now();this.evaluatedCells=new aF;let n=[];for(let e of this.getters.getSheetIds()){let t=this.getters.getSheetZone(e);n.push({sheetId:e,zone:t})}this.evaluate(n,e),console.debug(`evaluate all cells`,performance.now()-t,`ms`)}evaluateFormulaResult(e,t,n){let r=fd.Compile(t,e,this.getters);return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,r)}evaluateCompiledFormula(e,t,n){try{let r=jz(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return ht(r)?is(r,kz):kz(r)}catch(e){return $c(e,``)}}getArrayFormulasBlockedBy(e,t){let n=new mz,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 mz;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e,t){t&&(this.perfProfile=void 0),this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new mz(e);let n=0,r=t?[]:void 0;for(;!this.nextRangesToUpdate.isEmpty()&&n++<30;){this.updateCompilationParameters(r);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)}}wz.getAll().forEach(e=>e(this.getters))}n>=30&&console.warn(`Maximum iteration reached while evaluating cells`),t&&this.processPerfProfile()}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{...Tz,position:e};let r=n.id;try{return this.cellsBeingComputed.has(r)?Mz(e):(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):Jd(n,{format:this.getters.getCellFormat(e),locale:this.getters.getLocale()},e))}catch(t){return t.value=t?.value||F.GenericError,t.message=t?.message||nl,t.origin=e,t.errorOriginPosition=t?.errorOriginPosition,ef(t,this.getters.getLocale(),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=jz(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e),r=this.compilationParams.evalContext.__timingEntries,i=r&&ht(n)?performance.now():0,a=this.postProcessFormulaReturn(e,t,n);if(i){let t=r?.at(-1);t&&t.position.sheetId===e.sheetId&&t.position.col===e.col&&t.position.row===e.row&&(t.time+=performance.now()-i)}return a}postProcessFormulaReturn(e,t,n){let r=this.getters.getCellFormat(e);if(!ht(n)){let t=ef(Az(n),this.getters.getLocale(),e,r,e);return t.type===`error`&&(t.errorOriginPosition=n.errorOriginPosition??e),t}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let i=n.length,a=n[0].length;if(a===0)return ef({value:0},this.getters.getLocale(),e,r);if(a===1&&i===1)return ef(Az(n[0][0]),this.getters.getLocale(),e,r);let o={top:e.row,bottom:e.row+a-1,left:e.col,right:e.col+i-1};return this.spreadingRelations.addRelation({resultZone:o,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),Oz(i,a,this.checkCollision(e)),Oz(i,a,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,o),ef(Az(n[0][0]),this.getters.getLocale(),e,r)}invalidatePositionsDependingOnSpread(e,t){let n=this.getCellsDependingOn(ur(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 ko(P(`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 ko(P(`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 ko(P(`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.getCellFormat(o),c=ef(Az(r[i][a]),this.getters.getLocale(),o,s,o);c.type===`error`&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r},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 Mz(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]),xr(r.range.zone)>1||n?this.compilationParams.ensureRange(r.range):this.compilationParams.referenceDenormalizer(r.range)}return e?.(t,n)||new wo(P(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}processPerfProfile(){let e=this.compilationParams.evalContext.__timingEntries??[],t=Object.groupBy(e,e=>e.functionName),n=0,r=[];for(let e in t){let i=Ez[e]??e,a=Object.groupBy(t[e],({position:e})=>{let t=this.getters.getCell(e);return(t?this.getters.getCellFingerprint(t):void 0)??``});for(let e in a)for(let t of this.mergeIntoRangeTimings(i,a[e]))n+=t.time,r.push(t)}r.sort((e,t)=>t.time-e.time),this.perfProfile={totalTime:n,totalCells:this.evaluatedCells.keys().length,totalFunctionCalls:e.length,entries:r}}mergeIntoRangeTimings(e,t){let n=new aF,r=new mz;for(let{position:e,time:i}of t)n.set(e,(n.get(e)??0)+i),r.addPosition(e);let i=[];for(let{sheetId:t,zone:a}of r){let r=0;for(let e=a.left;e<=a.right;e++)for(let i=a.top;i<=a.bottom;i++)r+=n.get({sheetId:t,col:e,row:i})??0;i.push({functionName:e,range:this.getters.getRangeFromZone(t,a),time:r})}return i}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.rangeDependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}};function Oz(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 kz(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function Az(e){return typeof e.value==`number`&&Math.abs(e.value)>Number.MAX_VALUE?new jo:kz(e)}function jz(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 Mz(e){return ef({...new To,origin:void 0},void 0,e)}var Nz=class extends oF{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getVisibleRangeValues`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`,`getPerfProfile`];shouldRebuildDependenciesGraph=!0;forceEvaluation=!1;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new Dz(e.custom,this.getters)}beforeHandle(e){this.forceEvaluation=!1,(Ed.has(e.type)||Od.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(this.forceEvaluation=!0,!this.getters.isAutomaticEvaluationEnabled())this.shouldRebuildDependenciesGraph=!0;else 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(e.profiling);break}}finalize(){if(!this.shouldPerformEvaluation()){this.positionsToUpdate.length&&this.evaluator.evaluateCellsWithoutCascade(this.positionsToUpdate),this.positionsToUpdate=[];return}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 ht(r)?is(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 dr(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 dr(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}getPerfProfile(){return this.evaluator.getPerfProfile()}shouldPerformEvaluation(){return this.forceEvaluation||this.getters.isAutomaticEvaluationEnabled()}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return dr(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=hv(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===F.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 Pz=new k;Pz.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value,r=e.isDarkMode(),i,a;return n?(i=My(r),a=My(r)):(i=Ay(r),a=jy(r)),{svg:i,hoverSvg:a,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})}}}}),Pz.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:Dy(i),hoverSvg:ky(i),priority:2,horizontalAlign:`right`,size:Df(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`}}),Pz.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:Fy[n].svg,priority:1,horizontalAlign:`left`,size:Df(r),margin:4,position:t}}}),Pz.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??ZS.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?Ny(s,!1):void 0,hoverSvg:o?Ny(s,!0):void 0,position:t,onClick:EC}}}),Pz.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:Df(r),margin:0,svg:n===`asc`?Oy(r):Dy(r),position:t,onClick:void 0}});var Fz=class extends oF{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=Pz.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 Iz=/"(#[0-9a-fA-F]{6})"/g;function Lz(e){let t=[{leadColor:ep(255,0,0),colors:[]},{leadColor:ep(255,128,0),colors:[]},{leadColor:ep(128,128,0),colors:[]},{leadColor:ep(128,255,0),colors:[]},{leadColor:ep(0,255,0),colors:[]},{leadColor:ep(0,255,128),colors:[]},{leadColor:ep(0,255,255),colors:[]},{leadColor:ep(0,127,255),colors:[]},{leadColor:ep(0,0,255),colors:[]},{leadColor:ep(127,0,255),colors:[]},{leadColor:ep(128,0,128),colors:[]},{leadColor:ep(255,0,128),colors:[]}];for(let n of e.map(ip)){let e=500,r=0;t.forEach((t,i)=>{let a=Rz(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>op(e).s-op(t).s)).flat().map(rp)}function Rz(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var zz=class extends oF{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`SET_SHEET_BACKGROUND_COLOR`: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 Lz(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.backgroundColor].filter(w)}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=this.getters.getDefaultStyleColors(),r=new Set(n);for(let e of t)e.style?.textColor&&r.add(e.style.textColor),e.style?.fillColor&&r.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))r.add(t);return[...r]}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(Jf(t.minimum.color)),n.push(t.midpoint?Jf(t.midpoint.color):void 0),n.push(Jf(t.maximum.color)))}return n.filter(w)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getRangeDefinition()).matchAll(Iz)].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(!Zf(t))continue;let e=Xf(t);t&&!Ve.includes(e)&&this.history.update(`customColors`,e,!0)}}},Bz=class extends oF{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(Ed.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=>or(o,s,e.range.zone))){for(let e of n){let t=e.range.zone;ir(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,O(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=>or(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>ir(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(!Tr(t))return!1;let n=er(...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===F.SpilledBlocked&&!e.errorOriginPosition}else if(T(i,r)&&xr(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=kP(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:!dr(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=Wn(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 dr(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(!Bt(i)){let n=hv(i,e.styles);t.styles[o]=n}if(a){let n=hv(a,e.borders);t.borders[o]=n}}}t.tables=n}}};function Vz(e){return{...e,data:{...e.data,datasets:e.data.datasets.filter(e=>!ym(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 vm(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}var Hz=class extends oF{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};handle(e){if(Ed.has(e.type)||kd.has(e.type)||Dd.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){let n=this.getters.getSpreadsheetTheme().backgroundColor;if(e)return{background:e,fontColor:sm(e)};if(!t)return{background:n,fontColor:sm(n)};let r=t.zone.left,i=t.zone.top,a=t.sheetId,o=this.getters.getCellComputedStyle({sheetId:a,col:r,row:i}),s=o.fillColor||n;return{background:s,fontColor:o.textColor||sm(s)}}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 wg(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=Vz(e)}return r}},Uz=class extends oF{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(Ed.has(e.type)||kd.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]=Gt(()=>this.getComputedStyles(e)),this.computedIcons[e]=Gt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=Gt(()=>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 fd.Compile(t,e,this.getters)}),i=Q.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`?fn(a):pn(a);case`number`:return Number(n.value);case`percentage`:let t=pn(a);return t+(fn(a)-t)*Number(n.value)/100;case`percentile`:return mo(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=fn(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});!or(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:Jf(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=Ip(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=Q.get(t.operator),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(i,t,e)??``:$d(t,V));if(o.some(yS))return!1;let s={...t,type:t.operator,values:o.map(_S),dateValue:t.dateValue||`exactDate`};return a.isValueValid(r.value??``,s,n)}};let Wz={isValid:!0};var Gz=class extends oF{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};criterionPreComputeResult={};handle(e){if(Ed.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=Q.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?P(`The value must not be a formula`):this.isValidFormula(t)?void 0:U_.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?P(`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 dr(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 Wz;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:Wz}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:yp(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!fd.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]?.()||Wz}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of Eu(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=Gt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?Wz:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=Q.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,t,o,i);if(s.some(yS))return;let c={...i,values:s.map(_S)};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=>or(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 $d(r,V);let i=fd.Compile(r,e,this.getters),a=this.getters.getTranslatedCellFormula(e,n.col,n.row,i);return this.getters.evaluateFormula(e,a,t)})}};let Kz=[`SUBTOTAL`,`PIVOT`];var qz=class extends oF{static getters=[`getCellsWithTrackedFormula`];trackedCells={};handle(e){switch(e.type){case`START`:for(let e of Kz)this.trackedCells[e]={};for(let e of this.getters.getSheetIds())for(let t of this.getters.getCells(e))for(let e of Kz)bn(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 Kz)bn(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))}},Jz=class extends oF{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=hf();beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=qt(e.position,e.base),n=Array(e.quantity).fill(void 0),r=sn(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=on(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 dr(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 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 gf(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 Yz=`0.00%`;function Xz(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=nC[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return $c(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}=vN(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Do:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=vN(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Do:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return ht(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=vN(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=dC(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:F.NotAvailable,message:P(`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 $c(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:F.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:Yz}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:F.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:Yz}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:F.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:Yz}}asPercentOfParentRowTotal(e,t,n){let r=gN(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:Yz}}asPercentOfParentColumnTotal(e,t,n){let r=_N(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:Yz}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!EN(i,n))return{value:``};let a=wN(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:Yz}}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:F.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}=vN(this,n),u=kN(l),d=kN(c),f=s[u]?.[d];return f===void 0&&(f=this.getPreviousRunningTotalValue(a,n,s)),{value:f??``,format:i===`running_total`?e.format:Yz}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!EN(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:F.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:Yz}:s===void 0?{value:F.NullError}:{value:s/o,format:Yz}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!EN(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(!EN(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:F.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:F.NullError}:{value:(s-o)/o,format:Yz}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!EN(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}=vN(this,n),u=kN(l),d=kN(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=DN(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=os(o));for(let s of o){let o=kN(yN(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:yN(this,i,t.domain)})).filter(e=>EN(t,e.rowDomain)),l=Object.groupBy(c,e=>jN(e.rowDomain,t));for(let e in l)l[e]=hn(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=kN(yN(this,i,e.domain)),a=l[jN(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:gn(r)}computeRunningTotal(e,t,n){let r={},i=DN(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=os(o));for(let s of o){let o=kN(yN(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:yN(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>EN(t,e.rowDomain));for(let e of l){let n=kN(e.rowDomain),i=MN(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=kN(n),a=MN(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:gn(r)}getPreviousRunningTotalValue(e,t,n){let r=this.definition.getDimension(e);if(r.type!==`date`&&r.type!==`datetime`)return;let i=DN(this,e),{rowDomain:a,colDomain:o}=vN(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=kN(c),d=MN(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=MN(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=kN(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&&LS.contains(n)){let t=RS(n).toComparableValue?.(e);if(t!==void 0)return t}return L(e,V)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=vN(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=vN(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)`?ON(this,t,n,r):TN(t,n,r);if(T(i,t))return`sameValue`;if(!i||!xN(this,i))throw new Do;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;yC(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let Zz=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function Qz(e){return Zz.includes(e.type)}var $z=class extends oF{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotCellSortDirection`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`,`getAllPivotArrayFormulas`,`getPivotStyleAtPosition`];pivots={};unusedPivotsInFormulas;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(Ed.has(e.type))for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0});switch(e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.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(Qz);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:mD();break}}getPivotIdFromPosition(e){return this.getPivotIdsFromPosition(e)[0]}getPivotIdsFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getPivotIdsFromFormula(e.sheetId,t.compiledFormula):[]}getPivotIdsFromFormula(e,t){return this.getPivotFunctions(e,t).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=$N(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=NL(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||eP(t.compiledFormula,this.getters)===0)return IN;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!r)return IN;let{functionName:i,args:a}=r,o=a[0];if(!o)return IN;let s=this.getters.getPivotId(o.toString());if(!s)return IN;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!this.isMainFunctionPivotSpreadFunction(t))return IN;try{if(i===`PIVOT`){let t=DC(this.getters.getPivotCoreDefinition(s),_S(a[1]),_S(a[2]),_S(a[3]),_S(a[4]),_S(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=>ht(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:vN(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 IN}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return _n(P(`Calculated measure 1`),t,{compute:(e,t)=>P(`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)&&qN.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=vN(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=Xz(qN.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:DC(this.getters.getPivotCoreDefinition(i),_S(n.args[1]),_S(n.args[2]),_S(n.args[3]),_S(n.args[4]),_S(n.args[5]),this.getters.getLocale()),pivotId:i}}isMainFunctionPivotSpreadFunction(e){return e.compiledFormula.isFirstNonWhitespaceSymbol(`PIVOT`)}};let eB=new k;eB.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=Math.abs(e.current).toString();n=`0`.repeat(Math.max(e.numberPostfixLength-n.length,0))+n;let r=`${e.prefix}${n}`;return{cellData:{border:t.border,style:t.style,format:t.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.style,format:t.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=Jo(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=Ka(r);e.current=i;let a=n.getLocale(),o=H(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.style,format:t.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={sheetId:t.sheetId,col:t.col,row:t.row},a={locale:n.getLocale(),format:n.getCellFormat(i)};return{cellData:{border:t.border,style:t.style,format:t.format,content:r},tooltip:r?{props:{content:t.cell?Jd(t.cell,a,i).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula);return{cellData:{border:t.border,style:t.style,format:t.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let tB=new k,nB=/(\d+)$/,rB=/^(.*\D+)/,iB=/^(.*\D+)(\d+)$/,aB=/^0*/;function oB(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:Jd(a,{locale:V,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function sB(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 cB(e){let t=1;return e.length>=2&&(t=sB(e)*e.length),t}function lB(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 uB(e){if(e.length<2)return 1;let t=e.map(e=>Jo(e,V)),n=lB(dB(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}}tB.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&pc(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&Jd(e,{locale:V}).type===`text`&&iB.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(nB)[0]),i=e.content.match(rB)[0],a=oB(e,t,e=>e.type===`text`&&iB.test(e.value)).filter(e=>i===(e.value??``).toString().match(rB)[0]).map(e=>(e.value??``).toString().match(nB)[0]),o=a.reduce((e,t)=>{let n=t.match(aB)[0].length;return n>e[1]?[t,n]:e},[a[0],0]),s=o[1]?o[0].length:0,c=cB(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&&Jd(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&&Jd(e,{locale:V}).type===`number`&&!!e.format&&pc(e.format),generateRule:(e,t)=>{let n=uB(oB(e,t,e=>e.type===`number`&&!!e.format&&pc(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=Jd(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&&Jd(e,{locale:V}).type===`number`,generateRule:(e,t,n)=>{let r=oB(e,t,e=>e.type===`number`&&!pc(e.format||``)).map(e=>Number(e.value)),i=cB(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=Jd(e,{locale:V});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function dB(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=va.fromTimestamp(e[n-1].getTime()),i=eo(r,t),a=Qa(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:$a(r,t)}}).slice(1)}var fB=class extends cv{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){}},pB=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}=eB.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}}}},mB=class extends fB{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(O({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(O({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:D(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(Wn),[]);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=D(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(or(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??void 0}}getRule(e,t){let n=tB.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}=Nn(t),a={sheetId:r,col:e,row:i},o=this.getters.getCell(a),s=this.getters.getCellStyle(a);Object.keys(s).length===0&&(s=void 0);let c=this.getters.getCellFormat(a);n.push({col:e,row:i,cell:o,sheetId:r,style:s,format:c})}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 pB(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([]))}},hB=class extends fB{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}=or(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)||lr(er(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,er(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=fn(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=Dt(i.filter(e=>this.isNumber(r[e])))[0]||[];return fn(o)<a?1/0:pn(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&pc(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 lr(t)?(n.add(cr(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)},dr(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)},dr(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`))}},gB=class extends fB{static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(Ed.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(vB(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 Gt(()=>{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=jP(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 _B=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 vB(e){return _B.has(e.type)}var yB=class extends fB{static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles=new aF;borders=new aF;handle(e){if(Ed.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`||e.type===`SET_SHEET_BACKGROUND_COLOR`){this.styles=new aF,this.borders=new aF;return}if(vB(e)){`sheetId`in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new aF,this.borders=new aF);return}if(kd.has(e.type)){this.styles=new aF;return}if(Ad.has(e.type)){this.borders=new aF;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=Ae),n}getComputedStyle(e){let t=this.getters.getCellStyle(e),n=this.getters.getCellConditionalFormatStyle(e),r=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e);return{...Zt({fillColor:this.getters.getSheet(e.sheetId)?.backgroundColor}),...Zt(r),...Zt(i),...Zt(t),...Zt(n)}}exportForExcel(e){for(let t of e.sheets){let n={},r=[];for(let e in t.cells){let i={sheetId:t.id,...Nn(e)},a=this.getters.getEvaluatedCell(i),o=this.getComputedStyle(i);if(!a.link||o.textColor)continue;let s=Object.keys(t.styles).find(t=>sr(Wn(e),Wn(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(Wn),s=D([Wn(r)],o);delete t.styles[r];for(let e of s)t.styles[Yn(e)]=n;let c=hv({...a,textColor:Ae},e.styles);for(let e of i)t.styles[e]=c}for(let n of r){let r=this.getters.getCell({sheetId:t.id,...Nn(n)});t.styles[n]=hv({...r?.style,textColor:Ae},e.styles)}}}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...Zt(this.getters.getCellTableBorder(e)||{}),...Zt(t)};return Bt(n)?null:n}},bB=class extends fB{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 xB(e){let t=Au.get(e.type)?.(e),n=wB(e);if(!t&&!n)return;let r=t||CB(),i=n||(e=>e),a=SB(r.applyChange);return{applyChange:a,adaptRangeString:(e,t)=>qu(e,t,r),adaptFormulaString:(e,t)=>Gu(e,t,r,i),adaptCompiledFormula:e=>e.adaptCompiledFormula(a,i)}}function SB(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!qn(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}function CB(){return{applyChange:e=>({changeType:`NONE`,range:e}),sheetId:`ignoredSheetId`,sheetName:{old:`ignoredSheetName`,current:`ignoredSheetName`}}}function wB(e){if(e.type!==`UPDATE_NAMED_RANGE`)return;let t=e.oldRangeName.toLowerCase();return n=>n.toLowerCase()===t?e.newRangeName:n}let TB=new class extends k{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)}},EB=new class extends k{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};TB.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],zB),TB.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],zB),TB.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],AB),TB.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`,`UPDATE_CAROUSEL`],jB),TB.addTransformation(`DELETE_CHART`,[`UPDATE_CHART`],MB),TB.addTransformation(`DELETE_CHART`,[`UPDATE_CAROUSEL`],NB),TB.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],PB),TB.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],FB),TB.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],IB),TB.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],IB),TB.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],LB),TB.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],LB),TB.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],RB),TB.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],BB),TB.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],BB),TB.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],kB),TB.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],OB),TB.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],DB),TB.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],DB),TB.addTransformation(`UPDATE_NAMED_RANGE`,[`UPDATE_NAMED_RANGE`,`DELETE_NAMED_RANGE`],VB);function DB(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=Mr(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function OB(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function kB(e,t){if(e.pivotId!==t.pivotId)return e}function AB(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function jB(e,t){if(e.figureId!==t.figureId)return e}function MB(e,t){if(e.chartId!==t.chartId)return e}function NB(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!(e.type===`chart`&&e.chartId===t.chartId))}}}function PB(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 FB(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!ir(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function IB(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 LB(e,t){if(e.sheetId!==t.sheetId)return e;let n=Mr(e.zone,t);if(!n)return;let r=e.newTableRange?Nr(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function RB(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:ex.styleId}}:e}function zB(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=Bu(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=zu(qt(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function BB(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=Bu(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=zu(qt(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function VB(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 HB(e,{adaptFormulaString:t}){let n=e.content&&t(e.sheetId,e.content);return{...e,content:n}}EB.add(`UPDATE_CELL`,HB);function UB(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}EB.add(`ADD_CONDITIONAL_FORMAT`,UB);function WB(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}EB.add(`ADD_DATA_VALIDATION_RULE`,WB);function GB(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}EB.add(`ADD_PIVOT`,GB),EB.add(`UPDATE_PIVOT`,GB),EB.add(`CREATE_CHART`,KB),EB.add(`UPDATE_CHART`,KB);function KB(e,t){return{...e,definition:gk.transformDefinition(e.sheetId,e.definition,t)}}let qB=[{match:bd,fn:QB},{match:Sd,fn:$B},{match:Td,fn:eV},{match:wd,fn:rV},{match:xd,fn:nV},{match:Cd,fn:tV}];function JB(e,t){let n=TB.getTransformation(e.type,t.type),r=n?n(e,t):ZB(e,t);return r&&YB(r,t)}function YB(e,t){let n=EB.get(e.type);if(!n)return e;let r=xB(t);return r?n(e,r):e}function XB(e,t){let n=[...e],r=new Set(TB.getKeys());for(let e of t)(r.has(e.type)||Au.contains(e.type))&&(n=n.reduce((t,n)=>{let r=JB(n,e);return r&&t.push(r),t},[]));return n}function ZB(e,t){for(let{match:n,fn:r}of qB)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function QB(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 $B(e,t){let n=QB(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=Mr(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function eV(e,t){let n=QB(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=Mr(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function tV(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>Nr(e,t)).filter(w);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function nV(e,t){let n=QB(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=Bu(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=zu(qt(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function rV(e,t){let n=QB(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?iV(e,t):t.type===`ADD_MERGE`?aV(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function iV(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 aV(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&or(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var oV=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}},sV=class extends Error{},cV=class extends Wi{revisions;transportService;serverRevisionId;commandSquisher;clients={};clientId=`local`;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;lastLocalOperation;constructor(e,t,n=Xe,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 oV(G.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:G.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:G.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=G.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 sV(`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 oV(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:XB(r,t)})}break;case`SNAPSHOT_CREATED`:{let t=new oV(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.
|
|
114
|
-
${JSON.stringify(e)}`);this.waitingAck=!0,this.sendToTransport({...e,serverRevisionId:this.serverRevisionId}).catch(e=>{if(!(e instanceof sV))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`)}},lV=class extends fB{static getters=[`getClientsToDisplay`,`getClient`,`getCurrentClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];colors=new Np(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 sV)return[];throw e}let
|
|
113
|
+
/>`;props=(0,t.useProps)({topOffset:N.number().optional(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:`${t}px`}}onScroll(e){let{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:t,offsetY:e})}},ER=class extends A{static template=`o-spreadsheet-Selection`;static components={Highlight:xR};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:Oe}}},DR=class extends A{static template=`o-spreadsheet-TableResizer`;props=(0,t.useProps)({table:N.Table()});state=(0,t.proxy)({highlightZone:void 0});dragNDropGrid=uL(this.env);setup(){LA(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=tg(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 OR={ROW:oL,COL:$I,CELL:FI,GROUP_HEADERS:iL,UNGROUP_HEADERS:aL};var kR=class extends A{static template=`o-spreadsheet-Grid`;static components={GridComposer:zL,GridOverlay:rR,GridPopover:iR,HeadersOverlay:dR,MenuPopover:w_,Autofill:fL,ClientTag:mL,Highlight:xR,Popover:b_,VerticalScrollBar:TR,HorizontalScrollBar:wR,TableResizer:DR,Selection:ER};props=(0,t.useProps)({exposeFocus:N.function(),getGridSize:N.function()});HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef=(0,t.signal)(null);canvasRef=(0,t.signal)(null);highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=uL(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=j(ME),this.menuState=(0,t.proxy)({isOpen:!1,anchorRect:null,menuItems:[]}),this.hoveredCell=j(N_),this.composerFocusStore=j(Ur),this.DOMFocusableElementStore=j(l_),this.sidePanel=j(rF),this.paintFormatStore=j($L),this.clientFocusStore=j(cL),j(sL),Hi({getPopoverContainerRect:()=>this.getGridRect()}),Ii(document.body,`cut`,this.copy.bind(this,!0)),Ii(document.body,`copy`,this.copy.bind(this,!1)),Ii(document.body,`paste`,this.paste),(0,t.onMounted)(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),pR({canvasRef:this.canvasRef,renderingCtx:()=>({dpr:window.devicePixelRatio||1,viewports:this.env.model.getters.getViewportCollection(),...this.env.model.getters.getSelectionState()})}),this.onMouseWheel=_R((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=j(lw),Li((e,t)=>{!e&&!t&&this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),hR(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`),F9:()=>this.env.model.dispatch(`EVALUATE_CELLS`),"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":()=>cT(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&&Kd(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":()=>{rw(this.env,{type:`COPY_PASTE_CELLS_ABOVE`})},"Ctrl+R":()=>{rw(this.env,{type:`COPY_PASTE_CELLS_ON_LEFT`})},"Ctrl+Enter":()=>{rw(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":()=>Lw(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?$w(this.env):i&&!r&&Zw(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":()=>{tE.execute?.(this.env)},"Alt+T":()=>{HT.execute?.(this.env)},PageDown:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_DOWN`),PageUp:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_UP`),"Ctrl+Shift+K":()=>{this.closeMenu(),dT(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}OE(this.env.model.getters,this.env.model.selection,e)}moveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.env.model.selection.moveAnchorCell(e,1);return}OE(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.getSelectedFigureIds().length&&this.composerFocusStore.activeComposer.editionMode===`inactive`&&this.DOMFocusableElementStore.focus()}get gridEl(){let e=this.gridRef();if(!e)throw Error(`Grid el is not defined.`);return e}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{...y(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(),DE(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=se(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`;or(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=OR[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?zF(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=>dw.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()===gw(r.content[`text/html`]))ow(this.env,i);else{let e=hw(r.content);await sw(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(!LF(this.env,`COL`)&&!LF(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(AP)}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 AR=new k;AR.add(`SPREADSHEET`,!1);var jR=class extends A{static template=`o-spreadsheet-ClickableCellSortIcon`;props=(0,t.useProps)({position:N.CellPosition(),sortDirection:N.or([N.SortDirection,N.literal(`none`)])});hoveredTableStore;setup(){this.hoveredTableStore=j(eR)}get style(){let e=this.env.model.getters.getCellComputedStyle(this.props.position),t=Df(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?lp(e.fillColor||`#FFFFFF`,t):e.fillColor||`#FFFFFF`}},MR=class extends A{static template=`o-spreadsheet-FullScreenFigure`;static components={ChartFigure:k_};fullScreenFigureStore;fullScreenFigureRef=(0,t.signal)(null);spreadsheetRect=v_();figureRegistry=j_;setup(){this.fullScreenFigureStore=j(c_);let e=j(ha),n;(0,t.onWillUpdateProps)(()=>{n!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+`-fullscreen`),n=this.figureUI?.id}),(0,t.useEffect)(()=>this.fullScreenFigureRef()?.focus())}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 j_.get(this.figureUI.tag).Component}},NR=class extends A{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:wE};props=(0,t.useProps)({pivotId:N.UID(),onCellClicked:N.function()});pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.proxy)({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(R(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${cC(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(${cC(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(${cC(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=R(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(${cC(e,o,a).join(`,`)})`,value:H(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},PR=l({GHOST_SUNBURST_VALUE:()=>nh,canChartParseLabels:()=>LD,getBarChartData:()=>_D,getBarChartDatasets:()=>rh,getBarChartLegend:()=>pO,getBarChartScales:()=>Lm,getBarChartTooltip:()=>zO,getBubbleChartData:()=>OD,getBubbleChartDatasets:()=>lh,getBubbleChartLegend:()=>vO,getBubbleChartScales:()=>Wm,getBubbleChartTooltip:()=>HO,getCalendarChartData:()=>bD,getCalendarChartDatasetAndLabels:()=>ah,getCalendarChartLayout:()=>eO,getCalendarChartScales:()=>Rm,getCalendarChartShowValues:()=>AO,getCalendarChartTooltip:()=>BO,getCalendarColorScale:()=>zm,getChartColorsGenerator:()=>Eh,getChartLabelFormat:()=>YD,getChartLayout:()=>$D,getChartShowValues:()=>kO,getChartTitle:()=>FO,getComboChartDatasets:()=>fh,getComboChartLegend:()=>yO,getFunnelChartData:()=>ED,getFunnelChartDatasets:()=>hh,getFunnelChartScales:()=>Ym,getFunnelChartTooltip:()=>JO,getFunnelLabelColors:()=>gh,getGeoChartData:()=>TD,getGeoChartDatasets:()=>mh,getGeoChartScales:()=>Jm,getGeoChartTooltip:()=>qO,getHierarchalChartData:()=>DD,getLineChartData:()=>SD,getLineChartDatasets:()=>sh,getLineChartLegend:()=>hO,getLineChartScales:()=>Bm,getLineChartTooltip:()=>VO,getPieChartData:()=>CD,getPieChartDatasets:()=>dh,getPieChartLegend:()=>gO,getPieChartTooltip:()=>UO,getPyramidChartData:()=>xD,getPyramidChartLegend:()=>mO,getPyramidChartScales:()=>Km,getPyramidChartShowValues:()=>MO,getPyramidChartTooltip:()=>GO,getRadarChartData:()=>wD,getRadarChartDatasets:()=>ph,getRadarChartLegend:()=>xO,getRadarChartScales:()=>qm,getRadarChartTooltip:()=>KO,getRuntimeColorScale:()=>$m,getScatterChartDatasets:()=>ch,getScatterChartLegend:()=>_O,getScatterChartScales:()=>Um,getSunburstChartDatasets:()=>_h,getSunburstChartLegend:()=>SO,getSunburstChartTooltip:()=>YO,getSunburstShowValues:()=>jO,getTopPaddingForDashboard:()=>QD,getTreeMapChartDatasets:()=>Sh,getTreeMapChartTooltip:()=>XO,getTrendDatasetForBarChart:()=>AD,getTrendDatasetForLineChart:()=>jD,getWaterfallChartLegend:()=>bO,getWaterfallChartScales:()=>Gm,getWaterfallChartShowValues:()=>NO,getWaterfallChartTooltip:()=>WO,getWaterfallDatasetAndLabels:()=>oh,makeDatasetsCumulative:()=>ZD}),FR=class extends lv{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||Ye.style,color:e.border.color||Ye.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 Dt(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 D(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 D(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 _v(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,Wn(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=hv(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=gv(e)}e.borders=t}exportForExcel(e){this.export(e)}},IR=class extends lv{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]})}}},LR=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=fd.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=Yd(this.getters,-1,e.content,e.format??void 0,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=Nn(n[i]),o=0;for(o=0;o+i+1<n.length;o++){let t=Nn(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),Cu(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),Cu(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),Cu(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)}`:Cu(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 RR(e){return[Nn(e)]}function*zR(e,t){let n=Nn(e),r=Nn(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 BR=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=zR(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:Nn(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?RR(a):zR(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=fd.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:fd.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:fd.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=Xd(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 fd.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}}}},VR=class extends lv{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`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`;default:return`Success`}}handle(e){switch(e.type){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:null});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 D(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})}}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:null})}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 aF,i=new BR;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 _v(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 LR(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=E(l.col,l.row);if(c.style&&Object.keys(c.style).length){let e=hv(c.style,n);a[e]??=[],a[e].push(l)}if(c.format){let e=hv(c.format,r);o[e]??=[],o[e].push(l)}c.isFormula?s[u]=t?e.squish(c,i.id):c.compiledFormula.toFormulaString(this.getters):c.content&&(s[u]=t?e.squish(c,i.id):c.content)}i.styles=gv(a),i.formats=gv(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?Qd(a,i,r,n):Yd(this.getters,a,t||``,r,n,e,{avoidAutomaticDateFormat:!0})}exportForExcel(e){this.export(e,!1);let t=[];for(let n in e.formats||[])Pc(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}getCells(e){return 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 fd.CopyWithDependencies(t,e,n).toFormulaString(this.getters,{useBoundedReference:r})}getTranslatedCellFormula(e,t,n,r){r instanceof fd||(r=fd.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 fd.CopyWithDependencies(t,e,n).toFormulaString(this.getters)}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}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={sheetId:e,col:t,row:n},a=this.getters.getCell(i),o=r.content!==void 0||`formula`in r,s;s=o?nn(r?.content):a?.isFormula?a.compiledFormula.toFormulaString(this.getters):a?.content||``;let c;if(r.style!==void 0){let e=Object.fromEntries(Object.entries(r.style??{}).filter(([e,t])=>t!==this.getters.getCellDefaultStyleValue(i,e)));c=Bt(e)?void 0:e}else c=a?.style;let l;if(r.format!==void 0){let e=this.getters.getCellDefaultFormat(i);l=r.format===null?void 0:r.format,(l??``)===(e??``)&&(l=void 0)}else l=a?.format;if((o&&!s&&!r.formula||!o&&(!a||!a.isFormula&&a.content===``))&&!c&&l===void 0){a&&(this.history.update(`cells`,e,a.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let u=a?.id||this.getNextCellId(),d=Yd(this.getters,u,s,l,c,e);this.history.update(`cells`,e,d.id,d),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:d.id,col:t,row:n,sheetId:e})}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?or(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`}},HR=class extends lv{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=gk.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=gk.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=gk.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=gk.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 gk.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 UR(e){return e===``?NaN:Number(e)}var WR=class extends lv{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)or(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(Un));let s=D(o,r);return D([...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 lj.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=Q.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(fd.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&&UR(t)>=UR(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&&UR(t)>=UR(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&&UR(t)>=UR(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&fd.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)}},GR=class extends lv{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=>wu(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=D(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(or(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 Eu(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:!e?.style?.align||e.style.align==="default"?`center`:e.style.align,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 Q.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=Q.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=Q.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||fd.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`}},KR=class extends lv{static getters=[`getCellStyle`,`getDefaultStyle`,`getCellDefaultStyleValue`,`getCellFormat`,`getCellDefaultFormat`,`getDefaultFormat`,`getDefaultStyleColors`];style={};format={};allowDispatch(e){return e.type===`SET_FORMATTING`?this.checkUselessSetFormatting(e):`Success`}handle(e){switch(e.type){case`SET_FORMATTING`:e.style!==void 0&&this.setStyle(e.sheetId,e.target,e.style),e.format!==void 0&&this.setFormat(e.sheetId,e.target,e.format);break;case`CLEAR_FORMATTING`:this.setStyle(e.sheetId,e.target,Ue),this.setFormat(e.sheetId,e.target,null);break;case`ADD_COLUMNS_ROWS`:let t=e.position===`before`?e.base:e.base+1;this.moveColRows(e.sheetId,e.dimension,t,e.quantity);let n=e.position===`before`?e.base+e.quantity:e.base;for(let r=t;r<t+e.quantity;r++)this.copyColRow(e.sheetId,e.dimension,n,r);break;case`REMOVE_COLUMNS_ROWS`:for(let t of Dt(e.elements).toReversed()){for(let n of t)this.clearColRows(e.sheetId,e.dimension,n);this.moveColRows(e.sheetId,e.dimension,t[0],-t.length)}break;case`DUPLICATE_SHEET`:this.history.update(`style`,e.sheetIdTo,x(this.style[e.sheetId])),this.history.update(`format`,e.sheetIdTo,x(this.format[e.sheetId]));break}}clearColRows(e,t,n){let r=t===`COL`?`colDefault`:`rowDefault`;for(let t in this.style[e])this.history.update(`style`,e,t,r,n,void 0);this.history.update(`format`,e,r,n,void 0)}moveColRows(e,t,n,r){let i=t===`COL`?`colDefault`:`rowDefault`;for(let t in this.style[e]){let a=Object.entries(this.style[e][t]?.[i]??[]);r>0&&a.reverse();for(let[o,s]of a){let a=parseInt(o);a<n||(this.history.update(`style`,e,t,i,a+r,s),this.history.update(`style`,e,t,i,a,void 0))}}let a=Object.entries(this.format[e]?.[i]??[]);r>0&&a.reverse();for(let[t,o]of a){let a=parseInt(t);a<n||(this.history.update(`format`,e,i,a+r,o),this.history.update(`format`,e,i,a,void 0))}}copyColRow(e,t,n,r){let i=t===`COL`?`colDefault`:`rowDefault`;for(let t in this.style[e]){let a=this.style[e][t]?.[i]?.[n];this.history.update(`style`,e,t,i,r,a)}this.history.update(`format`,e,i,r,this.format[e]?.[i]?.[n])}setFormat(e,t,n){t=D(t);let{numberOfCols:r,numberOfRows:i}=this.getters.getSheetSize(e),a=r*i;for(let o of t){let t=o.bottom-o.top+1>i/2,s=o.right-o.left+1>r/2;s&&t&&xr(o)>a/2?this.setSheetFormat(e,o,n):t?this.setColsFormat(e,o,n??``):s?this.setRowsFormat(e,o,n??``):this.updateCellsFormat(e,o,n??``)}}setSheetFormat(e,t,n){this.updateCellsFormat(e,t,null);let r=this.getters.getSheetZone(e),i=this.getters.getRowsZone(e,t.top,t.bottom),a=D([i],[t]),o=this.getDefaultFormatInCell(e,a,{shouldUseDefaultSheet:!0,shouldUseDefaultRow:!0}),s=this.getters.getColsZone(e,t.left,t.right),c=D([s],[t]);o.push(...this.getDefaultFormatInCell(e,c,{shouldUseDefaultSheet:!0,shouldUseDefaultCol:!0}));let l=D([r],[i,s]);o.push(...this.getDefaultFormatInCell(e,l,{shouldUseDefaultSheet:!0})),this.history.update(`format`,e,`sheetDefault`,n??void 0);let u=Object.keys(this.format[e]?.rowDefault??{});for(let n of u){let r=parseInt(n);t.top<=r&&r<=t.bottom&&this.history.update(`format`,e,`rowDefault`,r,void 0)}let d=Object.keys(this.format[e]?.colDefault??{});for(let n of d){let r=parseInt(n);t.left<=r&&r<=t.right&&this.history.update(`format`,e,`colDefault`,r,void 0)}for(let[e,t]of o)this.updateCellFormat(e,t)}setColsFormat(e,t,n){this.updateCellsFormat(e,t,null);let r=D([this.getters.getColsZone(e,t.left,t.right)],[t]),i=this.getDefaultFormatInCell(e,r,{shouldUseDefaultSheet:!0,shouldUseDefaultCol:!0}),a=Object.keys(this.format[e]?.rowDefault??{}),o=n===(this.format[e]?.sheetDefault??``)?void 0:n;for(let r=t.left;r<=t.right;r++){this.history.update(`format`,e,`colDefault`,r,o);for(let i of a){let a=parseInt(i);t.top<=a&&a<=t.bottom&&this.updateCellFormat({col:r,row:a,sheetId:e},n)}}for(let[e,t]of i)this.updateCellFormat(e,t)}setRowsFormat(e,t,n){this.updateCellsFormat(e,t,null);let r=D([this.getters.getRowsZone(e,t.top,t.bottom)],[t]),i=this.getDefaultFormatInCell(e,r,{shouldUseDefaultSheet:!0,shouldUseDefaultCol:!0,shouldUseDefaultRow:!0});for(let r=t.top;r<=t.bottom;r++)this.history.update(`format`,e,`rowDefault`,r,n);for(let[e,t]of i)this.updateCellFormat(e,t)}updateCellsFormat(e,t,n){for(let r=t.left;r<=t.right;r++)for(let i=t.top;i<=t.bottom;i++)this.updateCellFormat({sheetId:e,col:r,row:i},n)}updateCellFormat(e,t){(t??``)===(this.getCellDefaultFormat(e)??``)?this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,format:null}):this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,format:t})}getDefaultFormatInCell(e,t,n){let r=[];for(let i of t.flatMap(t=>fr(e,t))){if(this.getters.getCell(i)?.format)continue;let t=this.format[e]?.rowDefault?.[i.row];if(t){n.shouldUseDefaultRow&&r.push([i,t]);continue}let a=this.format[e]?.colDefault?.[i.col];if(a){n.shouldUseDefaultCol&&r.push([i,a]);continue}let o=this.format[e]?.sheetDefault;if(o){n.shouldUseDefaultSheet&&r.push([i,o]);continue}}return r}setStyle(e,t,n){t=D(t);let{numberOfCols:r,numberOfRows:i}=this.getters.getSheetSize(e),a=r*i;for(let o of t){let t=o.bottom-o.top+1>i/2,s=o.right-o.left+1>r/2;s&&t&&xr(o)>a/2?this.setSheetStyle(e,o,n):t?this.setColsStyle(e,o,n):s?this.setRowsStyle(e,o,n):this.updateCellsStyle(e,o,n)}}setSheetStyle(e,t,n){this.clearCellStyle(e,t,n);let r=this.getters.getSheetZone(e),i=this.getters.getRowsZone(e,t.top,t.bottom),a=D([i],[t]),o=this.getPartialDefaultStyleInCell(e,a,n,{shouldUseDefaultSheet:!0,shouldUseDefaultRow:!0}),s=this.getters.getColsZone(e,t.left,t.right),c=D([s],[t]);o.push(...this.getPartialDefaultStyleInCell(e,c,n,{shouldUseDefaultSheet:!0,shouldUseDefaultCol:!0}));let l=D([r],[i,s]);o.push(...this.getPartialDefaultStyleInCell(e,l,n,{shouldUseDefaultSheet:!0}));for(let r in n){n[r]===Ue[r]?this.history.update(`style`,e,r,`sheetDefault`,void 0):this.history.update(`style`,e,r,`sheetDefault`,n[r]);let i=Object.keys(this.style[e]?.[r]?.rowDefault??{});for(let n of i){let i=parseInt(n);t.top<=i&&i<=t.bottom&&this.history.update(`style`,e,r,`rowDefault`,i,void 0)}let a=Object.keys(this.style[e]?.[r]?.colDefault??{});for(let n of a){let i=parseInt(n);t.left<=i&&i<=t.right&&this.history.update(`style`,e,r,`colDefault`,i,void 0)}}for(let[e,t]of o)this.updateCellStyle(e,t)}setColsStyle(e,t,n){this.clearCellStyle(e,t,n);let r=D([this.getters.getColsZone(e,t.left,t.right)],[t]),i=this.getPartialDefaultStyleInCell(e,r,n,{shouldUseDefaultSheet:!0,shouldUseDefaultCol:!0}),a=new aF;for(let r in n){let i=Object.keys(this.style[e]?.[r]?.rowDefault??{}),o=n[r]===(this.style[e]?.[r]?.sheetDefault??Ue[r])?void 0:n[r];for(let s=t.left;s<=t.right;s++){this.history.update(`style`,e,r,`colDefault`,s,o);for(let o of i){let i=parseInt(o);if(t.top<=i&&i<=t.bottom){let t={col:s,row:i,sheetId:e},o=a.get(t);if(o)o[r]=n[r];else{let e={};e[r]=n[r],a.set(t,e)}}}}}for(let[e,t]of a.entries())this.updateCellStyle(e,t);for(let[e,t]of i)this.updateCellStyle(e,t)}setRowsStyle(e,t,n){this.clearCellStyle(e,t,n);let r=D([this.getters.getRowsZone(e,t.top,t.bottom)],[t]),i=this.getPartialDefaultStyleInCell(e,r,n,{shouldUseDefaultSheet:!0,shouldUseDefaultCol:!0,shouldUseDefaultRow:!0});for(let r in n){let i=Object.keys(this.style[e]?.[r]?.colDefault??{}).length!==0;for(let a=t.top;a<=t.bottom;a++)i||n[r]!==(this.style[e]?.[r]?.sheetDefault??Ue[r])?this.history.update(`style`,e,r,`rowDefault`,a,n[r]):this.history.update(`style`,e,r,`rowDefault`,a,void 0)}for(let[e,t]of i)this.updateCellStyle(e,t)}updateCellsStyle(e,t,n,r){for(let i=t.left;i<=t.right;i++)for(let a=t.top;a<=t.bottom;a++)this.updateCellStyle({sheetId:e,col:i,row:a},n,r)}updateCellStyle(e,t,n){let r=this.getters.getCell(e),i=n?.cellPriority?{...t,...r?.style}:{...r?.style,...t};this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,style:i})}clearCellStyle(e,t,n){for(let r=t.top;r<=t.bottom;r++)for(let i of this.getters.getRowCellIds(e,r)){let a=this.getters.getCellPosition(i).col;if(a<t.left||t.right<a)continue;let o=this.getters.getCellById(i)?.style;if(!o)continue;o={...o};let s=!1;for(let e in n)o[e]!==void 0&&(s=!0,delete o[e]);s&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:r,style:Object.keys(o).length===0?null:o})}}getPartialDefaultStyleInCell(e,t,n,r){let i=[];for(let a of t.flatMap(t=>fr(e,t))){let e=this.getters.getCell(a)?.style??{},t={},o=!1,s=this.style[a.sheetId];for(let i in n){if(i in e)continue;let c=s?.[i];if(!c){n[i]!==Ue[i]&&(t[i]=Ue[i],o=!0);continue}let l=c.rowDefault?.[a.row];if(l!==void 0){r.shouldUseDefaultRow&&(t[i]=l,o=!0);continue}let u=c.colDefault?.[a.col];if(u!==void 0){r.shouldUseDefaultCol&&(t[i]=u,o=!0);continue}let d=c.sheetDefault;if(d!==void 0){r.shouldUseDefaultSheet&&(t[i]=d,o=!0);continue}n[i]!==Ue[i]&&(t[i]=Ue[i],o=!0)}o&&i.push([a,t])}return i}getCellStyle(e){let t=this.getters.getCell(e),n=this.style[e.sheetId];if(!n)return t?.style??{};let r={...t?.style};for(let t in n)if(!(t in r)){let i=n[t];if(!i)continue;let a=i.rowDefault?.[e.row]??i.colDefault?.[e.col]??i.sheetDefault;a!==void 0&&(r[t]=a)}return r}getCellDefaultStyleValue(e,t){let n=this.style[e.sheetId]?.[t];return n?.rowDefault?.[e.row]??n?.colDefault?.[e.col]??n?.sheetDefault??Ue[t]}getCellFormat(e){let t=this.getters.getCell(e);return t?.format===void 0?this.getCellDefaultFormat(e):t?.format}getCellDefaultFormat(e){let t=this.format[e.sheetId];return t?.rowDefault?.[e.row]??t?.colDefault?.[e.col]??t?.sheetDefault}getDefaultStyle(e,t,n,r){return n===`SHEET`?this.style[e]?.[t]?.sheetDefault:n===`COL`?this.style[e]?.[t]?.colDefault?.[r]:this.style[e]?.[t]?.rowDefault?.[r]}getDefaultStyleColors(){let e=new Set;for(let t in this.style){let n=this.style[t];if(n)for(let t of[`fillColor`,`textColor`]){let r=n[t];if(r){r.sheetDefault&&e.add(r.sheetDefault);for(let t of Object.values(r.colDefault??[]))t&&e.add(t);for(let t of Object.values(r.rowDefault??[]))t&&e.add(t)}}}return[...e]}getDefaultFormat(e,t,n){return t===`SHEET`?this.format[e]?.sheetDefault:t===`COL`?this.format[e]?.colDefault?.[n]:this.format[e]?.rowDefault?.[n]}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 D(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};if(r&&!T(this.getCellStyle(a),e.style)||i&&this.getCellFormat(a)!==e.format)return`Success`}return`NoChanges`}mapToId(e,t){let n={colDefault:{},rowDefault:{}};e.sheetDefault&&(n.sheetDefault=hv(e.sheetDefault,t));for(let r in e.colDefault)n.colDefault[r]=hv(e.colDefault[r],t);for(let r in e.rowDefault)n.rowDefault[r]=hv(e.rowDefault[r],t);return n}mapToValue(e,t){let n={colDefault:[],rowDefault:[]};e.sheetDefault&&(n.sheetDefault=t[e.sheetDefault]);for(let r in e.colDefault)n.colDefault[r]=t[e.colDefault[r]];for(let r in e.rowDefault)n.rowDefault[r]=t[e.rowDefault[r]];return n}mapStyleToId(e,t){let n=Sn({}),r=Sn({}),i={};for(let t in e){let a=e[t];a.sheetDefault&&(i[t]=a.sheetDefault);for(let e in a.colDefault)n.get(e)[t]=a.colDefault[e];for(let e in a.rowDefault)r.get(e)[t]=a.rowDefault[e]}let a=[];for(let[e,t]of Object.entries(n.state))a[e]=t;let o=[];for(let[e,t]of Object.entries(r.state))o[e]=t;return this.mapToId({colDefault:a,rowDefault:o,sheetDefault:i},t)}export(e){for(let t of e.sheets){let n=this.format[t.id];t.defaultFormat=n&&!Bt(n)?this.mapToId(n,e.formats):void 0;let r=this.style[t.id];t.defaultStyle=r&&!Bt(r)?this.mapStyleToId(r,e.styles):void 0}}import(e){for(let t of e.sheets)if(this.history.update(`format`,t.id,t.defaultFormat&&this.mapToValue(t.defaultFormat,e.formats)),t.defaultStyle){let n=this.mapToValue(t.defaultStyle,e.styles);for(let e in n.sheetDefault)this.history.update(`style`,t.id,e,`sheetDefault`,n.sheetDefault[e]);for(let e in n.colDefault??[]){let r=parseInt(e),i=n.colDefault?.[e];for(let e in i)this.history.update(`style`,t.id,e,`colDefault`,r,i[e])}for(let e in n.rowDefault??[]){let r=parseInt(e),i=n.rowDefault?.[e];for(let e in i)this.history.update(`style`,t.id,e,`rowDefault`,r,i[e])}}}exportForExcel(e){this.export(e)}},qR=class extends lv{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)}},JR=class extends lv{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=qt(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&&rn([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]=zu(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=Bu(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=Hy(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=Hy(t,e,n.end+1);r.collapsed=!0}}}}}},YR=class extends lv{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=on(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=qt(e.position,e.base),r=t[e.base],i=sn(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)})}}},XR=class extends lv{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`:pn(e.elements)<0||fn(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=qt(e.position,e.base),n=sn([...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 Xt(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])}}},ZR=class extends lv{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]}}},QR=class extends lv{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(ir(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&&ir(n,o)&&(o=er(n,o))}return rr(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:rr(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 rr(t,n);let{numberOfCols:r,numberOfRows:i}=cr(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:ez(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&&ir(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 Cr(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||!rr(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.getCellStyle({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,Yn({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:null,format: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)}o&&this.dispatch(`SET_FORMATTING`,{sheetId:e,target:[t],style:o});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||!rr(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}=cr(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 dr(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,Wn(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...$R(e))}}exportForExcel(e){this.export(e)}};function $R(e){return Object.entries(e).map(([e,t])=>t?ez(parseInt(e,10),t):void 0).filter(w).map(e=>E(e.left,e.top)+`:`+E(e.right,e.bottom))}function ez(e,t){return{...t.zone,id:e}}var tz=class extends lv{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 FN(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=qN.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=fd.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:uC(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||rC(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}},nz=class extends lv{static getters=[`getLocale`];locale=V;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return q_(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===av(e)&&(n=av(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}}},rz=class extends lv{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.getInvisibleSheetIds.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`:case`SET_SHEET_BACKGROUND_COLOR`:return!e.color||Zf(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=pn(e.elements),n=fn(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`,Uu(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`SET_SHEET_BACKGROUND_COLOR`:this.history.update(`sheets`,e.sheetId,`backgroundColor`,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[Uu(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:Ru(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,backgroundColor:t.backgroundColor,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,backgroundColor:t.backgroundColor};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[Uu(e)]}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}getInvisibleSheetIds(){return this.orderedSheetIds.filter(e=>!this.isSheetVisible(e))}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 Vu(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?Xt(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(qn))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>sr(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:Ru(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=>Wu(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:nt.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[Uu(n)],r[Uu(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[Uu(r.name)]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return Hu(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[Uu(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 Dt(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(Wn),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 Cd(e)&&e.ranges.length===0?`EmptyRange`:`sheetId`in e?`ranges`in e&&e.ranges.some(e=>e._sheetId!==``&&!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:Sd(e)&&e.target.length===0?`EmptyTarget`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},iz=class extends lv{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||!qn(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},az=class extends lv{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(!gx[e.templateName])return`InvalidTableStyle`;try{Xf(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=_x(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:ex.styleId}});break}}getTableStyle(e){if(xP[e])return xP[e];if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return _n(P(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!hx[e]&&!xP[e]}import(e){for(let e in hx)this.styles[e]=hx[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=_x(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)hx[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},oz=class extends lv{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 Tr(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(ir(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||ex,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=>!nr(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=>sr(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=>or(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>ir(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,[O(r)]).length)return`none`}return o}isPivotFormula(e,t){return e.startsWith(`=`)?QN(fd.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=vr(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,vr(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 kP(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 kP(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=kP(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<cr(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||ex,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:Yn(e.range.zone),type:e.type};T(e.config,ex)||(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=Yn(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}};let sz=al.mapping;function cz(e,t,n){return new lz(e,t,n).getParameters()}var lz=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(sz),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=nr(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(!qn(e.zone))return new Eo;if(e.invalidSheetName)return new Eo(P(`Invalid sheet name: %s`,e.invalidSheetName))}},uz=class{interval;left;right;max;constructor(e,t=null,n=null){this.interval=e,this.left=t,this.right=n,this.max=e.bottom}},dz=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(fz),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;)fz(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 uz(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 fz(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 pz=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){Pn(this.profilesStartingPosition,this.profiles,[e])}delete(e){Pn(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return Fn(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 zn(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}},mz=class e{setsBySheetId={};constructor(e=[]){for(let t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new pz),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(let t of e)this.add(t)}addPosition(e){this.add(Ou(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(Ou(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(Ou(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]()}},hz=class{forest={};removeAllDependencies(e){}addDependencies(e,t){let n={zone:O(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 mz){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 mz;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 dz,this.forest[e][t]=n),n}},gz=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=_z(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 _z(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var vz=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]=gz.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)}},yz=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),bz=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 xz,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new xz),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)}},xz=class extends yz.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}},Sz=class{resultsToArrayFormulas=new bz;arrayFormulasToResults=new aF;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||Cz}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 Cz=[],wz=new k;wz.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let Tz=Object.freeze(ef({value:null})),Ez={};for(let[e,t]of Object.entries(cd))Ez[t]=e;for(let[e,t]of Object.entries(ld))Ez[t]=e;var Dz=class{context;getters;compilationParams;evaluatedCells=new aF;formulaDependencies=Gt(new hz);blockedArrayFormulas=new vz({});spreadingRelations=new Sz;perfProfile;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=cz(this.context,this.getters,this.computeAndSave.bind(this))}getPerfProfile(){return this.perfProfile}getEvaluatedCell(e){return this.evaluatedCells.get(e)||Tz}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===F.SpilledBlocked)?O(e):er(O(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,O(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=cz(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(e){this.compilationParams=cz(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.__timingEntries=e,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 vz(e)}evaluateCells(e){let t=performance.now(),n=new mz;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`)}evaluateCellsWithoutCascade(e){let t=new mz;t.addManyPositions(e),this.evaluate(t)}getArrayFormulasImpactedByChangesOf(e){let t=new mz;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 Sz,this.formulaDependencies=Gt(()=>{let e=new hz;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(e){let t=performance.now();this.evaluatedCells=new aF;let n=[];for(let e of this.getters.getSheetIds()){let t=this.getters.getSheetZone(e);n.push({sheetId:e,zone:t})}this.evaluate(n,e),console.debug(`evaluate all cells`,performance.now()-t,`ms`)}evaluateFormulaResult(e,t,n){let r=fd.Compile(t,e,this.getters);return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,r)}evaluateCompiledFormula(e,t,n){try{let r=jz(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return ht(r)?is(r,kz):kz(r)}catch(e){return $c(e,``)}}getArrayFormulasBlockedBy(e,t){let n=new mz,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 mz;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e,t){t&&(this.perfProfile=void 0),this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new mz(e);let n=0,r=t?[]:void 0;for(;!this.nextRangesToUpdate.isEmpty()&&n++<30;){this.updateCompilationParameters(r);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)}}wz.getAll().forEach(e=>e(this.getters))}n>=30&&console.warn(`Maximum iteration reached while evaluating cells`),t&&this.processPerfProfile()}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{...Tz,position:e};let r=n.id;try{return this.cellsBeingComputed.has(r)?Mz(e):(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):Jd(n,{format:this.getters.getCellFormat(e),locale:this.getters.getLocale()},e))}catch(t){return t.value=t?.value||F.GenericError,t.message=t?.message||nl,t.origin=e,t.errorOriginPosition=t?.errorOriginPosition,ef(t,this.getters.getLocale(),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=jz(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e),r=this.compilationParams.evalContext.__timingEntries,i=r&&ht(n)?performance.now():0,a=this.postProcessFormulaReturn(e,t,n);if(i){let t=r?.at(-1);t&&t.position.sheetId===e.sheetId&&t.position.col===e.col&&t.position.row===e.row&&(t.time+=performance.now()-i)}return a}postProcessFormulaReturn(e,t,n){let r=this.getters.getCellFormat(e);if(!ht(n)){let t=ef(Az(n),this.getters.getLocale(),e,r,e);return t.type===`error`&&(t.errorOriginPosition=n.errorOriginPosition??e),t}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let i=n.length,a=n[0].length;if(a===0)return ef({value:0},this.getters.getLocale(),e,r);if(a===1&&i===1)return ef(Az(n[0][0]),this.getters.getLocale(),e,r);let o={top:e.row,bottom:e.row+a-1,left:e.col,right:e.col+i-1};return this.spreadingRelations.addRelation({resultZone:o,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),Oz(i,a,this.checkCollision(e)),Oz(i,a,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,o),ef(Az(n[0][0]),this.getters.getLocale(),e,r)}invalidatePositionsDependingOnSpread(e,t){let n=this.getCellsDependingOn(ur(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 ko(P(`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 ko(P(`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 ko(P(`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.getCellFormat(o),c=ef(Az(r[i][a]),this.getters.getLocale(),o,s,o);c.type===`error`&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r},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 Mz(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]),xr(r.range.zone)>1||n?this.compilationParams.ensureRange(r.range):this.compilationParams.referenceDenormalizer(r.range)}return e?.(t,n)||new wo(P(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}processPerfProfile(){let e=this.compilationParams.evalContext.__timingEntries??[],t=Object.groupBy(e,e=>e.functionName),n=0,r=[];for(let e in t){let i=Ez[e]??e,a=Object.groupBy(t[e],({position:e})=>{let t=this.getters.getCell(e);return(t?this.getters.getCellFingerprint(t):void 0)??``});for(let e in a)for(let t of this.mergeIntoRangeTimings(i,a[e]))n+=t.time,r.push(t)}r.sort((e,t)=>t.time-e.time),this.perfProfile={totalTime:n,totalCells:this.evaluatedCells.keys().length,totalFunctionCalls:e.length,entries:r}}mergeIntoRangeTimings(e,t){let n=new aF,r=new mz;for(let{position:e,time:i}of t)n.set(e,(n.get(e)??0)+i),r.addPosition(e);let i=[];for(let{sheetId:t,zone:a}of r){let r=0;for(let e=a.left;e<=a.right;e++)for(let i=a.top;i<=a.bottom;i++)r+=n.get({sheetId:t,col:e,row:i})??0;i.push({functionName:e,range:this.getters.getRangeFromZone(t,a),time:r})}return i}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.rangeDependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}};function Oz(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 kz(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function Az(e){return typeof e.value==`number`&&Math.abs(e.value)>Number.MAX_VALUE?new jo:kz(e)}function jz(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 Mz(e){return ef({...new To,origin:void 0},void 0,e)}var Nz=class extends oF{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getVisibleRangeValues`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`,`getPerfProfile`];shouldRebuildDependenciesGraph=!0;forceEvaluation=!1;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new Dz(e.custom,this.getters)}beforeHandle(e){this.forceEvaluation=!1,(Ed.has(e.type)||Od.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(this.forceEvaluation=!0,!this.getters.isAutomaticEvaluationEnabled())this.shouldRebuildDependenciesGraph=!0;else 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(e.profiling);break}}finalize(){if(!this.shouldPerformEvaluation()){this.positionsToUpdate.length&&this.evaluator.evaluateCellsWithoutCascade(this.positionsToUpdate),this.positionsToUpdate=[];return}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 ht(r)?is(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 dr(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 dr(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}getPerfProfile(){return this.evaluator.getPerfProfile()}shouldPerformEvaluation(){return this.forceEvaluation||this.getters.isAutomaticEvaluationEnabled()}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return dr(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=hv(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===F.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 Pz=new k;Pz.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value,r=e.isDarkMode(),i,a;return n?(i=My(r),a=My(r)):(i=Ay(r),a=jy(r)),{svg:i,hoverSvg:a,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})}}}}),Pz.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:Dy(i),hoverSvg:ky(i),priority:2,horizontalAlign:`right`,size:Df(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`}}),Pz.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:Fy[n].svg,priority:1,horizontalAlign:`left`,size:Df(r),margin:4,position:t}}}),Pz.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??ZS.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?Ny(s,!1):void 0,hoverSvg:o?Ny(s,!0):void 0,position:t,onClick:EC}}}),Pz.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:Df(r),margin:0,svg:n===`asc`?Oy(r):Dy(r),position:t,onClick:void 0}});var Fz=class extends oF{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=Pz.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 Iz=/"(#[0-9a-fA-F]{6})"/g;function Lz(e){let t=[{leadColor:ep(255,0,0),colors:[]},{leadColor:ep(255,128,0),colors:[]},{leadColor:ep(128,128,0),colors:[]},{leadColor:ep(128,255,0),colors:[]},{leadColor:ep(0,255,0),colors:[]},{leadColor:ep(0,255,128),colors:[]},{leadColor:ep(0,255,255),colors:[]},{leadColor:ep(0,127,255),colors:[]},{leadColor:ep(0,0,255),colors:[]},{leadColor:ep(127,0,255),colors:[]},{leadColor:ep(128,0,128),colors:[]},{leadColor:ep(255,0,128),colors:[]}];for(let n of e.map(ip)){let e=500,r=0;t.forEach((t,i)=>{let a=Rz(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>op(e).s-op(t).s)).flat().map(rp)}function Rz(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var zz=class extends oF{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`SET_SHEET_BACKGROUND_COLOR`: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 Lz(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.backgroundColor].filter(w)}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=this.getters.getDefaultStyleColors(),r=new Set(n);for(let e of t)e.style?.textColor&&r.add(e.style.textColor),e.style?.fillColor&&r.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))r.add(t);return[...r]}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(Jf(t.minimum.color)),n.push(t.midpoint?Jf(t.midpoint.color):void 0),n.push(Jf(t.maximum.color)))}return n.filter(w)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getRangeDefinition()).matchAll(Iz)].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(!Zf(t))continue;let e=Xf(t);t&&!Ve.includes(e)&&this.history.update(`customColors`,e,!0)}}},Bz=class extends oF{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(Ed.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=>or(o,s,e.range.zone))){for(let e of n){let t=e.range.zone;ir(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,O(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=>or(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>ir(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(!Tr(t))return!1;let n=er(...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===F.SpilledBlocked&&!e.errorOriginPosition}else if(T(i,r)&&xr(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=kP(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:!dr(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=Wn(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 dr(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(!Bt(i)){let n=hv(i,e.styles);t.styles[o]=n}if(a){let n=hv(a,e.borders);t.borders[o]=n}}}t.tables=n}}};function Vz(e){return{...e,data:{...e.data,datasets:e.data.datasets.filter(e=>!ym(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 vm(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}var Hz=class extends oF{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};handle(e){if(Ed.has(e.type)||kd.has(e.type)||Dd.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){let n=this.getters.getSpreadsheetTheme().backgroundColor;if(e)return{background:e,fontColor:sm(e)};if(!t)return{background:n,fontColor:sm(n)};let r=t.zone.left,i=t.zone.top,a=t.sheetId,o=this.getters.getCellComputedStyle({sheetId:a,col:r,row:i}),s=o.fillColor||n;return{background:s,fontColor:o.textColor||sm(s)}}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 wg(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=Vz(e)}return r}},Uz=class extends oF{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(Ed.has(e.type)||kd.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]=Gt(()=>this.getComputedStyles(e)),this.computedIcons[e]=Gt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=Gt(()=>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 fd.Compile(t,e,this.getters)}),i=Q.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`?fn(a):pn(a);case`number`:return Number(n.value);case`percentage`:let t=pn(a);return t+(fn(a)-t)*Number(n.value)/100;case`percentile`:return mo(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=fn(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});!or(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:Jf(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=Ip(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=Q.get(t.operator),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(i,t,e)??``:$d(t,V));if(o.some(yS))return!1;let s={...t,type:t.operator,values:o.map(_S),dateValue:t.dateValue||`exactDate`};return a.isValueValid(r.value??``,s,n)}};let Wz={isValid:!0};var Gz=class extends oF{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};criterionPreComputeResult={};handle(e){if(Ed.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=Q.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?P(`The value must not be a formula`):this.isValidFormula(t)?void 0:U_.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?P(`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 dr(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 Wz;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:Wz}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:yp(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!fd.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]?.()||Wz}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of Eu(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=Gt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?Wz:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=Q.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,t,o,i);if(s.some(yS))return;let c={...i,values:s.map(_S)};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=>or(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 $d(r,V);let i=fd.Compile(r,e,this.getters),a=this.getters.getTranslatedCellFormula(e,n.col,n.row,i);return this.getters.evaluateFormula(e,a,t)})}};let Kz=[`SUBTOTAL`,`PIVOT`];var qz=class extends oF{static getters=[`getCellsWithTrackedFormula`];trackedCells={};handle(e){switch(e.type){case`START`:for(let e of Kz)this.trackedCells[e]={};for(let e of this.getters.getSheetIds())for(let t of this.getters.getCells(e))for(let e of Kz)bn(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 Kz)bn(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))}},Jz=class extends oF{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=hf();beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=qt(e.position,e.base),n=Array(e.quantity).fill(void 0),r=sn(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=on(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 dr(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 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 gf(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 Yz=`0.00%`;function Xz(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=nC[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return $c(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}=vN(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Do:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=vN(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Do:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return ht(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=vN(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=dC(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:F.NotAvailable,message:P(`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 $c(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:F.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:Yz}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:F.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:Yz}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:F.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:Yz}}asPercentOfParentRowTotal(e,t,n){let r=gN(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:Yz}}asPercentOfParentColumnTotal(e,t,n){let r=_N(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:Yz}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!EN(i,n))return{value:``};let a=wN(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:Yz}}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:F.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}=vN(this,n),u=kN(l),d=kN(c),f=s[u]?.[d];return f===void 0&&(f=this.getPreviousRunningTotalValue(a,n,s)),{value:f??``,format:i===`running_total`?e.format:Yz}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!EN(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:F.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:Yz}:s===void 0?{value:F.NullError}:{value:s/o,format:Yz}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!EN(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(!EN(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:F.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:F.NullError}:{value:(s-o)/o,format:Yz}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!EN(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}=vN(this,n),u=kN(l),d=kN(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=DN(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=os(o));for(let s of o){let o=kN(yN(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:yN(this,i,t.domain)})).filter(e=>EN(t,e.rowDomain)),l=Object.groupBy(c,e=>jN(e.rowDomain,t));for(let e in l)l[e]=hn(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=kN(yN(this,i,e.domain)),a=l[jN(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:gn(r)}computeRunningTotal(e,t,n){let r={},i=DN(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=os(o));for(let s of o){let o=kN(yN(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:yN(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>EN(t,e.rowDomain));for(let e of l){let n=kN(e.rowDomain),i=MN(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=kN(n),a=MN(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:gn(r)}getPreviousRunningTotalValue(e,t,n){let r=this.definition.getDimension(e);if(r.type!==`date`&&r.type!==`datetime`)return;let i=DN(this,e),{rowDomain:a,colDomain:o}=vN(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=kN(c),d=MN(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=MN(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=kN(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&&LS.contains(n)){let t=RS(n).toComparableValue?.(e);if(t!==void 0)return t}return L(e,V)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=vN(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=vN(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)`?ON(this,t,n,r):TN(t,n,r);if(T(i,t))return`sameValue`;if(!i||!xN(this,i))throw new Do;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;yC(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let Zz=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function Qz(e){return Zz.includes(e.type)}var $z=class extends oF{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotCellSortDirection`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`,`getAllPivotArrayFormulas`,`getPivotStyleAtPosition`];pivots={};unusedPivotsInFormulas;custom;pivotPositionCache=new aF;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(Ed.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(Qz);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:mD();break}}finalize(){this.shouldInvalidateCache&&=(this.pivotPositionCache=new aF,!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=$N(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=NL(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||eP(t.compiledFormula,this.getters)===0)return IN;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!r)return IN;let{functionName:i,args:a}=r,o=a[0];if(!o)return IN;let s=this.getters.getPivotId(o.toString());if(!s)return IN;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!this.isMainFunctionPivotSpreadFunction(t))return IN;try{if(i===`PIVOT`){let t=DC(this.getters.getPivotCoreDefinition(s),_S(a[1]),_S(a[2]),_S(a[3]),_S(a[4]),_S(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=>ht(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:vN(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 IN}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return _n(P(`Calculated measure 1`),t,{compute:(e,t)=>P(`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)&&qN.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=vN(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=Xz(qN.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:DC(this.getters.getPivotCoreDefinition(i),_S(n.args[1]),_S(n.args[2]),_S(n.args[3]),_S(n.args[4]),_S(n.args[5]),this.getters.getLocale()),pivotId:i}}isMainFunctionPivotSpreadFunction(e){return e.compiledFormula.isFirstNonWhitespaceSymbol(`PIVOT`)}};let eB=new k;eB.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=Math.abs(e.current).toString();n=`0`.repeat(Math.max(e.numberPostfixLength-n.length,0))+n;let r=`${e.prefix}${n}`;return{cellData:{border:t.border,style:t.style,format:t.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.style,format:t.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=Jo(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=Ka(r);e.current=i;let a=n.getLocale(),o=H(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.style,format:t.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={sheetId:t.sheetId,col:t.col,row:t.row},a={locale:n.getLocale(),format:n.getCellFormat(i)};return{cellData:{border:t.border,style:t.style,format:t.format,content:r},tooltip:r?{props:{content:t.cell?Jd(t.cell,a,i).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula);return{cellData:{border:t.border,style:t.style,format:t.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let tB=new k,nB=/(\d+)$/,rB=/^(.*\D+)/,iB=/^(.*\D+)(\d+)$/,aB=/^0*/;function oB(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:Jd(a,{locale:V,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function sB(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 cB(e){let t=1;return e.length>=2&&(t=sB(e)*e.length),t}function lB(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 uB(e){if(e.length<2)return 1;let t=e.map(e=>Jo(e,V)),n=lB(dB(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}}tB.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&pc(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&Jd(e,{locale:V}).type===`text`&&iB.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(nB)[0]),i=e.content.match(rB)[0],a=oB(e,t,e=>e.type===`text`&&iB.test(e.value)).filter(e=>i===(e.value??``).toString().match(rB)[0]).map(e=>(e.value??``).toString().match(nB)[0]),o=a.reduce((e,t)=>{let n=t.match(aB)[0].length;return n>e[1]?[t,n]:e},[a[0],0]),s=o[1]?o[0].length:0,c=cB(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&&Jd(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&&Jd(e,{locale:V}).type===`number`&&!!e.format&&pc(e.format),generateRule:(e,t)=>{let n=uB(oB(e,t,e=>e.type===`number`&&!!e.format&&pc(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=Jd(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&&Jd(e,{locale:V}).type===`number`,generateRule:(e,t,n)=>{let r=oB(e,t,e=>e.type===`number`&&!pc(e.format||``)).map(e=>Number(e.value)),i=cB(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=Jd(e,{locale:V});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function dB(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=va.fromTimestamp(e[n-1].getTime()),i=eo(r,t),a=Qa(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:$a(r,t)}}).slice(1)}var fB=class extends cv{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){}},pB=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}=eB.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}}}},mB=class extends fB{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(O({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(O({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:D(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(Wn),[]);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=D(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(or(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??void 0}}getRule(e,t){let n=tB.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}=Nn(t),a={sheetId:r,col:e,row:i},o=this.getters.getCell(a),s=this.getters.getCellStyle(a);Object.keys(s).length===0&&(s=void 0);let c=this.getters.getCellFormat(a);n.push({col:e,row:i,cell:o,sheetId:r,style:s,format:c})}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 pB(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([]))}},hB=class extends fB{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}=or(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)||lr(er(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,er(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=fn(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=Dt(i.filter(e=>this.isNumber(r[e])))[0]||[];return fn(o)<a?1/0:pn(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&pc(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 lr(t)?(n.add(cr(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)},dr(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)},dr(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`))}},gB=class extends fB{static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(Ed.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(vB(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(Po(e)||e instanceof I)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(Po(e)||e instanceof I)return;throw e}}computeTableStyle(e,t){return Gt(()=>{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=jP(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 _B=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 vB(e){return _B.has(e.type)}var yB=class extends fB{static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles=new aF;borders=new aF;handle(e){if(Ed.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`||e.type===`SET_SHEET_BACKGROUND_COLOR`){this.styles=new aF,this.borders=new aF;return}if(vB(e)){`sheetId`in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new aF,this.borders=new aF);return}if(kd.has(e.type)){this.styles=new aF;return}if(Ad.has(e.type)){this.borders=new aF;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=Ae),n}getComputedStyle(e){let t=this.getters.getCellStyle(e),n=this.getters.getCellConditionalFormatStyle(e),r=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e);return{...Zt({fillColor:this.getters.getSheet(e.sheetId)?.backgroundColor}),...Zt(r),...Zt(i),...Zt(t),...Zt(n)}}exportForExcel(e){for(let t of e.sheets){let n={},r=[];for(let e in t.cells){let i={sheetId:t.id,...Nn(e)},a=this.getters.getEvaluatedCell(i),o=this.getComputedStyle(i);if(!a.link||o.textColor)continue;let s=Object.keys(t.styles).find(t=>sr(Wn(e),Wn(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(Wn),s=D([Wn(r)],o);delete t.styles[r];for(let e of s)t.styles[Yn(e)]=n;let c=hv({...a,textColor:Ae},e.styles);for(let e of i)t.styles[e]=c}for(let n of r){let r=this.getters.getCell({sheetId:t.id,...Nn(n)});t.styles[n]=hv({...r?.style,textColor:Ae},e.styles)}}}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...Zt(this.getters.getCellTableBorder(e)||{}),...Zt(t)};return Bt(n)?null:n}},bB=class extends fB{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 xB(e){let t=Au.get(e.type)?.(e),n=wB(e);if(!t&&!n)return;let r=t||CB(),i=n||(e=>e),a=SB(r.applyChange);return{applyChange:a,adaptRangeString:(e,t)=>qu(e,t,r),adaptFormulaString:(e,t)=>Gu(e,t,r,i),adaptCompiledFormula:e=>e.adaptCompiledFormula(a,i)}}function SB(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!qn(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}function CB(){return{applyChange:e=>({changeType:`NONE`,range:e}),sheetId:`ignoredSheetId`,sheetName:{old:`ignoredSheetName`,current:`ignoredSheetName`}}}function wB(e){if(e.type!==`UPDATE_NAMED_RANGE`)return;let t=e.oldRangeName.toLowerCase();return n=>n.toLowerCase()===t?e.newRangeName:n}let TB=new class extends k{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)}},EB=new class extends k{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};TB.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],zB),TB.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],zB),TB.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],AB),TB.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`,`UPDATE_CAROUSEL`],jB),TB.addTransformation(`DELETE_CHART`,[`UPDATE_CHART`],MB),TB.addTransformation(`DELETE_CHART`,[`UPDATE_CAROUSEL`],NB),TB.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],PB),TB.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],FB),TB.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],IB),TB.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],IB),TB.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],LB),TB.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],LB),TB.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],RB),TB.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],BB),TB.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],BB),TB.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],kB),TB.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],OB),TB.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],DB),TB.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],DB),TB.addTransformation(`UPDATE_NAMED_RANGE`,[`UPDATE_NAMED_RANGE`,`DELETE_NAMED_RANGE`],VB);function DB(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=Mr(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function OB(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function kB(e,t){if(e.pivotId!==t.pivotId)return e}function AB(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function jB(e,t){if(e.figureId!==t.figureId)return e}function MB(e,t){if(e.chartId!==t.chartId)return e}function NB(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!(e.type===`chart`&&e.chartId===t.chartId))}}}function PB(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 FB(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!ir(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function IB(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 LB(e,t){if(e.sheetId!==t.sheetId)return e;let n=Mr(e.zone,t);if(!n)return;let r=e.newTableRange?Nr(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function RB(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:ex.styleId}}:e}function zB(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=Bu(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=zu(qt(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function BB(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=Bu(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=zu(qt(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function VB(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 HB(e,{adaptFormulaString:t}){let n=e.content&&t(e.sheetId,e.content);return{...e,content:n}}EB.add(`UPDATE_CELL`,HB);function UB(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}EB.add(`ADD_CONDITIONAL_FORMAT`,UB);function WB(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}EB.add(`ADD_DATA_VALIDATION_RULE`,WB);function GB(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}EB.add(`ADD_PIVOT`,GB),EB.add(`UPDATE_PIVOT`,GB),EB.add(`CREATE_CHART`,KB),EB.add(`UPDATE_CHART`,KB);function KB(e,t){return{...e,definition:gk.transformDefinition(e.sheetId,e.definition,t)}}let qB=[{match:bd,fn:QB},{match:Sd,fn:$B},{match:Td,fn:eV},{match:wd,fn:rV},{match:xd,fn:nV},{match:Cd,fn:tV}];function JB(e,t){let n=TB.getTransformation(e.type,t.type),r=n?n(e,t):ZB(e,t);return r&&YB(r,t)}function YB(e,t){let n=EB.get(e.type);if(!n)return e;let r=xB(t);return r?n(e,r):e}function XB(e,t){let n=[...e],r=new Set(TB.getKeys());for(let e of t)(r.has(e.type)||Au.contains(e.type))&&(n=n.reduce((t,n)=>{let r=JB(n,e);return r&&t.push(r),t},[]));return n}function ZB(e,t){for(let{match:n,fn:r}of qB)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function QB(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 $B(e,t){let n=QB(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=Mr(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function eV(e,t){let n=QB(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=Mr(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function tV(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>Nr(e,t)).filter(w);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function nV(e,t){let n=QB(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=Bu(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=zu(qt(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function rV(e,t){let n=QB(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?iV(e,t):t.type===`ADD_MERGE`?aV(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function iV(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 aV(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&or(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var oV=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}},sV=class extends Error{},cV=class extends Wi{revisions;transportService;serverRevisionId;commandSquisher;clients={};clientId=`local`;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;lastLocalOperation;constructor(e,t,n=Xe,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 oV(G.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:G.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:G.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=G.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 sV(`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 oV(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:XB(r,t)})}break;case`SNAPSHOT_CREATED`:{let t=new oV(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.
|
|
114
|
+
${JSON.stringify(e)}`);this.waitingAck=!0,this.sendToTransport({...e,serverRevisionId:this.serverRevisionId}).catch(e=>{if(!(e instanceof sV))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`)}},lV=class extends fB{static getters=[`getClientsToDisplay`,`getClient`,`getCurrentClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];colors=new Np(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 sV)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 ${qe+1}px ${Je}`}}};let uV={light:{backgroundColor:`#FFFFFF`,gridBorderColor:`#CECFCF`,headerBackgroundColor:`#F8F9FA`,headerActiveBackgroundColor:`#595959`,headerSelectedBackgroundColor:`#E8EAED`,headerTextColor:`#666666`,headerBorderColor:`#C0C0C0`,frozenPaneBorderColor:`#DADFE8`,frozenPaneHeaderBorderColor:`#BCBCBC`,singleCellSelectionBackgroundColor:`#F3F7FE`,multipleCellsSelectionBackgroundColor:`#E9F0FF`},dark:{backgroundColor:_p(`#1A1C2E`),gridBorderColor:_p(`#6B706F`),headerBackgroundColor:_p(`#262A36`),headerActiveBackgroundColor:_p(`#3A4052`),headerSelectedBackgroundColor:_p(`#4E566E`),headerTextColor:_p(`#A1A6B3`),headerBorderColor:_p(`#7A7F91`),frozenPaneBorderColor:_p(`#7A7F91`),frozenPaneHeaderBorderColor:_p(`#9FA5BD`),singleCellSelectionBackgroundColor:_p(`#696E8044`),multipleCellsSelectionBackgroundColor:_p(`#828AA044`)}};var dV=class extends fB{static getters=[`isDarkMode`,`getSpreadsheetTheme`];colorScheme;constructor(e){super(e),this.colorScheme=e.colorScheme}handle(e){e.type===`UPDATE_COLOR_SCHEME`&&(this.colorScheme=e.colorScheme)}isDarkMode(){return this.colorScheme===`dark`}getSpreadsheetTheme(){switch(this.colorScheme){case`dark`:return uV.dark;default:return uV.light}}},fV=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){}},pV=class extends fV{copy(e,t,n=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of mw(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of D(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){}},mV=class extends pV{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=>sr(t,e))){let e=this.getters.getPivotCellFromPosition(l),t=uC(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 mw(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:mw(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){for(let t of e.zones.flatMap(t=>fr(e.sheetId,t)))this.dispatch(`UPDATE_CELL`,{...t,content:``})}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.getCell(t),s=this.getters.getEvaluatedCell(t),c=e.format||e.evaluatedCell.format,l={...o?.style,...e.style},u=Object.keys(l??{}).length===0?void 0:l;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:u,format:c??s.format});return}let d=e?.content;e?.compiledFormula?.hasDependencies&&!n?.isCutOperation?d=this.getters.getTranslatedCellFormula(r,i-e.position.col,a-e.position.row,e.compiledFormula):e?.compiledFormula?.hasDependencies&&(d=this.getters.getFormulaMovedInSheet(r,e.compiledFormula)),d!==``||e.format||u?this.dispatch(`UPDATE_CELL`,{...t,content:d,style:u,format:e.format}):s.type!==`empty`&&this.dispatch(`UPDATE_CELL`,{content:``,...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=Z_(e[n]||``,t);r.push({content:i,evaluatedCell:{formattedValue:i}})}n.cells.push(r)}return n}},hV=class extends fB{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===cr(r).numberOfRows){this.notifyRowsRemovedAndRemaining(0,a);return}let o=i.map(e=>({left:r.left,top:e,right:r.right,bottom:e})),s=new mV(this.getters,this.dispatch),c=s.copy(fw(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:P(`%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=D(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(dr).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=ln(a);o!==a&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:o}))}let r=n?P(`Trimmed whitespace from %s cells.`,n):P(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}},gV=class extends fB{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 Eu(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=(ht(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!kt(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==`boolean`&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}},_V=class extends fB{static getters=[`dynamicTranslate`];dynamicTranslate(e){return e}},vV=class extends fB{allowDispatch(e){switch(e.type){case`MOVE_FIGURES`:for(let t of e.figures){let e=this.canDispatch(`UPDATE_FIGURE`,t);if(!e.isSuccessful)return e.reasons}break;case`DELETE_FIGURES`:for(let t of e.figureIds)if(!this.getters.getFigure(e.sheetId,t))return`FigureDoesNotExist`;break;case`MERGE_CHART_FIGURES_INTO_CAROUSEL`:let t=e.chartFigureIds.map(t=>this.getters.getFigure(e.sheetId,t)),n=this.getters.getFigure(e.sheetId,e.baseFigureId);if(t.some(e=>e===void 0||e.tag!==`chart`)||!n||n.tag!==`chart`)return`FigureDoesNotExist`}return`Success`}handle(e){switch(e.type){case`MOVE_FIGURES`:for(let t of e.figures)this.dispatch(`UPDATE_FIGURE`,t);break;case`DELETE_FIGURES`:for(let t of e.figureIds)this.dispatch(`DELETE_FIGURE`,{figureId:t,sheetId:e.sheetId});break;case`MERGE_CHART_FIGURES_INTO_CAROUSEL`:let t=G.smallUuid(),n=this.getters.getFigure(e.sheetId,e.baseFigureId);if(!n)throw Error(`Figure ${e.baseFigureId} does not exists.`);this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetId,figureId:t,col:n.col,row:n.row,offset:n.offset,size:{width:n.width,height:n.height},definition:{items:[]}}),this.dispatch(`ADD_FIGURES_CHART_TO_CAROUSEL`,{sheetId:e.sheetId,carouselFigureId:t,chartFigureIds:e.chartFigureIds})}}},yV=class extends fB{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 D(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=D(r.map(O));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:D(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 D(t))for(let t of dr(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=Ac(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=D(r[t].map(e=>O(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&&pc(e.format)))return e.format||_c(e.value)}}},bV=class extends fB{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`){if(!globalThis.ChartGeo)return null;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`)}},xV=class extends fB{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))}},SV=class extends fB{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){xr(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:[],filters:[],name:P(`New pivot`),type:`SPREADSHEET`,style:{tableStyleId:ct}}});let r=this.getters.getSheetIds().findIndex(e=>e===n)+1,i=this.getters.getPivotFormulaId(e);this.dispatch(`CREATE_SHEET`,{sheetId:t,name:P(`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:P(`%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(P(`%(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 _n(Et(e),t)}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new FN(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:{...st,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:uC(s,r)})}}if(this.getters.getCoreTable(i)&&this.dispatch(`REMOVE_TABLE`,{sheetId:e,target:[O(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:TP(o.config.styleId)}})}}}};let CV=new k,wV=new k;function TV(e,t){if(t&&CV.contains(t.type))return CV.get(t.type)(e,t)}function EV(e,t,n){if(wV.contains(t.type))return wV.get(t.type)(e,t,n)}function DV(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:Fd(e.rootCommand)?CV.contains(e.rootCommand.type):wV.contains(e.rootCommand.type)}function OV(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return Fd(e.rootCommand)?TV(t,e.rootCommand):EV(t,e.rootCommand,e.commands)}var kV=class extends fB{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=OV(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:DV(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},AV=class extends fB{static getters=[`isCurrentSheetLocked`];allowDispatch(e){return Nd.has(e.type)||this.getters.isDashboard()?`Success`:`sheetId`in e&&this.getters.isSheetLocked(e.sheetId)||!Fd(e)&&this.isCurrentSheetLocked()?`SheetLocked`:`Success`}isCurrentSheetLocked(){return this.getters.isSheetLocked(this.getters.getActiveSheetId())}},jV=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,R(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)}},MV=class extends fB{static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new jV,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 NV=[`number`,`error`,`text`,`boolean`];function PV(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=NV.indexOf(e.type)-NV.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 FV(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(PV(t))}var IV=class extends fB{allowDispatch(e){switch(e.type){case`SORT_CELLS`:return or(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)&&dr(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=>ir(e,t)),r=cr(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 dr(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=FV(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,t=this.getters.getCellPosition(s.id);e=s.isFormula?this.getters.getTranslatedCellFormula(i,0,f-t.row,s.compiledFormula):s.content,p.style=this.getters.getCellStyle(t),p.content=e,p.format=this.getters.getCellFormat(t)}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}},LV=class extends fB{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=D(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(dr).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=ln(a);o!==a&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:o}))}let r=n?P(`Trimmed whitespace from %s cells.`,n):P(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}},gV=class extends fB{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 Eu(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=(ht(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!kt(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==`boolean`&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}},_V=class extends fB{static getters=[`dynamicTranslate`];dynamicTranslate(e){return e}},vV=class extends fB{allowDispatch(e){switch(e.type){case`MOVE_FIGURES`:for(let t of e.figures){let e=this.canDispatch(`UPDATE_FIGURE`,t);if(!e.isSuccessful)return e.reasons}break;case`DELETE_FIGURES`:for(let t of e.figureIds)if(!this.getters.getFigure(e.sheetId,t))return`FigureDoesNotExist`;break;case`MERGE_CHART_FIGURES_INTO_CAROUSEL`:let t=e.chartFigureIds.map(t=>this.getters.getFigure(e.sheetId,t)),n=this.getters.getFigure(e.sheetId,e.baseFigureId);if(t.some(e=>e===void 0||e.tag!==`chart`)||!n||n.tag!==`chart`)return`FigureDoesNotExist`}return`Success`}handle(e){switch(e.type){case`MOVE_FIGURES`:for(let t of e.figures)this.dispatch(`UPDATE_FIGURE`,t);break;case`DELETE_FIGURES`:for(let t of e.figureIds)this.dispatch(`DELETE_FIGURE`,{figureId:t,sheetId:e.sheetId});break;case`MERGE_CHART_FIGURES_INTO_CAROUSEL`:let t=G.smallUuid(),n=this.getters.getFigure(e.sheetId,e.baseFigureId);if(!n)throw Error(`Figure ${e.baseFigureId} does not exists.`);this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetId,figureId:t,col:n.col,row:n.row,offset:n.offset,size:{width:n.width,height:n.height},definition:{items:[]}}),this.dispatch(`ADD_FIGURES_CHART_TO_CAROUSEL`,{sheetId:e.sheetId,carouselFigureId:t,chartFigureIds:e.chartFigureIds})}}},yV=class extends fB{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 D(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=D(r.map(O));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:D(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 D(t))for(let t of dr(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=Ac(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=D(r[t].map(e=>O(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&&pc(e.format)))return e.format||_c(e.value)}}},bV=class extends fB{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`){if(!globalThis.ChartGeo)return null;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`)}},xV=class extends fB{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))}},SV=class extends fB{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){xr(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:[],filters:[],name:P(`New pivot`),type:`SPREADSHEET`,style:{tableStyleId:ct}}});let r=this.getters.getSheetIds().findIndex(e=>e===n)+1,i=this.getters.getPivotFormulaId(e);this.dispatch(`CREATE_SHEET`,{sheetId:t,name:P(`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:P(`%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(P(`%(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 _n(Et(e),t)}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new FN(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:{...st,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:uC(s,r)})}}if(this.getters.getCoreTable(i)&&this.dispatch(`REMOVE_TABLE`,{sheetId:e,target:[O(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:TP(o.config.styleId)}})}}}};let CV=new k,wV=new k;function TV(e,t){if(t&&CV.contains(t.type))return CV.get(t.type)(e,t)}function EV(e,t,n){if(wV.contains(t.type))return wV.get(t.type)(e,t,n)}function DV(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:Fd(e.rootCommand)?CV.contains(e.rootCommand.type):wV.contains(e.rootCommand.type)}function OV(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return Fd(e.rootCommand)?TV(t,e.rootCommand):EV(t,e.rootCommand,e.commands)}var kV=class extends fB{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=OV(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:DV(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},AV=class extends fB{static getters=[`isCurrentSheetLocked`];allowDispatch(e){return Nd.has(e.type)||this.getters.isDashboard()?`Success`:`sheetId`in e&&this.getters.isSheetLocked(e.sheetId)||!Fd(e)&&this.isCurrentSheetLocked()?`SheetLocked`:`Success`}isCurrentSheetLocked(){return this.getters.isSheetLocked(this.getters.getActiveSheetId())}},jV=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,R(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)}},MV=class extends fB{static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new jV,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 NV=[`number`,`error`,`text`,`boolean`];function PV(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=NV.indexOf(e.type)-NV.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 FV(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(PV(t))}var IV=class extends fB{allowDispatch(e){switch(e.type){case`SORT_CELLS`:return or(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)&&dr(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=>ir(e,t)),r=cr(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 dr(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=FV(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,t=this.getters.getCellPosition(s.id);e=s.isFormula?this.getters.getTranslatedCellFormula(i,0,f-t.row,s.compiledFormula):s.content,p.style=this.getters.getCellStyle(t),p.content=e,p.format=this.getters.getCellFormat(t)}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}},LV=class extends fB{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[`
|
|
117
117
|
`,`;`,`,`,` `,`.`])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:J_(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`}},RV=class extends fB{handle(e){jd.has(e.type)&&this.dispatch(`EVALUATE_CELLS`,{cellIds:this.getters.getCellsWithTrackedFormula(`SUBTOTAL`)})}},zV=class extends fB{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=DP(t.range.zone,t.config);if(a&&or(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)}},BV=class extends fB{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}}}}},VV=class extends fB{static getters=[`shouldShowFormulas`,`isAutomaticEvaluationEnabled`];showFormulas=!1;automaticEvaluation=!0;handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.showFormulas=e.show;break;case`SET_AUTOMATIC_EVALUATION`:let t=!this.automaticEvaluation;this.automaticEvaluation=e.enabled,t&&e.enabled&&this.dispatch(`EVALUATE_CELLS`);break}}shouldShowFormulas(){return this.showFormulas}isAutomaticEvaluationEnabled(){return this.automaticEvaluation}},HV=class extends fB{static getters=[`getCellWidth`,`getTextWidth`,`getCellText`,`getCellMultiLineText`,`getMultilineTextSize`,`getContiguousZone`,`computeTextYCoordinate`];ctx=hf();allowDispatch(e){return e.type===`SET_BACKGROUND_FOR_ALL_CELLS`&&e.color&&!Zf(e.color)?`InvalidColor`: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=Dt(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;case`SET_BACKGROUND_FOR_ALL_CELLS`:this.dispatch(`SET_FORMATTING`,{sheetId:e.sheetId,target:[this.getters.getSheetZone(e.sheetId)],style:{fillColor:void 0}}),this.dispatch(`SET_SHEET_BACKGROUND_COLOR`,{sheetId:e.sheetId,color:e.color});break}}getCellWidth(e){let t=this.getters.getCellComputedStyle(e),n=0,r=this.getters.getEvaluatedCell(e).formattedValue;if(r){let e=kf(this.ctx,r,t,void 0);n+=yf(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 bf(this.ctx,e,t)}getMultilineTextSize(e,t){return yf(this.ctx,e,t)}getCellText(e,t){let n=this.getters.getCell(e),r=this.getters.getLocale();if(t?.showFormula){if(n?.isFormula)return $_(n.compiledFormula.toFormulaString(this.getters),r);if(!n?.content)return``}let i=this.getters.getEvaluatedCell(e),a=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>bf(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 kf(this.ctx,r,n,t.wrapWidth)}computeTextYCoordinate(e,t,n=Ge,r=1){let i=e.y+1,a=mf(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);rr(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=dr(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,fn(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=_f(this.ctx,e,r?.style,a);n>t&&n>23&&(t=n)}else{let e=r.content,n=_f(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})}},UV=class extends fB{static getters=[`getSelectedCarouselItem`,`getChartFromFigureId`,`getChartIdFromFigureId`];carouselStates={};allowDispatch(e){switch(e.type){case`ADD_FIGURES_CHART_TO_CAROUSEL`:return!this.getters.doesCarouselExist(e.carouselFigureId)||e.chartFigureIds.some(t=>this.getters.getFigure(e.sheetId,t)?.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_FIGURES_CHART_TO_CAROUSEL`:e.chartFigureIds.forEach(t=>{this.addFigureChartToCarousel(e.carouselFigureId,t,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=G.smallUuid();this.dispatch(`CREATE_CHART`,{...s,chartId:G.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=G.smallUuid();this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:t,definition:Ug});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={type:`chart`,chartId:r},o={...i,items:[...i.items,a]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:o}),this.dispatch(`UPDATE_CHART`,{sheetId:n,chartId:r,figureId:e,definition:this.getters.getChartDefinition(r)}),this.dispatch(`DELETE_FIGURE`,{sheetId:n,figureId:t}),this.dispatch(`UPDATE_CAROUSEL_ACTIVE_ITEM`,{figureId:e,sheetId:n,item:a})}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=sn(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 WV(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 GV=class extends fB{static layers=[`Clipboard`];static getters=[`getClipboardTextAndImageContent`,`getClipboardId`,`getClipboardTextContent`,`isCutOperation`];status=`invisible`;originSheetId;copiedData;_isCutOperation=!1;clipboardId=G.uuidv4();fileStore;constructor(e){super(e),this.fileStore=e.external.fileStore}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!==IC()&&(t={...t},delete t.data),t.imageData){let n=this.getters.getActiveSheetId(),r=G.uuidv4(),i=t.imageData,a=jg(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(!qn(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:Fd(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=`figureIds`in e?ZL.figureHandlers:ZL.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`,`figureIds`])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}=yw(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),t.figureIds&&this.dispatch(`SELECT_FIGURE`,{figureId:null}),vw(i,t,a,n),n?.selectTarget&&bw(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.
|
|
118
118
|
Please select a smaller zone.`,sticky:!0})}return t&&e&&(n[t]=e),n}getSheetData(){let e={version:IC()};return this.copiedData&&`figureIds`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(`
|
|
119
119
|
`)||` `}async getHTMLContent(){let e=``,t=this.copiedData?.cells;if(!t)if(this.copiedData?.figureIds&&this.copiedData.figureIds.length){let t=this.copiedData.figureIds[0],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=Ox(`${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(qg(this.getters.getCellComputedStyle(t.position))),r=this.getters.getCellText(t.position);n+=`<td style="${e}">`+Ox(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='${Ox(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="${Ox(await this.readFileAsDataURL(n))}" />`:` `}async getImageContent(){let e=this.copiedData?.figureIds&&this.copiedData.figureIds[0];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:P(`The file you are trying to copy is too large (>%sMB).
|
|
@@ -954,4 +954,4 @@ If you meant to create a named range, named range cannot have the same name as a
|
|
|
954
954
|
<Relationships xmlns="${Vp.Relationships}">
|
|
955
955
|
<Relationship ${J(e)} />
|
|
956
956
|
</Relationships>
|
|
957
|
-
`),`_rels/.rels`)}function nK(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=_n(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(`'?${xt(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function rK(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>cr(Wn(e.range)).numberOfRows>1);return e}var iK=class e extends Wi{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},n=[],r=!1){let i=performance.now();console.debug(`##### Model creation #####`),super(),xo(),n=qC(e,n);let a=zC(e,r);this.state=new gW,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(a.revisionId),this.coreGetters={},this.range=new fW(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 mW(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 $V.getAll())this.setupCorePlugin(e,a);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(n);for(let e of nH.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of tH.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of eH.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()-i,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession({shouldSnapshot:e}={shouldSnapshot:!0}){let t=e&&!this.getters.isReadonly()?Gt(()=>this.exportData()):void 0;await this.session.leave(t)}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 cV(lW({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 eW(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:G.smallUuid(),name:P(`Anonymous`).toString()},n=e.transportService||new JH,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 tW(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(Ss));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,colorScheme:this.config.colorScheme}}checkDispatchAllowed(e){let t=Fd(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return this.processCommandResults(t)}processCommandResults(e){return e.some(e=>e!==`Success`)?new Ld(e.flat()):Ld.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(aK(e,t));dispatch=(e,t)=>{let n=aK(e,t),r=this.status;if(this.getters.isReadonly()&&!Id(n))return new Ld(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new Ld(`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();Fd(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(Fd(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(Fd(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return Ld.Success};dispatchFromCorePlugin=(e,t)=>{let n=aK(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,Ld.Success};dispatchToHandlers(e,t){let n=Fd(t);for(let r of e)!n&&r instanceof lv||r.beforeHandle(t);for(let r of e)!n&&r instanceof lv||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 JH};return T(n,new e(x(t),r)._exportData(!1))?t:(n.isNotSquishable=!0,n)}_exportData(e){let t=ew();for(let n of this.handlers)n instanceof lv&&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=nw();for(let t of this.handlers)t instanceof cv&&await t.exportForExcel(e);return e=x(e),qG(e)}};function aK(e,t={}){let n=x(t);return n.type=e,n}var oK=class extends pV{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(O(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=D(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}},sK=class extends fV{copy(e){}getCopyRect(e){return m_(...e.figureIds.map(t=>this.getters.getFigure(e.sheetId,t)).filter(w).map(t=>this.getters.getFigureUI(e.sheetId,t)))}},cK=class extends sK{copy(e){let t=e.sheetId,n=[],r=this.getCopyRect(e);for(let i of e.figureIds){let e=this.getters.getFigure(t,i);if(!e)throw Error(`No figure for the given id: ${i}`);if(e.tag!==`carousel`)continue;let a={...e},o=this.getters.getCarousel(i),{x:s,y:c}=this.getters.getFigureUI(t,e),l={};for(let e of o.items)if(e.type===`chart`){let t=this.getters.getChart(e.chartId);if(!t)throw Error(`No chart for the given id: ${e.chartId}`);l[e.chartId]=t}n.push({figureId:i,copiedFigure:a,copiedCarousel:o,copiedCharts:l,copiedSheetId:t,offset:{x:s-r.x,y:c-r.y}})}return{figures:n,figureIds:e.figureIds}}getPasteTarget(e,t,n,r){let i={};for(let e of n.figures)i[e.figureId]=G.smallUuid();return{zones:[],figureIds:i,sheetId:e}}paste(e,t,n){if(!e.figureIds)return;let{zones:r}=e,i=e.sheetId;for(let a of t.figures){let o=e.figureIds[a.figureId],{width:s,height:c}=a.copiedFigure,{col:l,row:u,offset:d}=Mg(this.getters,i,{col:r[0].left,row:r[0].top},{...a.copiedFigure,offset:a.offset});this.dispatch(`CREATE_CAROUSEL`,{figureId:o,sheetId:i,definition:{items:[]},col:l,row:u,offset:d,size:{height:c,width:s}});let f=x(a.copiedCarousel.items);for(let e of f){if(e.type!==`chart`)continue;let t=a.copiedCharts[e.chartId],n=G.smallUuid(),r=gk.fromDefinition(this.getters,i,t.copyInSheetId(i)).getDefinition();this.dispatch(`CREATE_CHART`,{figureId:o,chartId:n,sheetId:i,definition:r}),e.chartId=n}this.dispatch(`UPDATE_CAROUSEL`,{sheetId:i,figureId:o,definition:{...a.copiedCarousel,items:f}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:a.copiedSheetId,figureId:a.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:o,selectMultiple:t.figureIds.length>1})}}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},lK=class extends sK{copy(e){let t=e.sheetId,n=[],r=this.getCopyRect(e);for(let i of e.figureIds){let e=this.getters.getFigure(t,i);if(!e)throw Error(`No figure for the given id: ${i}`);if(e.tag!==`chart`)continue;let a={...e},{x:o,y:s}=this.getters.getFigureUI(t,e),c=this.getters.getChartFromFigureId(i);if(!c)throw Error(`No chart for the given id: ${i}`);n.push({figureId:i,copiedFigure:a,copiedChart:c,offset:{x:o-r.x,y:s-r.y}})}return{figures:n,figureIds:e.figureIds}}getPasteTarget(e,t,n,r){let i={};for(let e of n.figures)i[e.figureId]=G.smallUuid();return{zones:[],figureIds:i,sheetId:e}}paste(e,t,n){if(!e.figureIds)return;let{zones:r}=e,i=e.sheetId;for(let a of t.figures){let o=e.figureIds[a.figureId],{width:s,height:c}=a.copiedFigure,l=a.copiedChart,u=gk.fromDefinition(this.getters,i,l.copyInSheetId(i)).getDefinition();u=gk.fromStrDefinition(this.getters,i,u).getDefinition();let{col:d,row:f,offset:p}=Mg(this.getters,i,{col:r[0].left,row:r[0].top},{...a.copiedFigure,offset:a.offset});this.dispatch(`CREATE_CHART`,{figureId:o,chartId:G.smallUuid(),sheetId:i,definition:u,col:d,row:f,offset:p,size:{height:c,width:s}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:a.copiedChart.sheetId,figureId:a.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:o,selectMultiple:t.figureIds.length>1})}}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},uK=class extends pV{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=O(e.position),i=O(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:G.smallUuid(),ranges:[]}}},dK=class extends pV{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=O(t),i=O(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?G.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=D([...D(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})}}},fK=class extends pV{copy(e){let t={style:{},format:{},width:e.columnsIndexes.length,height:e.rowsIndexes.length,sheetId:e.sheetId,zones:e.clippedZones};t.format={sheetDefault:this.getters.getDefaultFormat(e.sheetId,`SHEET`,void 0)??``,colDefault:[],rowDefault:[]};let n=0;for(let r of e.columnsIndexes){let i=this.getters.getDefaultFormat(e.sheetId,`COL`,r);i&&t.format.colDefault&&(t.format.colDefault[n]=i),n++}let r=0;for(let n of e.rowsIndexes){let i=this.getters.getDefaultFormat(e.sheetId,`ROW`,n);i&&t.format.rowDefault&&(t.format.rowDefault[r]=i),r++}for(let n in Ue){t.style[n]={sheetDefault:this.getters.getDefaultStyle(e.sheetId,n,`SHEET`,void 0)??Ue[n],colDefault:[],rowDefault:[]};let r=0;for(let i of e.columnsIndexes){let a=this.getters.getDefaultStyle(e.sheetId,n,`COL`,i);a!==void 0&&(t.style[n].colDefault[r]=a),r++}let i=0;for(let r of e.rowsIndexes){let a=this.getters.getDefaultStyle(e.sheetId,n,`ROW`,r);a!==void 0&&(t.style[n].rowDefault[i]=a),i++}}return t}adaptContentToZone(e,t){let n=Math.max(Math.floor((e.right-e.left+1)/t.width),1),r=Math.max(Math.floor((e.bottom-e.top+1)/t.height),1);if(n===1&&r===1)return t;let i=x(t);i.height*=r,i.width*=n,r>1&&i.format.rowDefault&&(i.format.rowDefault.length=t.height,i.format.rowDefault=Cn(i.format.rowDefault,r)),n>1&&i.format.colDefault&&(i.format.colDefault.length=t.width,i.format.colDefault=Cn(i.format.colDefault,n));for(let e in t.style)r>1&&i.style[e].rowDefault&&(i.style[e].rowDefault.length=t.height,i.style[e].rowDefault=Cn(i.style[e].rowDefault,r)),n>1&&i.style[e].colDefault&&(i.style[e].colDefault.length=t.width,i.style[e].colDefault=Cn(i.style[e].colDefault,n));return i}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(n.isCutOperation){this.clearClippedZones(t);let{left:e,top:n}=i[0];this.pasteStyle(r,e,n,t.width,t.height,t.style),this.pasteFormat(r,e,n,t.width,t.height,t.format)}else for(let e of i){let n=this.adaptContentToZone(e,t);this.pasteStyle(r,e.left,e.top,n.width,n.height,n.style),this.pasteFormat(r,e.left,e.top,n.width,n.height,n.format)}}clearClippedZones(e){this.dispatch(`CLEAR_FORMATTING`,{sheetId:e.sheetId,target:e.zones})}pasteStyle(e,t,n,r,i,a){let o=Sn({}),s={},c=0;function l(e,t){let n=`${e.left}:${e.right}:${e.top}:${e.bottom}`;s[n]=[e,c++],o.set(n,{...o.get(n),...t})}l({left:t,right:t+r-1,top:n,bottom:n+i-1},Ue);for(let e in a)l({left:t,right:t+r-1,top:n,bottom:n+i-1},{[e]:a[e].sheetDefault});for(let e in a)for(let r in a[e].colDefault){let o=parseInt(r);l({left:t+o,right:t+o,top:n,bottom:n+i-1},{[e]:a[e].colDefault[r]})}for(let e in a)for(let i in a[e].rowDefault){let o=parseInt(i);l({left:t,right:t+r-1,top:n+o,bottom:n+o},{[e]:a[e].rowDefault[i]})}let u=[];for(let[e,[t,n]]of Object.entries(s)){let r=o.get(e);Bt(r)||u.push([n,t,r])}u.sort((e,t)=>e[0]-t[0]);for(let[t,n,r]of u)this.dispatch(`SET_FORMATTING`,{sheetId:e,target:[n],style:r})}pasteFormat(e,t,n,r,i,a){let o={},s={},c=0;function l(e,t){let n=`${e.left}:${e.right}:${e.top}:${e.bottom}`;s[n]=[e,c++],o[n]=t}l({left:t,right:t+r-1,top:n,bottom:n+i-1},a.sheetDefault??``);for(let e in a.colDefault){let r=parseInt(e);l({left:t+r,right:t+r,top:n,bottom:n+i-1},a.colDefault[e])}for(let e in a.rowDefault){let i=parseInt(e);l({left:t,right:t+r-1,top:n+i,bottom:n+i},a.rowDefault[e])}let u=[];for(let[e,[t,n]]of Object.entries(s)){let r=o[e];r!==void 0&&u.push([n,t,r])}u.sort((e,t)=>e[0]-t[0]);for(let[t,n,r]of u)this.dispatch(`SET_FORMATTING`,{sheetId:e,target:[n],format:r})}},pK=class extends sK{copy(e){let t=e.sheetId,n=[],r=this.getCopyRect(e);for(let i of e.figureIds){let e=this.getters.getFigure(t,i);if(!e)throw Error(`No figure for the given id: ${i}`);if(e.tag!==`image`)continue;let a={...e},{x:o,y:s}=this.getters.getFigureUI(t,e),c=x(this.getters.getImage(i));n.push({figureId:i,copiedFigure:a,copiedImage:c,sheetId:t,offset:{x:o-r.x,y:s-r.y}})}return{figures:n,figureIds:e.figureIds}}getPasteTarget(e,t,n,r){let i={};for(let e of n.figures)i[e.figureId]=G.smallUuid();return{sheetId:e,zones:[],figureIds:i}}paste(e,t,n){if(!e.figureIds)return;let{zones:r}=e;for(let i of t.figures){let a=e.figureIds[i.figureId],o=this.getters.getActiveSheetId(),{width:s,height:c}=i.copiedFigure,l=x(i.copiedImage),{col:u,row:d,offset:f}=Mg(this.getters,o,{col:r[0].left,row:r[0].top},{...i.copiedFigure,offset:i.offset});this.dispatch(`CREATE_IMAGE`,{figureId:a,sheetId:o,col:u,row:d,offset:f,size:{height:c,width:s},definition:l}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:i.sheetId,figureId:i.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:a,selectMultiple:t.figureIds.length>1})}}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},mK=class extends pV{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}]})}},hK=class extends pV{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})}}},gK=class extends pV{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return Cr(mw(t,n.cells),i,a)?`FrozenPaneOverlap`:`Success`}},_K=class extends pV{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=>sr(f,e))){s.add(u.id);let{numberOfRows:e}=cr(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=>sr(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=Zt({...this.getters.getCellTableStyle(e),hideGridLines:!1}),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Zt(n)},border:{...r,...Zt(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=cr(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}))}};ZL.figureHandlers.add(`chart`,lK).add(`image`,pK).add(`carousel`,cK),ZL.cellHandlers.add(`dataValidation`,dK).add(`default`,fK).add(`cell`,mV).add(`sheet`,gK).add(`merge`,mK).add(`border`,oK).add(`table`,_K).add(`conditionalFormat`,uK).add(`references`,hK);var vK=class extends A{static maxSize={maxHeight:80};static template=`o-spreadsheet-ErrorToolTip`;props=(0,t.useProps)({cellPosition:N.CellPosition(),onClosed:N.function().optional()});get dataValidationErrorMessage(){return this.env.model.getters.getInvalidDataValidationMessage(this.props.cellPosition)}get evaluationError(){let e=this.env.model.getters.getEvaluatedCell(this.props.cellPosition);if(e.message)return e}get errorOriginPositionString(){if(this.env.model.getters.isDashboard())return``;let e=this.evaluationError?.errorOriginPosition;if(!e||T(e,this.props.cellPosition))return``;let t=e.sheetId;return this.env.model.getters.getRangeString(this.env.model.getters.getRangeFromZone(t,O(e)),this.env.model.getters.getActiveSheetId())}selectCell(){let e=this.evaluationError?.errorOriginPosition;if(!e)return;let t=this.env.model.getters.getActiveSheetId();e.sheetId!==t&&this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:e.sheetId}),this.env.model.selection.selectCell(e.col,e.row)}get isSpillErrorBecauseOfMissingHeaders(){let e=this.evaluationError;return e?.value===F.SpilledBlocked&&!e.errorOriginPosition&&!this.env.model.getters.getSpreadZone(this.props.cellPosition,{ignoreSpillError:!0})}getMissingHeadersForSpread(){if(!this.isSpillErrorBecauseOfMissingHeaders)return;let e=this.env.model.getters.getCell(this.props.cellPosition);if(!e||!e.isFormula)return;let t=e.compiledFormula.toFormulaString(this.env.model.getters);return xn(this.env.model.getters,this.props.cellPosition,t)}addMissingHeaders({missingCols:e,missingRows:t}){let n=this.props.cellPosition.sheetId;e>0&&this.env.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:n,sheetName:this.env.model.getters.getSheetName(n),dimension:`COL`,base:this.env.model.getters.getNumberCols(n)-1,position:`after`,quantity:e+20}),t>0&&this.env.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:n,sheetName:this.env.model.getters.getSheetName(n),dimension:`ROW`,base:this.env.model.getters.getNumberRows(n)-1,position:`after`,quantity:t+50})}getAddMissingHeadersButtonText(e){return e.missingCols>0&&e.missingRows>0?P(`Add missing columns and rows`):e.missingCols>0?P(`Add missing columns`):P(`Add missing rows`)}};let yK={onHover:(e,t)=>{let n=t.getEvaluatedCell(e);return n.type===`error`&&n.message||t.getInvalidDataValidationMessage(e)?{isOpen:!0,props:{cellPosition:e},Component:vK,cellCorner:`top-right`}:{isOpen:!1}}};var bK=class extends A{static template=`o-spreadsheet-FilterMenu`;static components={FilterMenuValueList:tN,SidePanelCollapsible:WE,FilterMenuCriterion:$M};props=(0,t.useProps)({filterPosition:N.Position(),onClosed:N.function().optional()});state;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.state.values=this.getFilterHiddenValues(e.filterPosition))}),this.state=(0,t.proxy)({values:this.getFilterHiddenValues(this.props.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&&pc(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`?QM:this.criterionCategory===`number`?ZM:XM}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};LI(this.env,r,a,i,e,{emptyCellAsZero:!0,sortHeaders:!0}),this.props.onClosed?.()}getFilterHiddenValues(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getFilter({sheetId:t,...e});if(!n?.filteredRange)return[];let r=this.env.model.getters.getFilterValue({sheetId:t,...e}),i=dr(n.filteredRange.zone);r?.filterType!==`criterion`&&(i=i.filter(e=>!this.env.model.getters.isRowHidden(t,e.row)));let a=i.map(e=>this.env.model.getters.getEvaluatedCell({sheetId:t,...e}).formattedValue),o=r?.filterType===`values`?r.hiddenValues:[],s=new Set(o.map(jf)),c=new Set,l=[],u=e=>{let t=jf(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`}))}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:[]}}};let xK={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:bK,cellCorner:`bottom-left`})};var SK=class extends A{static template=`o-spreadsheet-LinkDisplay`;props=(0,t.useProps)({cellPosition:N.CellPosition(),onClosed:N.function().optional()});cellPopovers;setup(){this.cellPopovers=j(lw)}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 Gd(e,this.env.model.getters)}openLink(e){Kd(this.link,this.env,ue(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 CK={onHover:(e,t)=>{let n=t.getEvaluatedCell(e);return!t.isDashboard()&&n.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:SK,props:{cellPosition:e},cellCorner:`bottom-left`}:{isOpen:!1}}};var wK=class extends A{static template=`o-spreadsheet-LinkEditor`;static components={MenuPopover:w_};props=(0,t.useProps)({cellPosition:N.CellPosition(),onClosed:N.function().optional()});static size={maxHeight:500};urlInput=(0,t.signal)(null);suggestionListRef=(0,t.signal)(null);urlInputContainer=(0,t.signal)(null);state=(0,t.proxy)(this.defaultState);setup(){this.computeLinks(),(0,t.onMounted)(()=>this.urlInput()?.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 Vd.getKeys()){let i=Vd.get(r),a=i.getLinkProposals?.(this.env)||[],o=n&&this.state.isUrlEditable?rA(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()?.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 Gd(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?J_(this.state.label,n):this.state.url;this.env.model.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:this.env.model.getters.getActiveSheetId(),content:Pt(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()?.querySelector(`.suggestion-item[data-index="${this.state.selectedIndex}"]`)?.scrollIntoView({block:`nearest`})}};cw.add(`ErrorToolTip`,yK).add(`LinkCell`,CK).add(`LinkEditor`,{onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:wK,cellCorner:`bottom-left`})}).add(`FilterMenu`,xK),iA.add(`dataValidation`,{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(vn(t)||!this.composer.currentEditedCell)return[];let n=this.composer.currentEditedCell,r=this.getters.getValidationRuleForCell(n);if(!r||r.criterion.type!==`isValueInList`&&r.criterion.type!==`isValueInRange`)return[];let i=this.composer.currentEditedCell.sheetId,a=r.criterion.type===`isValueInRange`?this.getters.getDataValidationRangeValues(i,r.criterion):r.criterion.values.map(e=>({label:e,value:e}));if(r.criterion.displayStyle!==`chip`)return a.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));let o=r.criterion.colors;return a.map(e=>{let t=o?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:yp(t||`#E7E9ED`),backgroundColor:t||`#E7E9ED`,classes:[`badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start`]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t.text),this.composer.stopEdition()}}),iA.add(`functions_and_named_ranges`,{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if(e.type!==`SYMBOL`)return[];let t=e.value;if(!vn(this.composer.currentContent))return[];let n=Object.entries(al.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:n}])=>({type:`function`,text:e,icon:`o-spreadsheet-Icon.FX_SVG`,description:n,htmlContent:aN(t,e,Me,`o-semi-bold`)}));return n.push(...this.getters.getNamedRanges().map(e=>({type:`named_range`,text:e.name,description:this.getters.getRangeString(e.range),icon:`o-spreadsheet-Icon.NAMED_RANGE`,htmlContent:aN(t,e.name,Me,`o-semi-bold`)}))),n.sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text)),n},selectProposal(e,t){let n=e.end,r=e.end;[`SYMBOL`,`FUNCTION`].includes(e.type)&&(n=e.start);let i=this.composer.currentTokens,a=t.text;if(t.type===`function`){a+=`(`;let t=i.map(e=>e.start).indexOf(e.start);t+1<i.length&&i[t+1]?.type===`LEFT_PAREN`&&r++}this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(a)}});function TK(e,t){for(let n=0;n<t.length;n++){let r=t[n].proposalValues;r===void 0||r.length===0||iA.add(`${e}_function_${t[n].name}_argument_proposals`,{sequence:50,autoSelectFirstProposal:!0,selectProposal:EK,getProposals:t=>{let i=t.functionContext;if(!i||i.parent.toUpperCase()!==e.toUpperCase()||i.argPosition!==n)return;let a=[],o=``;for(let{value:e,label:t}of r){switch(typeof e){case`string`:o=`"${e}"`;break;case`number`:o=e.toString();break;case`boolean`:o=e?`TRUE`:`FALSE`;break;default:}a.push({text:o,description:t,htmlContent:[{value:o,color:typeof e==`string`?pt.STRING:pt.NUMBER}],fuzzySearchKey:o,alwaysExpanded:!0})}return a}})}}function EK(e,t){let n=e.end,r=e.end;[`LEFT_PAREN`,`ARG_SEPARATOR`].includes(e.type)||(n=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text)}al.getAll().forEach(e=>TK(e.name,e.args)),iA.add(`pivot_ids`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||![`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`].includes(t.parent.toUpperCase())||t.argPosition!==0)return;let n=this.getters.getPivotIds();if(!n.includes(e.value))return n.map(e=>{let t=this.getters.getPivotCoreDefinition(e),n=`${this.getters.getPivotFormulaId(e)}`;return{text:n,description:t.name,htmlContent:[{value:n,color:pt.NUMBER}],fuzzySearchKey:n+t.name,alwaysExpanded:!0}}).filter(w)},selectProposal:EK}),iA.add(`pivot_measures`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(t?.parent.toUpperCase()!==`PIVOT.VALUE`||t.argPosition!==1)return[];let n=aP(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return[];let i=this.getters.getPivot(r);return i.init(),i.isValid()?i.definition.measures.map(e=>{if(e.fieldName===`__count`){let e=`"__count"`;return{text:e,description:P(`Count`),htmlContent:[{value:e,color:pt.STRING}],fuzzySearchKey:P(`Count`)+e}}return nP(e)}).filter(w):[]},selectProposal:EK}),iA.add(`pivot_group_fields`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!DK(e)&&!OK(e))return;let n=aP(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);i.init();let a=i.getFields(),{columns:o,rows:s}=i.definition,c=t.args;t?.parent.toUpperCase()===`PIVOT.VALUE`?(c=c.filter((e,t)=>t%2==0),c=c.slice(1,t.argPosition)):c=c.filter((e,t)=>t%2==1);let l=c.map(e=>e?.value).filter(w),u=o.map(e=>e.nameWithGranularity),d=s.map(e=>e.nameWithGranularity),f=[],p=[`ARG_SEPARATOR`,`SPACE`].includes(e.type)?l.at(-1):l.at(-2),m=AR.get(i.type);if(m&&p?.startsWith(`#`)&&(p=p.slice(1)),p===void 0&&(f.push(u[0]),f.push(d[0])),d.includes(p)){let e=d[d.indexOf(p)+1];f.push(e),f.push(u[0])}if(u.includes(p)){let e=u[u.indexOf(p)+1];f.push(e)}let h=f.filter(w);return h.map(e=>{let[t,n]=e.split(`:`),r=a[t];return r?tP(r,n):void 0}).concat(h.map(e=>{if(!m)return;let t=a[e.split(`:`)[0]];if(!t)return;let n=`"#${e}"`;return{text:n,description:P(`%s (positional)`,t.string)+(t.help?` (${t.help})`:``),htmlContent:[{value:n,color:pt.STRING}],fuzzySearchKey:t.string+n}})).filter(w)},selectProposal:EK});function DK(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==0}function OK(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==1}iA.add(`pivot_group_values`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!e||!kK(e)&&!AK(e))return;let n=aP(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);if(!i.isValid())return;let a=t.argPosition,o=e.functionContext?.args[a-1]?.value;if(!o)return;let s;try{s=i.definition.getDimension(o)}catch{return}return s.granularity===`month_number`?Object.values(Zs).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:pt.NUMBER}]})):s.granularity===`quarter_number`?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:P(`Quarter %s`,e),htmlContent:[{value:`${e}`,color:pt.NUMBER}]})):s.granularity===`day_of_month`?C(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:pt.NUMBER}]})):s.granularity===`iso_week_number`?C(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:pt.NUMBER}]})):s.granularity===`day_of_week`?C(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:pt.NUMBER}]})):s.granularity===`hour_number`?C(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:pt.NUMBER}]})):s.granularity===`minute_number`?C(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:pt.NUMBER}]})):s.granularity===`second_number`?C(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:pt.NUMBER}]})):i.getPossibleFieldValues(s).map(({value:e,label:t})=>{let n=typeof e==`string`,r=n?`"${e}"`:e.toString(),i=n?pt.STRING:pt.NUMBER,a=t===e?``:t;return{text:r,description:a,htmlContent:[{value:r,color:i}],fuzzySearchKey:r+a}})},selectProposal:EK});function kK(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==1}function AK(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==0}iA.add(`sheet_names`,{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return e.type===`SYMBOL`||e.type===`UNKNOWN`&&e.value.startsWith(`'`)?this.getters.getSheetIds().map(e=>{let t=Tt(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith(`'`)?t:`'`+t}}):[]},selectProposal(e,t){let n=e.start,r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text+`!`)}});function jK(e){return e.yRanges.length&&!fl.test(e.yRanges[0])?`InvalidYRange`:e.xRange&&!fl.test(e.xRange)?`InvalidXRange`:e.labelRange&&!fl.test(e.labelRange)?`InvalidLabelRange`:e.sizeRange&&!fl.test(e.sizeRange)?`InvalidBubbleSizeRange`:`Success`}let MK={sequence:40,allowedDefinitionKeys:[...zh.commonKeys,`yRanges`,`xRange`,`labelRange`,`sizeRange`,`dataSetsHaveTitle`,`verticalAxisPosition`,`labelsAsText`,`bubbleColor`,`legendPosition`,`axesDesign`,`showValues`],fromStrDefinition(e,t,n){let r=e.yRanges.map(e=>Tu(n,t,e)).filter(w),i=Tu(n,t,e.xRange),a=Tu(n,t,e.labelRange),o=Tu(n,t,e.sizeRange);return{...e,yRanges:r,xRange:i,labelRange:a,sizeRange:o}},toStrDefinition(e,t,n){return{...e,yRanges:e.yRanges.map(e=>n.getRangeString(e,t)),xRange:e.xRange?n.getRangeString(e.xRange,t):void 0,labelRange:e.labelRange?n.getRangeString(e.labelRange,t):void 0,sizeRange:e.sizeRange?n.getRangeString(e.sizeRange,t):void 0}},validateDefinition(e,t){return e.checkValidations(t,jK)},transformDefinition(e,t,{adaptRangeString:n}){let r=e=>{if(!e)return;let{changeType:r,range:i}=n(t,e);return r===`REMOVE`?void 0:i};return{...e,yRanges:e.yRanges.map(r).filter(w),xRange:r(e.xRange),sizeRange:r(e.sizeRange),labelRange:r(e.labelRange)}},getDefinitionFromContextCreation(e,t){let n=e.dataSource?.type===`range`;return{background:e.background,yRanges:n?e.dataSource.dataSets?.map(e=>e.dataRange)??[]:[],verticalAxisPosition:e.dataSetStyles?.[0]?.verticalAxisPosition,dataSetsHaveTitle:n?e.dataSource.dataSetsHaveTitle??!1:!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`bubble`,labelRange:e.bubbleLabelRange||void 0,labelsAsText:e.labelsAsText??!1,xRange:e.auxiliaryRange||void 0,sizeRange:e.bubbleSizeRange||void 0,axesDesign:e.axesDesign,showValues:e.showValues,humanize:e.humanize,annotationText:e.annotationText,annotationLink:e.annotationLink,bubbleColor:e.bubbleColorMode||{color:`multiple`}}},getContextCreation(e,t){return{...e,dataSource:{type:`range`,dataSets:e.yRanges.map((e,t)=>({dataSetId:`${t}`,dataRange:e}))},bubbleLabelRange:e.labelRange,auxiliaryRange:e.xRange,bubbleSizeRange:e.sizeRange,bubbleColorMode:e.bubbleColor}},getDefinitionForExcel:()=>void 0,updateRanges(e,t){let n=e.yRanges.map(e=>nm(e,t)).filter(w),r=nm(e.xRange,t),i=nm(e.labelRange,t),a=nm(e.sizeRange,t);return{...e,yRanges:n,xRange:r,labelRange:i,sizeRange:a}},duplicateInDuplicatedSheet(e,t,n){let r=e=>tm(t,n,e);return{...e,yRanges:e.yRanges.map(r).filter(w),xRange:r(e.xRange),labelRange:r(e.labelRange),sizeRange:r(e.sizeRange)}},copyInSheetId:e=>e,getRuntime(e,t){let n=OD(t,e);return{chartJsConfig:{type:`line`,data:{datasets:lh(t,n),labels:n.labels},options:{...Cg,layout:$D(t,n),scales:Wm(t,n),plugins:{title:FO(t,e),legend:vO(t,n),tooltip:HO(t,n),chartShowValuesPlugin:kO(t,n),background:{color:t.background}}}}}}};function NK(e){return!Tk.includes(e.horizontalGroupBy)||!Tk.includes(e.verticalGroupBy)?`InvalidChartDefinition`:`Success`}let PK={sequence:110,dataSeriesLimit:1,allowedDefinitionKeys:[...zh.commonKeys,`dataSource`,`dataSetStyles`,`showValues`,`colorScale`,`missingValueColor`,`axesDesign`,`horizontalGroupBy`,`verticalGroupBy`,`legendPosition`],validateDefinition(e,t){return e.checkValidations(t,NK)},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`,annotationLink:e.annotationLink,annotationText:e.annotationText}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n}){let r=bD(t,n(),e),{labels:i,datasets:a}=ah(t,r);return{chartJsConfig:{type:`calendar`,data:{labels:i,datasets:a},options:{...Cg,indexAxis:`x`,layout:eO(t,r),scales:Rm(t,a),plugins:{title:FO(t,e),legend:{display:!1},tooltip:BO(t,r),chartShowValuesPlugin:AO(t,r),chartColorScalePlugin:zm(t,r),background:{color:r.background}}}}}}},FK={sequence:15,allowedDefinitionKeys:[...zh.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:uD(t.background||`#FFFFFF`),fontColor:uD(sm(t.background)),dataSets:n,labelRange:r,verticalAxis:pm(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,annotationText:e.annotationText,annotationLink:e.annotationLink}},getRuntime(e,t,{extractData:n},r,i){let a=_D(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:fh(t,a)},options:{...Cg,layout:$D(t,a),scales:Lm(t,a),plugins:{title:FO(t,e),legend:yO(t,a),tooltip:zO(t,a),chartShowValuesPlugin:kO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},IK={sequence:100,dataSeriesLimit:1,allowedDefinitionKeys:[...zh.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,annotationText:e.annotationText,annotationLink:e.annotationLink}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=ED(t,n(),e);return{chartJsConfig:{type:`funnel`,data:{labels:a.labels,datasets:hh(t,a)},options:{...Cg,indexAxis:`y`,layout:$D(t,a),scales:Ym(t,a),plugins:{title:FO(t,e),legend:{display:!1},tooltip:JO(t,a),chartShowValuesPlugin:kO(t,a),background:{color:a.background}},...i}}}}},LK={sequence:90,dataSeriesLimit:1,allowedDefinitionKeys:[...zh.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,annotationLink:e.annotationLink,annotationText:e.annotationText}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=TD(t,n(),e);return{chartJsConfig:{type:`choropleth`,data:{datasets:mh(t,a)},options:{...Cg,layout:$D(t,a),scales:Jm(t,a),plugins:{title:FO(t,e),tooltip:qO(t,a),legend:{display:!1},background:{color:a.background}},...i}}}}},RK={sequence:80,dataSeriesLimit:2,allowedDefinitionKeys:[...zh.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,annotationLink:e.annotationLink,annotationText:e.annotationText}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){if(t.dataSource.type!==`range`)return;let i=xD(t,bk(e,t.dataSource),e),{dataSetsValues:a}=i,o=Math.max(...a.map(e=>Math.max(...e.data.map(e=>nf(e)?Math.abs(e.value):-1/0))));return{...t,horizontal:!0,backgroundColor:uD(i.background||`#FFFFFF`),fontColor:uD(sm(i.background)),dataSets:n,labelRange:r,verticalAxis:pm(t),maxValue:o}},getRuntime(e,t,{extractData:n},r,i){let a=xD(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:rh(t,a)},options:{...Cg,indexAxis:`y`,layout:$D(t,a),scales:Km(t,a),plugins:{title:FO(t,e),legend:mO(t,a),tooltip:GO(t,a),chartShowValuesPlugin:MO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},zK={sequence:80,allowedDefinitionKeys:[...zh.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,annotationLink:e.annotationLink,annotationText:e.annotationText}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:uD(t.background||`#FFFFFF`),fontColor:uD(sm(t.background)),dataSets:n,labelRange:r}},getRuntime(e,t,{extractData:n},r,i){let a=wD(t,n(),e);return{chartJsConfig:{type:`radar`,data:{labels:a.labels,datasets:ph(t,a)},options:{...Cg,layout:$D(t,a),scales:qm(t,a),plugins:{title:FO(t,e),legend:xO(t,a),tooltip:KO(t,a),chartShowValuesPlugin:kO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},BK={sequence:60,allowedDefinitionKeys:[...zh.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,annotationLink:e.annotationLink,annotationText:e.annotationText}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:uD(t.background||`#FFFFFF`),fontColor:uD(sm(t.background)),dataSets:n,labelRange:r,verticalAxis:pm(t)}},getRuntime(e,t,{extractData:n},r,i){let a=SD(t,n(),e);return{chartJsConfig:{type:`line`,data:{labels:a.labels,datasets:ch(t,a)},options:{...Cg,layout:$D(t,a),scales:Um(t,a),plugins:{title:FO(t,e),legend:_O(t,a),tooltip:VO(t,a),chartShowValuesPlugin:kO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},VK={sequence:30,allowedDefinitionKeys:[...zh.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,annotationLink:e.annotationLink,annotationText:e.annotationText}},getContextCreation(e,t,n){return{...e,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=DD(t,n(),e);return{chartJsConfig:{type:`doughnut`,data:{datasets:_h(t,a)},options:{cutout:t.pieHolePercentage===void 0?`25%`:`${t.pieHolePercentage}%`,...Cg,layout:$D(t,a),plugins:{title:FO(t,e),legend:SO(t,a),tooltip:YO(t,a),sunburstLabelsPlugin:jO(t,a),sunburstHoverPlugin:{enabled:!0},background:{color:a.background}},...i}}}}},HK={sequence:100,allowedDefinitionKeys:[...zh.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,annotationText:e.annotationText,annotationLink:e.annotationLink}},getContextCreation(e,t,n){return{...e,treemapColoringOptions:e.coloringOptions,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=DD(t,n(),e);return{chartJsConfig:{type:`treemap`,data:{labels:a.labels,datasets:Sh(t,a)},options:{...Cg,layout:$D(t,a),plugins:{title:FO(t,e),legend:{display:!1},tooltip:XO(t,a),background:{color:a.background}},...i}}}}};Tb.add(`bar`,ek),Tb.add(`combo`,FK),Tb.add(`line`,dk),Tb.add(`pie`,fk),Tb.add(`scorecard`,Yh),Tb.add(`gauge`,ok),Tb.add(`scatter`,BK),Tb.add(`waterfall`,pk),Tb.add(`pyramid`,RK),Tb.add(`radar`,zK),Tb.add(`geo`,LK),Tb.add(`funnel`,IK),Tb.add(`sunburst`,VK),Tb.add(`treemap`,HK),Tb.add(`calendar`,PK),Tb.add(`bubble`,MK),Hg.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:P(`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:P(`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:P(`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:P(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:P(`Scatter`),chartType:`scatter`,chartSubtype:`scatter`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCATTER_CHART`}).add(`bubble`,{displayName:P(`Bubble`),chartType:`bubble`,chartSubtype:`bubble`,category:`misc`,preview:`o-spreadsheet-ChartPreview.BUBBLE_CHART`}).add(`column`,{matcher:e=>e.type===`bar`&&!e.stacked&&!e.horizontal,displayName:P(`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:P(`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:P(`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:P(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:P(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:P(`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:P(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:P(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:P(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:P(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:P(`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:P(`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:P(`Filled Radar`),chartType:`radar`,chartSubtype:`filled_radar`,subtypeDefinition:{fillArea:!0},category:`misc`,preview:`o-spreadsheet-ChartPreview.FILLED_RADAR_CHART`}).add(`geo`,{displayName:P(`Geo Chart`),chartSubtype:`geo`,chartType:`geo`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GEO_CHART`}).add(`funnel`,{displayName:P(`Funnel`),chartSubtype:`funnel`,chartType:`funnel`,category:`misc`,preview:`o-spreadsheet-ChartPreview.FUNNEL_CHART`}).add(`sunburst`,{matcher:e=>e.type===`sunburst`,displayName:P(`Sunburst`),chartSubtype:`sunburst`,chartType:`sunburst`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.SUNBURST_CHART`}).add(`treemap`,{matcher:e=>e.type===`treemap`,displayName:P(`Tree Map`),chartType:`treemap`,chartSubtype:`treemap`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.TREE_MAP_CHART`}).add(`calendar`,{displayName:P(`Calendar`),chartSubtype:`calendar`,chartType:`calendar`,category:`misc`,preview:`o-spreadsheet-ChartPreview.CALENDAR_CHART`}),Pz.add(`filter_icon`,(e,t)=>{if(e.isFilterHeader(t)){let n=e.isFilterActive(t),r=tp(e.getCellComputedStyle(t).fillColor||`#fff`)<.45;return{type:`filter_icon`,svg:Py(n,r,!1),hoverSvg:Py(n,r,!0),priority:3,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let n=t.getStore(lw),r=n.persistentCellPopover;if(r.isOpen&&r.col===e.col&&r.row===e.row&&r.type===`FilterMenu`){n.close();return}n.open(e,`FilterMenu`)}}}});var UK=l({ARRAYTOTEXT:()=>vq,ARRAY_CONSTRAIN:()=>KK,ARRAY_LITERAL:()=>qK,ARRAY_ROW:()=>JK,CHOOSECOLS:()=>YK,CHOOSEROWS:()=>XK,EXPAND:()=>ZK,FLATTEN:()=>QK,FREQUENCY:()=>$K,HSTACK:()=>eq,MDETERM:()=>tq,MINVERSE:()=>nq,MMULT:()=>rq,SUMPRODUCT:()=>iq,SUMX2MY2:()=>oq,SUMX2PY2:()=>sq,SUMXMY2:()=>cq,TOCOL:()=>dq,TOROW:()=>fq,TRANSPOSE:()=>pq,VSTACK:()=>mq,WRAPCOLS:()=>hq,WRAPROWS:()=>gq});function WK(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 I(P(`All ranges in [[FUNCTION_NAME]] must have the same number of rows (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 GK(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 I(P(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=rs(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 KK={description:P(`Returns a result array constrained to a specific width and height.`),args:[U(`input_range (any, range<any>)`,P(`The range to constrain.`)),U(`rows (number)`,P(`The number of rows in the constrained array.`)),U(`columns (number)`,P(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=B(e),i=Uo(t?.value,this.locale),a=Uo(n?.value,this.locale);if(i<=0)return new I(P(`The rows argument (%s) must be strictly positive.`,i.toString()));if(a<=0)return new I(P(`The columns argument (%s) must be strictly positive.`,a.toString()));let o=Math.min(i,r[0].length);return rs(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},qK={description:P(`Appends ranges vertically and in sequence to return a larger array. All ranges must have the same number of columns.`),args:[U(`range (any, range<any>, repeating)`,P(`The range to be appended.`))],compute:function(...e){return GK(e,{requireSameColCount:!0})},isExported:!1,hidden:!0},JK={description:P(`Appends ranges horizontally and in sequence to return a larger array. All ranges must have the same number of rows.`),args:[U(`range (any, range<any>, repeating)`,P(`The range to be appended.`))],compute:function(...e){return WK(e,{requireSameRowCount:!0})},isExported:!1,hidden:!0},YK={description:P(`Creates a new array from the selected columns in the existing range.`),args:[U(`array (any, range<any>)`,P(`The array that contains the columns to be returned.`)),U(`col_num (number, range<number>, repeating)`,P(`The column index of the column to be returned.`))],compute:function(e,...t){let n=B(e),r=vs(t,e=>Uo(e?.value,this.locale)),i=r.filter(e=>e===0||n.length<Math.abs(e));if(i.length!==0)return new I(P(`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},XK={description:P(`Creates a new array from the selected rows in the existing range.`),args:[U(`array (any, range<any>)`,P(`The array that contains the rows to be returned.`)),U(`row_num (number, range<number>, repeating)`,P(`The row index of the row to be returned.`))],compute:function(e,...t){let n=B(e),r=vs(t,e=>Uo(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?rs(i,r.length,(e,t)=>r[t]>0?n[e][r[t]-1]:n[e][n[e].length+r[t]]):new I(P(`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},ZK={description:P(`Expands or pads an array to specified row and column dimensions.`),args:[U(`array (any, range<any>)`,P(`The array to expand.`)),U(`rows (number)`,P(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),U(`columns (number, optional)`,P(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),U(`pad_with (any, default=0)`,P(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=B(e),a=Uo(t?.value,this.locale),o=n===void 0?i.length:Uo(n.value,this.locale);return a<i[0].length?new I(P(`The rows arguments (%s) must be greater or equal than the number of rows of the array.`,a.toString())):o<i.length?new I(P(`The columns arguments (%s) must be greater or equal than the number of columns of the array.`,o.toString())):rs(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},QK={description:P(`Flattens all the values from one or more ranges into a single column.`),args:[U(`range (any, range<any>, repeating)`,P(`The range to flatten.`))],compute:function(...e){return[vs(e,e=>e===void 0?{value:``}:e)]},isExported:!1},$K={description:P(`Calculates the frequency distribution of a range.`),args:[U(`data (range<number>)`,P(`The array of ranges containing the values to be counted.`)),U(`classes (number, range<number>)`,P(`The range containing the set of classes.`))],compute:function(e,t){let n=vs([e],e=>e.value).filter(e=>typeof e==`number`),r=vs([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},eq={description:P(`Appends ranges horizontally and in sequence to return a larger array.`),args:[U(`range (any, range<any>, repeating)`,P(`The range to be appended.`))],compute:function(...e){return WK(e)},isExported:!0},tq={description:P(`Returns the matrix determinant of a square matrix.`),args:[U(`square_matrix (number, range<number>)`,P(`An range with an equal number of rows and columns representing a matrix whose determinant will be calculated.`))],compute:function(e){let t=Vo(e,`square_matrix`);return dS(t)?mS(t).determinant:new I(P(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},nq={description:P(`Returns the multiplicative inverse of a square matrix.`),args:[U(`square_matrix (number, range<number>)`,P(`An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated.`))],compute:function(e){let t=Vo(e,`square_matrix`);if(!dS(t))return new I(P(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=mS(t);return n||new I(P(`The matrix is not invertible.`))},isExported:!0},rq={description:P(`Calculates the matrix product of two matrices.`),args:[U(`matrix1 (number, range<number>)`,P(`The first matrix in the matrix multiplication operation.`)),U(`matrix2 (number, range<number>)`,P(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=Vo(e,`matrix1`),r=Vo(t,`matrix2`);return n.length===0||r.length===0?new I(P(`The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.`)):n.length===r[0].length?gS(n,r):new I(P(`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},iq={description:P(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[U(`range (number, range<number>, repeating)`,P(`The range whose entries will be multiplied with corresponding entries in the other range.`))],compute:function(...e){if(!uS(...e))return new I(P(`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*=L(n[e][r],this.locale);n+=i}return n},isExported:!0};function aq(e,t,n){if(!uS(e,t))return new I(P(`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 I(P(`The arguments array_x and array_y must contain at least one pair of numbers.`))}let oq={description:P(`Calculates the sum of the difference of the squares of the values in two array.`),args:[U(`array_x (number, range<number>)`,P(`The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.`)),U(`array_y (number, range<number>)`,P(`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 aq(e,t,(e,t)=>e**2-t**2)},isExported:!0},sq={description:P(`Calculates the sum of the sum of the squares of the values in two array.`),args:[U(`array_x (number, range<number>)`,P(`The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.`)),U(`array_y (number, range<number>)`,P(`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 aq(e,t,(e,t)=>e**2+t**2)},isExported:!0},cq={description:P(`Calculates the sum of squares of the differences of values in two array.`),args:[U(`array_x (number, range<number>)`,P(`The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.`)),U(`array_y (number, range<number>)`,P(`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 aq(e,t,(e,t)=>(e-t)**2)},isExported:!0},lq=[U(`array (any, range<any>)`,P(`The array which will be transformed.`)),U(`ignore (number, default=0)`,P(`Whether to ignore certain types of values. By default, no values are ignored.`),[{value:0,label:P(`Keep all values (default)`)},{value:1,label:P(`Ignore blanks`)},{value:2,label:P(`Ignore errors`)},{value:3,label:P(`Ignore blanks and errors`)}]),U(`scan_by_column (number, default=false)`,P(`Scan the array by column. By default, the array is scanned by row.`),[{value:!1,label:P(`Scan by row (default)`)},{value:!0,label:P(`Scan by column`)}])];function uq(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!Po(e.value);if(t===3)return e=>e.value!==null&&!Po(e.value);throw new I(P(`Argument ignore must be between 0 and 3`))}let dq={description:P(`Transforms a range of cells into a single column.`),args:lq,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=L(t.value,this.locale),a=(z(n.value)?r:os(r)).flat().filter(uq(i));return a.length===0?new Do(P(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},fq={description:P(`Transforms a range of cells into a single row.`),args:lq,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=L(t.value,this.locale),a=(z(n.value)?r:os(r)).flat().filter(uq(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Do(P(`No results for the given arguments of TOROW.`)):a},isExported:!0},pq={description:P(`Transposes the rows and columns of a range.`),args:[U(`range (any, range<any>)`,P(`The range to be transposed.`))],compute:function(e){let t=B(e),n=t[0].length,r=t.length;return rs(n,r,(e,n)=>t[n][e])},isExported:!0},mq={description:P(`Appends ranges vertically and in sequence to return a larger array.`),args:[U(`range (any, range<any>, repeating)`,P(`The range to be appended.`))],compute:function(...e){return GK(e)},isExported:!0},hq={description:P(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[U(`range (any, range<any>)`,P(`The range to wrap.`)),U(`wrap_count (number)`,P(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),U(`pad_with (any, default=0)`,P(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Uo(t?.value,this.locale);if(!lS(r))return new I(P(`Argument range must be a single row or column.`));if(i<1)return new I(P(`The wrap_count (%s) must be strictly positive.`,i),F.InvalidNumber);let a=r.flat();return rs(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},gq={description:P(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[U(`range (any, range<any>)`,P(`The range to wrap.`)),U(`wrap_count (number)`,P(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),U(`pad_with (any, default=0)`,P(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Uo(t?.value,this.locale);if(!lS(r))return new I(P(`Argument range must be a single row or column.`));if(i<1)return new I(P(`The wrap_count (%s) must be strictly positive.`,i),F.InvalidNumber);let a=r.flat();return rs(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0},_q=[{value:0,label:P(`Concise format\xA0(default)`)},{value:1,label:P(`Strict format`)}],vq={description:P(`returns an array of text values from any specified range. It passes text values unchanged, and converts non-text values to text.`),args:[U(`array (range)`,P(`The array to convert into text`)),U(`format (number, default=0)`,P(`The format of the returned data.`),_q)],compute:function(e,t={value:0}){let n=L(t,this.locale),r=B(e);if(n===1)return $k(r,``,this.locale);if(n===0){let e=this.locale.decimalSeparator===`,`?`/`:`,`;return os(r).flatMap(e=>e.map(e=>Po(e.value)?e.value:R(e))).join(e)}else return new I(P(`Format must be 0 or 1`))},isExported:!0};var yq=l({ABS:()=>xq,ACOS:()=>Sq,ACOSH:()=>Cq,ACOT:()=>wq,ACOTH:()=>Tq,ASIN:()=>Eq,ASINH:()=>Dq,ATAN:()=>Oq,ATAN2:()=>kq,ATANH:()=>Aq,CEILING:()=>jq,CEILING_MATH:()=>Nq,CEILING_PRECISE:()=>Pq,COS:()=>Fq,COSH:()=>Iq,COT:()=>Lq,COTH:()=>Rq,COUNTBLANK:()=>zq,COUNTIF:()=>Bq,COUNTIFS:()=>Vq,COUNTUNIQUE:()=>Hq,COUNTUNIQUEIFS:()=>Uq,CSC:()=>Wq,CSCH:()=>Gq,DECIMAL:()=>Kq,DEGREES:()=>qq,EXP:()=>Jq,FLOOR:()=>Yq,FLOOR_MATH:()=>Zq,FLOOR_PRECISE:()=>Qq,INT:()=>PJ,ISEVEN:()=>$q,ISODD:()=>tJ,ISO_CEILING:()=>eJ,LN:()=>nJ,LOG:()=>rJ,MOD:()=>aJ,MUNIT:()=>oJ,ODD:()=>sJ,PI:()=>cJ,POWER:()=>lJ,PRODUCT:()=>uJ,RAND:()=>dJ,RANDARRAY:()=>fJ,RANDBETWEEN:()=>pJ,ROUND:()=>mJ,ROUNDDOWN:()=>hJ,ROUNDUP:()=>gJ,SEC:()=>_J,SECH:()=>vJ,SEQUENCE:()=>yJ,SIN:()=>bJ,SINH:()=>xJ,SQRT:()=>SJ,SUBTOTAL:()=>EJ,SUM:()=>DJ,SUMIF:()=>OJ,SUMIFS:()=>kJ,TAN:()=>AJ,TANH:()=>jJ,TRUNC:()=>NJ});let bq=/^-?[a-z0-9]+$/i,xq={description:P(`Absolute value of a number.`),args:[U(`value (number)`,P(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(L(e,this.locale))},isExported:!0},Sq={description:P(`Inverse cosine of a value, in radians.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=L(e,this.locale);return Math.abs(t)>1?new I(P(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.acos(t)},isExported:!0},Cq={description:P(`Inverse hyperbolic cosine of a number.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.`))],compute:function(e){let t=L(e,this.locale);return t<1?new I(P(`The value (%s) must be greater than or equal to 1.`,t)):Math.acosh(t)},isExported:!0},wq={description:P(`Inverse cotangent of a value.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=L(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Tq={description:P(`Inverse hyperbolic cotangent of a value.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.`))],compute:function(e){let t=L(e,this.locale);return Math.abs(t)<=1?new I(P(`The value (%s) cannot be between -1 and 1 inclusive.`,t)):Math.log((t+1)/(t-1))/2},isExported:!0},Eq={description:P(`Inverse sine of a value, in radians.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=L(e,this.locale);return Math.abs(t)>1?new I(P(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.asin(t)},isExported:!0},Dq={description:P(`Inverse hyperbolic sine of a number.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(L(e,this.locale))},isExported:!0},Oq={description:P(`Inverse tangent of a value, in radians.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(L(e,this.locale))},isExported:!0},kq={description:P(`Angle from the X axis to a point (x,y), in radians.`),args:[U(`x (number)`,P(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),U(`y (number)`,P(`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=L(e,this.locale),r=L(t,this.locale);return n===0&&r===0?new Ao(P(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},Aq={description:P(`Inverse hyperbolic tangent of a number.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.`))],compute:function(e){let t=L(e,this.locale);return Math.abs(t)>=1?new I(P(`The value (%s) must be between -1 and 1 exclusive.`,t)):Math.atanh(t)},isExported:!0},jq={description:P(`Rounds number up to nearest multiple of factor.`),args:[U(`value (number)`,P(`The value to round up to the nearest integer multiple of factor.`)),U(`factor (number, default=1)`,P(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=L(e,this.locale),r=L(t,this.locale);return r<0&&n>0?new I(P(`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 Mq(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 Nq={description:P(`Rounds number up to nearest multiple of factor.`),args:[U(`number (number)`,P(`The value to round up to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,P(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),U(`mode (number, default=0)`,P(`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=L(t,this.locale);return{value:Mq(L(e,this.locale),r,L(n,this.locale)),format:e?.format}},isExported:!0},Pq={description:P(`Rounds number up to nearest multiple of factor.`),args:[U(`number (number)`,P(`The value to round up to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,P(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=L(t,this.locale);return{value:Mq(L(e,this.locale),n),format:e?.format}},isExported:!0},Fq={description:P(`Cosine of an angle provided in radians.`),args:[U(`angle (number)`,P(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(L(e,this.locale))},isExported:!0},Iq={description:P(`Hyperbolic cosine of any real number.`),args:[U(`value (number)`,P(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(L(e,this.locale))},isExported:!0},Lq={description:P(`Cotangent of an angle provided in radians.`),args:[U(`angle (number)`,P(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=L(e,this.locale);return t===0?new Ao(P(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},Rq={description:P(`Hyperbolic cotangent of any real number.`),args:[U(`value (number)`,P(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=L(e,this.locale);return t===0?new Ao(P(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},zq={description:P(`Number of empty values.`),args:[U(`value (any, range, repeating)`,P(`Value or range in which to count the number of blanks.`))],compute:function(...e){return es(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},Bq={description:P(`A conditional count across a range.`),args:[U(`range (range)`,P(`The range that is tested against criterion.`)),U(`criterion (string)`,P(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return fs(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},Vq={description:P(`Count values depending on multiple criteria.`),args:[U(`criteria_range (any, range, repeating)`,P(`Range over which to evaluate criteria.`)),U(`criterion (string, repeating)`,P(`Criteria to check.`))],compute:function(...e){let t=0;return fs(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},Hq={description:P(`Counts number of unique values in a range.`),args:[U(`value (any, range, repeating)`,P(`Value or range to consider for uniqueness.`))],compute:function(...e){return oS(e)}},Uq={description:P(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[U(`range (range)`,P(`The range of cells from which the number of unique values will be counted.`)),U(`criteria_range (any, range, repeating)`,P(`Range over which to evaluate criteria.`)),U(`criterion (string, repeating)`,P(`Criteria to check.`))],compute:function(e,...t){let n=new Set;return fs(t,(t,r)=>{let i=e[t]?.[r];ys(i)&&n.add(i.value)},this.locale),n.size}},Wq={description:P(`Cosecant of an angle provided in radians.`),args:[U(`angle (number)`,P(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=L(e,this.locale);return t===0?new Ao(P(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},Gq={description:P(`Hyperbolic cosecant of any real number.`),args:[U(`value (number)`,P(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=L(e,this.locale);return t===0?new Ao(P(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},Kq={description:P(`Converts from another base to decimal.`),args:[U(`value (string)`,P(`The number to convert.`)),U(`base (number)`,P(`The base to convert the value from.`))],compute:function(e,t){let n=L(t,this.locale);if(n=Math.floor(n),2>n||n>36)return new I(P(`The base (%s) must be between 2 and 36 inclusive.`,n));let r=R(e);if(r===``)return 0;if(!bq.test(r))return new I(P(`The value (%s) must be a valid base %s representation.`,r,n));let i=r.replace(`-`,``);for(let e of i)if(parseInt(e,36)>=n)return new I(P(`The value (%s) must be a valid base %s representation.`,r,n));let a=parseInt(r,n);return isNaN(a)?new I(P(`The value (%s) must be a valid base %s representation.`,r,n)):a},isExported:!0},qq={description:P(`Converts an angle value in radians to degrees.`),args:[U(`angle (number)`,P(`The angle to convert from radians to degrees.`))],compute:function(e){return L(e,this.locale)*180/Math.PI},isExported:!0},Jq={description:P(`Euler's number, e (~2.718) raised to a power.`),args:[U(`value (number)`,P(`The exponent to raise e.`))],compute:function(e){return Math.exp(L(e,this.locale))},isExported:!0},Yq={description:P(`Rounds number down to nearest multiple of factor.`),args:[U(`value (number)`,P(`The value to round down to the nearest integer multiple of factor.`)),U(`factor (number, default=1)`,P(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=L(e,this.locale),r=L(t,this.locale);return r<0&&n>0?new I(P(`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 Xq(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 Zq={description:P(`Rounds number down to nearest multiple of factor.`),args:[U(`number (number)`,P(`The value to round down to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,P(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),U(`mode (number, default=0)`,P(`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=L(t,this.locale);return{value:Xq(L(e,this.locale),r,L(n,this.locale)),format:e?.format}},isExported:!0},Qq={description:P(`Rounds number down to nearest multiple of factor.`),args:[U(`number (number)`,P(`The value to round down to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,P(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=L(t,this.locale);return{value:Xq(L(e,this.locale),n),format:e?.format}},isExported:!0},$q={description:P(`Whether the provided value is even.`),args:[U(`value (number)`,P(`The value to be verified as even.`))],compute:function(e){let t=Ho(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},eJ={description:P(`Rounds number up to nearest multiple of factor.`),args:[U(`number (number)`,P(`The value to round up to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,P(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:Mq(L(e,this.locale),L(t,this.locale)),format:e?.format}},isExported:!0},tJ={description:P(`Whether the provided value is even.`),args:[U(`value (number)`,P(`The value to be verified as even.`))],compute:function(e){let t=Ho(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},nJ={description:P(`The logarithm of a number, base e (euler's number).`),args:[U(`value (number)`,P(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=L(e,this.locale);return t<=0?new I(P(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},rJ={description:P(`The logarithm of a number, for a given base.`),args:[U(`value (number)`,P(`The value for which to calculate the logarithm.`)),U(`base (number, default=10)`,P(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=L(e,this.locale),r=L(t,this.locale);return n<=0?new I(P(`The value (%s) must be strictly positive.`,n)):r<=0?new I(P(`The base (%s) must be strictly positive.`,r)):r===1?new I(P(`The base must be different from 1.`)):Math.log10(n)/Math.log10(r)},isExported:!0};function iJ(e,t){cS(t,P(`The divisor must be different from 0.`));let n=e%t;return n>0&&t<0||n<0&&t>0?n+t:n}let aJ={description:P(`Modulo (remainder) operator.`),args:[U(`dividend (number)`,P(`The number to be divided to find the remainder.`)),U(`divisor (number)`,P(`The number to divide by.`))],compute:function(e,t){let n=L(t,this.locale);return{value:iJ(L(e,this.locale),n),format:e?.format}},isExported:!0},oJ={description:P(`Returns a n x n unit matrix, where n is the input dimension.`),args:[U(`dimension (number)`,P(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=Uo(e,this.locale);return t<1?new I(P(`The argument dimension must be positive`)):pS(t)},isExported:!0},sJ={description:P(`Rounds a number up to the nearest odd integer.`),args:[U(`value (number)`,P(`The value to round to the next greatest odd number.`))],compute:function(e){let t=L(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},cJ={description:P(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},lJ={description:P(`A number raised to a power.`),args:[U(`base (number)`,P(`The number to raise to the exponent power.`)),U(`exponent (number)`,P(`The exponent to raise base to.`))],compute:function(e,t){let n=L(e,this.locale),r=L(t,this.locale);return n<0&&!Number.isInteger(r)?new I(P(`The exponent (%s) must be an integer when the base is negative.`,r)):{value:n**+r,format:e?.format}},isExported:!0},uJ={description:P(`Result of multiplying a series of numbers together.`),args:[U(`factor (number, range<number>, repeating)`,P(`Number or range to calculate for the product.`))],compute:function(...e){let t=0,n=1;for(let r of e)if(ht(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),Po(e))return r}else r!==void 0&&r.value!==null&&(n*=Ho(r,this.locale),t+=1);return{value:t===0?0:n,format:No(e[0])}},isExported:!0},dJ={description:P(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},fJ={description:P(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[U(`rows (number, default=1)`,P(`The number of rows to be returned.`)),U(`columns (number, default=1)`,P(`The number of columns to be returned.`)),U(`min (number, default=0)`,P(`The minimum number you would like returned.`)),U(`max (number, default=1)`,P(`The maximum number you would like returned.`)),U(`whole_number (boolean, default=FALSE)`,P(`Return a whole number or a decimal value.`),[{value:!1,label:P(`Decimal (default)`)},{value:!0,label:P(`Integer`)}])],compute:function(e={value:1},t={value:1},n={value:0},r={value:1},i={value:!1}){let a=Uo(t,this.locale),o=Uo(e,this.locale),s=L(n,this.locale),c=L(r,this.locale),l=z(i);if(a<1)return new I(P(`The number of columns (%s) must be positive.`,a));if(o<1)return new I(P(`The number of rows (%s) must be positive.`,o));if(s>c)return new I(P(`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 I(P(`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},pJ={description:P(`Random integer between two values, inclusive.`),args:[U(`low (number)`,P(`The low end of the random range.`)),U(`high (number)`,P(`The high end of the random range.`))],compute:function(e,t){let n=L(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=L(t,this.locale);return Number.isInteger(r)||(r=Math.floor(r)),n>r?new I(P(`The high (%s) must be greater than or equal to the low (%s).`,r,n)):{value:n+Math.floor((r-n+1)*Math.random()),format:e?.format}},isExported:!0},mJ={description:P(`Rounds a number according to standard rules.`),args:[U(`value (number)`,P(`The value to round to places number of places.`)),U(`places (number, default=0)`,P(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=L(e,this.locale),r=L(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},hJ={description:P(`Rounds down a number.`),args:[U(`value (number)`,P(`The value to round to places number of places, always rounding down.`)),U(`places (number, default=0)`,P(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=L(e,this.locale),r=L(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},gJ={description:P(`Rounds up a number.`),args:[U(`value (number)`,P(`The value to round to places number of places, always rounding up.`)),U(`places (number, default=0)`,P(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=L(e,this.locale),r=L(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},_J={description:P(`Secant of an angle provided in radians.`),args:[U(`angle (number)`,P(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(L(e,this.locale))},isExported:!0},vJ={description:P(`Hyperbolic secant of any real number.`),args:[U(`value (number)`,P(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(L(e,this.locale))},isExported:!0},yJ={description:P(`Returns a sequence of numbers.`),args:[U(`rows (number)`,P(`The number of rows to return`)),U(`columns (number, optional, default=1)`,P(`The number of columns to return`)),U(`start (number, optional, default=1)`,P(`The first number in the sequence`)),U(`step (number, optional, default=1)`,P(`The amount to increment each value in the sequence`))],compute:function(e,t={value:1},n={value:1},r={value:1}){let i=L(n,this.locale),a=L(r,this.locale),o=Uo(e,this.locale),s=Uo(t,this.locale);return s<1?new I(P(`The number of columns (%s) must be positive.`,s)):o<1?new I(P(`The number of rows (%s) must be positive.`,o)):rs(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},bJ={description:P(`Sine of an angle provided in radians.`),args:[U(`angle (number)`,P(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(L(e,this.locale))},isExported:!0},xJ={description:P(`Hyperbolic sine of any real number.`),args:[U(`value (number)`,P(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(L(e,this.locale))},isExported:!0},SJ={description:P(`Positive square root of a positive number.`),args:[U(`value (number)`,P(`The number for which to calculate the positive square root.`))],compute:function(e){let t=L(e,this.locale);return t<0?new I(P(`The value (%s) must be positive or null.`,t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},CJ={1:`AVERAGE`,2:`COUNT`,3:`COUNTA`,4:`MAX`,5:`MIN`,6:`PRODUCT`,7:`STDEV`,8:`STDEVP`,9:`SUM`,10:`VAR`,11:`VARP`},wJ=Object.entries(CJ).map(([e,t])=>({value:parseInt(e),label:P(`%s (include manually-hidden rows)`,t)})),TJ=Object.entries(CJ).map(([e,t])=>({value:parseInt(e)+100,label:P(`%s (exclude manually-hidden rows)`,t)})),EJ={description:P(`Returns a subtotal for a vertical range of cells using a specified aggregation function.`),args:[U(`function_code (number)`,P(`The function to use in subtotal aggregation.`),[...wJ,...TJ]),U(`ref (any, range<any>, repeating)`,P(`Range or reference for which you want the subtotal.`))],compute:function(e,...t){let n=Uo(e,this.locale),r=!0;if(n>100&&(n-=100,r=!1),n<1||n>11)return new I(P(`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 Eo(Lo);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||!bn(n,`SUBTOTAL`))&&i.push(this.getFormulaResult({sheetId:s,col:t,row:e}))}}return this[CJ[n]].apply(this,[[i]])},isExported:!0},DJ={description:P(`Sum of a series of numbers and/or cells.`),args:[U(`value (number, range<number>, repeating)`,P(`Number or range to add together.`))],compute:function(...e){let t=e[0];return{value:aS(e,this.locale),format:No(t)}},isExported:!0},OJ={description:P(`A conditional sum across a range.`),args:[U(`criteria_range (range)`,P(`The range which is tested against criterion.`)),U(`criterion (string)`,P(`The pattern or test to apply to range.`)),U(`sum_range (range, default=criteria_range)`,P(`The range to be summed, if different from range.`))],compute:function(e,t,n){n===void 0&&(n=e);let r=0;return fs([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},kJ={description:P(`Sums a range depending on multiple criteria.`),args:[U(`sum_range (range)`,P(`The range to sum.`)),U(`criteria_range (any, range, repeating)`,P(`Range to check.`)),U(`criterion (string, repeating)`,P(`Criteria to check.`))],compute:function(e,...t){let n=0;return fs(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},AJ={description:P(`Tangent of an angle provided in radians.`),args:[U(`angle (number)`,P(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(L(e,this.locale))},isExported:!0},jJ={description:P(`Hyperbolic tangent of any real number.`),args:[U(`value (number)`,P(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(L(e,this.locale))},isExported:!0};function MJ(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let NJ={description:P(`Truncates a number.`),args:[U(`value (number)`,P(`The value to be truncated.`)),U(`places (number, default=0)`,P(`The number of significant digits to the right of the decimal point to retain.`))],compute:function(e,t={value:0}){return{value:MJ(L(e,this.locale),L(t,this.locale)),format:e?.format}},isExported:!0},PJ={description:P(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[U(`value (number)`,P(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(L(e,this.locale))},isExported:!0};var FJ=l({AVEDEV:()=>GJ,AVERAGE:()=>KJ,AVERAGEA:()=>XJ,AVERAGEIF:()=>ZJ,AVERAGEIFS:()=>QJ,AVERAGE_WEIGHTED:()=>YJ,CORREL:()=>bY,COUNT:()=>$J,COUNTA:()=>eY,COVAR:()=>tY,COVARIANCE_P:()=>nY,COVARIANCE_S:()=>rY,FORECAST:()=>iY,GROWTH:()=>aY,INTERCEPT:()=>oY,LARGE:()=>sY,LINEST:()=>cY,LOGEST:()=>lY,MATTHEWS:()=>uY,MAX:()=>dY,MAXA:()=>fY,MAXIFS:()=>pY,MEDIAN:()=>mY,MIN:()=>hY,MINA:()=>gY,MINIFS:()=>_Y,PEARSON:()=>yY,PERCENTILE:()=>xY,PERCENTILE_EXC:()=>SY,PERCENTILE_INC:()=>CY,POLYFIT_COEFFS:()=>wY,POLYFIT_FORECAST:()=>TY,QUARTILE:()=>EY,QUARTILE_EXC:()=>DY,QUARTILE_INC:()=>OY,RANK:()=>kY,RSQ:()=>AY,SLOPE:()=>jY,SMALL:()=>MY,SPEARMAN:()=>NY,STDEV:()=>PY,STDEVA:()=>LY,STDEVP:()=>RY,STDEVPA:()=>zY,STDEV_P:()=>FY,STDEV_S:()=>IY,STEYX:()=>BY,TREND:()=>VY,VAR:()=>HY,VARA:()=>GY,VARP:()=>KY,VARPA:()=>qY,VAR_P:()=>UY,VAR_S:()=>WY});let IJ=[{value:!0,label:P(`b is calculated normally`)},{value:!1,label:P(`b is forced to 1`)}],LJ=[{value:!1,label:P(`do not return additional regression statistics`)},{value:!0,label:P(`return additional regression statistics`)}],RJ=[{value:1,label:P(`order 1 (Linear)`)},{value:2,label:P(`order 2 (Quadratic)`)},{value:3,label:P(`order 3 (Cubic)`)},{value:4,label:P(`order 4 (Quartic)`)},{value:5,label:P(`order 5 (Quintic)`)},{value:6,label:P(`order 6 (Sextic)`)}],zJ=[{value:!0,label:P(`Compute intercept`)},{value:!1,label:P(`Force intercept to 0`)}],BJ=[{value:0,label:P(`Minimum value`)},{value:1,label:P(`First quartile (25th percentile)`)},{value:2,label:P(`Median value (50th percentile)`)},{value:3,label:P(`Third quartile (75th percentile)`)},{value:4,label:P(`Maximum value`)}];function VJ(e,t){let n=[],r=[],i=0,a=0;Zo([e],e=>{n.push(e),i+=1}),Zo([t],e=>{r.push(e),a+=1}),sS(i===a,P(`[[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 HJ(e,t,n){let{flatDataX:r,flatDataY:i}=VJ(e,t),a=i.length;cS(a),n&&cS(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 UJ(e,t,n,r){let i=0,a=n?ns:ts,o=a(e,(e,t)=>(i+=1,e+t),0,r);cS(i),t&&cS(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function WJ(e,t,n,r){let i=L(t,r);sS(n?0<=i&&i<=1:0<i&&i<1,P(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`));let a=[],o,s=0;return Zo(e,e=>{let t=e?.value;typeof t==`number`&&(o=ps(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),sS(s!==0,bs),n||sS(1/(s+1)<=i&&i<=s/(s+1),P(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),mo(a,i,n)}let GJ={description:P(`Average magnitude of deviations from mean.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the sample.`))],compute:function(...e){let t=0,n=ts(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new Ao(P(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return ts(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},KJ={description:P(`Numerical average value in a dataset, ignoring text.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to consider when calculating the average value.`))],compute:function(...e){return{value:xS(e,this.locale),format:No(e[0])}},isExported:!0},qJ=P(`[[FUNCTION_NAME]] has mismatched range sizes.`),JJ=P(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),YJ={description:P(`Weighted average.`),args:[U(`values (number, range<number>, repeating)`,P(`Value to average.`)),U(`weights (number, range<number>, repeating)`,P(`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(!uS(i,a))return new I(qJ);if(ht(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=ht(a)?a?.[e][r].value:L(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new I(JJ);t+=o*s,n+=s;continue}if(c!==l)return new I(P(`[[FUNCTION_NAME]] expects number values.`))}else{let e=L(i,this.locale),r=ht(a)?a?.[0][0].value:L(a,this.locale);if(typeof r==`number`){if(r<0)return new I(JJ);t+=e*r,n+=r}}}return n===0?new Ao(P(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:No(e[0])}}},XJ={description:P(`Numerical average value in a dataset.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to consider when calculating the average value.`))],compute:function(...e){let t=0,n=ns(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new Ao(P(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:No(e[0])}},isExported:!0},ZJ={description:P(`Average of values depending on criteria.`),args:[U(`criteria_range (number, range<number>)`,P(`The range to check against criterion.`)),U(`criterion (string)`,P(`The pattern or test to apply to criteria_range.`)),U(`average_range (number, range<number>, default=criteria_range)`,P(`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 fs([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new Ao(P(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},QJ={description:P(`Average of values depending on multiple criteria.`),args:[U(`average_range (range)`,P(`The range to average.`)),U(`criteria_range (any, range, repeating)`,P(`Range to check.`)),U(`criterion (string, repeating)`,P(`Criterion to check.`))],compute:function(e,...t){let n=B(e),r=0,i=0;return fs(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new Ao(P(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},$J={description:P(`The number of numeric values in dataset.`),args:[U(`value (number, any, range<number>, repeating)`,P(`Value or range to consider when counting.`))],compute:function(...e){return CS(e,this.locale)},isExported:!0},eY={description:P(`The number of values in a dataset.`),args:[U(`value (any, range, repeating)`,P(`Value or range to consider when counting.`))],compute:function(...e){return wS(e)},isExported:!0},tY={description:P(`The covariance of a dataset.`),args:[U(`data_y (any, range)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (any, range)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return HJ(e,t,!1)},isExported:!0},nY={description:P(`The covariance of a dataset.`),args:[U(`data_y (any, range)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (any, range)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return HJ(e,t,!1)},isExported:!0},rY={description:P(`The sample covariance of a dataset.`),args:[U(`data_y (any, range)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (any, range)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return HJ(e,t,!0)},isExported:!0},iY={description:P(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[U(`x (number, range<number>)`,P(`The value(s) on the x-axis to forecast.`)),U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t,n){let{flatDataX:r,flatDataY:i}=VJ(t,n);return r.length===0||i.length===0?new Do(bs):PS([i],[r],is(B(e),e=>L(e,this.locale)),!0)},isExported:!0},aY={description:P(`Fits points to exponential growth trend.`),args:[U(`known_data_y (range<number>)`,P(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.`)),U(`known_data_x (range<number>, default={1;2;3;...})`,P(`The values of the independent variable(s) corresponding with known_data_y.`)),U(`new_data_x (any, range, default=known_data_x)`,P(`The data points to return the y values for on the ideal curve fit.`)),U(`b (boolean, default=TRUE)`,P(`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.`),IJ)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new I(xs(`known_data_y`)):MS(PS(NS(Vo(e,`known_data_y`)),Vo(t,`known_data_x`),Vo(n,`new_data_y`),z(r)))}},oY={description:P(`Compute the intercept of the linear regression.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=VJ(e,t);if(n.length===0||r.length===0)return new Do(bs);let[[],[i]]=OS([n],[r]);return i},isExported:!0},sY={description:P(`Nth largest element from a data set.`),args:[U(`data (any, range)`,P(`Array or range containing the dataset to consider.`)),U(`n (number)`,P(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(L(t?.value,this.locale)),r=[],i,a=0;Zo([e],e=>{typeof e?.value==`number`&&(i=ps(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 I(bs):a<n?new I(P(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},cY={description:P(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>, default={1;2;3;...})`,P(`The range representing the array or matrix of independent data.`)),U(`calculate_b (boolean, default=TRUE)`,P(`A flag specifying whether to compute the slope or not`),IJ),U(`verbose (boolean, default=FALSE)`,P(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),LJ)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new I(xs(`data_y`)):OS(Vo(t,`data_x`),Vo(e,`data_y`),z(n),z(r))},isExported:!0},lY={description:P(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>, optional, default={1;2;3;...})`,P(`The range representing the array or matrix of independent data.`)),U(`calculate_b (boolean, default=TRUE)`,P(`A flag specifying whether to compute the slope or not`),IJ),U(`verbose (boolean, default=FALSE)`,P(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),LJ)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new I(xs(`data_y`));let i=OS(Vo(t,`data_x`),NS(Vo(e,`data_y`)),z(n),z(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},uY={description:P(`Compute the Matthews correlation coefficient of a dataset.`),args:[U(`data_x (range)`,P(`The range representing the array or matrix of observed data.`)),U(`data_y (range)`,P(`The range representing the array or matrix of predicted data.`))],compute:function(e,t){let n=e.flat(),r=t.flat();if(bS(n,r),n.length===0||r.length===0)return new Do(bs);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=z(n[e]);t===z(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},dY={description:P(`Maximum value in a numeric dataset.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){return TS(e,this.locale)},isExported:!0},fY={description:P(`Maximum numeric value in a dataset.`),args:[U(`value (any, range, repeating)`,P(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){let t=ns(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:No(e[0])}},isExported:!0},pY={description:P(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[U(`range (range)`,P(`The range of cells from which the maximum will be determined.`)),U(`criteria_range (any, range, repeating)`,P(`Range to evaluate criteria.`)),U(`criterion (string, repeating)`,P(`Criteria to check.`))],compute:function(e,...t){let n=-1/0;return fs(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},mY={description:P(`Median value in a numeric dataset.`),args:[U(`value (any, range, repeating)`,P(`Value or range to consider when calculating the median value.`))],compute:function(...e){let t=[];return Qo(e,e=>{t.push(e)},this.locale),{value:WJ(t,{value:.5},!0,this.locale),format:No(t[0])}},isExported:!0},hY={description:P(`Minimum value in a numeric dataset.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){return ES(e,this.locale)},isExported:!0},gY={description:P(`Minimum numeric value in a dataset.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){let t=ns(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:No(e[0])}},isExported:!0},_Y={description:P(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[U(`range (range)`,P(`The range of cells from which the minimum will be determined.`)),U(`criteria_range (any, range, repeating)`,P(`Range to evaluate criteria.`)),U(`criterion (string, repeating)`,P(`Criterion to check.`))],compute:function(e,...t){let n=1/0;return fs(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 vY(e,t){let{flatDataX:n,flatDataY:r}=VJ(e,t);if(n.length===0||r.length===0)return new Do(bs);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}let u=Math.sqrt((i*c-a*a)*(i*l-o*o));return u===0?new Ao:(i*s-a*o)/u}let yY={description:P(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return vY(e,t)},isExported:!0},bY=yY,xY={description:P(`Value at a given percentile of a dataset.`),args:[U(`data (any, range)`,P(`The array or range containing the dataset to consider.`)),U(`percentile (number)`,P(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return CY.compute.bind(this)(e,t)},isExported:!0},SY={description:P(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[U(`data (any, range)`,P(`The array or range containing the dataset to consider.`)),U(`percentile (number)`,P(`The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.`))],compute:function(e,t){return{value:WJ([e],t,!1,this.locale),format:No(e)}},isExported:!0},CY={description:P(`Value at a given percentile of a dataset.`),args:[U(`data (any, range)`,P(`The array or range containing the dataset to consider.`)),U(`percentile (number)`,P(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:WJ([e],t,!0,this.locale),format:No(e)}},isExported:!0},wY={description:P(`Compute the coefficients of polynomial regression of the dataset.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`)),U(`order (number)`,P(`The order of the polynomial to fit the data, between 1 and 6.`),RJ),U(`intercept (boolean, default=TRUE)`,P(`A flag specifying whether to compute the intercept or not.`),zJ)],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=VJ(e,t);return i.length===0||a.length===0?new Do(bs):kS(a,i,L(n,this.locale),z(r))},isExported:!1},TY={description:P(`Predict value by computing a polynomial regression of the dataset.`),args:[U(`x (number, range<number>)`,P(`The value(s) on the x-axis to forecast.`)),U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`)),U(`order (number)`,P(`The order of the polynomial to fit the data, between 1 and 6.`),RJ),U(`intercept (boolean, default=TRUE)`,P(`A flag specifying whether to compute the intercept or not.`),zJ)],compute:function(e,t,n,r,i={value:!0}){let a=L(r,this.locale),{flatDataX:o,flatDataY:s}=VJ(t,n);if(o.length===0||s.length===0)return new Do(bs);let c=kS(s,o,a,z(i)).flat();return is(B(e),e=>jS(c,L(e,this.locale),a))},isExported:!1},EY={description:P(`Value nearest to a specific quartile of a dataset.`),args:[U(`data (any, range)`,P(`The array or range containing the dataset to consider.`)),U(`quartile_number (number)`,P(`Which quartile value to return.`),BJ)],compute:function(e,t){return OY.compute.bind(this)(e,t)},isExported:!0},DY={description:P(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[U(`data (any, range)`,P(`The array or range containing the dataset to consider.`)),U(`quartile_number (number)`,P(`Which quartile value, exclusive of 0 and 4, to return.`),[{value:1,label:P(`First quartile (25th percentile)`)},{value:2,label:P(`Median value (50th percentile)`)},{value:3,label:P(`Third quartile (75th percentile)`)}])],compute:function(e,t){let n={value:.25*Math.trunc(L(t,this.locale))};return{value:WJ([e],n,!1,this.locale),format:No(e)}},isExported:!0},OY={description:P(`Value nearest to a specific quartile of a dataset.`),args:[U(`data (any, range)`,P(`The array or range containing the dataset to consider.`)),U(`quartile_number (number)`,P(`Which quartile value to return.`),BJ)],compute:function(e,t){let n={value:.25*Math.trunc(L(t,this.locale))};return{value:WJ([e],n,!0,this.locale),format:No(e)}},isExported:!0},kY={description:P(`Returns the rank of a specified value in a dataset.`),args:[U(`value (number)`,P(`The value whose rank will be determined.`)),U(`data (range)`,P(`The range containing the dataset to consider.`)),U(`is_ascending (boolean, default=FALSE)`,P(`Whether to consider the values in data in descending or ascending order.`),[{value:!1,label:P(`Descending`)},{value:!0,label:P(`Ascending`)}])],compute:function(e,t,n={value:!1}){let r=z(n),i=L(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=L(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Do(P(`Value not found in the given data.`))},isExported:!0},AY={description:P(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=vY(e,t);return typeof n==`number`?n**2:n},isExported:!0},jY={description:P(`Compute the slope of the linear regression.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=VJ(e,t);if(n.length===0||r.length===0)return new Do(bs);let[[i]]=OS([n],[r]);return i},isExported:!0},MY={description:P(`Nth smallest element in a data set.`),args:[U(`data (any, range)`,P(`The array or range containing the dataset to consider.`)),U(`n (number)`,P(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(L(t?.value,this.locale)),r=[],i,a=0;Zo([e],e=>{typeof e?.value==`number`&&(i=ps(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 I(bs):a<n?new I(P(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},NY={description:P(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=VJ(t,e);if(n.length===0||r.length===0)return new Do(bs);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},PY={description:P(`Standard deviation.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(HY.compute.bind(this)(...e))},isExported:!0},FY={description:P(`Standard deviation of entire population.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(UY.compute.bind(this)(...e))},isExported:!0},IY={description:P(`Standard deviation.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(WY.compute.bind(this)(...e))},isExported:!0},LY={description:P(`Standard deviation of sample (text as 0).`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(GY.compute.bind(this)(...e))},isExported:!0},RY={description:P(`Standard deviation of entire population.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(KY.compute.bind(this)(...e))},isExported:!0},zY={description:P(`Standard deviation of entire population (text as 0).`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(qY.compute.bind(this)(...e))},isExported:!0},BY={description:P(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=VJ(e,t);return n.length===0||r.length===0?new Do(bs):OS([n],[r],!0,!0)[1][2]},isExported:!0},VY={description:P(`Fits points to linear trend derived via least-squares.`),args:[U(`known_data_y (number, range<number>)`,P(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.`)),U(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,P(`The values of the independent variable(s) corresponding with known_data_y.`)),U(`new_data_x (number, range<number>, optional, default=known_data_x)`,P(`The data points to return the y values for on the ideal curve fit.`)),U(`b (boolean, optional, default=TRUE)`,P(`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.`),IJ)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new I(xs(`known_data_y`)):PS(Vo(e,`known_data_y`),Vo(t,`known_data_x`),Vo(n,`new_data_y`),z(r))}},HY={description:P(`Variance.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the sample.`))],compute:function(...e){return UJ(e,!0,!1,this.locale)},isExported:!0},UY={description:P(`Variance of entire population.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the population.`))],compute:function(...e){return UJ(e,!1,!1,this.locale)},isExported:!0},WY={description:P(`Variance.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the sample.`))],compute:function(...e){return UJ(e,!0,!1,this.locale)},isExported:!0},GY={description:P(`Variance of sample (text as 0).`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the sample.`))],compute:function(...e){return UJ(e,!0,!0,this.locale)},isExported:!0},KY={description:P(`Variance of entire population.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the population.`))],compute:function(...e){return UJ(e,!1,!1,this.locale)},isExported:!0},qY={description:P(`Variance of entire population (text as 0).`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the population.`))],compute:function(...e){return UJ(e,!1,!0,this.locale)},isExported:!0};var JY=l({DAVERAGE:()=>ZY,DCOUNT:()=>QY,DCOUNTA:()=>$Y,DGET:()=>eX,DMAX:()=>tX,DMIN:()=>nX,DPRODUCT:()=>rX,DSTDEV:()=>iX,DSTDEVP:()=>aX,DSUM:()=>oX,DVAR:()=>sX,DVARP:()=>cX});function YY(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(R(e[t][0]).toUpperCase(),t);let o=t?.value;if(typeof o!=`number`&&typeof o!=`string`)throw new I(P(`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 I(P(`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=R(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new I(P(`The field (%s) must be one of %s.`,R(t),[...i.keys()].toString()))}let c=n[0].length;if(c<2)throw new I(P(`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=R(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)fs(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 XY=[U(`database (range)`,P(`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.`)),U(`field (number, string)`,P(`Indicates which column in database contains the values to be extracted and operated on.`)),U(`criteria (range)`,P(`An array or range containing zero or more criteria to filter the database values by before operating.`))],ZY={description:P(`Average of a set of values from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return KJ.compute.bind(this)([r])},isExported:!0},QY={description:P(`Counts values from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return $J.compute.bind(this)([r])},isExported:!0},$Y={description:P(`Counts values and text from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return eY.compute.bind(this)([r])},isExported:!0},eX={description:P(`Single value from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return r.length===0?new I(P(`No match found in DGET evaluation.`)):r.length>1?new I(P(`More than one match found in DGET evaluation.`)):r[0]},isExported:!0},tX={description:P(`Maximum of values from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return dY.compute.bind(this)([r])},isExported:!0},nX={description:P(`Minimum of values from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return hY.compute.bind(this)([r])},isExported:!0},rX={description:P(`Product of values from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return uJ.compute.bind(this)([r])},isExported:!0},iX={description:P(`Standard deviation of population sample from table.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return PY.compute.bind(this)([r])},isExported:!0},aX={description:P(`Standard deviation of entire population from table.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return RY.compute.bind(this)([r])},isExported:!0},oX={description:P(`Sum of values from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return DJ.compute.bind(this)([r])},isExported:!0},sX={description:P(`Variance of population sample from table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return HY.compute.bind(this)([r])},isExported:!0},cX={description:P(`Variance of a population from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return KY.compute.bind(this)([r])},isExported:!0},lX=P(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),uX=P(`There must be both positive and negative values in cashflow_amounts.`),dX=e=>P(`The cost (%s) must be positive or null.`,e),fX=e=>P(`The cost (%s) must be strictly positive.`,e),pX=e=>P(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),mX=e=>P(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),hX=e=>P(`The depreciation factor (%s) must be strictly positive.`,e),gX=e=>P(`The discount (%s) must be different from -1.`,e),_X=e=>P(`The discount (%s) must be strictly positive.`,e),vX=e=>P(`The discount (%s) must be smaller than 1.`,e),yX=e=>P(`The effective_rate (%s) must be strictly positive.`,e),bX=e=>P(`The end_period (%s) must be positive or null.`,e),xX=(e,t)=>P(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),SX=e=>P(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),CX=(e,t)=>P(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),wX=e=>P(`The first_period (%s) must be strictly positive.`,e),TX=e=>P(`The future_value (%s) must be strictly positive.`,e),EX=e=>P(`The investment (%s) must be strictly positive.`,e),DX=e=>P(`The issue (%s) must be positive or null.`,e),OX=(e,t)=>P(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),kX=e=>P(`The last_period (%s) must be strictly positive.`,e),AX=e=>P(`The life (%s) must be strictly positive.`,e),jX=(e,t)=>P(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),MX=e=>P(`The month (%s) must be between 1 and 12 inclusive.`,e),NX=e=>P(`The nominal_rate (%s) must be strictly positive.`,e),PX=e=>P(`The number_of_periods (%s) must be different from zero.`,e),FX=e=>P(`The number_of_periods (%s) must be strictly positive.`,e),IX=e=>P(`The period must be between 1 and number_of_periods (%s)`,e),LX=(e,t)=>P(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),RX=e=>P(`The period (%s) must be positive or null.`,e),zX=e=>P(`The periods_by_year (%s) must be strictly positive.`,e),BX=(e,t)=>P(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),VX=e=>P(`The period (%s) must be strictly positive.`,e),HX=e=>P(`The present_value (%s) must be strictly positive.`,e),UX=e=>P(`The price (%s) must be strictly positive.`,e),WX=(e,t)=>P(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),GX=e=>P(`The purchase_date (%s) must be positive or null.`,e),KX=e=>P(`The rate_guess (%s) must be strictly greater than -1.`,e),qX=e=>P(`The rate (%s) must be positive or null.`,e),JX=e=>P(`The rate (%s) must be strictly positive.`,e),YX=e=>P(`The redemption (%s) must be strictly positive.`,e),XX=e=>P(`The salvage (%s) must be positive or null.`,e),ZX=(e,t)=>P(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),QX=(e,t)=>P(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),$X=(e,t)=>P(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),eZ=(e,t)=>P(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),tZ=e=>P(`The start_period (%s) must be positive or null.`,e),nZ=(e,t)=>P(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),rZ=e=>P(`The unit (%s) must be strictly positive.`,e),iZ=e=>P(`The yield (%s) must be positive or null.`,e);function aZ(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function oZ(e){return![0,1,2,3,4].includes(e)}function sZ(e){return![1,2,4].includes(e)}function cZ(e,t,n){let r=Jo(e,n),i=Jo(t,n),a=Jo(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}let lZ=[{value:0,label:P(`US (NASD) 30/360`)},{value:1,label:P(`Actual/Actual`)},{value:2,label:P(`Actual/360`)},{value:3,label:P(`Actual/365`)},{value:4,label:P(`European 30/360`)}];var uZ=l({DATE:()=>fZ,DATEDIF:()=>pZ,DATEVALUE:()=>mZ,DAY:()=>hZ,DAYS:()=>gZ,DAYS360:()=>_Z,EDATE:()=>vZ,EOMONTH:()=>yZ,HOUR:()=>bZ,ISOWEEKNUM:()=>xZ,MINUTE:()=>SZ,MONTH:()=>CZ,MONTH_END:()=>BZ,MONTH_START:()=>zZ,NETWORKDAYS:()=>wZ,NETWORKDAYS_INTL:()=>DZ,NOW:()=>OZ,QUARTER:()=>VZ,QUARTER_END:()=>UZ,QUARTER_START:()=>HZ,SECOND:()=>kZ,TIME:()=>AZ,TIMEVALUE:()=>jZ,TODAY:()=>MZ,WEEKDAY:()=>NZ,WEEKNUM:()=>PZ,WORKDAY:()=>FZ,WORKDAY_INTL:()=>IZ,YEAR:()=>LZ,YEARFRAC:()=>RZ,YEAR_END:()=>GZ,YEAR_START:()=>WZ}),dZ=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}(dZ||{});let fZ={description:P(`Converts year/month/day into a date.`),args:[U(`year (number)`,P(`The year component of the date.`)),U(`month (number)`,P(`The month component of the date.`)),U(`day (number)`,P(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(L(e,this.locale)),i=Math.trunc(L(t,this.locale)),a=Math.trunc(L(n,this.locale));if(r<0||r>9999)return new I(P(`The year (%s) must be between 0 and 9999 inclusive.`,r.toString()));r<1900&&(r+=1900);let o=Ga(new va(r,i-1,a));return o<0?new I(P(`The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.`)):{value:o,format:this.locale.dateFormat}},isExported:!0},pZ={description:P(`Calculates the number of days, months, or years between two dates.`),args:[U(`start_date (date)`,P(`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.`)),U(`end_date (date)`,P(`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.`)),U(`unit (string)`,P(`A text abbreviation for unit of time.`),[{value:`Y`,label:P(`The number of whole years between start_date and end_date`)},{value:`M`,label:P(`The number of whole months between start_date and end_date`)},{value:`D`,label:P(`The number of days between start_date and end_date`)},{value:`MD`,label:P(`The number of days between start_date and end_date after subtracting whole months`)},{value:`YM`,label:P(`The number of whole months between start_date and end_date after subtracting whole years`)},{value:`YD`,label:P(`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=R(n).toUpperCase();if(!Object.values(dZ).includes(r))return new I(zo(Object.values(dZ),R(n)));let i=Math.trunc(L(e,this.locale)),a=Math.trunc(L(t,this.locale)),o=Wa(i),s=Wa(a);if(a<i)return new I(P(`start_date (%s) should be on or before end_date (%s).`,o.toLocaleDateString(),s.toLocaleDateString()));switch(r){case`Y`:return eo(o,s);case`M`:return Qa(o,s);case`D`:return $a(o,s);case`YM`:return Qa(o,s)-eo(o,s)*12;case`MD`:let e=s.getDate()-o.getDate();return e<0&&(e=qa(new va(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case`YD`:{if(to(i,a))return $a(o,s);let e=new va(o.getFullYear(),s.getMonth(),s.getDate()),t=$a(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=$a(o,e)),t}}},isExported:!0},mZ={description:P(`Converts a date string to a date value.`),args:[U(`date_string (string)`,P(`The string representing the date.`))],compute:function(e){let t=R(e),n=Pa(t,this.locale);return n===null?new I(P(`The date_string (%s) cannot be parsed to date/time.`,t.toString())):Math.trunc(n.value)},isExported:!0},hZ={description:P(`Day of the month that a specific date falls on.`),args:[U(`date (string)`,P(`The date from which to extract the day.`))],compute:function(e){return Jo(e,this.locale).getDate()},isExported:!0},gZ={description:P(`Number of days between two dates.`),args:[U(`end_date (date)`,P(`The end of the date range.`)),U(`start_date (date)`,P(`The start of the date range.`))],compute:function(e,t){let n=Jo(e,this.locale),r=Jo(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/ba)},isExported:!0},_Z={description:P(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[U(`start_date (date)`,P(`The start date to consider in the calculation.`)),U(`end_date (date)`,P(`The end date to consider in the calculation.`)),U(`method (boolean, default=false)`,P(`An indicator of what day count method to use.`),[{value:!1,label:P(`U.S. NASD method (default)`)},{value:!0,label:P(`European method`)}])],compute:function(e,t,n={value:!1}){let r=Math.trunc(L(e,this.locale)),i=Math.trunc(L(t,this.locale)),a=Za(r,i,z(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},vZ={description:P(`Date a number of months before/after another date.`),args:[U(`start_date (date)`,P(`The date from which to calculate the result.`)),U(`months (number)`,P(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:Ga(Ya(Jo(e,this.locale),Math.trunc(L(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},yZ={description:P(`Last day of a month before or after a date.`),args:[U(`start_date (date)`,P(`The date from which to calculate the result.`)),U(`months (number)`,P(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=Jo(e,this.locale),r=Math.trunc(L(t,this.locale));return{value:Ga(new va(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},bZ={description:P(`Hour component of a specific time.`),args:[U(`time (date)`,P(`The time from which to calculate the hour component.`))],compute:function(e){return Jo(e,this.locale).getHours()},isExported:!0},xZ={description:P(`ISO week number of the year.`),args:[U(`date (date)`,P(`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=Jo(e,this.locale),n=t.getFullYear(),r=1;for(;new va(n,0,r).getDay()!==4;)r+=1;let i=new va(n,0,r-3),a=31;for(;new va(n,11,a).getDay()!==4;)--a;let o=new va(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 va(n,11,a+3+1);break;case-1:let e=1;for(;new va(n-1,0,e).getDay()!==4;)e+=1;c=new va(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/ba;return Math.floor(l/7)+1},isExported:!0},SZ={description:P(`Minute component of a specific time.`),args:[U(`time (date)`,P(`The time from which to calculate the minute component.`))],compute:function(e){return Jo(e,this.locale).getMinutes()},isExported:!0},CZ={description:P(`Month of the year a specific date falls in`),args:[U(`date (date)`,P(`The date from which to extract the month.`))],compute:function(e){return Jo(e,this.locale).getMonth()+1},isExported:!0},wZ={description:P(`Net working days between two provided days.`),args:[U(`start_date (date)`,P(`The start date of the period from which to calculate the number of net working days.`)),U(`end_date (date)`,P(`The end date of the period from which to calculate the number of net working days.`)),U(`holidays (date, range<date>, optional)`,P(`A range or array constant containing the date serial numbers to consider holidays.`))],compute:function(e,t,n){return DZ.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function TZ(e){let t=e?.value;if(typeof t==`string`){sS(t.length===7&&[...t].every(e=>e===`0`||e===`1`),P(`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 sS(1<=t&&t<=7||11<=t&&t<=17,P(`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 I(P(`The weekend must be a number or a string.`))}let EZ=[{value:1,label:P(`Saturday/Sunday are weekends`)},{value:2,label:P(`Sunday/Monday are weekends`)},{value:3,label:P(`Monday/Tuesday are weekends`)},{value:4,label:P(`Tuesday/Wednesday are weekends`)},{value:5,label:P(`Wednesday/Thursday are weekends`)},{value:6,label:P(`Thursday/Friday are weekends`)},{value:7,label:P(`Friday/Saturday are weekends`)},{value:11,label:P(`Sunday is the only weekend`)},{value:12,label:P(`Monday is the only weekend`)},{value:13,label:P(`Tuesday is the only weekend`)},{value:14,label:P(`Wednesday is the only weekend`)},{value:15,label:P(`Thursday is the only weekend`)},{value:16,label:P(`Friday is the only weekend`)},{value:17,label:P(`Saturday is the only weekend`)}],DZ={description:P(`Net working days between two dates (specifying weekends).`),args:[U(`start_date (date)`,P(`The start date of the period from which to calculate the number of net working days.`)),U(`end_date (date)`,P(`The end date of the period from which to calculate the number of net working days.`)),U(`weekend (any, default=1)`,P(`A number or string representing which days of the week are considered weekends.`),EZ),U(`holidays (date, range<date>, optional)`,P(`A range or array constant containing the dates to consider as holidays.`))],compute:function(e,t,n={value:1},r){let i=Jo(e,this.locale),a=Jo(t,this.locale),o=TZ(n),s=new Set;r!==void 0&&Zo([r],e=>{let t=Jo(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=va.fromTimestamp((c?i:a).getTime()),u=va.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},OZ={description:P(`Current date and time as a date value.`),args:[],compute:function(){let e=va.now(),t=e.getTime()-ya.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/ba)+n,format:av(this.locale)}},isExported:!0},kZ={description:P(`Minute component of a specific time.`),args:[U(`time (date)`,P(`The time from which to calculate the second component.`))],compute:function(e){return Jo(e,this.locale).getSeconds()},isExported:!0},AZ={description:P(`Converts hour/minute/second into a time.`),args:[U(`hour (number)`,P(`The hour component of the time.`)),U(`minute (number)`,P(`The minute component of the time.`)),U(`second (number)`,P(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(L(e,this.locale)),i=Math.trunc(L(t,this.locale)),a=Math.trunc(L(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 I(P(`The function [[FUNCTION_NAME]] result cannot be negative`)):{value:r/24+i/1440+a/(1440*60),format:this.locale.timeFormat}},isExported:!0},jZ={description:P(`Converts a time string into its serial number representation.`),args:[U(`time_string (string)`,P(`The string that holds the time representation.`))],compute:function(e){let t=R(e),n=Pa(t,this.locale);if(n===null)return new I(P(`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},MZ={description:P(`Current date as a date value.`),args:[],compute:function(){let e=va.now();return{value:Ga(new va(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},NZ={description:P(`Day of the week of the date provided (as number).`),args:[U(`date (date)`,P(`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.`)),U(`type (number, default=1)`,P(`A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.`),[{value:1,label:P(`Numbers 1 (Sunday) trough 7 (Saturday)`)},{value:2,label:P(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:3,label:P(`Numbers 0 (Monday) trough 6 (Sunday)`)},{value:11,label:P(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:12,label:P(`Numbers 1 (Tuesday) trough 7 (Monday)`)},{value:13,label:P(`Numbers 1 (Wednesday) trough 7 (Tuesday)`)},{value:14,label:P(`Numbers 1 (Thursday) trough 7 (Wednesday)`)},{value:15,label:P(`Numbers 1 (Friday) trough 7 (Thursday)`)},{value:16,label:P(`Numbers 1 (Saturday) trough 7 (Friday)`)},{value:17,label:P(`Numbers 1 (Sunday) trough 7 (Saturday)`)}])],compute:function(e,t={value:1}){let n=Jo(e,this.locale),r=Math.round(L(t,this.locale)),i=n.getDay();if(!(1<=r&&r<=3)&&!(11<=r&&r<=17))return new I(P(`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},PZ={description:P(`Week number of the year.`),args:[U(`date (date)`,P(`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.`)),U(`type (number, default=1)`,P(`A number representing the day that a week starts on. Sunday = 1.`),[{value:1,label:P(`Sunday`)},{value:2,label:P(`Monday`)},{value:11,label:P(`Monday`)},{value:12,label:P(`Tuesday`)},{value:13,label:P(`Wednesday`)},{value:14,label:P(`Thursday`)},{value:15,label:P(`Friday`)},{value:16,label:P(`Saturday`)},{value:17,label:P(`Sunday`)},{value:21,label:P(`ISO week number (Monday as first day of the week)`)}])],compute:function(e,t={value:1}){let n=Jo(e,this.locale),r=Math.round(L(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(r))return new I(P(`The type (%s) is out of range.`,r.toString()));if(r===21)return xZ.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 va(a,0,o);for(;s.getDay()!==i;)o+=1,s=new va(a,0,o);let c=(n.getTime()-s.getTime())/ba;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},FZ={description:P(`Date after a number of workdays.`),args:[U(`start_date (date)`,P(`The date from which to begin counting.`)),U(`num_days (number)`,P(`The number of working days to advance from start_date. If negative, counts backwards.`)),U(`holidays (date, range<date>, optional)`,P(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:null}){return IZ.compute.bind(this)(e,t,{value:1},n)},isExported:!0},IZ={description:P(`Date after a number of workdays (specifying weekends).`),args:[U(`start_date (date)`,P(`The date from which to begin counting.`)),U(`num_days (number)`,P(`The number of working days to advance from start_date. If negative, counts backwards.`)),U(`weekend (any, default=1)`,P(`A number or string representing which days of the week are considered weekends.`),EZ),U(`holidays (date, range<date>, optional)`,P(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:1},r){let i=Jo(e,this.locale),a=Math.trunc(L(t,this.locale));if(n.value===`1111111`)return new I(P(`The weekend must be different from '1111111'.`));let o=TZ(n),s=new Set;r!==void 0&&Zo([r],e=>{let t=Jo(e,this.locale);s.add(t.getTime())});let c=va.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-ya.getTime();return{value:Math.round(f/ba),format:this.locale.dateFormat}},isExported:!0},LZ={description:P(`Year specified by a given date.`),args:[U(`date (date)`,P(`The date from which to extract the year.`))],compute:function(e){return Jo(e,this.locale).getFullYear()},isExported:!0},RZ={description:P(`Exact number of years between two dates.`),args:[U(`start_date (date)`,P(`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.`)),U(`end_date (date)`,P(`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.`)),U(`day_count_convention (number, default=0)`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n={value:0}){let r=Math.trunc(L(e,this.locale)),i=Math.trunc(L(t,this.locale)),a=Math.trunc(L(n,this.locale));return r<0?new I(P(`The start_date (%s) must be positive or null.`,r)):i<0?new I(P(`The end_date (%s) must be positive or null.`,i)):0>a||a>4?new I(P(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,a)):Za(r,i,a)}},zZ={description:P(`First day of the month a date falls in.`),args:[U(`date (date)`,P(`The date from which to calculate the result.`))],compute:function(e){let t=Jo(e,this.locale);return{value:Ga(new va(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},BZ={description:P(`Last day of the month a date falls in.`),args:[U(`date (date)`,P(`The date from which to calculate the result.`))],compute:function(e){return yZ.compute.bind(this)(e,{value:0})}},VZ={description:P(`Quarter of the year a specific date falls in`),args:[U(`date (date)`,P(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((Jo(e,this.locale).getMonth()+1)/3)}},HZ={description:P(`First day of the quarter of the year a specific date falls in.`),args:[U(`date (date)`,P(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=VZ.compute.bind(this)(e);return{value:Ga(new va(LZ.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},UZ={description:P(`Last day of the quarter of the year a specific date falls in.`),args:[U(`date (date)`,P(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=VZ.compute.bind(this)(e);return{value:Ga(new va(LZ.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},WZ={description:P(`First day of the year a specific date falls in.`),args:[U(`date (date)`,P(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:Ga(new va(LZ.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},GZ={description:P(`Last day of the year a specific date falls in.`),args:[U(`date (date)`,P(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:Ga(new va(LZ.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var KZ=l({DELTA:()=>qZ});let qZ={description:P(`Compare two numeric values, returning 1 if they're equal.`),args:[U(`number1 (number)`,P(`The first number to compare.`)),U(`number2 (number, default=0)`,P(`The second number to compare.`))],compute:function(e,t={value:0}){return+(L(e,this.locale)===L(t,this.locale))},isExported:!0};var JZ=l({FILTER:()=>XZ,SORT:()=>ZZ,SORTN:()=>QZ,UNIQUE:()=>$Z});function YZ(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;sS(n[e]!==void 0,P(`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(z(_S(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(ht(s)&&(s.length>1||s[0].length>1))sS(s.length===1&&s[0].length===a,P(`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=L(_S(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:PV(`desc`),asc:PV(`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 XZ={description:P(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[U(`range (any, range<any>)`,P(`The data to be filtered.`)),U(`condition (boolean, range<boolean>, repeating)`,P(`Column or row containing true or false values corresponding to the range.`))],compute:function(e,...t){let n=B(e),r=t.map(e=>is(B(e),e=>e.value));for(let e of r)if(!lS(e))return new I(P(`The arguments condition must be a single column or row.`));if(!uS(...t))return new I(P(`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`?os(n):n,i.some(e=>e.length!==n.length))return new I(P(`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`?os(o):o:new Do(P(`No match found in FILTER evaluation`))},isExported:!1},ZZ={description:P(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[U(`range (range)`,P(`The data to be sorted.`)),U(`sort_column (any, range<number>, repeating, optional)`,P(`The index of the column in range or a range outside of range containing the value by which to sort.`)),U(`is_ascending (boolean, repeating, optional)`,P(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:P(`Ascending`)},{value:!1,label:P(`Descending`)}])],compute:function(e,...t){return os(YZ(os(e),this.locale,...t))},isExported:!0},QZ={description:P(`Returns the first n items in a data set after performing a sort.`),args:[U(`range (range)`,P(`The data to be sorted.`)),U(`n (number)`,P(`The number of items to return.`)),U(`display_ties_mode (number, default=0)`,P(`A number representing the way to display ties.`)),U(`sort_column (number, range<number>, repeating, optional)`,P(`The index of the column in range or a range outside of range containing the value by which to sort.`)),U(`is_ascending (boolean, repeating, optional)`,P(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:P(`Ascending`)},{value:!1,label:P(`Descending`)}])],compute:function(e,t,...n){let r=L(t?.value??1,this.locale),i=n.length%2==0?0:L(n[0]?.value,this.locale),a=n.length%2==0?n:n.slice(1);if(r<0)return new I(P(`Wrong value of 'n'. Expected a positive number. Got %s.`,r));if(i<0||i>3)return new I(P(`Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.`,i));let o=YZ(os(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 os(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return os(o.slice(0,e));return os(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 os(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 os(e)}}},isExported:!1},$Z={description:P(`Unique rows in the provided source range.`),args:[U(`range (any, range<any>)`,P(`The data to filter by unique entries.`)),U(`by_column (boolean, default=FALSE)`,P(`Whether to filter the data by columns or by rows.`),[{value:!0,label:P(`Return unique columns`)},{value:!1,label:P(`Return unique rows`)}]),U(`exactly_once (boolean, default=FALSE)`,P(`Whether to return only entries with no duplicates.`),[{value:!0,label:P(`Return items that appear exactly once`)},{value:!1,label:P(`Return every distinct item`)}])],compute:function(e={value:``},t,n){if(!ht(e))return[[e]];let r=z(t?.value)||!1,i=z(n?.value)||!1;r||(e=os(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:os(o):new I(P(`No unique values found`))},isExported:!0};var eQ=l({ACCRINTM:()=>aQ,AMORLINC:()=>oQ,COUPDAYBS:()=>cQ,COUPDAYS:()=>sQ,COUPDAYSNC:()=>lQ,COUPNCD:()=>uQ,COUPNUM:()=>dQ,COUPPCD:()=>fQ,CUMIPMT:()=>pQ,CUMPRINC:()=>mQ,DB:()=>hQ,DDB:()=>_Q,DISC:()=>vQ,DOLLARDE:()=>yQ,DOLLARFR:()=>bQ,DURATION:()=>xQ,EFFECT:()=>SQ,FV:()=>wQ,FVSCHEDULE:()=>TQ,INTRATE:()=>EQ,IPMT:()=>OQ,IRR:()=>AQ,ISPMT:()=>jQ,MDURATION:()=>MQ,MIRR:()=>NQ,NOMINAL:()=>PQ,NPER:()=>FQ,NPV:()=>LQ,PDURATION:()=>RQ,PMT:()=>BQ,PPMT:()=>HQ,PRICE:()=>WQ,PRICEDISC:()=>GQ,PRICEMAT:()=>KQ,PV:()=>UQ,RATE:()=>JQ,RECEIVED:()=>YQ,RRI:()=>XQ,SLN:()=>ZQ,SYD:()=>QQ,TBILLEQ:()=>t$,TBILLPRICE:()=>e$,TBILLYIELD:()=>n$,VDB:()=>r$,XIRR:()=>i$,XNPV:()=>a$,YIELD:()=>o$,YIELDDISC:()=>s$,YIELDMAT:()=>c$});let tQ=[{value:1,label:P(`Annual`)},{value:2,label:P(`Semi-annual`)},{value:4,label:P(`Quarterly`)}],nQ=[{value:0,label:P(`End of period (default)`)},{value:1,label:P(`Beginning of period`)}],rQ=[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`frequency (number)`,P(`The number of interest or coupon payments per year (1, 2, or 4).`),tQ),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)];function iQ(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)){sS(d<r&&a!==void 0,P(`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,sS(d<r,P(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let aQ={description:P(`Accrued interest of security paying at maturity.`),args:[U(`issue (date)`,P(`The date the security was initially issued.`)),U(`maturity (date)`,P(`The maturity date of the security.`)),U(`rate (number)`,P(`The annualized rate of interest.`)),U(`redemption (number)`,P(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(L(e,this.locale)),o=Math.trunc(L(t,this.locale)),s=L(r,this.locale),c=L(n,this.locale),l=Math.trunc(L(i,this.locale));if(a<0)return new I(DX(a));if(a>=o)return new I(jX(a,o));if(oZ(l))return new I(mX(l));if(s<=0)return new I(YX(s));if(c<=0)return new I(JX(c));let u=Za(a,o,l);return s*c*u},isExported:!0},oQ={description:P(`Depreciation for an accounting period.`),args:[U(`cost (number)`,P(`The initial cost of the asset.`)),U(`purchase_date (date)`,P(`The date the asset was purchased.`)),U(`first_period_end (date)`,P(`The date the first period ended.`)),U(`salvage (number)`,P(`The value of the asset at the end of depreciation.`)),U(`period (number)`,P(`The single period within life for which to calculate depreciation.`)),U(`rate (number)`,P(`The deprecation rate.`)),U(`day_count_convention (number, optional)`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=L(e,this.locale),c=Math.trunc(L(t,this.locale)),l=Math.trunc(L(n,this.locale)),u=L(r,this.locale),d=L(i,this.locale),f=L(a,this.locale),p=Math.trunc(L(o,this.locale));if(s<=0)return new I(fX(s));if(c<0)return new I(GX(c));if(u<0)return new I(XX(u));if(u>s)return new I(ZX(u,s));if(d<0)return new I(RX(d));if(f<=0)return new I(JX(f));if(oZ(p))return new I(mX(p));if(c>l)return new I(WX(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=Za(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},sQ={description:P(`Days in coupon period containing settlement date.`),args:rQ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(L(e,this.locale)),a=Math.trunc(L(t,this.locale)),o=Math.trunc(L(n,this.locale)),s=Math.trunc(L(r,this.locale));if(i>=a)return new I(jX(i,a));if(sZ(o))return new I(pX(o));if(oZ(s))return new I(mX(s));if(s===1){let i=fQ.compute.bind(this)(e,t,n,r).value,a=uQ.compute.bind(this)(e,t,n,r).value;return L(a,this.locale)-L(i,this.locale)}return(s===3?365:360)/o},isExported:!0},cQ={description:P(`Days from settlement until next coupon.`),args:rQ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(L(e,this.locale)),a=Math.trunc(L(t,this.locale)),o=Math.trunc(L(n,this.locale)),s=Math.trunc(L(r,this.locale));if(i>=a)return new I(jX(i,a));if(sZ(o))return new I(pX(o));if(oZ(s))return new I(mX(s));let c=fQ.compute.bind(this)(e,t,n,r).value,l=L(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=Za(l,i,s);return Math.round(e*360)}let u=Jo(i,this.locale),d=Jo(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&&Ja(d)&&Ja(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&Ja(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},lQ={description:P(`Days from settlement until next coupon.`),args:rQ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(L(e,this.locale)),a=Math.trunc(L(t,this.locale)),o=Math.trunc(L(n,this.locale)),s=Math.trunc(L(r,this.locale));if(i>=a)return new I(jX(i,a));if(sZ(o))return new I(pX(o));if(oZ(s))return new I(mX(s));let c=uQ.compute.bind(this)(e,t,n,r).value,l=L(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=Za(i,l,s);return Math.round(e*360)}let u=cQ.compute.bind(this)(e,t,n,r);return L(sQ.compute.bind(this)(e,t,n,r),this.locale)-L(u,this.locale)},isExported:!0},uQ={description:P(`Next coupon date after the settlement date.`),args:rQ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(L(e,this.locale)),a=Math.trunc(L(t,this.locale)),o=Math.trunc(L(n,this.locale)),s=Math.trunc(L(r,this.locale));if(i>=a)return new I(jX(i,a));if(sZ(o))return new I(pX(o));if(oZ(s))return new I(mX(s));let c=12/o,l=dQ.compute.bind(this)(e,t,n,r);return{value:Ga(Ya(Jo(a,this.locale),-(L(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},dQ={description:P(`Number of coupons between settlement and maturity.`),args:rQ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(L(e,this.locale)),a=Math.trunc(L(t,this.locale)),o=Math.trunc(L(n,this.locale)),s=Math.trunc(L(r,this.locale));if(i>=a)return new I(jX(i,a));if(sZ(o))return new I(pX(o));if(oZ(s))return new I(mX(s));let c=1,l=a,u=12/o;for(;l>i;)l=Ga(Ya(Jo(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},fQ={description:P(`Last coupon date prior to or on the settlement date.`),args:rQ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(L(e,this.locale)),a=Math.trunc(L(t,this.locale)),o=Math.trunc(L(n,this.locale)),s=Math.trunc(L(r,this.locale));if(i>=a)return new I(jX(i,a));if(sZ(o))return new I(pX(o));if(oZ(s))return new I(mX(s));let c=12/o,l=dQ.compute.bind(this)(e,t,n,r);return{value:Ga(Ya(Jo(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},pQ={description:P(`Cumulative interest paid over a set of periods.`),args:[U(`rate (number)`,P(`The interest rate.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`present_value (number)`,P(`The current value of the annuity.`)),U(`first_period (number)`,P(`The number of the payment period to begin the cumulative calculation.`)),U(`last_period (number)`,P(`The number of the payment period to end the cumulative calculation.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r,i,a={value:0}){let o=L(r,this.locale),s=L(i,this.locale),c=L(e,this.locale),l=L(n,this.locale),u=L(t,this.locale),d=+!!z(a);if(u<=0)return new I(FX(u));if(o<=0)return new I(wX(o));if(s<=0)return new I(kX(s));if(o>s)return new I(CX(o,s));if(s>u)return new I(OX(s,u));if(c<=0)return new I(JX(c));if(l<=0)return new I(HX(l));let f=0;for(let e=o;e<=s;e++)f+=DQ(c,e,u,l,0,d);return f},isExported:!0},mQ={description:P(`Cumulative principal paid over a set of periods.`),args:[U(`rate (number)`,P(`The interest rate.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`present_value (number)`,P(`The current value of the annuity.`)),U(`first_period (number)`,P(`The number of the payment period to begin the cumulative calculation.`)),U(`last_period (number)`,P(`The number of the payment period to end the cumulative calculation.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r,i,a={value:0}){let o=L(r,this.locale),s=L(i,this.locale),c=L(e,this.locale),l=L(n,this.locale),u=L(t,this.locale),d=+!!z(a);if(u<=0)return new I(FX(u));if(o<=0)return new I(wX(o));if(s<=0)return new I(kX(s));if(o>s)return new I(CX(o,s));if(s>u)return new I(OX(s,u));if(c<=0)return new I(JX(c));if(l<=0)return new I(HX(l));let f=0;for(let e=o;e<=s;e++)f+=VQ(c,e,u,l,0,d);return f},isExported:!0},hQ={description:P(`Depreciation via declining balance method.`),args:[U(`cost (number)`,P(`The initial cost of the asset.`)),U(`salvage (number)`,P(`The value of the asset at the end of depreciation.`)),U(`life (number)`,P(`The number of periods over which the asset is depreciated.`)),U(`period (number)`,P(`The single period within life for which to calculate depreciation.`)),U(`month (number, optional)`,P(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=L(e,this.locale),o=L(t,this.locale),s=L(n,this.locale),c=Math.trunc(L(r,this.locale)),l=i.length?Math.trunc(L(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new I(dX(a));if(o<0)return new I(XX(o));if(c<=0)return new I(VX(c));if(s<=0)return new I(AX(s));if(1>l||l>12)return new I(MX(l));if(c>u)return new I(LX(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},gQ=`#,##0.00`,_Q={description:P(`Depreciation via double-declining balance method.`),args:[U(`cost (number)`,P(`The initial cost of the asset.`)),U(`salvage (number)`,P(`The value of the asset at the end of depreciation.`)),U(`life (number)`,P(`The number of periods over which the asset is depreciated.`)),U(`period (number)`,P(`The single period within life for which to calculate depreciation.`)),U(`factor (number, default=2)`,P(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=L(e,this.locale),o=L(t,this.locale),s=L(n,this.locale),c=L(r,this.locale),l=L(i,this.locale);if(a<0)return new I(dX(a));if(o<0)return new I(XX(o));if(c<=0)return new I(VX(c));if(s<=0)return new I(AX(s));if(c>s)return new I(BX(c,s));if(l<=0)return new I(hX(l));if(a===0||o>=a)return{value:0,format:gQ};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:gQ};if(c<=1)return{value:a*u,format:gQ};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:gQ}},isExported:!0},vQ={description:P(`Discount rate of a security based on price.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`price (number)`,P(`The price at which the security is bought per 100 face value.`)),U(`redemption (number)`,P(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(L(e,this.locale)),o=Math.trunc(L(t,this.locale)),s=L(n,this.locale),c=L(r,this.locale),l=Math.trunc(L(i,this.locale));if(a>=o)return new I(jX(a,o));if(oZ(l))return new I(mX(l));if(s<=0)return new I(UX(s));if(c<=0)return new I(YX(c));let u=Za(a,o,l);return(c-s)/c/u},isExported:!0},yQ={description:P(`Convert a decimal fraction to decimal value.`),args:[U(`fractional_price (number)`,P(`The price quotation given using fractional decimal conventions.`)),U(`unit (number)`,P(`The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=L(e,this.locale),r=Math.trunc(L(t,this.locale));if(r<=0)return new I(rZ(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},bQ={description:P(`Convert a decimal value to decimal fraction.`),args:[U(`decimal_price (number)`,P(`The price quotation given as a decimal value.`)),U(`unit (number)`,P(`The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=L(e,this.locale),r=Math.trunc(L(t,this.locale));if(r<=0)return new I(rZ(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},xQ={description:P(`Number of periods for an investment to reach a value.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,P(`The annualized rate of interest.`)),U(`yield (number)`,P(`The expected annual yield of the security.`)),U(`frequency (number)`,P(`The number of interest or coupon payments per year (1, 2, or 4).`),tQ),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(L(e,this.locale)),s=Math.trunc(L(t,this.locale)),c=L(n,this.locale),l=L(r,this.locale),u=Math.trunc(L(i,this.locale)),d=Math.trunc(L(a,this.locale));if(o>=s)return new I(jX(o,s));if(sZ(u))return new I(pX(u));if(oZ(d))return new I(mX(d));if(c<0)return new I(qX(c));if(l<0)return new I(iZ(l));let f=Za(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},SQ={description:P(`Annual effective interest rate.`),args:[U(`nominal_rate (number)`,P(`The nominal interest rate per year.`)),U(`periods_per_year (number)`,P(`The number of compounding periods per year.`))],compute:function(e,t){let n=L(e,this.locale),r=Math.trunc(L(t,this.locale));return n<=0?new I(NX(n)):r<=0?new I(zX(r)):(1+n/r)**+r-1},isExported:!0};function CQ(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 wQ={description:P(`Future value of an annuity investment.`),args:[U(`rate (number)`,P(`The interest rate.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`payment_amount (number)`,P(`The amount per period to be paid.`)),U(`present_value (number, default=0)`,P(`The current value of the annuity.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:CQ(L(e,this.locale),L(t,this.locale),L(n,this.locale),L(r,this.locale),+!!z(i)),format:`#,##0.00`}},isExported:!0},TQ={description:P(`Future value of principal from series of rates.`),args:[U(`principal (number)`,P(`The amount of initial capital or value to compound against.`)),U(`rate_schedule (number, range<number>)`,P(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=L(e,this.locale);return es([t],(e,t)=>e*(1+L(t,this.locale)),n)},isExported:!0},EQ={description:P(`Calculates effective interest rate.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`investment (number)`,P(`The amount invested in the security.`)),U(`redemption (number)`,P(`The amount to be received at maturity.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(L(e,this.locale)),o=Math.trunc(L(t,this.locale)),s=L(r,this.locale),c=L(n,this.locale),l=Math.trunc(L(i,this.locale));if(a>=o)return new I(jX(a,o));if(c<=0)return new I(EX(c));if(s<=0)return new I(YX(s));if(oZ(l))return new I(mX(l));let u=Za(a,o,l);return(s-c)/c/u},isExported:!0};function DQ(e,t,n,r,i,a){return zQ(e,n,r,i,a)-VQ(e,t,n,r,i,a)}let OQ={description:P(`Payment on the principal of an investment.`),args:[U(`rate (number)`,P(`The annualized rate of interest.`)),U(`period (number)`,P(`The amortization period, in terms of number of periods.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`present_value (number)`,P(`The current value of the annuity.`)),U(`future_value (number, default=0)`,P(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:DQ(L(e,this.locale),L(t,this.locale),L(n,this.locale),L(r,this.locale),L(i,this.locale),+!!z(a)),format:`#,##0.00`}},isExported:!0},kQ=.1,AQ={description:P(`Internal rate of return given periodic cashflows.`),args:[U(`cashflow_amounts (number, range<number>)`,P(`An array or range containing the income or payments associated with the investment.`)),U(`rate_guess (number, default=${kQ})`,P(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:kQ}){let n=L(t,this.locale);if(n<=-1)return new I(KX(n));let r=!1,i=!1,a=[];if(Qo([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new I(uX);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:iQ(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},jQ={description:P(`Returns the interest paid at a particular period of an investment.`),args:[U(`rate (number)`,P(`The interest rate.`)),U(`period (number)`,P(`The period for which you want to view the interest payment.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`present_value (number)`,P(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=L(e,this.locale),a=L(t,this.locale),o=L(n,this.locale),s=L(r,this.locale);return o===0?new I(PX(o)):-1*(s-a/o*s)*i},isExported:!0},MQ={description:P(`Modified Macaulay duration.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,P(`The annualized rate of interest.`)),U(`yield (number)`,P(`The expected annual yield of the security.`)),U(`frequency (number)`,P(`The number of interest or coupon payments per year (1, 2, or 4).`),tQ),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=xQ.compute.bind(this)(e,t,n,r,i,a),s=L(r,this.locale),c=Math.trunc(L(i,this.locale));return L(o,this.locale)/(1+s/c)},isExported:!0},NQ={description:P(`Modified internal rate of return.`),args:[U(`cashflow_amounts (range<number>)`,P(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),U(`financing_rate (number)`,P(`The interest rate paid on funds invested.`)),U(`reinvestment_return_rate (number)`,P(`The return (as a percentage) earned on reinvestment of income received from the investment.`))],compute:function(e,t,n){let r=L(t,this.locale),i=L(n,this.locale),a=os(e).flat().filter(e=>e.value!==null).map(e=>L(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 I(uX);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},PQ={description:P(`Annual nominal interest rate.`),args:[U(`effective_rate (number)`,P(`The effective interest rate per year.`)),U(`periods_per_year (number)`,P(`The number of compounding periods per year.`))],compute:function(e,t){let n=L(e,this.locale),r=Math.trunc(L(t,this.locale));return n<=0?new I(yX(n)):r<=0?new I(zX(r)):((n+1)**(1/r)-1)*r},isExported:!0},FQ={description:P(`Number of payment periods for an investment.`),args:[U(`rate (number)`,P(`The interest rate.`)),U(`payment_amount (number)`,P(`The amount of each payment made.`)),U(`present_value (number)`,P(`The current value of the annuity.`)),U(`future_value (number, default=0)`,P(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=L(e,this.locale),o=L(t,this.locale),s=L(n,this.locale),c=L(r,this.locale),l=+!!z(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 IQ(e,t,n,r){let i=0;return ts(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let LQ={description:P(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[U(`discount (number)`,P(`The discount rate of the investment over one period.`)),U(`cashflow (number, range<number>, repeating)`,P(`The future cash flows.`))],compute:function(e,...t){let n=L(e,this.locale);return n===-1?new I(gX(n)):{value:IQ(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},RQ={description:P(`Computes the number of periods needed for an investment to reach a value.`),args:[U(`rate (number)`,P(`The rate at which the investment grows each period.`)),U(`present_value (number)`,P(`The investment's current value.`)),U(`future_value (number)`,P(`The investment's desired future value.`))],compute:function(e,t,n){let r=L(e,this.locale),i=L(t,this.locale),a=L(n,this.locale);return r<=0?new I(JX(r)):i<=0?new I(HX(i)):a<=0?new I(TX(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function zQ(e,t,n,r,i){if(t<=0)throw new I(FX(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 BQ={description:P(`Periodic payment for an annuity investment.`),args:[U(`rate (number)`,P(`The annualized rate of interest.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`present_value (number)`,P(`The current value of the annuity.`)),U(`future_value (number, default=0)`,P(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r={value:0},i={value:0}){let a=L(t,this.locale),o=L(e,this.locale),s=+!!z(i),c=L(r,this.locale);return{value:zQ(o,a,L(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function VQ(e,t,n,r,i,a){if(n<=0)throw new I(FX(n));if(t<=0||t>n)throw new I(IX(n));let o=zQ(e,n,r,i,a);return a===1&&t===1?o:o+-CQ(e,a===0?t-1:t-2,o,r+o*a,0)*e}let HQ={description:P(`Payment on the principal of an investment.`),args:[U(`rate (number)`,P(`The annualized rate of interest.`)),U(`period (number)`,P(`The amortization period, in terms of number of periods.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`present_value (number)`,P(`The current value of the annuity.`)),U(`future_value (number, default=0)`,P(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=L(n,this.locale),s=L(e,this.locale),c=L(t,this.locale),l=+!!z(a),u=L(i,this.locale);return{value:VQ(s,c,o,L(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},UQ={description:P(`Present value of an annuity investment.`),args:[U(`rate (number)`,P(`The interest rate.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`payment_amount (number)`,P(`The amount per period to be paid.`)),U(`future_value (number, default=0)`,P(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=L(e,this.locale),o=L(t,this.locale),s=L(n,this.locale),c=L(r,this.locale),l=+!!z(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},WQ={description:P(`Price of a security paying periodic interest.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,P(`The annualized rate of interest.`)),U(`yield (number)`,P(`The expected annual yield of the security.`)),U(`redemption (number)`,P(`The redemption amount per 100 face value, or par.`)),U(`frequency (number)`,P(`The number of interest or coupon payments per year (1, 2, or 4).`),tQ),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(L(e,this.locale)),c=Math.trunc(L(t,this.locale)),l=L(n,this.locale),u=L(r,this.locale),d=L(i,this.locale),f=Math.trunc(L(a,this.locale)),p=Math.trunc(L(o,this.locale));if(s>=c)return new I(jX(s,c));if(sZ(f))return new I(pX(f));if(oZ(p))return new I(mX(p));if(l<0)return new I(qX(l));if(u<0)return new I(iZ(u));if(d<=0)return new I(YX(d));let m=Za(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 ee=0;for(let e=1;e<=h;e++)ee+=v/_**(e-1+g);return d/_**(h-1+g)+ee-v*(1-g)},isExported:!0},GQ={description:P(`Price of a discount security.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`discount (number)`,P(`The discount rate of the security at time of purchase.`)),U(`redemption (number)`,P(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(L(e,this.locale)),o=Math.trunc(L(t,this.locale)),s=L(n,this.locale),c=L(r,this.locale),l=Math.trunc(L(i,this.locale));if(a>=o)return new I(jX(a,o));if(oZ(l))return new I(mX(l));if(s<=0)return new I(_X(s));if(c<=0)return new I(YX(c));let u=Za(a,o,l);return c-s*c*u},isExported:!0},KQ={description:P(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`issue (date)`,P(`The date the security was initially issued.`)),U(`rate (number)`,P(`The annualized rate of interest.`)),U(`yield (number)`,P(`The expected annual yield of the security.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(L(e,this.locale)),s=Math.trunc(L(t,this.locale)),c=Math.trunc(L(n,this.locale)),l=L(r,this.locale),u=L(i,this.locale),d=Math.trunc(L(a,this.locale));if(o<=c)return new I(eZ(o,c));if(o>=s)return new I(jX(o,s));if(oZ(d))return new I(mX(d));if(l<0)return new I(qX(l));if(u<0)return new I(iZ(u));let f=Za(o,s,d),p=Za(o,c,d),m=100+Za(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},qQ=.1,JQ={description:P(`Interest rate of an annuity investment.`),args:[U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`payment_per_period (number)`,P(`The amount per period to be paid.`)),U(`present_value (number)`,P(`The current value of the annuity.`)),U(`future_value (number, default=0)`,P(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ),U(`rate_guess (number, default=${qQ})`,P(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:qQ}){let o=L(e,this.locale),s=L(t,this.locale),c=+!!z(i),l=L(a,this.locale)||qQ,u=L(r,this.locale),d=L(n,this.locale);return o<=0?new I(FX(o)):aZ([s,d,u])?l<=-1?new I(KX(l)):(u-=s*c,d+=s*c,{value:iQ(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 I(P(`There must be both positive and negative values in [payment_amount, present_value, future_value].`))},isExported:!0},YQ={description:P(`Amount received at maturity for a security.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`investment (number)`,P(`The amount invested (irrespective of face value of each security).`)),U(`discount (number)`,P(`The discount rate of the security invested in.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(L(e,this.locale)),o=Math.trunc(L(t,this.locale)),s=L(n,this.locale),c=L(r,this.locale),l=Math.trunc(L(i,this.locale));return a>=o?new I(jX(a,o)):oZ(l)?new I(mX(l)):s<=0?new I(EX(s)):c<=0?new I(_X(c)):s/(1-c*Za(a,o,l))},isExported:!0},XQ={description:P(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[U(`number_of_periods (number)`,P(`The number of periods.`)),U(`present_value (number)`,P(`The present value of the investment.`)),U(`future_value (number)`,P(`The future value of the investment.`))],compute:function(e,t,n){let r=L(e,this.locale),i=L(t,this.locale),a=L(n,this.locale);return r<=0?new I(FX(r)):(a/i)**(1/r)-1},isExported:!0},ZQ={description:P(`Depreciation of an asset using the straight-line method.`),args:[U(`cost (number)`,P(`The initial cost of the asset.`)),U(`salvage (number)`,P(`The value of the asset at the end of depreciation.`)),U(`life (number)`,P(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=L(e,this.locale),i=L(t,this.locale),a=L(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},QQ={description:P(`Depreciation via sum of years digit method.`),args:[U(`cost (number)`,P(`The initial cost of the asset.`)),U(`salvage (number)`,P(`The value of the asset at the end of depreciation.`)),U(`life (number)`,P(`The number of periods over which the asset is depreciated.`)),U(`period (number)`,P(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=L(e,this.locale),a=L(t,this.locale),o=L(n,this.locale),s=L(r,this.locale);if(s<=0)return new I(VX(s));if(o<=0)return new I(AX(o));if(s>o)return new I(BX(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function $Q(e,t,n){return 100*(1-n*Za(e,t,2))}let e$={description:P(`Price of a US Treasury bill.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`discount (number)`,P(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(L(e,this.locale)),i=Math.trunc(L(t,this.locale)),a=L(n,this.locale);return r>=i?new I(jX(r,i)):cZ(r,i,this.locale)?a<=0?new I(_X(a)):a>=1?new I(vX(a)):$Q(r,i,a):new I($X(r,i))},isExported:!0},t$={description:P(`Equivalent rate of return for a US Treasury bill.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`discount (number)`,P(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(L(e,this.locale)),i=Math.trunc(L(t,this.locale)),a=L(n,this.locale);if(r>=i)return new I(jX(r,i));if(!cZ(r,i,this.locale))return new I($X(r,i));if(a<=0)return new I(_X(a));if(a>=1)return new I(vX(a));let o=gZ.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=$Q(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},n$={description:P(`The yield of a US Treasury bill based on price.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`price (number)`,P(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(L(e,this.locale)),i=Math.trunc(L(t,this.locale)),a=L(n,this.locale);if(r>=i)return new I(jX(r,i));if(!cZ(r,i,this.locale))return new I($X(r,i));if(a<=0)return new I(UX(a));let o=Za(r,i,2);return(100-a)/a*(1/o)},isExported:!0},r$={description:P(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[U(`cost (number)`,P(`The initial cost of the asset.`)),U(`salvage (number)`,P(`The value of the asset at the end of depreciation.`)),U(`life (number)`,P(`The number of periods over which the asset is depreciated.`)),U(`start (number)`,P(`Starting period to calculate depreciation.`)),U(`end (number)`,P(`Ending period to calculate depreciation.`)),U(`factor (number, default=2)`,P(`The number of months in the first year of depreciation.`)),U(`no_switch (number, default=false)`,P(`Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.`),[{value:!1,label:P(`Switch to straight-line depreciation`)},{value:!0,label:P(`Do not switch to straight-line depreciation`)}])],compute:function(e,t,n,r,i,a={value:2},o={value:!1}){a||=0;let s=L(e,this.locale),c=L(t,this.locale),l=L(n,this.locale),u=Math.trunc(L(r,this.locale)),d=Math.trunc(L(i,this.locale)),f=L(a,this.locale),p=z(o);if(s<0)return new I(dX(s));if(c<0)return new I(XX(c));if(l<=0)return new I(AX(l));if(u<0)return new I(tZ(u));if(d<0)return new I(bX(d));if(u>d)return new I(nZ(u,d));if(d>l)return new I(xX(d,l));if(f<=0)return new I(hX(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},i$={description:P(`Internal rate of return given non-periodic cash flows.`),args:[U(`cashflow_amounts (range<number>)`,P(`An range containing the income or payments associated with the investment.`)),U(`cashflow_dates (range<number>)`,P(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),U(`rate_guess (number, default=${qQ})`,P(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:qQ}){let r=L(n,this.locale);if(!uS(e,t))return new I(lX);let i=e.flat().map(e=>L(e,this.locale)),a=t.flat().map(e=>L(e,this.locale));if(!aZ(i))return new I(uX);if(a.some(e=>e<a[0]))return new I(SX(a[0]));if(r<=-1)return new I(KX(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 iQ(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},a$={description:P(`Net present value given to non-periodic cash flows..`),args:[U(`discount (number)`,P(`The discount rate of the investment over one period.`)),U(`cashflow_amounts (number, range<number>)`,P(`An range containing the income or payments associated with the investment.`)),U(`cashflow_dates (number, range<number>)`,P(`An range with dates corresponding to the cash flows in cashflow_amounts.`))],compute:function(e,t,n){let r=L(e,this.locale);if(!uS(t,n))return new I(lX);let i=B(t).flat().map(e=>Ho(e,this.locale)),a=B(n).flat().map(e=>Ho(e,this.locale));if(a.some(e=>e<a[0]))return new I(SX(a[0]));if(r<=0)return new I(JX(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},o$={description:P(`Annual yield of a security paying periodic interest.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,P(`The annualized rate of interest.`)),U(`price (number)`,P(`The price at which the security is bought per 100 face value.`)),U(`redemption (number)`,P(`The redemption amount per 100 face value, or par.`)),U(`frequency (number)`,P(`The number of interest or coupon payments per year (1, 2, or 4).`),tQ),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(L(e,this.locale)),c=Math.trunc(L(t,this.locale)),l=L(n,this.locale),u=L(r,this.locale),d=L(i,this.locale),f=Math.trunc(L(a,this.locale)),p=Math.trunc(L(o,this.locale));if(s>=c)return new I(jX(s,c));if(sZ(f))return new I(pX(f));if(oZ(p))return new I(mX(p));if(l<0)return new I(qX(l));if(u<=0)return new I(UX(u));if(d<=0)return new I(YX(d));let m=Za(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 ee(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 y(e){return v(u,g,h,e,_,d)}function b(e){return ee(u,g,h,e,_)}return(iQ(y,b,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},s$={description:P(`Annual yield of a discount security.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`price (number)`,P(`The price at which the security is bought per 100 face value.`)),U(`redemption (number)`,P(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(L(e,this.locale)),o=Math.trunc(L(t,this.locale)),s=L(n,this.locale),c=L(r,this.locale),l=Math.trunc(L(i,this.locale));if(a>=o)return new I(jX(a,o));if(oZ(l))return new I(mX(l));if(s<=0)return new I(UX(s));if(c<=0)return new I(YX(c));let u=Za(a,o,l);return(c/s-1)/u},isExported:!0},c$={description:P(`Annual yield of a security paying interest at maturity.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`issue (date)`,P(`The date the security was initially issued.`)),U(`rate (number)`,P(`The annualized rate of interest.`)),U(`price (number)`,P(`The price at which the security is bought.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(L(e,this.locale)),s=Math.trunc(L(t,this.locale)),c=Math.trunc(L(n,this.locale)),l=L(r,this.locale),u=L(i,this.locale),d=Math.trunc(L(a,this.locale));if(o>=s)return new I(jX(o,s));if(oZ(d))return new I(mX(d));if(o<c)return new I(QX(o,c));if(l<0)return new I(qX(l));if(u<=0)return new I(UX(u));let f=Za(c,s,d),p=Za(c,o,d),m=Za(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0};var l$=l({CELL:()=>d$,ISBLANK:()=>y$,ISERR:()=>f$,ISERROR:()=>p$,ISFORMULA:()=>x$,ISLOGICAL:()=>m$,ISNA:()=>h$,ISNONTEXT:()=>g$,ISNUMBER:()=>_$,ISTEXT:()=>v$,NA:()=>b$});let u$=[{value:`address`,label:P(`Returns an absolute reference as plain text of the top left cell in reference.`)},{value:`col`,label:P(`Returns the column number of the cell in reference.`)},{value:`contents`,label:P(`Returns the value contained in the top left cell in reference.`)},{value:`format`,label:P(`Returns the format of the top left cell in reference.`)},{value:`row`,label:P(`Returns the row number of the top left cell in reference.`)},{value:`type`,label:P(`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.`)}],d$={description:P(`Gets information about a cell.`),args:[U(`info_type (string)`,P(`The type of information requested.`),u$),U(`reference (any, range<any>)`,P(`The reference to the cell.`))],compute:function(e,t){let n=R(e).toLowerCase();if(!u$.map(e=>e.value).includes(n))return new I(P(`The info_type should be one of %s.`,u$.join(`, `)));let r=B(t)[0][0],i=r.position;if(i===void 0)return new I(P(`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`:Fc(r.format)?`l`:typeof r.value==`number`||typeof r.value==`boolean`?`v`:`l`}return``},isExported:!0},f$={description:P(`Whether a value is an error other than #N/A.`),args:[U(`value (any)`,P(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return Po(t)&&t!==F.NotAvailable},isExported:!0},p$={description:P(`Whether a value is an error.`),args:[U(`value (any)`,P(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return Po(t)},isExported:!0},m$={description:P("Whether a value is `true` or `false`."),args:[U(`value (any)`,P(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},h$={description:P(`Whether a value is the error #N/A.`),args:[U(`value (any)`,P(`The value to be verified as an error type.`))],compute:function(e){return e?.value===F.NotAvailable},isExported:!0},g$={description:P(`Whether a value is non-textual.`),args:[U(`value (any)`,P(`The value to be checked.`))],compute:function(e){return!v$.compute.bind(this)(e)},isExported:!0},_$={description:P(`Whether a value is a number.`),args:[U(`value (any)`,P(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},v$={description:P(`Whether a value is text.`),args:[U(`value (any)`,P(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&Po(e?.value)===!1},isExported:!0},y$={description:P(`Whether the referenced cell is empty`),args:[U(`value (any)`,P(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},b$={description:P(`Returns the error value #N/A.`),args:[],compute:function(){return{value:F.NotAvailable}},isExported:!0},x$={description:P(`Checks whether there is a reference to a cell that contains a formula, and returns TRUE or FALSE.`),args:[U(`cell_reference (any)`,P(`A reference to a cell.`))],compute:function(e){return e?.position===void 0?new Eo(Lo):this.getters.getCell(e.position)?.isFormula??!1},isExported:!0};var S$=l({AND:()=>C$,FALSE:()=>w$,IF:()=>T$,IFERROR:()=>E$,IFNA:()=>D$,IFS:()=>O$,NOT:()=>k$,OR:()=>A$,SWITCH:()=>j$,TRUE:()=>M$,XOR:()=>N$});let C$={description:P("Logical `and` operator."),args:[U(`logical_expression (boolean, range<boolean>, repeating)`,P(`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}=rS(e);return n?t:new I(bs)},isExported:!0},w$={description:P("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},T$={description:P(`Returns value depending on logical expression.`),args:[U(`logical_expression (boolean, range<boolean>)`,P(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.`)),U(`value_if_true (any, range)`,P(`The value the function returns if logical_expression is TRUE.`)),U(`value_if_false (any, range, default=FALSE)`,P(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return yS(e)?Jc(this,al.get(`IF`),[e,t,n]):(z(_S(e))?t:n)??{value:0}},isExported:!0},E$={description:P(`Value if it is not an error, otherwise 2nd argument.`),args:[U(`value (any, range)`,P(`The value to return if value itself is not an error.`)),U(`value_if_error (any, range, default="empty")`,P(`The value the function returns if value is an error.`))],compute:function(e,t){return yS(e)?Jc(this,al.get(`IFERROR`),[e,t]):(Po(_S(e)?.value)?t:e)??{value:0}},isExported:!0},D$={description:P(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[U(`value (any, range)`,P(`The value to return if value itself is not #N/A an error.`)),U(`value_if_error (any, range, default="empty")`,P(`The value the function returns if value is an #N/A error.`))],compute:function(e,t){return yS(e)?Jc(this,al.get(`IFNA`),[e,t]):(_S(e)?.value===F.NotAvailable?t:e)??{value:0}},isExported:!0},O$={description:P(`Returns a value depending on multiple logical expressions.`),args:[U(`condition (any, range, repeating)`,P(`The condition to be evaluated. It can be a boolean, a number, an array, or a reference to any of those.`)),U(`value (any, range, repeating)`,P(`The value to be returned if its corresponding condition is TRUE.`))],compute:function(...e){if(e.length%2!=0)return new I(P(`Wrong number of arguments. Expected an even number of arguments.`));for(;e.length>0;){if(yS(e[0]))return Jc(this,al.get(`IFS`),e);let t=z(_S(e.shift())),n=e.shift();if(t)return n??{value:0}}return new I(P(`No match.`))},isExported:!0},k$={description:P(`Returns opposite of provided logical value.`),args:[U(`logical_expression (boolean)`,P(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!z(e)},isExported:!0},A$={description:P("Logical `or` operator."),args:[U(`logical_expression (boolean, range<boolean>, repeating)`,P(`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}=iS(e);return n?t:new I(bs)},isExported:!0},j$={description:P(`Returns a value by comparing cases to an expression.`),args:[U(`expression (number, boolean, string)`,P(`The value to be checked.`)),U(`case (any, repeating)`,P(`Case to be checked against expression.`)),U(`value (any, repeating)`,P(`Value to be returned if its corresponding case matches expression.`)),U(`default (any, default="empty")`,P(`An optional default value to be returned if none of the cases match expression.`))],compute:function(e,...t){let n=t.length%2==0?Fo(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&Po(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},M$={description:P("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},N$={description:P("Logical `xor` operator."),args:[U(`logical_expression (boolean, range<boolean>, repeating)`,P(`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 cs(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new I(bs)},isExported:!0};function P$(e,t){let n=t.getPivotId(e);if(!n)throw new I(P(`There is no pivot with id "%s"`,e));return n}function F$(e,t,n){let{measures:r}=n.getPivotCoreDefinition(e);if(!r.find(e=>e.id===t))throw new I(P(`The argument %s is not a valid measure. Here are the measures: %s`,t,`(${r.map(e=>e.id).join(`, `)})`))}function I$(e){if(e.length%2!=0)throw new I(P(`Function PIVOT takes an even number of arguments.`))}function L$(e,t,n){let r=[],i=e.getters.getPivotCoreDefinition(t);if(i.type===`SPREADSHEET`&&i.dataSet){let{sheetId:t,zone:n}=i.dataSet,a=Yn(n),o=e.getters.getRangeFromSheetXC(t,a);if(o===void 0||o.invalidXc||o.invalidSheetName)throw new Eo;if(e.__originCellPosition&&o.sheetId===e.__originSheetId&&sr(O(e.__originCellPosition),n))throw new To;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 R$=l({ADDRESS:()=>V$,CHOOSE:()=>i1,COLUMN:()=>H$,COLUMNS:()=>U$,DROP:()=>a1,FORMULATEXT:()=>s1,HLOOKUP:()=>W$,INDEX:()=>G$,INDIRECT:()=>K$,LOOKUP:()=>q$,MATCH:()=>J$,OFFSET:()=>r1,PIVOT:()=>n1,PIVOT_HEADER:()=>t1,PIVOT_VALUE:()=>e1,ROW:()=>Y$,ROWS:()=>X$,TAKE:()=>o1,VLOOKUP:()=>Z$,XLOOKUP:()=>$$});let z$=[{value:!0,label:P(`A1 style (default)`)},{value:!1,label:P(`R1C1 style`)}],B$=[{value:!0,label:P(`Approximate match (default)`)},{value:!1,label:P(`Exact match`)}],V$={description:P(`Returns a cell reference as a string. `),args:[U(`row (number)`,P(`The row number of the cell reference. `)),U(`column (number)`,P(`The column number (not name) of the cell reference. A is column number 1. `)),U(`absolute_relative_mode (number, default=1)`,P(`An indicator of whether the reference is row/column absolute.`),[{value:1,label:P(`Absolute row and column (e.g. $A$1)`)},{value:2,label:P(`Absolute row, relative column (e.g. A$1)`)},{value:3,label:P(`Relative row, absolute column (e.g. $A1)`)},{value:4,label:P(`Relative row and column (e.g. A1)`)}]),U(`use_a1_notation (boolean, default=TRUE)`,P(`A boolean indicating whether to use A1 style notation or R1C1 style notation.`),z$),U(`sheet (string, optional)`,P(`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=Wo(e,this.locale),o=Wo(t,this.locale);if(a<1)return new I(fS(a));if(o<1)return new I(fS(o));let s=Wo(n,this.locale);if(![1,2,3,4].includes(s))return new I(Ro(1,4,s));let c=z(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:yl(R(i),l)},isExported:!0},H$={description:P(`Column number of a specified cell.`),args:[U(`cell_reference (any, range<any>, default='this cell')`,P(`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 I(P(`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 I(P(`The range is out of bounds.`));if(n.position===void 0)return new Eo(Lo);let r=n.position.col;return t.length===1?r+1:rs(t.length,1,e=>({value:r+e+1}))},isExported:!0},U$={description:P(`Number of columns in a specified array or range.`),args:[U(`range (any, range<any>)`,P(`The range whose column count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new I(P(`The range is out of bounds.`)):t[0][0].value===F.InvalidReference?t[0][0]:t.length},isExported:!0},W$={description:P(`Horizontal lookup`),args:[U(`search_key (string, number, boolean)`,P(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`range (any, range)`,P(`The range to consider for the search. The first row in the range is searched for the key specified in search_key.`)),U(`index (number)`,P(`The row index of the value to be returned, where the first row in range is numbered 1.`)),U(`is_sorted (boolean, default=true)`,P(`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.`),B$)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(L(n?.value,this.locale)),a=B(t);if(1>i||i>a[0].length)return new I(P(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[t][0].value,s=a[z(r.value)?ps(a,e,`nextSmaller`,`asc`,a.length,o):ms(a,e,`wildcard`,a.length,o,this.lookupCaches)];return s===void 0?Fo(e):s[i-1]},isExported:!0},G$={description:P(`Returns the content of a cell, specified by row and column offset.`),args:[U(`reference (any, range)`,P(`The range of cells from which the values are returned.`)),U(`row (number, default=0)`,P(`The index of the row to be returned from within the reference range of cells.`)),U(`column (number, default=0)`,P(`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=L(t.value,this.locale),a=L(n.value,this.locale);return a<0||a-1>=r.length||i<0||i-1>=r[0].length?new I(P(`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},K$={description:P(`Returns the content of a cell, specified by a string.`),args:[U(`reference (string)`,P(`The range of cells from which the values are returned.`)),U(`use_a1_notation (boolean, default=TRUE)`,P(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`),z$)],compute:function(e,t={value:!0}){let n=e?.value?.toString();if(!n)return new Eo(P(`Reference should be defined.`));if(!z(t))return new I(P(`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 Eo;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},q$={description:P(`Look up a value.`),args:[U(`search_key (string, number, boolean)`,P(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`search_array (any, range)`,P(`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.`)),U(`result_range (any, range, optional)`,P(`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=ps(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?Fo(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 I(P(`The result_range must be a single row or a single column.`)):a>1?c>a-1?new I(P(`[[FUNCTION_NAME]] evaluates to an out of range row value %s.`,c+1)):i[c][0]:c>o-1?new I(P(`[[FUNCTION_NAME]] evaluates to an out of range column value %s.`,c+1)):i[0][c])},isExported:!0},J$={description:P(`Position of item in range that matches value.`),args:[U(`search_key (string, number, boolean)`,P(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`range (any, range)`,P(`The one-dimensional array to be searched.`)),U(`search_type (number, default=1)`,P(`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:P(`Ascending order (default)`)},{value:0,label:P(`Exact match`)},{value:-1,label:P(`Descending order`)}])],compute:function(e,t,n={value:1}){let r=L(n,this.locale),i=B(t),a=i.length,o=i[0].length;if(a!==1&&o!==1)return new I(P(`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=ps(i,e,`nextSmaller`,`asc`,l,c);break;case 0:s=ms(i,e,`wildcard`,l,c,this.lookupCaches);break;case-1:s=ps(i,e,`nextGreater`,`desc`,l,c);break}return a===1&&i[0][s]===void 0||a!==1&&i[s]===void 0?Fo(e):s+1},isExported:!0},Y$={description:P(`Row number of a specified cell.`),args:[U(`cell_reference (any, range<any>, default='this cell')`,P(`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 I(P(`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 I(P(`The range is out of bounds.`));if(n.position===void 0)return new Eo(Lo);let r=n.position.row;return t[0].length===1?r+1:rs(1,t[0].length,(e,t)=>({value:r+t+1}))},isExported:!0},X$={description:P(`Number of rows in a specified array or range.`),args:[U(`range (any, range<any>)`,P(`The range whose row count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new I(P(`The range is out of bounds.`)):t[0][0].value===F.InvalidReference?t[0][0]:t[0].length},isExported:!0},Z$={description:P(`Vertical lookup.`),args:[U(`search_key (string, number, boolean)`,P(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`range (any, range)`,P(`The range to consider for the search. The first column in the range is searched for the key specified in search_key.`)),U(`index (number)`,P(`The column index of the value to be returned, where the first column in range is numbered 1.`)),U(`is_sorted (boolean, default=true)`,P(`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.`),B$)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(L(n?.value,this.locale)),a=B(t);if(1>i||i>a.length)return new I(P(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[0][t].value,s=z(r.value)?ps(a,e,`nextSmaller`,`asc`,a[0].length,o):ms(a,e,`wildcard`,a[0].length,o,this.lookupCaches),c=a[i-1][s];return c===void 0?Fo(e):c},isExported:!0},Q$={0:`strict`,1:`nextGreater`,"-1":`nextSmaller`,2:`wildcard`},$$={description:P(`Search a range for a match and return the corresponding item from a second range.`),args:[U(`search_key (string,number,boolean)`,P(`The value to search for.`)),U(`lookup_range (any, range)`,P(`The range to consider for the search. Should be a single column or a single row.`)),U(`return_range (any, range)`,P(`The range containing the return value. Should have the same dimensions as lookup_range.`)),U(`if_not_found (any, optional)`,P(`If a valid match is not found, return this value.`)),U(`match_mode (any, default=0)`,P(`Specifies how to match search_key with the items in lookup_range. `),[{value:0,label:P(`Exact match (default)`)},{value:-1,label:P(`Exact match or next smaller item`)},{value:1,label:P(`Exact match or next larger item`)},{value:2,label:P(`Wildcard character match`)}]),U(`search_mode (any, default=1)`,P(`Specifies the search mode to use. By default, a first to last search will be used.`),[{value:1,label:P(`Search first to last (default)`)},{value:-1,label:P(`Search last to first`)},{value:2,label:P(`Binary search (sorted ascending order)`)},{value:-2,label:P(`Binary search (sorted descending order)`)}])],compute:function(e,t,n,r,i={value:0},a={value:1}){let o=Math.trunc(L(i.value,this.locale)),s=Math.trunc(L(a.value,this.locale)),c=B(t),l=B(n);if(c.length!==1&&c[0].length!==1)return new I(P(`lookup_range should be either a single row or single column.`));if(![1,-1,2,-2].includes(s))return new I(P(`search_mode should be a value in [-1, 1, -2, 2].`));if(![-1,0,1,2].includes(o))return new I(P(`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 I(P(`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 I(P(`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=Q$[o],m=s===-1,h=s===2||s===-2?ps(c,e,p,s===2?`asc`:`desc`,f,d):ms(c,e,p,f,d,this.lookupCaches,m);return h===-1?r===void 0?Fo(e):[[r]]:u===`col`?l.map(e=>[e[h]]):[l[h]]},isExported:!0},e1={description:P(`Get the value from a pivot.`),args:[U(`pivot_id (number,string)`,P(`ID of the pivot.`)),U(`measure_name (string)`,P(`Name of the measure.`)),U(`domain_field_name (string,repeating,optional)`,P(`Field name.`)),U(`domain_value (number,string,boolean,repeating,optional)`,P(`Value.`))],compute:function(e,t,...n){let r=R(e),i=R(t),a=P$(r,this.getters);F$(a,i,this.getters),I$(n);let o=this.getters.getPivot(a),s=this.getters.getPivotCoreDefinition(a);L$(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=P(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${r})`);return{value:F.GenericError,message:P(`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)}},t1={description:P(`Get the header of a pivot.`),args:[U(`pivot_id (number,string)`,P(`ID of the pivot.`)),U(`domain_field_name (string,repeating,optional)`,P(`Field name.`)),U(`domain_value (number,string,value,repeating,optional)`,P(`Value.`))],compute:function(e,...t){let n=R(e),r=P$(n,this.getters);I$(t);let i=this.getters.getPivot(r);L$(this,r,[]),i.init({reload:i.needsReevaluation});let a=i.assertIsValid({throwOnError:!1});if(a)return a;if(!i.areDomainArgsFieldsValid(t)){let e=P(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${n})`);return{value:F.GenericError,message:P(`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(R(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}}},n1={description:P(`Get a pivot table.`),args:[U(`pivot_id (string)`,P(`ID of the pivot.`)),U(`row_count (number, optional)`,P(`number of rows`)),U(`include_total (boolean, default=TRUE)`,P(`Whether to include total/sub-totals or not.`)),U(`include_column_titles (boolean, default=TRUE)`,P(`Whether to include the column titles or not.`)),U(`column_count (number, optional)`,P(`number of columns`)),U(`include_measure_titles (boolean, default=TRUE)`,P(`Whether to include the measure titles row or not.`))],compute:function(e,t,n,r,i,a){let o=P$(R(e),this.getters),s=this.getters.getPivot(o),c=this.getters.getPivotCoreDefinition(o),l=DC(c,t,n,r,i,a,this.locale);if(l.numberOfRows<0)return new I(P(`The number of rows must be positive.`));if(l.numberOfColumns<0)return new I(P(`The number of columns must be positive.`));L$(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 I(K_(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(vC(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}},r1={description:P(`Returns a range reference shifted by a specified number of rows and columns from a starting cell reference.`),args:[U(`cell_reference (any, range<any>)`,P(`The starting point from which to count the offset rows and columns.`)),U(`offset_rows (number)`,P(`The number of rows to offset by.`)),U(`offset_columns (number)`,P(`The number of columns to offset by.`)),U(`height (number, default='height of cell_reference')`,P(`The number of rows of the range to return starting at the offset target.`)),U(`width (number, default='width of cell_reference')`,P(`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 Eo(Lo);let a=B(e),o=a[0][0];if(o===void 0)return new I(P(`The range is out of bounds.`));if(o.position===void 0)return new Eo(Lo);let s=a[0].length,c=a.length;if(r){let e=L(r,this.locale);if(e<1)return new I(P(`Height value is %(_height)s. It should be greater than or equal to 1.`,{_height:e}));s=e}if(i){let e=L(i,this.locale);if(e<1)return new I(P(`Width value is %(_width)s. It should be greater than or equal to 1.`,{_width:e}));c=e}let l=L(t,this.locale),u=L(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 Eo(P(`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 Eo:(d&&this.addDependencies?.(d,[g]),rs(c,s,(e,t)=>this.getFormulaResult({sheetId:h,col:f+e,row:p+t})))}},i1={description:P(`Returns an element from a list of choices based on index.`),args:[U(`index (number)`,P(`Which choice to return.`)),U(`choice (any, range<any>, repeating)`,P(`A potential value to return. May be a reference to a cell or an individual value.`))],compute:function(e,...t){let n=Math.floor(L(e,this.locale))-1;return n<0||n>=t.length?new I(P(`Index for CHOOSE is invalid. Valid values are between 1 and %(choices)s inclusive.`,{choices:t.length})):t[n]??new I(P(`Choice is undefined.`))},isExported:!0},a1={description:P(`Excludes a specified number of rows or columns from the start or end of an array.`),args:[U(`array (range)`,P(`The array from which to drop rows or columns`)),U(`rows (number)`,P(`The number of rows to drop. A negative value drops from the end of the array.`)),U(`columns (number, optional)`,P(`The number of columns to exclude. A negative value drops from the end of the array.`))],compute:function(e,t,n){let r=L(t,this.locale),i=L(n,this.locale),a=e;if(Math.abs(i)>=e.length||Math.abs(r)>=e[0].length)return new I(P(`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},o1={description:P(`Returns a specified number of contiguous rows or columns from the start or end of an array.`),args:[U(`array (range)`,P(`The array from which to take rows or columns.`)),U(`rows (number)`,P(`The number of rows to take. A negative value takes from the end of the array.`)),U(`columns (number, optional)`,P(`The number of columns to take. A negative value takes from the end of the array.`))],compute:function(e,t,n){let r=t?L(t,this.locale):e[0].length,i=L(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 I(P(`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},s1={description:P(`Returns a formula as a string.`),args:[U(`cell_reference (any)`,P(`A reference to a cell.`))],compute:function(e){if(e?.position===void 0)return new Eo(Lo);let t=this.getters.getCell(e.position);return t?.isFormula?t.compiledFormula.toFormulaString(this.getters):new Do(P(`The cell does not contain a formula.`))},isExported:!0};var c1=l({ADD:()=>l1,CONCAT:()=>u1,DIVIDE:()=>d1,EQ:()=>h1,GT:()=>v1,GTE:()=>y1,LT:()=>b1,LTE:()=>x1,MINUS:()=>S1,MULTIPLY:()=>C1,NE:()=>w1,POW:()=>T1,SPILLED_RANGE:()=>E1,UMINUS:()=>D1,UNARY_PERCENT:()=>O1,UPLUS:()=>k1});let l1={description:P(`Sum of two numbers.`),args:[U(`value1 (number)`,P(`The first addend.`)),U(`value2 (number)`,P(`The second addend.`))],compute:function(e,t){return{value:L(e,this.locale)+L(t,this.locale),format:e?.format||t?.format}}},u1={description:P(`Concatenation of two values.`),args:[U(`value1 (string)`,P(`The value to which value2 will be appended.`)),U(`value2 (string)`,P(`The value to append to value1.`))],compute:function(e,t){return R(e)+R(t)},isExported:!0},d1={description:P(`One number divided by another.`),args:[U(`dividend (number)`,P(`The number to be divided.`)),U(`divisor (number)`,P(`The number to divide by.`))],compute:function(e,t){let n=L(t,this.locale);return n===0?new Ao(P(`The divisor must be different from zero.`)):{value:L(e,this.locale)/n,format:e?.format||t?.format}}};function f1(e){return e===void 0||e.value===null}let p1={number:0,string:``,boolean:!1};function m1(e,t,n=2e-16){return Math.abs(e-t)<n}let h1={description:P(`Equal.`),args:[U(`value1 (string, number, boolean)`,P(`The first value.`)),U(`value2 (string, number, boolean)`,P(`The value to test against value1 for equality.`))],compute:function(e,t){if(Po(e?.value))return e;if(Po(t?.value))return t;let n=f1(e)?p1[typeof t?.value]:e?.value,r=f1(t)?p1[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:m1(n,r)}:{value:n===r}}};function g1(e,t,n){if(Po(e?.value))return e;if(Po(t?.value))return t;let r=f1(e)?p1[typeof t?.value]??``:e?.value,i=f1(t)?p1[typeof e?.value]??``:t?.value,a=_1[typeof r],o=_1[typeof i];if(a!==o)return{value:n(a,o)};switch(typeof r){case`string`:r=r.toUpperCase();break;case`boolean`:r=Number(r);break}switch(typeof i){case`string`:i=i.toUpperCase();break;case`boolean`:i=Number(i);break}return{value:n(r,i)}}let _1={number:0,string:1,boolean:2},v1={description:P(`Strictly greater than.`),args:[U(`value1 (number, string, boolean)`,P(`The value to test as being greater than value2.`)),U(`value2 (number, string, boolean)`,P(`The second value.`))],compute:function(e,t){return g1(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?!m1(e,t)&&e>t:e>t)}},y1={description:P(`Greater than or equal to.`),args:[U(`value1 (number, string, boolean)`,P(`The value to test as being greater than or equal to value2.`)),U(`value2 (number, string, boolean)`,P(`The second value.`))],compute:function(e,t){return g1(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?m1(e,t)||e>t:e>=t)}},b1={description:P(`Less than.`),args:[U(`value1 (number, string, boolean)`,P(`The value to test as being less than value2.`)),U(`value2 (number, string, boolean)`,P(`The second value.`))],compute:function(e,t){let n=y1.compute.bind(this)(e,t);return Po(n.value)?n:{value:!n.value}}},x1={description:P(`Less than or equal to.`),args:[U(`value1 (number, string, boolean)`,P(`The value to test as being less than or equal to value2.`)),U(`value2 (number, string, boolean)`,P(`The second value.`))],compute:function(e,t){let n=v1.compute.bind(this)(e,t);return Po(n.value)?n:{value:!n.value}}},S1={description:P(`Difference of two numbers.`),args:[U(`value1 (number)`,P(`The minuend, or number to be subtracted from.`)),U(`value2 (number)`,P(`The subtrahend, or number to subtract from value1.`))],compute:function(e,t){return{value:L(e,this.locale)-L(t,this.locale),format:e?.format||t?.format}}},C1={description:P(`Product of two numbers`),args:[U(`factor1 (number)`,P(`The first multiplicand.`)),U(`factor2 (number)`,P(`The second multiplicand.`))],compute:function(e,t){return{value:L(e,this.locale)*L(t,this.locale),format:e?.format||t?.format}}},w1={description:P(`Not equal.`),args:[U(`value1 (string, number, boolean)`,P(`The first value.`)),U(`value2 (string, number, boolean)`,P(`The value to test against value1 for inequality.`))],compute:function(e,t){let n=h1.compute.bind(this)(e,t);return Po(n.value)?n:{value:!n.value}}},T1={description:P(`A number raised to a power.`),args:[U(`base (number)`,P(`The number to raise to the exponent power.`)),U(`exponent (number)`,P(`The exponent to raise base to.`))],compute:function(e,t){return lJ.compute.bind(this)(e,t)}},E1={description:P(`Gets the spilled range of an array formula.`),args:[U(`ref (any, range<any>)`,P(`The reference to get the spilled range from.`))],compute:function(e){if(e===void 0)return new Eo(Lo);let t=B(e);if(t.length!==1||t[0].length!==1)return new I(P(`Only single-cell references are allowed to get the spilled range.`));let n=t[0][0];if(Po(n.value))return n;if(n.position===void 0)return new Eo(Lo);let r=this.__originCellPosition;r&&this.updateDependencies?.(r);let i=this.getters.getSpreadZone(n.position);if(i===void 0)return new Eo;let a=this.getters.getRangeFromZone(this.__originSheetId,i);return r&&this.addDependencies?.(r,[a]),rs(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},D1={description:P(`A number with the sign reversed.`),args:[U(`value (number)`,P(`The number to have its sign reversed. Equivalently, the number to multiply by -1.`))],compute:function(e){return{value:-L(e,this.locale),format:e?.format}}},O1={description:P(`Value interpreted as a percentage.`),args:[U(`percentage (number)`,P(`The value to interpret as a percentage.`))],compute:function(e){return L(e,this.locale)/100}},k1={description:P(`A specified number, unchanged.`),args:[U(`value (any)`,P(`The number to return.`))],compute:function(e={value:null}){return e}},$=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),A1={transform:e=>e,inverseTransform:e=>e},j1=1e-10,M1=.0254,N1=M1/72,P1=.3048,F1=.9144,I1=1609.34,L1=1852,R1=946073047258e4,z1={g:{...A1,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:{...A1,category:`distance`},km:{...$(1e3),category:`distance`},ang:{...$(j1),category:`distance`},Picapt:{...$(N1),category:`distance`},pica:{...$(M1/6),category:`distance`},in:{...$(M1),category:`distance`},ft:{...$(P1),category:`distance`},yd:{...$(F1),category:`distance`},ell:{...$(1.143),category:`distance`},mi:{...$(I1),category:`distance`},survey_mi:{...$(1609.34),category:`distance`},Nmi:{...$(L1),category:`distance`},ly:{...$(R1),category:`distance`},parsec:{...$(0x6da012f95c9fd0),category:`distance`},sec:{...A1,category:`time`},min:{...$(60),category:`time`},hr:{...$(3600),category:`time`},day:{...$(86400),category:`time`},yr:{...$(31556952),category:`time`},Pa:{...A1,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:{...A1,category:`force`},dyn:{...$(1e-5),category:`force`},pond:{...$(.00980665),category:`force`},lbf:{...$(4.44822),category:`force`},J:{...A1,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:{...A1,category:`power`},PS:{...$(735.499),category:`power`},HP:{...$(745.7),category:`power`},T:{...A1,category:`magnetism`},ga:{...$(1e-4),category:`magnetism`},K:{...A1,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":{...A1,category:`volume`,order:3},"ang^3":{...$(j1**3),category:`volume`,order:3},"Picapt^3":{...$(N1**3),category:`volume`,order:3},tsp:{...$(492892e-11),category:`volume`},tspm:{...$(5e-6),category:`volume`},tbs:{...$(14786764825785619e-21),category:`volume`},"in^3":{...$(M1**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":{...$(P1**3),category:`volume`,order:3},bushel:{...$(.0352390704),category:`volume`},barrel:{...$(.158987295),category:`volume`},"yd^3":{...$(F1**3),category:`volume`,order:3},MTON:{...$(1.13267386368),category:`volume`},GRT:{...$(2.83168),category:`volume`},"mi^3":{...$(I1**3),category:`volume`,order:3},"Nmi^3":{...$(L1**3),category:`volume`,order:3},"ly^3":{...$(R1**3),category:`volume`,order:3},"m^2":{...A1,category:`area`,order:2},"ang^2":{...$(j1**2),category:`area`,order:2},"Picapt^2":{...$(N1**2),category:`area`,order:2},"in^2":{...$(M1**2),category:`area`,order:2},"ft^2":{...$(P1**2),category:`area`,order:2},"yd^2":{...$(F1**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":{...$(I1**2),category:`area`,order:2},"Nmi^2":{...$(L1**2),category:`area`,order:2},"ly^2":{...$(R1**2),category:`area`,order:2},bit:{...A1,category:`information`},byte:{...$(8),category:`information`},"m/s":{...A1,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`}},B1={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`},V1={"":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},H1={weight:P(`Weight`),distance:P(`Distance`),time:P(`Time`),pressure:P(`Pressure`),force:P(`Force`),energy:P(`Energy`),power:P(`Power`),magnetism:P(`Magnetism`),temperature:P(`Temperature`),volume:P(`Volume`),area:P(`Area`),information:P(`Information`),speed:P(`Speed`)},U1=Object.entries(z1).map(([e,t])=>({value:e,label:W1(t.category)}));function W1(e){return H1[e]??``}function G1(e){for(let[t,n]of Object.entries(V1)){if(t&&!e.startsWith(t))continue;let r=e.slice(t.length),i=z1[r];if(!i&&B1[r]&&(i=z1[B1[r]]),i)return{...i,factor:i.order?n**+i.order:n}}}var K1=l({CONVERT:()=>q1});let q1={description:P(`Converts a numeric value to a different unit of measure.`),args:[U(`value (number)`,P(`the numeric value in start_unit to convert to end_unit`)),U(`start_unit (string)`,P(`The starting unit, the unit currently assigned to value`),U1),U(`end_unit (string)`,P(`The unit of measure into which to convert value`),U1)],compute:function(e,t,n){let r=L(e,this.locale),i=R(t),a=R(n),o=G1(i),s=G1(a);return o?s?o.category===s.category?{value:s.inverseTransform(o.factor*o.transform(r))/s.factor,format:e?.format}:{value:F.GenericError,message:P(`Incompatible units of measure ('%s' vs '%s')`,W1(o.category),W1(s.category))}:{value:F.GenericError,message:P(`Invalid units of measure ('%s')`,a)}:{value:F.GenericError,message:P(`Invalid units of measure ('%s')`,i)}},isExported:!0};var J1=l({CHAR:()=>Q1,CLEAN:()=>$1,CONCATENATE:()=>e0,EXACT:()=>t0,FIND:()=>n0,FORMAT_LARGE_NUMBER:()=>r0,JOIN:()=>i0,LEFT:()=>a0,LEN:()=>o0,LOWER:()=>s0,MID:()=>c0,PROPER:()=>l0,REGEXEXTRACT:()=>d0,REGEXREPLACE:()=>f0,REGEXTEST:()=>u0,REPLACE:()=>p0,RIGHT:()=>m0,SEARCH:()=>h0,SPLIT:()=>g0,SUBSTITUTE:()=>_0,TEXT:()=>S0,TEXTAFTER:()=>w0,TEXTBEFORE:()=>T0,TEXTJOIN:()=>v0,TEXTSPLIT:()=>y0,TRIM:()=>b0,UPPER:()=>x0,VALUE:()=>C0});let Y1=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,X1=[{value:0,label:P(`Case-sensitive (default)`)},{value:1,label:P(`Case-insensitive`)}],Z1=[{value:0,label:P(`Don't match to end (default)`)},{value:1,label:P(`Match to end`)}],Q1={description:P(`Gets character associated with number.`),args:[U(`table_number (number)`,P(`The number of the character to look up from the current Unicode table in decimal format.`))],compute:function(e){let t=Math.trunc(L(e,this.locale));return t<1?new I(P(`The table_number (%s) is out of range.`,t)):String.fromCharCode(t)},isExported:!0},$1={description:P(`Remove non-printable characters from a piece of text.`),args:[U(`text (string)`,P(`The text whose non-printable characters are to be removed.`))],compute:function(e){let t=R(e),n=``;for(let e of t)e&&e.charCodeAt(0)>31&&(n+=e);return n},isExported:!0},e0={description:P(`Appends strings to one another.`),args:[U(`string (string, range<string>, repeating)`,P(`String to append in sequence.`))],compute:function(...e){return es(e,(e,t)=>e+R(t),``)},isExported:!0},t0={description:P(`Tests whether two strings are identical.`),args:[U(`string1 (string)`,P(`The first string to compare.`)),U(`string2 (string)`,P(`The second string to compare.`))],compute:function(e,t){return R(e)===R(t)},isExported:!0},n0={description:P(`First position of string found in text, case-sensitive.`),args:[U(`search_for (string)`,P(`The string to look for within text_to_search.`)),U(`text_to_search (string)`,P(`The text to search for the first occurrence of search_for.`)),U(`starting_at (number, default=1)`,P(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=R(e),i=R(t),a=L(n,this.locale);if(i===``)return new I(P(`The text_to_search must be non-empty.`));if(a<1)return new I(P(`The starting_at (%s) must be greater than or equal to 1.`,a));let o=i.indexOf(r,a-1);return o===-1?new I(P(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)):o+1},isExported:!0},r0={description:P(`Apply a large number format`),args:[U(`value (number)`,P(`The number.`)),U(`unit (string, optional)`,P(`The formatting unit. Use 'k', 'm', or 'b' to force the unit`),[{value:`k`,label:P(`Thousand`)},{value:`m`,label:P(`Million`)},{value:`b`,label:P(`Billion`)}])],compute:function(e,t){return{value:L(e,this.locale),format:Dc(e,t,this.locale)}}},i0={description:P(`Concatenates elements of arrays with delimiter.`),args:[U(`delimiter (string)`,P(`The character or string to place between each concatenated value.`)),U(`value_or_array (string, range<string>, repeating)`,P(`Value to be appended using delimiter.`))],compute:function(e,...t){let n=R(e);return es(t,(e,t)=>(e?e+n:``)+R(t),``)}},a0={description:P(`Substring from beginning of specified string.`),args:[U(`text (string)`,P(`The string from which the left portion will be returned.`)),U(`number_of_characters (number, optional)`,P(`The number of characters to return from the left side of string.`))],compute:function(e,...t){let n=t.length?L(t[0],this.locale):1;return n<0?new I(P(`The number_of_characters (%s) must be positive or null.`,n)):R(e).substring(0,n)},isExported:!0},o0={description:P(`Length of a string.`),args:[U(`text (string)`,P(`The string whose length will be returned.`))],compute:function(e){return R(e).length},isExported:!0},s0={description:P(`Converts a specified string to lowercase.`),args:[U(`text (string)`,P(`The string to convert to lowercase.`))],compute:function(e){return R(e).toLowerCase()},isExported:!0},c0={description:P(`A segment of a string.`),args:[U(`text (string)`,P(`The string to extract a segment from.`)),U(`starting_at (number)`,P(`The index from the left of string from which to begin extracting. The first character in string has the index 1.`)),U(`extract_length (number)`,P(`The length of the segment to extract.`))],compute:function(e,t,n){let r=R(e),i=L(t,this.locale),a=L(n,this.locale);return i<1?new I(P(`The starting_at argument (%s) must be positive greater than one.`,i.toString())):a<0?new I(P(`The extract_length argument (%s) must be positive or null.`,a)):r.slice(i-1,i+a-1)},isExported:!0},l0={description:P(`Capitalizes each word in a specified string.`),args:[U(`text_to_capitalize (string)`,P(`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 R(e).replace(Y1,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},u0={description:P(`Checks whether a string matches the supplied regular expression.`),args:[U(`text (string)`,P(`The string to test.`)),U(`pattern (string)`,P(`The regular expression pattern to match against the text.`)),U(`case_sensitivity (number, default=0)`,P(`Whether the match is case-sensitive.`),[{value:0,label:P(`Case-sensitive`)},{value:1,label:P(`Case-insensitive`)}])],compute:function(e,t,n={value:0}){let r=R(e),i=R(t),a=L(n,this.locale);if(i===``)return!0;if(r===``)return!1;if(a!==0&&a!==1)return new I(P(`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 I(P(`Invalid regular expression`))}return s.test(r)},isExported:!0},d0={description:P(`Extract text from a string based on the supplied regular expression.`),args:[U(`text (string)`,P(`The string on which you want to extract text.`)),U(`pattern (string)`,P(`The regular expression pattern to match against the text.`)),U(`return_mode (number, default=0)`,P(`0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array.`),[{value:0,label:P(`First match`)},{value:1,label:P(`All matches`)},{value:2,label:P(`Capture groups of first match`)}]),U(`case_sensitivity (number, default=0)`,P(`Whether the match is case-sensitive.`),[{value:0,label:P(`Case-sensitive`)},{value:1,label:P(`Case-insensitive`)}])],compute:function(e,t,n={value:0},r={value:0}){let i=R(e),a=R(t),o=L(n,this.locale),s=L(r,this.locale);if(i===``||a===``)return{value:``};if(o<0||o>2)return new I(P(`The return_mode (%s) must be 0, 1 or 2.`,o));if(s!==0&&s!==1)return new I(P(`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 I(P(`Invalid regular expression`))}let u=[...i.matchAll(l)];return u.length===0?{value:F.NotAvailable,message:P(`No matches found.`)}:o===0?u[0][0]:o===1?u.map(e=>[e[0]]):u[0].length<2?new I(P(`No capturing groups found.`)):u[0].slice(1).map(e=>[e])},isExported:!0},f0={description:P(`Replace text in a string based on the supplied regular expression.`),args:[U(`text (string)`,P(`The string in which you want to replace text.`)),U(`pattern (string)`,P(`The regular expression pattern to match against the text.`)),U(`replacement (string)`,P(`The text to use as the replacement.`)),U(`occurrence (number, default=0)`,P(`0 = replace all matches. A negative number counts from the end.`)),U(`case_sensitivity (number, default=0)`,P(`Whether the match is case-sensitive.`),[{value:0,label:P(`Case-sensitive`)},{value:1,label:P(`Case-insensitive`)}])],compute:function(e,t,n,r={value:0},i={value:0}){let a=R(e),o=R(t),s=R(n),c=L(r,this.locale),l=L(i,this.locale);if(l!==0&&l!==1)return new I(P(`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 I(P(`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},p0={description:P(`Replaces part of a text string with different text.`),args:[U(`text (string)`,P(`The text, a part of which will be replaced.`)),U(`position (number)`,P(`The position where the replacement will begin (starting from 1).`)),U(`length (number)`,P(`The number of characters in the text to be replaced.`)),U(`new_text (string)`,P(`The text which will be inserted into the original text.`))],compute:function(e,t,n,r){let i=L(t,this.locale);if(i<1)return new I(P(`The position (%s) must be greater than or equal to 1.`,i));let a=L(n,this.locale);if(a<0)return new I(P(`The length (%s) must be positive or zero.`,a));let o=R(e),s=R(r);return o.substring(0,i-1)+s+o.substring(i-1+a)},isExported:!0},m0={description:P(`A substring from the end of a specified string.`),args:[U(`text (string)`,P(`The string from which the right portion will be returned.`)),U(`number_of_characters (number, optional)`,P(`The number of characters to return from the right side of string.`))],compute:function(e,...t){let n=t.length?L(t[0],this.locale):1;if(n<0)return new I(P(`The number_of_characters (%s) must be positive or zero.`,n));let r=R(e),i=r.length;return r.substring(i-n,i)},isExported:!0},h0={description:P(`First position of string found in text, ignoring case.`),args:[U(`search_for (string)`,P(`The string to look for within text_to_search.`)),U(`text_to_search (string)`,P(`The text to search for the first occurrence of search_for.`)),U(`starting_at (number, default=1)`,P(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=R(e).toLowerCase(),i=R(t).toLowerCase(),a=L(n,this.locale);if(i===``)return{value:F.GenericError,message:P(`The text_to_search must be non-empty.`)};if(a<1)return{value:F.GenericError,message:P(`The starting_at (%s) must be greater than or equal to 1.`,a)};let o=i.indexOf(r,a-1);return o===-1?{value:F.GenericError,message:P(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)}:{value:o+1}},isExported:!0},g0={description:P(`Split text by specific character delimiter(s).`),args:[U(`text (string)`,P(`The text to divide.`)),U(`delimiter (string)`,P(`The character or characters to use to split text.`)),U(`split_by_each (boolean, default=true})`,P(`Whether or not to divide text around each character contained in delimiter.`)),U(`remove_empty_text (boolean, default=true)`,P(`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=R(e),a=xt(R(t)),o=z(n),s=z(r);if(a.length<=0)return new I(P(`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!==``)),os([l])},isExported:!1},_0={description:P(`Replaces existing text with new text in a string.`),args:[U(`text_to_search (string)`,P(`The text within which to search and replace.`)),U(`search_for (string)`,P(`The string to search for within text_to_search.`)),U(`replace_with (string)`,P(`The string that will replace search_for.`)),U(`occurrence_number (number, optional)`,P(`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=L(r,this.locale);if(i<0)return new I(P(`The occurrenceNumber (%s) must be positive or null.`,i));let a=R(e),o=R(t);if(o===``)return a;let s=R(n),c=new RegExp(xt(o),`g`);if(i===0)return a.replace(c,s);let l=0;return a.replace(c,e=>++l===i?s:e)},isExported:!0},v0={description:P(`Combines text from multiple strings and/or arrays.`),args:[U(`delimiter (string)`,P(`A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.`)),U(`ignore_empty (boolean)`,P(`A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.`),[{value:!0,label:P(`Ignore empty cells`)},{value:!1,label:P(`Include empty cells (default)`)}]),U(`texts (string, range<string>, repeating)`,P(`Text item to join.`))],compute:function(e,t={value:!0},...n){let r=R(e),i=z(t),a=0;return es(n,(e,t)=>i&&R(t)===``?e:(a++?e+r:``)+R(t),``)},isExported:!0},y0={description:P(`Splits text into rows or columns using specified column and row delimiters.`),args:[U(`text (string)`,P(`The text to split.`)),U(`col_delimiter (string, range<string>)`,P(`Character or string to split columns by.`)),U(`row_delimiter (string, range<string>, optional)`,P(`Character or string to split rows by.`)),U(`ignore_empty (boolean, default=false)`,P(`Whether to ignore empty cells.`),[{value:!1,label:P(`Include empty cells (default)`)},{value:!0,label:P(`Ignore empty cells`)}]),U(`match_mode (number, default=0)`,P(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),X1),U(`pad_with (string, default="${F.NotAvailable}")`,P(`The value to use for padding empty cells.`))],compute:function(e,t,n,r={value:!1},i={value:0},a=new Do){let o=R(e);if(o.length<=0)return new I(P(`No text to split.`));if(t===void 0&&n===void 0)return new I(P(`At least one delimiter must be provided.`));let s=B(t).flat().map(e=>xt(R(e))),c=B(n).flat().map(e=>xt(R(e)));if(s.some(e=>e===``)||c.some(e=>e===``))return new I(P(`The delimiters cannot be empty values.`));let l=z(r),u=L(i,this.locale);if(![0,1].includes(u))return new I(P(`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 os(d)},isExported:!0},b0={description:P(`Removes space characters.`),args:[U(`text (string)`,P(`The text or reference to a cell containing text to be trimmed.`))],compute:function(e){return ln(R(e))},isExported:!0},x0={description:P(`Converts a specified string to uppercase.`),args:[U(`text (string)`,P(`The string to convert to uppercase.`))],compute:function(e){return R(e).toUpperCase()},isExported:!0},S0={description:P(`Converts a number to text according to a specified format.`),args:[U(`number (number)`,P(`The number, date or time to format.`)),U(`format (string)`,P(`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(L(e,this.locale),{format:R(t),locale:this.locale})},isExported:!0},C0={description:P(`Converts a string to a numeric value.`),args:[U(`value (number)`,P(`the string to be converted`))],compute:function(e){return L(e,this.locale)},isExported:!0},w0={description:P(`Returns text that occurs after a given substring or delimiter.`),args:[U(`text (string)`,P(`The source text.`)),U(`delimiter (string)`,P(`The substring after which text will be returned.`)),U(`instance_num (number, default=1)`,P(`The desired instance of the delimiter after which we extract the text. A negative number searches from the end.`)),U(`match_mode (number, default=0)`,P(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),X1),U(`match_end (number, default=0))`,P(`Whether to treat the end of text as a delimiter.`),Z1),U(`if_not_found (string, default="${F.NotAvailable}")`,P(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Do){let o=R(e),s=L(n,this.locale),c=L(r,this.locale),l=L(i,this.locale);if(s===0)return new I(P(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new I(P(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new I(P(`match_end should have a value of 0 or 1.`));let u=R(t);if(u===``)return Math.sign(s)>0?{value:o}:{value:``};let d=c===1?`gi`:`g`,f=xt(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+u.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},T0={description:P(`Returns text that occurs before a given substring or delimiter.`),args:[U(`text (string)`,P(`The source text.`)),U(`delimiter (string)`,P(`The substring after which text will be returned.`)),U(`instance_num (number, default=1)`,P(`The desired instance of the delimiter before which we extract the text. A negative number searches from the end.`)),U(`match_mode (number, default=0)`,P(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),X1),U(`match_end (number, default=0))`,P(`Whether to match a delimiter against the end of the text.`),Z1),U(`if_not_found (string, default="${F.NotAvailable}")`,P(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Do){let o=R(e),s=L(n,this.locale),c=L(r,this.locale),l=L(i,this.locale);if(s===0)return new I(P(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new I(P(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new I(P(`match_end should have a value of 0 or 1.`));let u=R(t);if(u===``)return Math.sign(s)>0?{value:``}:{value:o};let d=c===1?`gi`:`g`,f=xt(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+u.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 E0=l({HYPERLINK:()=>D0});let D0={description:P(`Creates a hyperlink in a cell.`),args:[U(`url (string)`,P(`The full URL of the link enclosed in quotation marks.`)),U(`link_label (string, optional)`,P(`The text to display in the cell, enclosed in quotation marks.`))],compute:function(e,t){let n=R(e).trim(),r=R(t)||n;return n===``?r:Pt(r,n)},isExported:!0},O0=[{name:P(`Array`),functions:UK},{name:P(`Database`),functions:JY},{name:P(`Date`),functions:uZ},{name:P(`Filter`),functions:JZ},{name:P(`Financial`),functions:eQ},{name:P(`Info`),functions:l$},{name:P(`Lookup`),functions:R$},{name:P(`Logical`),functions:S$},{name:P(`Math`),functions:yq},{name:P(`Operator`),functions:c1},{name:P(`Statistical`),functions:FJ},{name:P(`Text`),functions:J1},{name:P(`Engineering`),functions:KZ},{name:P(`Web`),functions:E0},{name:P(`Parser`),functions:K1}];for(let e of O0){let t=e.functions;for(let n in t){let r=t[n];r.category=r.category||e.name,n=n.replace(/_/g,`.`),al.add(n,{isExported:!1,...r})}}let k0={},A0={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},j0={autoCompleteProviders:iA,autofillModifiersRegistry:eB,autofillRulesRegistry:tB,cellMenuRegistry:FI,colMenuRegistry:$I,errorTypes:Co,functionRegistry:al,featurePluginRegistry:eH,iconsOnCellRegistry:Pz,statefulUIPluginRegistry:tH,coreViewsPluginRegistry:nH,corePluginRegistry:$V,rowMenuRegistry:oL,sidePanelRegistry:tF,figureRegistry:j_,chartSidePanelComponentRegistry:AA,chartDataSourceSidePanelComponentRegistry:CE,chartComponentRegistry:s_,chartTypeRegistry:Tb,chartSubtypeRegistry:Hg,chartDataSourceRegistry:wb,topbarMenuRegistry:OH,topbarComponentRegistry:qH,topBarToolBarRegistry:YU,clickableCellRegistry:rH,otRegistry:TB,inverseCommandRegistry:oH,urlRegistry:Vd,cellPopoverRegistry:cw,numberFormatMenuRegistry:wH,repeatLocalCommandTransformRegistry:wV,repeatCommandTransformRegistry:CV,clipboardHandlersRegistries:ZL,pivotRegistry:qN,pivotTimeAdapterRegistry:LS,pivotSidePanelRegistry:cP,pivotNormalizationValueRegistry:hC,supportedPivotPositionalFormulaRegistry:AR,pivotToFunctionValueRegistry:gC,migrationStepRegistry:PC,chartJsExtensionRegistry:Wr,onIterationEndEvaluationRegistry:wz,specificRangeTransformRegistry:EB},M0={arg:U,isEvaluationError:Po,toBoolean:z,toJsDate:Jo,toNumber:L,toString:R,toNormalizedPivotValue:dC,toFunctionPivotValue:pC,toXC:E,toZone:Wn,toUnboundedZone:Un,toCartesian:Nn,numberToLetters:wn,lettersToNumber:Tn,UuidGenerator:G,formatValue:H,createCurrencyFormat:bc,ColorGenerator:jp,computeTextWidth:bf,createEmptyWorkbookData:ew,createEmptySheet:$C,createEmptyExcelSheet:tw,doesCellContainFunction:bn,rgbaToHex:rp,colorToRGBA:ip,positionToZone:O,isDefined:w,isMatrix:ht,lazy:Gt,genericRepeat:KH,createAction:xe,createActions:_e,transformRangeData:Nr,deepEquals:T,overlap:ir,union:er,isInside:or,deepCopy:x,expandZoneOnInsertion:Xn,reduceZoneOnDeletion:$n,unquote:wt,getMaxObjectId:rC,getFirstPivotFunction:QN,getNumberOfPivotFunctions:eP,parseDimension:oC,isDateOrDatetimeField:sC,makeFieldProposal:tP,periodYearToComparable:IS,insertTokenAfterArgSeparator:rP,insertTokenAfterLeftParenthesis:iP,mergeContiguousZones:Ar,getPivotHighlights:WM,pivotTimeAdapter:RS,UNDO_REDO_PIVOT_COMMANDS:Zz,createPivotFormula:uC,areDomainArgsFieldsValid:lC,splitReference:vl,sanitizeSheetName:Et,getUniqueText:_n,isNumber:uo,isDateTime:Ma,createCustomFields:SC,schemeToColorScale:jC,isDateTimeFormat:pc,jsDateToNumber:Ka,numberToJsDate:Wa,DateTime:va,parseFormat:Ls,isFormula:vn,domainToColRowDomain:vN,collapseHierarchicalDisplayName:OC,getCanonicalSymbolName:Tt,fuzzyLookup:rA,replaceSymbolInFormula:Zu},N0={isMarkdownLink:Mt,parseMarkdownLink:Ft,markdownLink:Pt,openLink:Kd,urlRepresentation:Gd},P0={Checkbox:wE,Section:Z,Select:T_,RoundColorPicker:QE,ChartDataSeries:IE,ChartErrorSection:BE,ChartLabelRange:LE,ChartRangeDataSourceComponent:hk,ChartTitle:YE,ChartPanel:PA,ChartFigure:k_,ChartJsComponent:Rh,ClickableCellSortIcon:jR,ZoomableChartJsComponent:$g,Grid:kR,GridOverlay:rR,ScorecardChart:ag,GaugeChartComponent:a_,LineConfigPanel:hA,BarConfigPanel:HE,PieChartDesignPanel:vA,GenericChartConfigPanel:VE,ChartWithAxisDesignPanel:aD,GenericZoomableChartDesignPanel:oD,LineChartDesignPanel:gA,GaugeChartConfigPanel:Nk,GaugeChartDesignPanel:uA,ScorecardChartConfigPanel:xA,ScorecardChartDesignPanel:SA,GeoChartDesignPanel:pA,RadarChartDesignPanel:yA,WaterfallChartDesignPanel:kA,ComboChartDesignPanel:Ak,FunnelChartDesignPanel:Mk,SunburstChartDesignPanel:CA,TreeMapChartDesignPanel:OA,ChartTypePicker:MA,FigureComponent:M_,MenuPopover:w_,Popover:b_,SelectionInput:FE,StandaloneComposer:lA,ValidationMessages:zE,AddDimensionButton:oN,PivotDimensionGranularity:cN,PivotDimensionOrder:lN,PivotDimension:rN,PivotLayoutConfigurator:pN,PivotHTMLRenderer:NR,PivotDeferUpdate:KM,PivotTitleSection:mN,CogWheelMenu:xE,TextInput:mE,SidePanelCollapsible:WE,RadioSelection:ZE,GeoChartRegionSelectSection:dA,ChartMenu:D_,FullScreenFigure:MR,NumberInput:KE,TopBar:XU,Composer:Wk},F0={useDragAndDropListItems:oE,useHighlights:LA,useHighlightsOnHover:IA},I0={Component:A,useExternalListener:Ii,EnvPlugin:Ri,App:Ui},L0={useStoreProvider:qi,DependencyContainer:Gi,CellPopoverStore:lw,ComposerFocusStore:Ur,CellComposerStore:LL,FindAndReplaceStore:wj,HighlightStore:ME,DelayedHoveredCellStore:N_,HoveredTableStore:eR,ModelStore:Ir,NotificationStore:aA,RendererStore:Br,SelectionInputStore:PE,SpreadsheetStore:Vr,useStore:j,useLocalStore:Ji,SidePanelStore:rF,PivotSidePanelStore:oP,PivotMeasureDisplayPanelStore:HM,ClientFocusStore:cL,GridRenderer:fR};function R0(e,t){return al.add(e,t),{addFunction:(e,t)=>R0(e,t)}}let z0={DEFAULT_LOCALE:V,HIGHLIGHT_COLOR:De,PIVOT_STATIC_TABLE_CONFIG:st,PIVOT_INSERT_TABLE_STYLE_ID:ct,ChartTerms:L_,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2,CHART_TYPES:AC,DARK_MODE_FILTER_STRING:hp},B0={...mk,...PR};e.AbstractCellClipboardHandler=pV,e.AbstractChart=zh,e.AbstractFigureClipboardHandler=sK,e.BadExpressionError=wo,e.CHART_TYPES=AC,e.CellErrorType=F,e.CellValueType=yd,e.CircularDependencyError=To,e.ClientDisconnectedError=sV,e.ClipboardMIMEType=uw,e.CommandResult=zd,e.CompiledFormula=fd,e.CorePlugin=lv,e.CoreViewPlugin=oF,e.DEFAULT_LOCALE=V,e.DEFAULT_LOCALES=Ss,e.DEFAULT_LOCALE_DIGIT_GROUPING=`[3,0]`,e.DIRECTION=_t,e.DispatchResult=Ld,e.DivisionByZeroError=Ao,e.EvaluationError=I,e.InvalidReferenceError=Eo,e.LocalTransportService=JH,e.Model=iK,e.NEXT_VALUE=F_,e.NotAvailableError=Do,e.NumberTooLargeError=jo,e.OrderedLayers=Rr,e.PREVIOUS_VALUE=P_,e.PivotRuntimeDefinition=qM,e.Registry=k,e.Revision=oV,e.SPREADSHEET_DIMENSIONS=A0,e.SplillBlockedError=ko,e.Spreadsheet=$U,e.SpreadsheetPivotTable=FN,e.UIPlugin=fB,e.UnknownFunctionError=Oo,e.__info__=k0,e.addFunction=R0,e.addRenderingLayer=zr,e.astToFormula=NL,e.availableConditionalFormatOperators=lj,e.availableDataValidationOperators=xj,e.availableFiltersOperators=YM,e.borderPositions=gt,e.borderStyles=mt,e.canExecuteInReadonly=Id,e.categories=O0,e.chartHelpers=B0,e.compatibility=I0,e.components=P0,e.composerFocusTypes=vt,e.constants=z0,e.convertAstNodes=pu,e.coreTypes=Pd,e.createAutocompleteArgumentsProvider=TK,e.errorTypes=Co,e.filterDateCriterionOperators=QM,e.filterNumberCriterionOperators=ZM,e.filterTextCriterionOperators=XM,e.findCellInNewZone=_r,e.functionCache=ud,e.getCaretDownSvg=Dy,e.getCaretUpSvg=Oy,e.helpers=M0,e.hooks=F0,e.invalidSubtotalFormulasCommands=jd,e.invalidateBordersCommands=Ad,e.invalidateCFEvaluationCommands=kd,e.invalidateChartEvaluationCommands=Dd,e.invalidateDependenciesCommands=Od,e.invalidateEvaluationCommands=Ed,e.isCoreCommand=Fd,e.isHeadersDependant=xd,e.isMatrix=ht,e.isPositionDependent=wd,e.isRangeDependant=Cd,e.isSheetDependent=bd,e.isTargetDependent=Sd,e.isZoneDependent=Td,e.iterateAstNodes=mu,e.links=N0,e.load=zC,e.lockedSheetAllowedCommands=Nd,e.parse=du,e.parseTokens=fu,e.readonlyAllowedCommands=Md,e.registries=j0,e.schemeToColorScale=jC,e.setDefaultSheetViewSize=at,e.setTranslationMethod=bo,e.stores=L0,e.tokenColors=pt,e.tokenize=Al,k0.version=`19.4.3`,k0.date=`2026-07-20T11:02:36.941Z`,k0.hash=`d32e61b`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|
|
957
|
+
`),`_rels/.rels`)}function nK(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=_n(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(`'?${xt(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function rK(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>cr(Wn(e.range)).numberOfRows>1);return e}var iK=class e extends Wi{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},n=[],r=!1){let i=performance.now();console.debug(`##### Model creation #####`),super(),xo(),n=qC(e,n);let a=zC(e,r);this.state=new gW,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(a.revisionId),this.coreGetters={},this.range=new fW(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 mW(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 $V.getAll())this.setupCorePlugin(e,a);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(n);for(let e of nH.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of tH.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of eH.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()-i,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession({shouldSnapshot:e}={shouldSnapshot:!0}){let t=e&&!this.getters.isReadonly()?Gt(()=>this.exportData()):void 0;await this.session.leave(t)}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 cV(lW({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 eW(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:G.smallUuid(),name:P(`Anonymous`).toString()},n=e.transportService||new JH,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 tW(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(Ss));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,colorScheme:this.config.colorScheme}}checkDispatchAllowed(e){let t=Fd(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return this.processCommandResults(t)}processCommandResults(e){return e.some(e=>e!==`Success`)?new Ld(e.flat()):Ld.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(aK(e,t));dispatch=(e,t)=>{let n=aK(e,t),r=this.status;if(this.getters.isReadonly()&&!Id(n))return new Ld(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new Ld(`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();Fd(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(Fd(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(Fd(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return Ld.Success};dispatchFromCorePlugin=(e,t)=>{let n=aK(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,Ld.Success};dispatchToHandlers(e,t){let n=Fd(t);for(let r of e)!n&&r instanceof lv||r.beforeHandle(t);for(let r of e)!n&&r instanceof lv||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 JH};return T(n,new e(x(t),r)._exportData(!1))?t:(n.isNotSquishable=!0,n)}_exportData(e){let t=ew();for(let n of this.handlers)n instanceof lv&&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=nw();for(let t of this.handlers)t instanceof cv&&await t.exportForExcel(e);return e=x(e),qG(e)}};function aK(e,t={}){let n=x(t);return n.type=e,n}var oK=class extends pV{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(O(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=D(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}},sK=class extends fV{copy(e){}getCopyRect(e){return m_(...e.figureIds.map(t=>this.getters.getFigure(e.sheetId,t)).filter(w).map(t=>this.getters.getFigureUI(e.sheetId,t)))}},cK=class extends sK{copy(e){let t=e.sheetId,n=[],r=this.getCopyRect(e);for(let i of e.figureIds){let e=this.getters.getFigure(t,i);if(!e)throw Error(`No figure for the given id: ${i}`);if(e.tag!==`carousel`)continue;let a={...e},o=this.getters.getCarousel(i),{x:s,y:c}=this.getters.getFigureUI(t,e),l={};for(let e of o.items)if(e.type===`chart`){let t=this.getters.getChart(e.chartId);if(!t)throw Error(`No chart for the given id: ${e.chartId}`);l[e.chartId]=t}n.push({figureId:i,copiedFigure:a,copiedCarousel:o,copiedCharts:l,copiedSheetId:t,offset:{x:s-r.x,y:c-r.y}})}return{figures:n,figureIds:e.figureIds}}getPasteTarget(e,t,n,r){let i={};for(let e of n.figures)i[e.figureId]=G.smallUuid();return{zones:[],figureIds:i,sheetId:e}}paste(e,t,n){if(!e.figureIds)return;let{zones:r}=e,i=e.sheetId;for(let a of t.figures){let o=e.figureIds[a.figureId],{width:s,height:c}=a.copiedFigure,{col:l,row:u,offset:d}=Mg(this.getters,i,{col:r[0].left,row:r[0].top},{...a.copiedFigure,offset:a.offset});this.dispatch(`CREATE_CAROUSEL`,{figureId:o,sheetId:i,definition:{items:[]},col:l,row:u,offset:d,size:{height:c,width:s}});let f=x(a.copiedCarousel.items);for(let e of f){if(e.type!==`chart`)continue;let t=a.copiedCharts[e.chartId],n=G.smallUuid(),r=gk.fromDefinition(this.getters,i,t.copyInSheetId(i)).getDefinition();this.dispatch(`CREATE_CHART`,{figureId:o,chartId:n,sheetId:i,definition:r}),e.chartId=n}this.dispatch(`UPDATE_CAROUSEL`,{sheetId:i,figureId:o,definition:{...a.copiedCarousel,items:f}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:a.copiedSheetId,figureId:a.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:o,selectMultiple:t.figureIds.length>1})}}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},lK=class extends sK{copy(e){let t=e.sheetId,n=[],r=this.getCopyRect(e);for(let i of e.figureIds){let e=this.getters.getFigure(t,i);if(!e)throw Error(`No figure for the given id: ${i}`);if(e.tag!==`chart`)continue;let a={...e},{x:o,y:s}=this.getters.getFigureUI(t,e),c=this.getters.getChartFromFigureId(i);if(!c)throw Error(`No chart for the given id: ${i}`);n.push({figureId:i,copiedFigure:a,copiedChart:c,offset:{x:o-r.x,y:s-r.y}})}return{figures:n,figureIds:e.figureIds}}getPasteTarget(e,t,n,r){let i={};for(let e of n.figures)i[e.figureId]=G.smallUuid();return{zones:[],figureIds:i,sheetId:e}}paste(e,t,n){if(!e.figureIds)return;let{zones:r}=e,i=e.sheetId;for(let a of t.figures){let o=e.figureIds[a.figureId],{width:s,height:c}=a.copiedFigure,l=a.copiedChart,u=gk.fromDefinition(this.getters,i,l.copyInSheetId(i)).getDefinition();u=gk.fromStrDefinition(this.getters,i,u).getDefinition();let{col:d,row:f,offset:p}=Mg(this.getters,i,{col:r[0].left,row:r[0].top},{...a.copiedFigure,offset:a.offset});this.dispatch(`CREATE_CHART`,{figureId:o,chartId:G.smallUuid(),sheetId:i,definition:u,col:d,row:f,offset:p,size:{height:c,width:s}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:a.copiedChart.sheetId,figureId:a.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:o,selectMultiple:t.figureIds.length>1})}}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},uK=class extends pV{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=O(e.position),i=O(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:G.smallUuid(),ranges:[]}}},dK=class extends pV{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=O(t),i=O(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?G.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=D([...D(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})}}},fK=class extends pV{copy(e){let t={style:{},format:{},width:e.columnsIndexes.length,height:e.rowsIndexes.length,sheetId:e.sheetId,zones:e.clippedZones};t.format={sheetDefault:this.getters.getDefaultFormat(e.sheetId,`SHEET`,void 0)??``,colDefault:[],rowDefault:[]};let n=0;for(let r of e.columnsIndexes){let i=this.getters.getDefaultFormat(e.sheetId,`COL`,r);i&&t.format.colDefault&&(t.format.colDefault[n]=i),n++}let r=0;for(let n of e.rowsIndexes){let i=this.getters.getDefaultFormat(e.sheetId,`ROW`,n);i&&t.format.rowDefault&&(t.format.rowDefault[r]=i),r++}for(let n in Ue){t.style[n]={sheetDefault:this.getters.getDefaultStyle(e.sheetId,n,`SHEET`,void 0)??Ue[n],colDefault:[],rowDefault:[]};let r=0;for(let i of e.columnsIndexes){let a=this.getters.getDefaultStyle(e.sheetId,n,`COL`,i);a!==void 0&&(t.style[n].colDefault[r]=a),r++}let i=0;for(let r of e.rowsIndexes){let a=this.getters.getDefaultStyle(e.sheetId,n,`ROW`,r);a!==void 0&&(t.style[n].rowDefault[i]=a),i++}}return t}adaptContentToZone(e,t){let n=Math.max(Math.floor((e.right-e.left+1)/t.width),1),r=Math.max(Math.floor((e.bottom-e.top+1)/t.height),1);if(n===1&&r===1)return t;let i=x(t);i.height*=r,i.width*=n,r>1&&i.format.rowDefault&&(i.format.rowDefault.length=t.height,i.format.rowDefault=Cn(i.format.rowDefault,r)),n>1&&i.format.colDefault&&(i.format.colDefault.length=t.width,i.format.colDefault=Cn(i.format.colDefault,n));for(let e in t.style)r>1&&i.style[e].rowDefault&&(i.style[e].rowDefault.length=t.height,i.style[e].rowDefault=Cn(i.style[e].rowDefault,r)),n>1&&i.style[e].colDefault&&(i.style[e].colDefault.length=t.width,i.style[e].colDefault=Cn(i.style[e].colDefault,n));return i}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(n.isCutOperation){this.clearClippedZones(t);let{left:e,top:n}=i[0];this.pasteStyle(r,e,n,t.width,t.height,t.style),this.pasteFormat(r,e,n,t.width,t.height,t.format)}else for(let e of i){let n=this.adaptContentToZone(e,t);this.pasteStyle(r,e.left,e.top,n.width,n.height,n.style),this.pasteFormat(r,e.left,e.top,n.width,n.height,n.format)}}clearClippedZones(e){this.dispatch(`CLEAR_FORMATTING`,{sheetId:e.sheetId,target:e.zones})}pasteStyle(e,t,n,r,i,a){let o=Sn({}),s={},c=0;function l(e,t){let n=`${e.left}:${e.right}:${e.top}:${e.bottom}`;s[n]=[e,c++],o.set(n,{...o.get(n),...t})}l({left:t,right:t+r-1,top:n,bottom:n+i-1},Ue);for(let e in a)l({left:t,right:t+r-1,top:n,bottom:n+i-1},{[e]:a[e].sheetDefault});for(let e in a)for(let r in a[e].colDefault){let o=parseInt(r);l({left:t+o,right:t+o,top:n,bottom:n+i-1},{[e]:a[e].colDefault[r]})}for(let e in a)for(let i in a[e].rowDefault){let o=parseInt(i);l({left:t,right:t+r-1,top:n+o,bottom:n+o},{[e]:a[e].rowDefault[i]})}let u=[];for(let[e,[t,n]]of Object.entries(s)){let r=o.get(e);Bt(r)||u.push([n,t,r])}u.sort((e,t)=>e[0]-t[0]);for(let[t,n,r]of u)this.dispatch(`SET_FORMATTING`,{sheetId:e,target:[n],style:r})}pasteFormat(e,t,n,r,i,a){let o={},s={},c=0;function l(e,t){let n=`${e.left}:${e.right}:${e.top}:${e.bottom}`;s[n]=[e,c++],o[n]=t}l({left:t,right:t+r-1,top:n,bottom:n+i-1},a.sheetDefault??``);for(let e in a.colDefault){let r=parseInt(e);l({left:t+r,right:t+r,top:n,bottom:n+i-1},a.colDefault[e])}for(let e in a.rowDefault){let i=parseInt(e);l({left:t,right:t+r-1,top:n+i,bottom:n+i},a.rowDefault[e])}let u=[];for(let[e,[t,n]]of Object.entries(s)){let r=o[e];r!==void 0&&u.push([n,t,r])}u.sort((e,t)=>e[0]-t[0]);for(let[t,n,r]of u)this.dispatch(`SET_FORMATTING`,{sheetId:e,target:[n],format:r})}},pK=class extends sK{copy(e){let t=e.sheetId,n=[],r=this.getCopyRect(e);for(let i of e.figureIds){let e=this.getters.getFigure(t,i);if(!e)throw Error(`No figure for the given id: ${i}`);if(e.tag!==`image`)continue;let a={...e},{x:o,y:s}=this.getters.getFigureUI(t,e),c=x(this.getters.getImage(i));n.push({figureId:i,copiedFigure:a,copiedImage:c,sheetId:t,offset:{x:o-r.x,y:s-r.y}})}return{figures:n,figureIds:e.figureIds}}getPasteTarget(e,t,n,r){let i={};for(let e of n.figures)i[e.figureId]=G.smallUuid();return{sheetId:e,zones:[],figureIds:i}}paste(e,t,n){if(!e.figureIds)return;let{zones:r}=e;for(let i of t.figures){let a=e.figureIds[i.figureId],o=this.getters.getActiveSheetId(),{width:s,height:c}=i.copiedFigure,l=x(i.copiedImage),{col:u,row:d,offset:f}=Mg(this.getters,o,{col:r[0].left,row:r[0].top},{...i.copiedFigure,offset:i.offset});this.dispatch(`CREATE_IMAGE`,{figureId:a,sheetId:o,col:u,row:d,offset:f,size:{height:c,width:s},definition:l}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:i.sheetId,figureId:i.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:a,selectMultiple:t.figureIds.length>1})}}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},mK=class extends pV{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}]})}},hK=class extends pV{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})}}},gK=class extends pV{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return Cr(mw(t,n.cells),i,a)?`FrozenPaneOverlap`:`Success`}},_K=class extends pV{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=>sr(f,e))){s.add(u.id);let{numberOfRows:e}=cr(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=>sr(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=Zt({...this.getters.getCellTableStyle(e),hideGridLines:!1}),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Zt(n)},border:{...r,...Zt(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=cr(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}))}};ZL.figureHandlers.add(`chart`,lK).add(`image`,pK).add(`carousel`,cK),ZL.cellHandlers.add(`dataValidation`,dK).add(`default`,fK).add(`cell`,mV).add(`sheet`,gK).add(`merge`,mK).add(`border`,oK).add(`table`,_K).add(`conditionalFormat`,uK).add(`references`,hK);var vK=class extends A{static maxSize={maxHeight:80};static template=`o-spreadsheet-ErrorToolTip`;props=(0,t.useProps)({cellPosition:N.CellPosition(),onClosed:N.function().optional()});get dataValidationErrorMessage(){return this.env.model.getters.getInvalidDataValidationMessage(this.props.cellPosition)}get evaluationError(){let e=this.env.model.getters.getEvaluatedCell(this.props.cellPosition);if(e.message)return e}get errorOriginPositionString(){if(this.env.model.getters.isDashboard())return``;let e=this.evaluationError?.errorOriginPosition;if(!e||T(e,this.props.cellPosition))return``;let t=e.sheetId;return this.env.model.getters.getRangeString(this.env.model.getters.getRangeFromZone(t,O(e)),this.env.model.getters.getActiveSheetId())}selectCell(){let e=this.evaluationError?.errorOriginPosition;if(!e)return;let t=this.env.model.getters.getActiveSheetId();e.sheetId!==t&&this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:e.sheetId}),this.env.model.selection.selectCell(e.col,e.row)}get isSpillErrorBecauseOfMissingHeaders(){let e=this.evaluationError;return e?.value===F.SpilledBlocked&&!e.errorOriginPosition&&!this.env.model.getters.getSpreadZone(this.props.cellPosition,{ignoreSpillError:!0})}getMissingHeadersForSpread(){if(!this.isSpillErrorBecauseOfMissingHeaders)return;let e=this.env.model.getters.getCell(this.props.cellPosition);if(!e||!e.isFormula)return;let t=e.compiledFormula.toFormulaString(this.env.model.getters);return xn(this.env.model.getters,this.props.cellPosition,t)}addMissingHeaders({missingCols:e,missingRows:t}){let n=this.props.cellPosition.sheetId;e>0&&this.env.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:n,sheetName:this.env.model.getters.getSheetName(n),dimension:`COL`,base:this.env.model.getters.getNumberCols(n)-1,position:`after`,quantity:e+20}),t>0&&this.env.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:n,sheetName:this.env.model.getters.getSheetName(n),dimension:`ROW`,base:this.env.model.getters.getNumberRows(n)-1,position:`after`,quantity:t+50})}getAddMissingHeadersButtonText(e){return e.missingCols>0&&e.missingRows>0?P(`Add missing columns and rows`):e.missingCols>0?P(`Add missing columns`):P(`Add missing rows`)}};let yK={onHover:(e,t)=>{let n=t.getEvaluatedCell(e);return n.type===`error`&&n.message||t.getInvalidDataValidationMessage(e)?{isOpen:!0,props:{cellPosition:e},Component:vK,cellCorner:`top-right`}:{isOpen:!1}}};var bK=class extends A{static template=`o-spreadsheet-FilterMenu`;static components={FilterMenuValueList:tN,SidePanelCollapsible:WE,FilterMenuCriterion:$M};props=(0,t.useProps)({filterPosition:N.Position(),onClosed:N.function().optional()});state;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.state.values=this.getFilterHiddenValues(e.filterPosition))}),this.state=(0,t.proxy)({values:this.getFilterHiddenValues(this.props.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&&pc(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`?QM:this.criterionCategory===`number`?ZM:XM}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};LI(this.env,r,a,i,e,{emptyCellAsZero:!0,sortHeaders:!0}),this.props.onClosed?.()}getFilterHiddenValues(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getFilter({sheetId:t,...e});if(!n?.filteredRange)return[];let r=this.env.model.getters.getFilterValue({sheetId:t,...e}),i=dr(n.filteredRange.zone);r?.filterType!==`criterion`&&(i=i.filter(e=>!this.env.model.getters.isRowHidden(t,e.row)));let a=i.map(e=>this.env.model.getters.getEvaluatedCell({sheetId:t,...e}).formattedValue),o=r?.filterType===`values`?r.hiddenValues:[],s=new Set(o.map(jf)),c=new Set,l=[],u=e=>{let t=jf(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`}))}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:[]}}};let xK={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:bK,cellCorner:`bottom-left`})};var SK=class extends A{static template=`o-spreadsheet-LinkDisplay`;props=(0,t.useProps)({cellPosition:N.CellPosition(),onClosed:N.function().optional()});cellPopovers;setup(){this.cellPopovers=j(lw)}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 Gd(e,this.env.model.getters)}openLink(e){Kd(this.link,this.env,ue(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 CK={onHover:(e,t)=>{let n=t.getEvaluatedCell(e);return!t.isDashboard()&&n.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:SK,props:{cellPosition:e},cellCorner:`bottom-left`}:{isOpen:!1}}};var wK=class extends A{static template=`o-spreadsheet-LinkEditor`;static components={MenuPopover:w_};props=(0,t.useProps)({cellPosition:N.CellPosition(),onClosed:N.function().optional()});static size={maxHeight:500};urlInput=(0,t.signal)(null);suggestionListRef=(0,t.signal)(null);urlInputContainer=(0,t.signal)(null);state=(0,t.proxy)(this.defaultState);setup(){this.computeLinks(),(0,t.onMounted)(()=>this.urlInput()?.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 Vd.getKeys()){let i=Vd.get(r),a=i.getLinkProposals?.(this.env)||[],o=n&&this.state.isUrlEditable?rA(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()?.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 Gd(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?J_(this.state.label,n):this.state.url;this.env.model.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:this.env.model.getters.getActiveSheetId(),content:Pt(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()?.querySelector(`.suggestion-item[data-index="${this.state.selectedIndex}"]`)?.scrollIntoView({block:`nearest`})}};cw.add(`ErrorToolTip`,yK).add(`LinkCell`,CK).add(`LinkEditor`,{onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:wK,cellCorner:`bottom-left`})}).add(`FilterMenu`,xK),iA.add(`dataValidation`,{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(vn(t)||!this.composer.currentEditedCell)return[];let n=this.composer.currentEditedCell,r=this.getters.getValidationRuleForCell(n);if(!r||r.criterion.type!==`isValueInList`&&r.criterion.type!==`isValueInRange`)return[];let i=this.composer.currentEditedCell.sheetId,a=r.criterion.type===`isValueInRange`?this.getters.getDataValidationRangeValues(i,r.criterion):r.criterion.values.map(e=>({label:e,value:e}));if(r.criterion.displayStyle!==`chip`)return a.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));let o=r.criterion.colors;return a.map(e=>{let t=o?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:yp(t||`#E7E9ED`),backgroundColor:t||`#E7E9ED`,classes:[`badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start`]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t.text),this.composer.stopEdition()}}),iA.add(`functions_and_named_ranges`,{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if(e.type!==`SYMBOL`)return[];let t=e.value;if(!vn(this.composer.currentContent))return[];let n=Object.entries(al.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:n}])=>({type:`function`,text:e,icon:`o-spreadsheet-Icon.FX_SVG`,description:n,htmlContent:aN(t,e,Me,`o-semi-bold`)}));return n.push(...this.getters.getNamedRanges().map(e=>({type:`named_range`,text:e.name,description:this.getters.getRangeString(e.range),icon:`o-spreadsheet-Icon.NAMED_RANGE`,htmlContent:aN(t,e.name,Me,`o-semi-bold`)}))),n.sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text)),n},selectProposal(e,t){let n=e.end,r=e.end;[`SYMBOL`,`FUNCTION`].includes(e.type)&&(n=e.start);let i=this.composer.currentTokens,a=t.text;if(t.type===`function`){a+=`(`;let t=i.map(e=>e.start).indexOf(e.start);t+1<i.length&&i[t+1]?.type===`LEFT_PAREN`&&r++}this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(a)}});function TK(e,t){for(let n=0;n<t.length;n++){let r=t[n].proposalValues;r===void 0||r.length===0||iA.add(`${e}_function_${t[n].name}_argument_proposals`,{sequence:50,autoSelectFirstProposal:!0,selectProposal:EK,getProposals:t=>{let i=t.functionContext;if(!i||i.parent.toUpperCase()!==e.toUpperCase()||i.argPosition!==n)return;let a=[],o=``;for(let{value:e,label:t}of r){switch(typeof e){case`string`:o=`"${e}"`;break;case`number`:o=e.toString();break;case`boolean`:o=e?`TRUE`:`FALSE`;break;default:}a.push({text:o,description:t,htmlContent:[{value:o,color:typeof e==`string`?pt.STRING:pt.NUMBER}],fuzzySearchKey:o,alwaysExpanded:!0})}return a}})}}function EK(e,t){let n=e.end,r=e.end;[`LEFT_PAREN`,`ARG_SEPARATOR`].includes(e.type)||(n=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text)}al.getAll().forEach(e=>TK(e.name,e.args)),iA.add(`pivot_ids`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||![`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`].includes(t.parent.toUpperCase())||t.argPosition!==0)return;let n=this.getters.getPivotIds();if(!n.includes(e.value))return n.map(e=>{let t=this.getters.getPivotCoreDefinition(e),n=`${this.getters.getPivotFormulaId(e)}`;return{text:n,description:t.name,htmlContent:[{value:n,color:pt.NUMBER}],fuzzySearchKey:n+t.name,alwaysExpanded:!0}}).filter(w)},selectProposal:EK}),iA.add(`pivot_measures`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(t?.parent.toUpperCase()!==`PIVOT.VALUE`||t.argPosition!==1)return[];let n=aP(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return[];let i=this.getters.getPivot(r);return i.init(),i.isValid()?i.definition.measures.map(e=>{if(e.fieldName===`__count`){let e=`"__count"`;return{text:e,description:P(`Count`),htmlContent:[{value:e,color:pt.STRING}],fuzzySearchKey:P(`Count`)+e}}return nP(e)}).filter(w):[]},selectProposal:EK}),iA.add(`pivot_group_fields`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!DK(e)&&!OK(e))return;let n=aP(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);i.init();let a=i.getFields(),{columns:o,rows:s}=i.definition,c=t.args;t?.parent.toUpperCase()===`PIVOT.VALUE`?(c=c.filter((e,t)=>t%2==0),c=c.slice(1,t.argPosition)):c=c.filter((e,t)=>t%2==1);let l=c.map(e=>e?.value).filter(w),u=o.map(e=>e.nameWithGranularity),d=s.map(e=>e.nameWithGranularity),f=[],p=[`ARG_SEPARATOR`,`SPACE`].includes(e.type)?l.at(-1):l.at(-2),m=AR.get(i.type);if(m&&p?.startsWith(`#`)&&(p=p.slice(1)),p===void 0&&(f.push(u[0]),f.push(d[0])),d.includes(p)){let e=d[d.indexOf(p)+1];f.push(e),f.push(u[0])}if(u.includes(p)){let e=u[u.indexOf(p)+1];f.push(e)}let h=f.filter(w);return h.map(e=>{let[t,n]=e.split(`:`),r=a[t];return r?tP(r,n):void 0}).concat(h.map(e=>{if(!m)return;let t=a[e.split(`:`)[0]];if(!t)return;let n=`"#${e}"`;return{text:n,description:P(`%s (positional)`,t.string)+(t.help?` (${t.help})`:``),htmlContent:[{value:n,color:pt.STRING}],fuzzySearchKey:t.string+n}})).filter(w)},selectProposal:EK});function DK(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==0}function OK(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==1}iA.add(`pivot_group_values`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!e||!kK(e)&&!AK(e))return;let n=aP(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);if(!i.isValid())return;let a=t.argPosition,o=e.functionContext?.args[a-1]?.value;if(!o)return;let s;try{s=i.definition.getDimension(o)}catch{return}return s.granularity===`month_number`?Object.values(Zs).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:pt.NUMBER}]})):s.granularity===`quarter_number`?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:P(`Quarter %s`,e),htmlContent:[{value:`${e}`,color:pt.NUMBER}]})):s.granularity===`day_of_month`?C(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:pt.NUMBER}]})):s.granularity===`iso_week_number`?C(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:pt.NUMBER}]})):s.granularity===`day_of_week`?C(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:pt.NUMBER}]})):s.granularity===`hour_number`?C(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:pt.NUMBER}]})):s.granularity===`minute_number`?C(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:pt.NUMBER}]})):s.granularity===`second_number`?C(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:pt.NUMBER}]})):i.getPossibleFieldValues(s).map(({value:e,label:t})=>{let n=typeof e==`string`,r=n?`"${e}"`:e.toString(),i=n?pt.STRING:pt.NUMBER,a=t===e?``:t;return{text:r,description:a,htmlContent:[{value:r,color:i}],fuzzySearchKey:r+a}})},selectProposal:EK});function kK(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==1}function AK(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==0}iA.add(`sheet_names`,{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return e.type===`SYMBOL`||e.type===`UNKNOWN`&&e.value.startsWith(`'`)?this.getters.getSheetIds().map(e=>{let t=Tt(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith(`'`)?t:`'`+t}}):[]},selectProposal(e,t){let n=e.start,r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text+`!`)}});function jK(e){return e.yRanges.length&&!fl.test(e.yRanges[0])?`InvalidYRange`:e.xRange&&!fl.test(e.xRange)?`InvalidXRange`:e.labelRange&&!fl.test(e.labelRange)?`InvalidLabelRange`:e.sizeRange&&!fl.test(e.sizeRange)?`InvalidBubbleSizeRange`:`Success`}let MK={sequence:40,allowedDefinitionKeys:[...zh.commonKeys,`yRanges`,`xRange`,`labelRange`,`sizeRange`,`dataSetsHaveTitle`,`verticalAxisPosition`,`labelsAsText`,`bubbleColor`,`legendPosition`,`axesDesign`,`showValues`],fromStrDefinition(e,t,n){let r=e.yRanges.map(e=>Tu(n,t,e)).filter(w),i=Tu(n,t,e.xRange),a=Tu(n,t,e.labelRange),o=Tu(n,t,e.sizeRange);return{...e,yRanges:r,xRange:i,labelRange:a,sizeRange:o}},toStrDefinition(e,t,n){return{...e,yRanges:e.yRanges.map(e=>n.getRangeString(e,t)),xRange:e.xRange?n.getRangeString(e.xRange,t):void 0,labelRange:e.labelRange?n.getRangeString(e.labelRange,t):void 0,sizeRange:e.sizeRange?n.getRangeString(e.sizeRange,t):void 0}},validateDefinition(e,t){return e.checkValidations(t,jK)},transformDefinition(e,t,{adaptRangeString:n}){let r=e=>{if(!e)return;let{changeType:r,range:i}=n(t,e);return r===`REMOVE`?void 0:i};return{...e,yRanges:e.yRanges.map(r).filter(w),xRange:r(e.xRange),sizeRange:r(e.sizeRange),labelRange:r(e.labelRange)}},getDefinitionFromContextCreation(e,t){let n=e.dataSource?.type===`range`;return{background:e.background,yRanges:n?e.dataSource.dataSets?.map(e=>e.dataRange)??[]:[],verticalAxisPosition:e.dataSetStyles?.[0]?.verticalAxisPosition,dataSetsHaveTitle:n?e.dataSource.dataSetsHaveTitle??!1:!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`bubble`,labelRange:e.bubbleLabelRange||void 0,labelsAsText:e.labelsAsText??!1,xRange:e.auxiliaryRange||void 0,sizeRange:e.bubbleSizeRange||void 0,axesDesign:e.axesDesign,showValues:e.showValues,humanize:e.humanize,annotationText:e.annotationText,annotationLink:e.annotationLink,bubbleColor:e.bubbleColorMode||{color:`multiple`}}},getContextCreation(e,t){return{...e,dataSource:{type:`range`,dataSets:e.yRanges.map((e,t)=>({dataSetId:`${t}`,dataRange:e}))},bubbleLabelRange:e.labelRange,auxiliaryRange:e.xRange,bubbleSizeRange:e.sizeRange,bubbleColorMode:e.bubbleColor}},getDefinitionForExcel:()=>void 0,updateRanges(e,t){let n=e.yRanges.map(e=>nm(e,t)).filter(w),r=nm(e.xRange,t),i=nm(e.labelRange,t),a=nm(e.sizeRange,t);return{...e,yRanges:n,xRange:r,labelRange:i,sizeRange:a}},duplicateInDuplicatedSheet(e,t,n){let r=e=>tm(t,n,e);return{...e,yRanges:e.yRanges.map(r).filter(w),xRange:r(e.xRange),labelRange:r(e.labelRange),sizeRange:r(e.sizeRange)}},copyInSheetId:e=>e,getRuntime(e,t){let n=OD(t,e);return{chartJsConfig:{type:`line`,data:{datasets:lh(t,n),labels:n.labels},options:{...Cg,layout:$D(t,n),scales:Wm(t,n),plugins:{title:FO(t,e),legend:vO(t,n),tooltip:HO(t,n),chartShowValuesPlugin:kO(t,n),background:{color:t.background}}}}}}};function NK(e){return!Tk.includes(e.horizontalGroupBy)||!Tk.includes(e.verticalGroupBy)?`InvalidChartDefinition`:`Success`}let PK={sequence:110,dataSeriesLimit:1,allowedDefinitionKeys:[...zh.commonKeys,`dataSource`,`dataSetStyles`,`showValues`,`colorScale`,`missingValueColor`,`axesDesign`,`horizontalGroupBy`,`verticalGroupBy`,`legendPosition`],validateDefinition(e,t){return e.checkValidations(t,NK)},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`,annotationLink:e.annotationLink,annotationText:e.annotationText}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n}){let r=bD(t,n(),e),{labels:i,datasets:a}=ah(t,r);return{chartJsConfig:{type:`calendar`,data:{labels:i,datasets:a},options:{...Cg,indexAxis:`x`,layout:eO(t,r),scales:Rm(t,a),plugins:{title:FO(t,e),legend:{display:!1},tooltip:BO(t,r),chartShowValuesPlugin:AO(t,r),chartColorScalePlugin:zm(t,r),background:{color:r.background}}}}}}},FK={sequence:15,allowedDefinitionKeys:[...zh.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:uD(t.background||`#FFFFFF`),fontColor:uD(sm(t.background)),dataSets:n,labelRange:r,verticalAxis:pm(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,annotationText:e.annotationText,annotationLink:e.annotationLink}},getRuntime(e,t,{extractData:n},r,i){let a=_D(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:fh(t,a)},options:{...Cg,layout:$D(t,a),scales:Lm(t,a),plugins:{title:FO(t,e),legend:yO(t,a),tooltip:zO(t,a),chartShowValuesPlugin:kO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},IK={sequence:100,dataSeriesLimit:1,allowedDefinitionKeys:[...zh.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,annotationText:e.annotationText,annotationLink:e.annotationLink}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=ED(t,n(),e);return{chartJsConfig:{type:`funnel`,data:{labels:a.labels,datasets:hh(t,a)},options:{...Cg,indexAxis:`y`,layout:$D(t,a),scales:Ym(t,a),plugins:{title:FO(t,e),legend:{display:!1},tooltip:JO(t,a),chartShowValuesPlugin:kO(t,a),background:{color:a.background}},...i}}}}},LK={sequence:90,dataSeriesLimit:1,allowedDefinitionKeys:[...zh.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,annotationLink:e.annotationLink,annotationText:e.annotationText}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=TD(t,n(),e);return{chartJsConfig:{type:`choropleth`,data:{datasets:mh(t,a)},options:{...Cg,layout:$D(t,a),scales:Jm(t,a),plugins:{title:FO(t,e),tooltip:qO(t,a),legend:{display:!1},background:{color:a.background}},...i}}}}},RK={sequence:80,dataSeriesLimit:2,allowedDefinitionKeys:[...zh.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,annotationLink:e.annotationLink,annotationText:e.annotationText}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){if(t.dataSource.type!==`range`)return;let i=xD(t,bk(e,t.dataSource),e),{dataSetsValues:a}=i,o=Math.max(...a.map(e=>Math.max(...e.data.map(e=>nf(e)?Math.abs(e.value):-1/0))));return{...t,horizontal:!0,backgroundColor:uD(i.background||`#FFFFFF`),fontColor:uD(sm(i.background)),dataSets:n,labelRange:r,verticalAxis:pm(t),maxValue:o}},getRuntime(e,t,{extractData:n},r,i){let a=xD(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:rh(t,a)},options:{...Cg,indexAxis:`y`,layout:$D(t,a),scales:Km(t,a),plugins:{title:FO(t,e),legend:mO(t,a),tooltip:GO(t,a),chartShowValuesPlugin:MO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},zK={sequence:80,allowedDefinitionKeys:[...zh.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,annotationLink:e.annotationLink,annotationText:e.annotationText}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:uD(t.background||`#FFFFFF`),fontColor:uD(sm(t.background)),dataSets:n,labelRange:r}},getRuntime(e,t,{extractData:n},r,i){let a=wD(t,n(),e);return{chartJsConfig:{type:`radar`,data:{labels:a.labels,datasets:ph(t,a)},options:{...Cg,layout:$D(t,a),scales:qm(t,a),plugins:{title:FO(t,e),legend:xO(t,a),tooltip:KO(t,a),chartShowValuesPlugin:kO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},BK={sequence:60,allowedDefinitionKeys:[...zh.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,annotationLink:e.annotationLink,annotationText:e.annotationText}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:uD(t.background||`#FFFFFF`),fontColor:uD(sm(t.background)),dataSets:n,labelRange:r,verticalAxis:pm(t)}},getRuntime(e,t,{extractData:n},r,i){let a=SD(t,n(),e);return{chartJsConfig:{type:`line`,data:{labels:a.labels,datasets:ch(t,a)},options:{...Cg,layout:$D(t,a),scales:Um(t,a),plugins:{title:FO(t,e),legend:_O(t,a),tooltip:VO(t,a),chartShowValuesPlugin:kO(t,a),background:{color:a.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},VK={sequence:30,allowedDefinitionKeys:[...zh.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,annotationLink:e.annotationLink,annotationText:e.annotationText}},getContextCreation(e,t,n){return{...e,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=DD(t,n(),e);return{chartJsConfig:{type:`doughnut`,data:{datasets:_h(t,a)},options:{cutout:t.pieHolePercentage===void 0?`25%`:`${t.pieHolePercentage}%`,...Cg,layout:$D(t,a),plugins:{title:FO(t,e),legend:SO(t,a),tooltip:YO(t,a),sunburstLabelsPlugin:jO(t,a),sunburstHoverPlugin:{enabled:!0},background:{color:a.background}},...i}}}}},HK={sequence:100,allowedDefinitionKeys:[...zh.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,annotationText:e.annotationText,annotationLink:e.annotationLink}},getContextCreation(e,t,n){return{...e,treemapColoringOptions:e.coloringOptions,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=DD(t,n(),e);return{chartJsConfig:{type:`treemap`,data:{labels:a.labels,datasets:Sh(t,a)},options:{...Cg,layout:$D(t,a),plugins:{title:FO(t,e),legend:{display:!1},tooltip:XO(t,a),background:{color:a.background}},...i}}}}};Tb.add(`bar`,ek),Tb.add(`combo`,FK),Tb.add(`line`,dk),Tb.add(`pie`,fk),Tb.add(`scorecard`,Yh),Tb.add(`gauge`,ok),Tb.add(`scatter`,BK),Tb.add(`waterfall`,pk),Tb.add(`pyramid`,RK),Tb.add(`radar`,zK),Tb.add(`geo`,LK),Tb.add(`funnel`,IK),Tb.add(`sunburst`,VK),Tb.add(`treemap`,HK),Tb.add(`calendar`,PK),Tb.add(`bubble`,MK),Hg.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:P(`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:P(`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:P(`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:P(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:P(`Scatter`),chartType:`scatter`,chartSubtype:`scatter`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCATTER_CHART`}).add(`bubble`,{displayName:P(`Bubble`),chartType:`bubble`,chartSubtype:`bubble`,category:`misc`,preview:`o-spreadsheet-ChartPreview.BUBBLE_CHART`}).add(`column`,{matcher:e=>e.type===`bar`&&!e.stacked&&!e.horizontal,displayName:P(`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:P(`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:P(`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:P(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:P(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:P(`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:P(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:P(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:P(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:P(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:P(`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:P(`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:P(`Filled Radar`),chartType:`radar`,chartSubtype:`filled_radar`,subtypeDefinition:{fillArea:!0},category:`misc`,preview:`o-spreadsheet-ChartPreview.FILLED_RADAR_CHART`}).add(`geo`,{displayName:P(`Geo Chart`),chartSubtype:`geo`,chartType:`geo`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GEO_CHART`}).add(`funnel`,{displayName:P(`Funnel`),chartSubtype:`funnel`,chartType:`funnel`,category:`misc`,preview:`o-spreadsheet-ChartPreview.FUNNEL_CHART`}).add(`sunburst`,{matcher:e=>e.type===`sunburst`,displayName:P(`Sunburst`),chartSubtype:`sunburst`,chartType:`sunburst`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.SUNBURST_CHART`}).add(`treemap`,{matcher:e=>e.type===`treemap`,displayName:P(`Tree Map`),chartType:`treemap`,chartSubtype:`treemap`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.TREE_MAP_CHART`}).add(`calendar`,{displayName:P(`Calendar`),chartSubtype:`calendar`,chartType:`calendar`,category:`misc`,preview:`o-spreadsheet-ChartPreview.CALENDAR_CHART`}),Pz.add(`filter_icon`,(e,t)=>{if(e.isFilterHeader(t)){let n=e.isFilterActive(t),r=tp(e.getCellComputedStyle(t).fillColor||`#fff`)<.45;return{type:`filter_icon`,svg:Py(n,r,!1),hoverSvg:Py(n,r,!0),priority:3,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let n=t.getStore(lw),r=n.persistentCellPopover;if(r.isOpen&&r.col===e.col&&r.row===e.row&&r.type===`FilterMenu`){n.close();return}n.open(e,`FilterMenu`)}}}});var UK=l({ARRAYTOTEXT:()=>vq,ARRAY_CONSTRAIN:()=>KK,ARRAY_LITERAL:()=>qK,ARRAY_ROW:()=>JK,CHOOSECOLS:()=>YK,CHOOSEROWS:()=>XK,EXPAND:()=>ZK,FLATTEN:()=>QK,FREQUENCY:()=>$K,HSTACK:()=>eq,MDETERM:()=>tq,MINVERSE:()=>nq,MMULT:()=>rq,SUMPRODUCT:()=>iq,SUMX2MY2:()=>oq,SUMX2PY2:()=>sq,SUMXMY2:()=>cq,TOCOL:()=>dq,TOROW:()=>fq,TRANSPOSE:()=>pq,VSTACK:()=>mq,WRAPCOLS:()=>hq,WRAPROWS:()=>gq});function WK(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 I(P(`All ranges in [[FUNCTION_NAME]] must have the same number of rows (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 GK(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 I(P(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=rs(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 KK={description:P(`Returns a result array constrained to a specific width and height.`),args:[U(`input_range (any, range<any>)`,P(`The range to constrain.`)),U(`rows (number)`,P(`The number of rows in the constrained array.`)),U(`columns (number)`,P(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=B(e),i=Uo(t?.value,this.locale),a=Uo(n?.value,this.locale);if(i<=0)return new I(P(`The rows argument (%s) must be strictly positive.`,i.toString()));if(a<=0)return new I(P(`The columns argument (%s) must be strictly positive.`,a.toString()));let o=Math.min(i,r[0].length);return rs(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},qK={description:P(`Appends ranges vertically and in sequence to return a larger array. All ranges must have the same number of columns.`),args:[U(`range (any, range<any>, repeating)`,P(`The range to be appended.`))],compute:function(...e){return GK(e,{requireSameColCount:!0})},isExported:!1,hidden:!0},JK={description:P(`Appends ranges horizontally and in sequence to return a larger array. All ranges must have the same number of rows.`),args:[U(`range (any, range<any>, repeating)`,P(`The range to be appended.`))],compute:function(...e){return WK(e,{requireSameRowCount:!0})},isExported:!1,hidden:!0},YK={description:P(`Creates a new array from the selected columns in the existing range.`),args:[U(`array (any, range<any>)`,P(`The array that contains the columns to be returned.`)),U(`col_num (number, range<number>, repeating)`,P(`The column index of the column to be returned.`))],compute:function(e,...t){let n=B(e),r=vs(t,e=>Uo(e?.value,this.locale)),i=r.filter(e=>e===0||n.length<Math.abs(e));if(i.length!==0)return new I(P(`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},XK={description:P(`Creates a new array from the selected rows in the existing range.`),args:[U(`array (any, range<any>)`,P(`The array that contains the rows to be returned.`)),U(`row_num (number, range<number>, repeating)`,P(`The row index of the row to be returned.`))],compute:function(e,...t){let n=B(e),r=vs(t,e=>Uo(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?rs(i,r.length,(e,t)=>r[t]>0?n[e][r[t]-1]:n[e][n[e].length+r[t]]):new I(P(`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},ZK={description:P(`Expands or pads an array to specified row and column dimensions.`),args:[U(`array (any, range<any>)`,P(`The array to expand.`)),U(`rows (number)`,P(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),U(`columns (number, optional)`,P(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),U(`pad_with (any, default=0)`,P(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=B(e),a=Uo(t?.value,this.locale),o=n===void 0?i.length:Uo(n.value,this.locale);return a<i[0].length?new I(P(`The rows arguments (%s) must be greater or equal than the number of rows of the array.`,a.toString())):o<i.length?new I(P(`The columns arguments (%s) must be greater or equal than the number of columns of the array.`,o.toString())):rs(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},QK={description:P(`Flattens all the values from one or more ranges into a single column.`),args:[U(`range (any, range<any>, repeating)`,P(`The range to flatten.`))],compute:function(...e){return[vs(e,e=>e===void 0?{value:``}:e)]},isExported:!1},$K={description:P(`Calculates the frequency distribution of a range.`),args:[U(`data (range<number>)`,P(`The array of ranges containing the values to be counted.`)),U(`classes (number, range<number>)`,P(`The range containing the set of classes.`))],compute:function(e,t){let n=vs([e],e=>e.value).filter(e=>typeof e==`number`),r=vs([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},eq={description:P(`Appends ranges horizontally and in sequence to return a larger array.`),args:[U(`range (any, range<any>, repeating)`,P(`The range to be appended.`))],compute:function(...e){return WK(e)},isExported:!0},tq={description:P(`Returns the matrix determinant of a square matrix.`),args:[U(`square_matrix (number, range<number>)`,P(`An range with an equal number of rows and columns representing a matrix whose determinant will be calculated.`))],compute:function(e){let t=Vo(e,`square_matrix`);return dS(t)?mS(t).determinant:new I(P(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},nq={description:P(`Returns the multiplicative inverse of a square matrix.`),args:[U(`square_matrix (number, range<number>)`,P(`An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated.`))],compute:function(e){let t=Vo(e,`square_matrix`);if(!dS(t))return new I(P(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=mS(t);return n||new I(P(`The matrix is not invertible.`))},isExported:!0},rq={description:P(`Calculates the matrix product of two matrices.`),args:[U(`matrix1 (number, range<number>)`,P(`The first matrix in the matrix multiplication operation.`)),U(`matrix2 (number, range<number>)`,P(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=Vo(e,`matrix1`),r=Vo(t,`matrix2`);return n.length===0||r.length===0?new I(P(`The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.`)):n.length===r[0].length?gS(n,r):new I(P(`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},iq={description:P(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[U(`range (number, range<number>, repeating)`,P(`The range whose entries will be multiplied with corresponding entries in the other range.`))],compute:function(...e){if(!uS(...e))return new I(P(`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*=L(n[e][r],this.locale);n+=i}return n},isExported:!0};function aq(e,t,n){if(!uS(e,t))return new I(P(`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 I(P(`The arguments array_x and array_y must contain at least one pair of numbers.`))}let oq={description:P(`Calculates the sum of the difference of the squares of the values in two array.`),args:[U(`array_x (number, range<number>)`,P(`The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.`)),U(`array_y (number, range<number>)`,P(`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 aq(e,t,(e,t)=>e**2-t**2)},isExported:!0},sq={description:P(`Calculates the sum of the sum of the squares of the values in two array.`),args:[U(`array_x (number, range<number>)`,P(`The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.`)),U(`array_y (number, range<number>)`,P(`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 aq(e,t,(e,t)=>e**2+t**2)},isExported:!0},cq={description:P(`Calculates the sum of squares of the differences of values in two array.`),args:[U(`array_x (number, range<number>)`,P(`The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.`)),U(`array_y (number, range<number>)`,P(`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 aq(e,t,(e,t)=>(e-t)**2)},isExported:!0},lq=[U(`array (any, range<any>)`,P(`The array which will be transformed.`)),U(`ignore (number, default=0)`,P(`Whether to ignore certain types of values. By default, no values are ignored.`),[{value:0,label:P(`Keep all values (default)`)},{value:1,label:P(`Ignore blanks`)},{value:2,label:P(`Ignore errors`)},{value:3,label:P(`Ignore blanks and errors`)}]),U(`scan_by_column (number, default=false)`,P(`Scan the array by column. By default, the array is scanned by row.`),[{value:!1,label:P(`Scan by row (default)`)},{value:!0,label:P(`Scan by column`)}])];function uq(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!Po(e.value);if(t===3)return e=>e.value!==null&&!Po(e.value);throw new I(P(`Argument ignore must be between 0 and 3`))}let dq={description:P(`Transforms a range of cells into a single column.`),args:lq,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=L(t.value,this.locale),a=(z(n.value)?r:os(r)).flat().filter(uq(i));return a.length===0?new Do(P(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},fq={description:P(`Transforms a range of cells into a single row.`),args:lq,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=L(t.value,this.locale),a=(z(n.value)?r:os(r)).flat().filter(uq(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Do(P(`No results for the given arguments of TOROW.`)):a},isExported:!0},pq={description:P(`Transposes the rows and columns of a range.`),args:[U(`range (any, range<any>)`,P(`The range to be transposed.`))],compute:function(e){let t=B(e),n=t[0].length,r=t.length;return rs(n,r,(e,n)=>t[n][e])},isExported:!0},mq={description:P(`Appends ranges vertically and in sequence to return a larger array.`),args:[U(`range (any, range<any>, repeating)`,P(`The range to be appended.`))],compute:function(...e){return GK(e)},isExported:!0},hq={description:P(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[U(`range (any, range<any>)`,P(`The range to wrap.`)),U(`wrap_count (number)`,P(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),U(`pad_with (any, default=0)`,P(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Uo(t?.value,this.locale);if(!lS(r))return new I(P(`Argument range must be a single row or column.`));if(i<1)return new I(P(`The wrap_count (%s) must be strictly positive.`,i),F.InvalidNumber);let a=r.flat();return rs(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},gq={description:P(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[U(`range (any, range<any>)`,P(`The range to wrap.`)),U(`wrap_count (number)`,P(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),U(`pad_with (any, default=0)`,P(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Uo(t?.value,this.locale);if(!lS(r))return new I(P(`Argument range must be a single row or column.`));if(i<1)return new I(P(`The wrap_count (%s) must be strictly positive.`,i),F.InvalidNumber);let a=r.flat();return rs(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0},_q=[{value:0,label:P(`Concise format\xA0(default)`)},{value:1,label:P(`Strict format`)}],vq={description:P(`returns an array of text values from any specified range. It passes text values unchanged, and converts non-text values to text.`),args:[U(`array (range)`,P(`The array to convert into text`)),U(`format (number, default=0)`,P(`The format of the returned data.`),_q)],compute:function(e,t={value:0}){let n=L(t,this.locale),r=B(e);if(n===1)return $k(r,``,this.locale);if(n===0){let e=this.locale.decimalSeparator===`,`?`/`:`,`;return os(r).flatMap(e=>e.map(e=>Po(e.value)?e.value:R(e))).join(e)}else return new I(P(`Format must be 0 or 1`))},isExported:!0};var yq=l({ABS:()=>xq,ACOS:()=>Sq,ACOSH:()=>Cq,ACOT:()=>wq,ACOTH:()=>Tq,ASIN:()=>Eq,ASINH:()=>Dq,ATAN:()=>Oq,ATAN2:()=>kq,ATANH:()=>Aq,CEILING:()=>jq,CEILING_MATH:()=>Nq,CEILING_PRECISE:()=>Pq,COS:()=>Fq,COSH:()=>Iq,COT:()=>Lq,COTH:()=>Rq,COUNTBLANK:()=>zq,COUNTIF:()=>Bq,COUNTIFS:()=>Vq,COUNTUNIQUE:()=>Hq,COUNTUNIQUEIFS:()=>Uq,CSC:()=>Wq,CSCH:()=>Gq,DECIMAL:()=>Kq,DEGREES:()=>qq,EXP:()=>Jq,FLOOR:()=>Yq,FLOOR_MATH:()=>Zq,FLOOR_PRECISE:()=>Qq,INT:()=>PJ,ISEVEN:()=>$q,ISODD:()=>tJ,ISO_CEILING:()=>eJ,LN:()=>nJ,LOG:()=>rJ,MOD:()=>aJ,MUNIT:()=>oJ,ODD:()=>sJ,PI:()=>cJ,POWER:()=>lJ,PRODUCT:()=>uJ,RAND:()=>dJ,RANDARRAY:()=>fJ,RANDBETWEEN:()=>pJ,ROUND:()=>mJ,ROUNDDOWN:()=>hJ,ROUNDUP:()=>gJ,SEC:()=>_J,SECH:()=>vJ,SEQUENCE:()=>yJ,SIN:()=>bJ,SINH:()=>xJ,SQRT:()=>SJ,SUBTOTAL:()=>EJ,SUM:()=>DJ,SUMIF:()=>OJ,SUMIFS:()=>kJ,TAN:()=>AJ,TANH:()=>jJ,TRUNC:()=>NJ});let bq=/^-?[a-z0-9]+$/i,xq={description:P(`Absolute value of a number.`),args:[U(`value (number)`,P(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(L(e,this.locale))},isExported:!0},Sq={description:P(`Inverse cosine of a value, in radians.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=L(e,this.locale);return Math.abs(t)>1?new I(P(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.acos(t)},isExported:!0},Cq={description:P(`Inverse hyperbolic cosine of a number.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.`))],compute:function(e){let t=L(e,this.locale);return t<1?new I(P(`The value (%s) must be greater than or equal to 1.`,t)):Math.acosh(t)},isExported:!0},wq={description:P(`Inverse cotangent of a value.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=L(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Tq={description:P(`Inverse hyperbolic cotangent of a value.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.`))],compute:function(e){let t=L(e,this.locale);return Math.abs(t)<=1?new I(P(`The value (%s) cannot be between -1 and 1 inclusive.`,t)):Math.log((t+1)/(t-1))/2},isExported:!0},Eq={description:P(`Inverse sine of a value, in radians.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=L(e,this.locale);return Math.abs(t)>1?new I(P(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.asin(t)},isExported:!0},Dq={description:P(`Inverse hyperbolic sine of a number.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(L(e,this.locale))},isExported:!0},Oq={description:P(`Inverse tangent of a value, in radians.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(L(e,this.locale))},isExported:!0},kq={description:P(`Angle from the X axis to a point (x,y), in radians.`),args:[U(`x (number)`,P(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),U(`y (number)`,P(`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=L(e,this.locale),r=L(t,this.locale);return n===0&&r===0?new Ao(P(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},Aq={description:P(`Inverse hyperbolic tangent of a number.`),args:[U(`value (number)`,P(`The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.`))],compute:function(e){let t=L(e,this.locale);return Math.abs(t)>=1?new I(P(`The value (%s) must be between -1 and 1 exclusive.`,t)):Math.atanh(t)},isExported:!0},jq={description:P(`Rounds number up to nearest multiple of factor.`),args:[U(`value (number)`,P(`The value to round up to the nearest integer multiple of factor.`)),U(`factor (number, default=1)`,P(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=L(e,this.locale),r=L(t,this.locale);return r<0&&n>0?new I(P(`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 Mq(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 Nq={description:P(`Rounds number up to nearest multiple of factor.`),args:[U(`number (number)`,P(`The value to round up to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,P(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),U(`mode (number, default=0)`,P(`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=L(t,this.locale);return{value:Mq(L(e,this.locale),r,L(n,this.locale)),format:e?.format}},isExported:!0},Pq={description:P(`Rounds number up to nearest multiple of factor.`),args:[U(`number (number)`,P(`The value to round up to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,P(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=L(t,this.locale);return{value:Mq(L(e,this.locale),n),format:e?.format}},isExported:!0},Fq={description:P(`Cosine of an angle provided in radians.`),args:[U(`angle (number)`,P(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(L(e,this.locale))},isExported:!0},Iq={description:P(`Hyperbolic cosine of any real number.`),args:[U(`value (number)`,P(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(L(e,this.locale))},isExported:!0},Lq={description:P(`Cotangent of an angle provided in radians.`),args:[U(`angle (number)`,P(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=L(e,this.locale);return t===0?new Ao(P(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},Rq={description:P(`Hyperbolic cotangent of any real number.`),args:[U(`value (number)`,P(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=L(e,this.locale);return t===0?new Ao(P(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},zq={description:P(`Number of empty values.`),args:[U(`value (any, range, repeating)`,P(`Value or range in which to count the number of blanks.`))],compute:function(...e){return es(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},Bq={description:P(`A conditional count across a range.`),args:[U(`range (range)`,P(`The range that is tested against criterion.`)),U(`criterion (string)`,P(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return fs(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},Vq={description:P(`Count values depending on multiple criteria.`),args:[U(`criteria_range (any, range, repeating)`,P(`Range over which to evaluate criteria.`)),U(`criterion (string, repeating)`,P(`Criteria to check.`))],compute:function(...e){let t=0;return fs(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},Hq={description:P(`Counts number of unique values in a range.`),args:[U(`value (any, range, repeating)`,P(`Value or range to consider for uniqueness.`))],compute:function(...e){return oS(e)}},Uq={description:P(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[U(`range (range)`,P(`The range of cells from which the number of unique values will be counted.`)),U(`criteria_range (any, range, repeating)`,P(`Range over which to evaluate criteria.`)),U(`criterion (string, repeating)`,P(`Criteria to check.`))],compute:function(e,...t){let n=new Set;return fs(t,(t,r)=>{let i=e[t]?.[r];ys(i)&&n.add(i.value)},this.locale),n.size}},Wq={description:P(`Cosecant of an angle provided in radians.`),args:[U(`angle (number)`,P(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=L(e,this.locale);return t===0?new Ao(P(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},Gq={description:P(`Hyperbolic cosecant of any real number.`),args:[U(`value (number)`,P(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=L(e,this.locale);return t===0?new Ao(P(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},Kq={description:P(`Converts from another base to decimal.`),args:[U(`value (string)`,P(`The number to convert.`)),U(`base (number)`,P(`The base to convert the value from.`))],compute:function(e,t){let n=L(t,this.locale);if(n=Math.floor(n),2>n||n>36)return new I(P(`The base (%s) must be between 2 and 36 inclusive.`,n));let r=R(e);if(r===``)return 0;if(!bq.test(r))return new I(P(`The value (%s) must be a valid base %s representation.`,r,n));let i=r.replace(`-`,``);for(let e of i)if(parseInt(e,36)>=n)return new I(P(`The value (%s) must be a valid base %s representation.`,r,n));let a=parseInt(r,n);return isNaN(a)?new I(P(`The value (%s) must be a valid base %s representation.`,r,n)):a},isExported:!0},qq={description:P(`Converts an angle value in radians to degrees.`),args:[U(`angle (number)`,P(`The angle to convert from radians to degrees.`))],compute:function(e){return L(e,this.locale)*180/Math.PI},isExported:!0},Jq={description:P(`Euler's number, e (~2.718) raised to a power.`),args:[U(`value (number)`,P(`The exponent to raise e.`))],compute:function(e){return Math.exp(L(e,this.locale))},isExported:!0},Yq={description:P(`Rounds number down to nearest multiple of factor.`),args:[U(`value (number)`,P(`The value to round down to the nearest integer multiple of factor.`)),U(`factor (number, default=1)`,P(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=L(e,this.locale),r=L(t,this.locale);return r<0&&n>0?new I(P(`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 Xq(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 Zq={description:P(`Rounds number down to nearest multiple of factor.`),args:[U(`number (number)`,P(`The value to round down to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,P(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),U(`mode (number, default=0)`,P(`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=L(t,this.locale);return{value:Xq(L(e,this.locale),r,L(n,this.locale)),format:e?.format}},isExported:!0},Qq={description:P(`Rounds number down to nearest multiple of factor.`),args:[U(`number (number)`,P(`The value to round down to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,P(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=L(t,this.locale);return{value:Xq(L(e,this.locale),n),format:e?.format}},isExported:!0},$q={description:P(`Whether the provided value is even.`),args:[U(`value (number)`,P(`The value to be verified as even.`))],compute:function(e){let t=Ho(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},eJ={description:P(`Rounds number up to nearest multiple of factor.`),args:[U(`number (number)`,P(`The value to round up to the nearest integer multiple of significance.`)),U(`significance (number, default=1)`,P(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:Mq(L(e,this.locale),L(t,this.locale)),format:e?.format}},isExported:!0},tJ={description:P(`Whether the provided value is even.`),args:[U(`value (number)`,P(`The value to be verified as even.`))],compute:function(e){let t=Ho(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},nJ={description:P(`The logarithm of a number, base e (euler's number).`),args:[U(`value (number)`,P(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=L(e,this.locale);return t<=0?new I(P(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},rJ={description:P(`The logarithm of a number, for a given base.`),args:[U(`value (number)`,P(`The value for which to calculate the logarithm.`)),U(`base (number, default=10)`,P(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=L(e,this.locale),r=L(t,this.locale);return n<=0?new I(P(`The value (%s) must be strictly positive.`,n)):r<=0?new I(P(`The base (%s) must be strictly positive.`,r)):r===1?new I(P(`The base must be different from 1.`)):Math.log10(n)/Math.log10(r)},isExported:!0};function iJ(e,t){cS(t,P(`The divisor must be different from 0.`));let n=e%t;return n>0&&t<0||n<0&&t>0?n+t:n}let aJ={description:P(`Modulo (remainder) operator.`),args:[U(`dividend (number)`,P(`The number to be divided to find the remainder.`)),U(`divisor (number)`,P(`The number to divide by.`))],compute:function(e,t){let n=L(t,this.locale);return{value:iJ(L(e,this.locale),n),format:e?.format}},isExported:!0},oJ={description:P(`Returns a n x n unit matrix, where n is the input dimension.`),args:[U(`dimension (number)`,P(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=Uo(e,this.locale);return t<1?new I(P(`The argument dimension must be positive`)):pS(t)},isExported:!0},sJ={description:P(`Rounds a number up to the nearest odd integer.`),args:[U(`value (number)`,P(`The value to round to the next greatest odd number.`))],compute:function(e){let t=L(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},cJ={description:P(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},lJ={description:P(`A number raised to a power.`),args:[U(`base (number)`,P(`The number to raise to the exponent power.`)),U(`exponent (number)`,P(`The exponent to raise base to.`))],compute:function(e,t){let n=L(e,this.locale),r=L(t,this.locale);return n<0&&!Number.isInteger(r)?new I(P(`The exponent (%s) must be an integer when the base is negative.`,r)):{value:n**+r,format:e?.format}},isExported:!0},uJ={description:P(`Result of multiplying a series of numbers together.`),args:[U(`factor (number, range<number>, repeating)`,P(`Number or range to calculate for the product.`))],compute:function(...e){let t=0,n=1;for(let r of e)if(ht(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),Po(e))return r}else r!==void 0&&r.value!==null&&(n*=Ho(r,this.locale),t+=1);return{value:t===0?0:n,format:No(e[0])}},isExported:!0},dJ={description:P(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},fJ={description:P(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[U(`rows (number, default=1)`,P(`The number of rows to be returned.`)),U(`columns (number, default=1)`,P(`The number of columns to be returned.`)),U(`min (number, default=0)`,P(`The minimum number you would like returned.`)),U(`max (number, default=1)`,P(`The maximum number you would like returned.`)),U(`whole_number (boolean, default=FALSE)`,P(`Return a whole number or a decimal value.`),[{value:!1,label:P(`Decimal (default)`)},{value:!0,label:P(`Integer`)}])],compute:function(e={value:1},t={value:1},n={value:0},r={value:1},i={value:!1}){let a=Uo(t,this.locale),o=Uo(e,this.locale),s=L(n,this.locale),c=L(r,this.locale),l=z(i);if(a<1)return new I(P(`The number of columns (%s) must be positive.`,a));if(o<1)return new I(P(`The number of rows (%s) must be positive.`,o));if(s>c)return new I(P(`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 I(P(`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},pJ={description:P(`Random integer between two values, inclusive.`),args:[U(`low (number)`,P(`The low end of the random range.`)),U(`high (number)`,P(`The high end of the random range.`))],compute:function(e,t){let n=L(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=L(t,this.locale);return Number.isInteger(r)||(r=Math.floor(r)),n>r?new I(P(`The high (%s) must be greater than or equal to the low (%s).`,r,n)):{value:n+Math.floor((r-n+1)*Math.random()),format:e?.format}},isExported:!0},mJ={description:P(`Rounds a number according to standard rules.`),args:[U(`value (number)`,P(`The value to round to places number of places.`)),U(`places (number, default=0)`,P(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=L(e,this.locale),r=L(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},hJ={description:P(`Rounds down a number.`),args:[U(`value (number)`,P(`The value to round to places number of places, always rounding down.`)),U(`places (number, default=0)`,P(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=L(e,this.locale),r=L(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},gJ={description:P(`Rounds up a number.`),args:[U(`value (number)`,P(`The value to round to places number of places, always rounding up.`)),U(`places (number, default=0)`,P(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=L(e,this.locale),r=L(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},_J={description:P(`Secant of an angle provided in radians.`),args:[U(`angle (number)`,P(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(L(e,this.locale))},isExported:!0},vJ={description:P(`Hyperbolic secant of any real number.`),args:[U(`value (number)`,P(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(L(e,this.locale))},isExported:!0},yJ={description:P(`Returns a sequence of numbers.`),args:[U(`rows (number)`,P(`The number of rows to return`)),U(`columns (number, optional, default=1)`,P(`The number of columns to return`)),U(`start (number, optional, default=1)`,P(`The first number in the sequence`)),U(`step (number, optional, default=1)`,P(`The amount to increment each value in the sequence`))],compute:function(e,t={value:1},n={value:1},r={value:1}){let i=L(n,this.locale),a=L(r,this.locale),o=Uo(e,this.locale),s=Uo(t,this.locale);return s<1?new I(P(`The number of columns (%s) must be positive.`,s)):o<1?new I(P(`The number of rows (%s) must be positive.`,o)):rs(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},bJ={description:P(`Sine of an angle provided in radians.`),args:[U(`angle (number)`,P(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(L(e,this.locale))},isExported:!0},xJ={description:P(`Hyperbolic sine of any real number.`),args:[U(`value (number)`,P(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(L(e,this.locale))},isExported:!0},SJ={description:P(`Positive square root of a positive number.`),args:[U(`value (number)`,P(`The number for which to calculate the positive square root.`))],compute:function(e){let t=L(e,this.locale);return t<0?new I(P(`The value (%s) must be positive or null.`,t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},CJ={1:`AVERAGE`,2:`COUNT`,3:`COUNTA`,4:`MAX`,5:`MIN`,6:`PRODUCT`,7:`STDEV`,8:`STDEVP`,9:`SUM`,10:`VAR`,11:`VARP`},wJ=Object.entries(CJ).map(([e,t])=>({value:parseInt(e),label:P(`%s (include manually-hidden rows)`,t)})),TJ=Object.entries(CJ).map(([e,t])=>({value:parseInt(e)+100,label:P(`%s (exclude manually-hidden rows)`,t)})),EJ={description:P(`Returns a subtotal for a vertical range of cells using a specified aggregation function.`),args:[U(`function_code (number)`,P(`The function to use in subtotal aggregation.`),[...wJ,...TJ]),U(`ref (any, range<any>, repeating)`,P(`Range or reference for which you want the subtotal.`))],compute:function(e,...t){let n=Uo(e,this.locale),r=!0;if(n>100&&(n-=100,r=!1),n<1||n>11)return new I(P(`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 Eo(Lo);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||!bn(n,`SUBTOTAL`))&&i.push(this.getFormulaResult({sheetId:s,col:t,row:e}))}}return this[CJ[n]].apply(this,[[i]])},isExported:!0},DJ={description:P(`Sum of a series of numbers and/or cells.`),args:[U(`value (number, range<number>, repeating)`,P(`Number or range to add together.`))],compute:function(...e){let t=e[0];return{value:aS(e,this.locale),format:No(t)}},isExported:!0},OJ={description:P(`A conditional sum across a range.`),args:[U(`criteria_range (range)`,P(`The range which is tested against criterion.`)),U(`criterion (string)`,P(`The pattern or test to apply to range.`)),U(`sum_range (range, default=criteria_range)`,P(`The range to be summed, if different from range.`))],compute:function(e,t,n){n===void 0&&(n=e);let r=0;return fs([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},kJ={description:P(`Sums a range depending on multiple criteria.`),args:[U(`sum_range (range)`,P(`The range to sum.`)),U(`criteria_range (any, range, repeating)`,P(`Range to check.`)),U(`criterion (string, repeating)`,P(`Criteria to check.`))],compute:function(e,...t){let n=0;return fs(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},AJ={description:P(`Tangent of an angle provided in radians.`),args:[U(`angle (number)`,P(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(L(e,this.locale))},isExported:!0},jJ={description:P(`Hyperbolic tangent of any real number.`),args:[U(`value (number)`,P(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(L(e,this.locale))},isExported:!0};function MJ(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let NJ={description:P(`Truncates a number.`),args:[U(`value (number)`,P(`The value to be truncated.`)),U(`places (number, default=0)`,P(`The number of significant digits to the right of the decimal point to retain.`))],compute:function(e,t={value:0}){return{value:MJ(L(e,this.locale),L(t,this.locale)),format:e?.format}},isExported:!0},PJ={description:P(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[U(`value (number)`,P(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(L(e,this.locale))},isExported:!0};var FJ=l({AVEDEV:()=>GJ,AVERAGE:()=>KJ,AVERAGEA:()=>XJ,AVERAGEIF:()=>ZJ,AVERAGEIFS:()=>QJ,AVERAGE_WEIGHTED:()=>YJ,CORREL:()=>bY,COUNT:()=>$J,COUNTA:()=>eY,COVAR:()=>tY,COVARIANCE_P:()=>nY,COVARIANCE_S:()=>rY,FORECAST:()=>iY,GROWTH:()=>aY,INTERCEPT:()=>oY,LARGE:()=>sY,LINEST:()=>cY,LOGEST:()=>lY,MATTHEWS:()=>uY,MAX:()=>dY,MAXA:()=>fY,MAXIFS:()=>pY,MEDIAN:()=>mY,MIN:()=>hY,MINA:()=>gY,MINIFS:()=>_Y,PEARSON:()=>yY,PERCENTILE:()=>xY,PERCENTILE_EXC:()=>SY,PERCENTILE_INC:()=>CY,POLYFIT_COEFFS:()=>wY,POLYFIT_FORECAST:()=>TY,QUARTILE:()=>EY,QUARTILE_EXC:()=>DY,QUARTILE_INC:()=>OY,RANK:()=>kY,RSQ:()=>AY,SLOPE:()=>jY,SMALL:()=>MY,SPEARMAN:()=>NY,STDEV:()=>PY,STDEVA:()=>LY,STDEVP:()=>RY,STDEVPA:()=>zY,STDEV_P:()=>FY,STDEV_S:()=>IY,STEYX:()=>BY,TREND:()=>VY,VAR:()=>HY,VARA:()=>GY,VARP:()=>KY,VARPA:()=>qY,VAR_P:()=>UY,VAR_S:()=>WY});let IJ=[{value:!0,label:P(`b is calculated normally`)},{value:!1,label:P(`b is forced to 1`)}],LJ=[{value:!1,label:P(`do not return additional regression statistics`)},{value:!0,label:P(`return additional regression statistics`)}],RJ=[{value:1,label:P(`order 1 (Linear)`)},{value:2,label:P(`order 2 (Quadratic)`)},{value:3,label:P(`order 3 (Cubic)`)},{value:4,label:P(`order 4 (Quartic)`)},{value:5,label:P(`order 5 (Quintic)`)},{value:6,label:P(`order 6 (Sextic)`)}],zJ=[{value:!0,label:P(`Compute intercept`)},{value:!1,label:P(`Force intercept to 0`)}],BJ=[{value:0,label:P(`Minimum value`)},{value:1,label:P(`First quartile (25th percentile)`)},{value:2,label:P(`Median value (50th percentile)`)},{value:3,label:P(`Third quartile (75th percentile)`)},{value:4,label:P(`Maximum value`)}];function VJ(e,t){let n=[],r=[],i=0,a=0;Zo([e],e=>{n.push(e),i+=1}),Zo([t],e=>{r.push(e),a+=1}),sS(i===a,P(`[[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 HJ(e,t,n){let{flatDataX:r,flatDataY:i}=VJ(e,t),a=i.length;cS(a),n&&cS(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 UJ(e,t,n,r){let i=0,a=n?ns:ts,o=a(e,(e,t)=>(i+=1,e+t),0,r);cS(i),t&&cS(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function WJ(e,t,n,r){let i=L(t,r);sS(n?0<=i&&i<=1:0<i&&i<1,P(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`));let a=[],o,s=0;return Zo(e,e=>{let t=e?.value;typeof t==`number`&&(o=ps(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),sS(s!==0,bs),n||sS(1/(s+1)<=i&&i<=s/(s+1),P(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),mo(a,i,n)}let GJ={description:P(`Average magnitude of deviations from mean.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the sample.`))],compute:function(...e){let t=0,n=ts(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new Ao(P(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return ts(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},KJ={description:P(`Numerical average value in a dataset, ignoring text.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to consider when calculating the average value.`))],compute:function(...e){return{value:xS(e,this.locale),format:No(e[0])}},isExported:!0},qJ=P(`[[FUNCTION_NAME]] has mismatched range sizes.`),JJ=P(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),YJ={description:P(`Weighted average.`),args:[U(`values (number, range<number>, repeating)`,P(`Value to average.`)),U(`weights (number, range<number>, repeating)`,P(`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(!uS(i,a))return new I(qJ);if(ht(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=ht(a)?a?.[e][r].value:L(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new I(JJ);t+=o*s,n+=s;continue}if(c!==l)return new I(P(`[[FUNCTION_NAME]] expects number values.`))}else{let e=L(i,this.locale),r=ht(a)?a?.[0][0].value:L(a,this.locale);if(typeof r==`number`){if(r<0)return new I(JJ);t+=e*r,n+=r}}}return n===0?new Ao(P(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:No(e[0])}}},XJ={description:P(`Numerical average value in a dataset.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to consider when calculating the average value.`))],compute:function(...e){let t=0,n=ns(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new Ao(P(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:No(e[0])}},isExported:!0},ZJ={description:P(`Average of values depending on criteria.`),args:[U(`criteria_range (number, range<number>)`,P(`The range to check against criterion.`)),U(`criterion (string)`,P(`The pattern or test to apply to criteria_range.`)),U(`average_range (number, range<number>, default=criteria_range)`,P(`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 fs([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new Ao(P(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},QJ={description:P(`Average of values depending on multiple criteria.`),args:[U(`average_range (range)`,P(`The range to average.`)),U(`criteria_range (any, range, repeating)`,P(`Range to check.`)),U(`criterion (string, repeating)`,P(`Criterion to check.`))],compute:function(e,...t){let n=B(e),r=0,i=0;return fs(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new Ao(P(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},$J={description:P(`The number of numeric values in dataset.`),args:[U(`value (number, any, range<number>, repeating)`,P(`Value or range to consider when counting.`))],compute:function(...e){return CS(e,this.locale)},isExported:!0},eY={description:P(`The number of values in a dataset.`),args:[U(`value (any, range, repeating)`,P(`Value or range to consider when counting.`))],compute:function(...e){return wS(e)},isExported:!0},tY={description:P(`The covariance of a dataset.`),args:[U(`data_y (any, range)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (any, range)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return HJ(e,t,!1)},isExported:!0},nY={description:P(`The covariance of a dataset.`),args:[U(`data_y (any, range)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (any, range)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return HJ(e,t,!1)},isExported:!0},rY={description:P(`The sample covariance of a dataset.`),args:[U(`data_y (any, range)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (any, range)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return HJ(e,t,!0)},isExported:!0},iY={description:P(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[U(`x (number, range<number>)`,P(`The value(s) on the x-axis to forecast.`)),U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t,n){let{flatDataX:r,flatDataY:i}=VJ(t,n);return r.length===0||i.length===0?new Do(bs):PS([i],[r],is(B(e),e=>L(e,this.locale)),!0)},isExported:!0},aY={description:P(`Fits points to exponential growth trend.`),args:[U(`known_data_y (range<number>)`,P(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.`)),U(`known_data_x (range<number>, default={1;2;3;...})`,P(`The values of the independent variable(s) corresponding with known_data_y.`)),U(`new_data_x (any, range, default=known_data_x)`,P(`The data points to return the y values for on the ideal curve fit.`)),U(`b (boolean, default=TRUE)`,P(`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.`),IJ)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new I(xs(`known_data_y`)):MS(PS(NS(Vo(e,`known_data_y`)),Vo(t,`known_data_x`),Vo(n,`new_data_y`),z(r)))}},oY={description:P(`Compute the intercept of the linear regression.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=VJ(e,t);if(n.length===0||r.length===0)return new Do(bs);let[[],[i]]=OS([n],[r]);return i},isExported:!0},sY={description:P(`Nth largest element from a data set.`),args:[U(`data (any, range)`,P(`Array or range containing the dataset to consider.`)),U(`n (number)`,P(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(L(t?.value,this.locale)),r=[],i,a=0;Zo([e],e=>{typeof e?.value==`number`&&(i=ps(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 I(bs):a<n?new I(P(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},cY={description:P(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>, default={1;2;3;...})`,P(`The range representing the array or matrix of independent data.`)),U(`calculate_b (boolean, default=TRUE)`,P(`A flag specifying whether to compute the slope or not`),IJ),U(`verbose (boolean, default=FALSE)`,P(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),LJ)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new I(xs(`data_y`)):OS(Vo(t,`data_x`),Vo(e,`data_y`),z(n),z(r))},isExported:!0},lY={description:P(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>, optional, default={1;2;3;...})`,P(`The range representing the array or matrix of independent data.`)),U(`calculate_b (boolean, default=TRUE)`,P(`A flag specifying whether to compute the slope or not`),IJ),U(`verbose (boolean, default=FALSE)`,P(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),LJ)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new I(xs(`data_y`));let i=OS(Vo(t,`data_x`),NS(Vo(e,`data_y`)),z(n),z(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},uY={description:P(`Compute the Matthews correlation coefficient of a dataset.`),args:[U(`data_x (range)`,P(`The range representing the array or matrix of observed data.`)),U(`data_y (range)`,P(`The range representing the array or matrix of predicted data.`))],compute:function(e,t){let n=e.flat(),r=t.flat();if(bS(n,r),n.length===0||r.length===0)return new Do(bs);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=z(n[e]);t===z(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},dY={description:P(`Maximum value in a numeric dataset.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){return TS(e,this.locale)},isExported:!0},fY={description:P(`Maximum numeric value in a dataset.`),args:[U(`value (any, range, repeating)`,P(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){let t=ns(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:No(e[0])}},isExported:!0},pY={description:P(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[U(`range (range)`,P(`The range of cells from which the maximum will be determined.`)),U(`criteria_range (any, range, repeating)`,P(`Range to evaluate criteria.`)),U(`criterion (string, repeating)`,P(`Criteria to check.`))],compute:function(e,...t){let n=-1/0;return fs(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},mY={description:P(`Median value in a numeric dataset.`),args:[U(`value (any, range, repeating)`,P(`Value or range to consider when calculating the median value.`))],compute:function(...e){let t=[];return Qo(e,e=>{t.push(e)},this.locale),{value:WJ(t,{value:.5},!0,this.locale),format:No(t[0])}},isExported:!0},hY={description:P(`Minimum value in a numeric dataset.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){return ES(e,this.locale)},isExported:!0},gY={description:P(`Minimum numeric value in a dataset.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){let t=ns(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:No(e[0])}},isExported:!0},_Y={description:P(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[U(`range (range)`,P(`The range of cells from which the minimum will be determined.`)),U(`criteria_range (any, range, repeating)`,P(`Range to evaluate criteria.`)),U(`criterion (string, repeating)`,P(`Criterion to check.`))],compute:function(e,...t){let n=1/0;return fs(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 vY(e,t){let{flatDataX:n,flatDataY:r}=VJ(e,t);if(n.length===0||r.length===0)return new Do(bs);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}let u=Math.sqrt((i*c-a*a)*(i*l-o*o));return u===0?new Ao:(i*s-a*o)/u}let yY={description:P(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return vY(e,t)},isExported:!0},bY=yY,xY={description:P(`Value at a given percentile of a dataset.`),args:[U(`data (any, range)`,P(`The array or range containing the dataset to consider.`)),U(`percentile (number)`,P(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return CY.compute.bind(this)(e,t)},isExported:!0},SY={description:P(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[U(`data (any, range)`,P(`The array or range containing the dataset to consider.`)),U(`percentile (number)`,P(`The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.`))],compute:function(e,t){return{value:WJ([e],t,!1,this.locale),format:No(e)}},isExported:!0},CY={description:P(`Value at a given percentile of a dataset.`),args:[U(`data (any, range)`,P(`The array or range containing the dataset to consider.`)),U(`percentile (number)`,P(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:WJ([e],t,!0,this.locale),format:No(e)}},isExported:!0},wY={description:P(`Compute the coefficients of polynomial regression of the dataset.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`)),U(`order (number)`,P(`The order of the polynomial to fit the data, between 1 and 6.`),RJ),U(`intercept (boolean, default=TRUE)`,P(`A flag specifying whether to compute the intercept or not.`),zJ)],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=VJ(e,t);return i.length===0||a.length===0?new Do(bs):kS(a,i,L(n,this.locale),z(r))},isExported:!1},TY={description:P(`Predict value by computing a polynomial regression of the dataset.`),args:[U(`x (number, range<number>)`,P(`The value(s) on the x-axis to forecast.`)),U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`)),U(`order (number)`,P(`The order of the polynomial to fit the data, between 1 and 6.`),RJ),U(`intercept (boolean, default=TRUE)`,P(`A flag specifying whether to compute the intercept or not.`),zJ)],compute:function(e,t,n,r,i={value:!0}){let a=L(r,this.locale),{flatDataX:o,flatDataY:s}=VJ(t,n);if(o.length===0||s.length===0)return new Do(bs);let c=kS(s,o,a,z(i)).flat();return is(B(e),e=>jS(c,L(e,this.locale),a))},isExported:!1},EY={description:P(`Value nearest to a specific quartile of a dataset.`),args:[U(`data (any, range)`,P(`The array or range containing the dataset to consider.`)),U(`quartile_number (number)`,P(`Which quartile value to return.`),BJ)],compute:function(e,t){return OY.compute.bind(this)(e,t)},isExported:!0},DY={description:P(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[U(`data (any, range)`,P(`The array or range containing the dataset to consider.`)),U(`quartile_number (number)`,P(`Which quartile value, exclusive of 0 and 4, to return.`),[{value:1,label:P(`First quartile (25th percentile)`)},{value:2,label:P(`Median value (50th percentile)`)},{value:3,label:P(`Third quartile (75th percentile)`)}])],compute:function(e,t){let n={value:.25*Math.trunc(L(t,this.locale))};return{value:WJ([e],n,!1,this.locale),format:No(e)}},isExported:!0},OY={description:P(`Value nearest to a specific quartile of a dataset.`),args:[U(`data (any, range)`,P(`The array or range containing the dataset to consider.`)),U(`quartile_number (number)`,P(`Which quartile value to return.`),BJ)],compute:function(e,t){let n={value:.25*Math.trunc(L(t,this.locale))};return{value:WJ([e],n,!0,this.locale),format:No(e)}},isExported:!0},kY={description:P(`Returns the rank of a specified value in a dataset.`),args:[U(`value (number)`,P(`The value whose rank will be determined.`)),U(`data (range)`,P(`The range containing the dataset to consider.`)),U(`is_ascending (boolean, default=FALSE)`,P(`Whether to consider the values in data in descending or ascending order.`),[{value:!1,label:P(`Descending`)},{value:!0,label:P(`Ascending`)}])],compute:function(e,t,n={value:!1}){let r=z(n),i=L(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=L(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Do(P(`Value not found in the given data.`))},isExported:!0},AY={description:P(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=vY(e,t);return typeof n==`number`?n**2:n},isExported:!0},jY={description:P(`Compute the slope of the linear regression.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=VJ(e,t);if(n.length===0||r.length===0)return new Do(bs);let[[i]]=OS([n],[r]);return i},isExported:!0},MY={description:P(`Nth smallest element in a data set.`),args:[U(`data (any, range)`,P(`The array or range containing the dataset to consider.`)),U(`n (number)`,P(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(L(t?.value,this.locale)),r=[],i,a=0;Zo([e],e=>{typeof e?.value==`number`&&(i=ps(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 I(bs):a<n?new I(P(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},NY={description:P(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=VJ(t,e);if(n.length===0||r.length===0)return new Do(bs);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},PY={description:P(`Standard deviation.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(HY.compute.bind(this)(...e))},isExported:!0},FY={description:P(`Standard deviation of entire population.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(UY.compute.bind(this)(...e))},isExported:!0},IY={description:P(`Standard deviation.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(WY.compute.bind(this)(...e))},isExported:!0},LY={description:P(`Standard deviation of sample (text as 0).`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(GY.compute.bind(this)(...e))},isExported:!0},RY={description:P(`Standard deviation of entire population.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(KY.compute.bind(this)(...e))},isExported:!0},zY={description:P(`Standard deviation of entire population (text as 0).`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(qY.compute.bind(this)(...e))},isExported:!0},BY={description:P(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[U(`data_y (range<number>)`,P(`The range representing the array or matrix of dependent data.`)),U(`data_x (range<number>)`,P(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=VJ(e,t);return n.length===0||r.length===0?new Do(bs):OS([n],[r],!0,!0)[1][2]},isExported:!0},VY={description:P(`Fits points to linear trend derived via least-squares.`),args:[U(`known_data_y (number, range<number>)`,P(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.`)),U(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,P(`The values of the independent variable(s) corresponding with known_data_y.`)),U(`new_data_x (number, range<number>, optional, default=known_data_x)`,P(`The data points to return the y values for on the ideal curve fit.`)),U(`b (boolean, optional, default=TRUE)`,P(`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.`),IJ)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new I(xs(`known_data_y`)):PS(Vo(e,`known_data_y`),Vo(t,`known_data_x`),Vo(n,`new_data_y`),z(r))}},HY={description:P(`Variance.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the sample.`))],compute:function(...e){return UJ(e,!0,!1,this.locale)},isExported:!0},UY={description:P(`Variance of entire population.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the population.`))],compute:function(...e){return UJ(e,!1,!1,this.locale)},isExported:!0},WY={description:P(`Variance.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the sample.`))],compute:function(...e){return UJ(e,!0,!1,this.locale)},isExported:!0},GY={description:P(`Variance of sample (text as 0).`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the sample.`))],compute:function(...e){return UJ(e,!0,!0,this.locale)},isExported:!0},KY={description:P(`Variance of entire population.`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the population.`))],compute:function(...e){return UJ(e,!1,!1,this.locale)},isExported:!0},qY={description:P(`Variance of entire population (text as 0).`),args:[U(`value (number, range<number>, repeating)`,P(`Value or range to include in the population.`))],compute:function(...e){return UJ(e,!1,!0,this.locale)},isExported:!0};var JY=l({DAVERAGE:()=>ZY,DCOUNT:()=>QY,DCOUNTA:()=>$Y,DGET:()=>eX,DMAX:()=>tX,DMIN:()=>nX,DPRODUCT:()=>rX,DSTDEV:()=>iX,DSTDEVP:()=>aX,DSUM:()=>oX,DVAR:()=>sX,DVARP:()=>cX});function YY(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(R(e[t][0]).toUpperCase(),t);let o=t?.value;if(typeof o!=`number`&&typeof o!=`string`)throw new I(P(`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 I(P(`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=R(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new I(P(`The field (%s) must be one of %s.`,R(t),[...i.keys()].toString()))}let c=n[0].length;if(c<2)throw new I(P(`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=R(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)fs(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 XY=[U(`database (range)`,P(`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.`)),U(`field (number, string)`,P(`Indicates which column in database contains the values to be extracted and operated on.`)),U(`criteria (range)`,P(`An array or range containing zero or more criteria to filter the database values by before operating.`))],ZY={description:P(`Average of a set of values from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return KJ.compute.bind(this)([r])},isExported:!0},QY={description:P(`Counts values from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return $J.compute.bind(this)([r])},isExported:!0},$Y={description:P(`Counts values and text from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return eY.compute.bind(this)([r])},isExported:!0},eX={description:P(`Single value from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return r.length===0?new I(P(`No match found in DGET evaluation.`)):r.length>1?new I(P(`More than one match found in DGET evaluation.`)):r[0]},isExported:!0},tX={description:P(`Maximum of values from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return dY.compute.bind(this)([r])},isExported:!0},nX={description:P(`Minimum of values from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return hY.compute.bind(this)([r])},isExported:!0},rX={description:P(`Product of values from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return uJ.compute.bind(this)([r])},isExported:!0},iX={description:P(`Standard deviation of population sample from table.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return PY.compute.bind(this)([r])},isExported:!0},aX={description:P(`Standard deviation of entire population from table.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return RY.compute.bind(this)([r])},isExported:!0},oX={description:P(`Sum of values from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return DJ.compute.bind(this)([r])},isExported:!0},sX={description:P(`Variance of population sample from table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return HY.compute.bind(this)([r])},isExported:!0},cX={description:P(`Variance of a population from a table-like range.`),args:XY,compute:function(e,t,n){let r=YY(e,t,n,this.locale);return KY.compute.bind(this)([r])},isExported:!0},lX=P(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),uX=P(`There must be both positive and negative values in cashflow_amounts.`),dX=e=>P(`The cost (%s) must be positive or null.`,e),fX=e=>P(`The cost (%s) must be strictly positive.`,e),pX=e=>P(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),mX=e=>P(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),hX=e=>P(`The depreciation factor (%s) must be strictly positive.`,e),gX=e=>P(`The discount (%s) must be different from -1.`,e),_X=e=>P(`The discount (%s) must be strictly positive.`,e),vX=e=>P(`The discount (%s) must be smaller than 1.`,e),yX=e=>P(`The effective_rate (%s) must be strictly positive.`,e),bX=e=>P(`The end_period (%s) must be positive or null.`,e),xX=(e,t)=>P(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),SX=e=>P(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),CX=(e,t)=>P(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),wX=e=>P(`The first_period (%s) must be strictly positive.`,e),TX=e=>P(`The future_value (%s) must be strictly positive.`,e),EX=e=>P(`The investment (%s) must be strictly positive.`,e),DX=e=>P(`The issue (%s) must be positive or null.`,e),OX=(e,t)=>P(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),kX=e=>P(`The last_period (%s) must be strictly positive.`,e),AX=e=>P(`The life (%s) must be strictly positive.`,e),jX=(e,t)=>P(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),MX=e=>P(`The month (%s) must be between 1 and 12 inclusive.`,e),NX=e=>P(`The nominal_rate (%s) must be strictly positive.`,e),PX=e=>P(`The number_of_periods (%s) must be different from zero.`,e),FX=e=>P(`The number_of_periods (%s) must be strictly positive.`,e),IX=e=>P(`The period must be between 1 and number_of_periods (%s)`,e),LX=(e,t)=>P(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),RX=e=>P(`The period (%s) must be positive or null.`,e),zX=e=>P(`The periods_by_year (%s) must be strictly positive.`,e),BX=(e,t)=>P(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),VX=e=>P(`The period (%s) must be strictly positive.`,e),HX=e=>P(`The present_value (%s) must be strictly positive.`,e),UX=e=>P(`The price (%s) must be strictly positive.`,e),WX=(e,t)=>P(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),GX=e=>P(`The purchase_date (%s) must be positive or null.`,e),KX=e=>P(`The rate_guess (%s) must be strictly greater than -1.`,e),qX=e=>P(`The rate (%s) must be positive or null.`,e),JX=e=>P(`The rate (%s) must be strictly positive.`,e),YX=e=>P(`The redemption (%s) must be strictly positive.`,e),XX=e=>P(`The salvage (%s) must be positive or null.`,e),ZX=(e,t)=>P(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),QX=(e,t)=>P(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),$X=(e,t)=>P(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),eZ=(e,t)=>P(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),tZ=e=>P(`The start_period (%s) must be positive or null.`,e),nZ=(e,t)=>P(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),rZ=e=>P(`The unit (%s) must be strictly positive.`,e),iZ=e=>P(`The yield (%s) must be positive or null.`,e);function aZ(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function oZ(e){return![0,1,2,3,4].includes(e)}function sZ(e){return![1,2,4].includes(e)}function cZ(e,t,n){let r=Jo(e,n),i=Jo(t,n),a=Jo(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}let lZ=[{value:0,label:P(`US (NASD) 30/360`)},{value:1,label:P(`Actual/Actual`)},{value:2,label:P(`Actual/360`)},{value:3,label:P(`Actual/365`)},{value:4,label:P(`European 30/360`)}];var uZ=l({DATE:()=>fZ,DATEDIF:()=>pZ,DATEVALUE:()=>mZ,DAY:()=>hZ,DAYS:()=>gZ,DAYS360:()=>_Z,EDATE:()=>vZ,EOMONTH:()=>yZ,HOUR:()=>bZ,ISOWEEKNUM:()=>xZ,MINUTE:()=>SZ,MONTH:()=>CZ,MONTH_END:()=>BZ,MONTH_START:()=>zZ,NETWORKDAYS:()=>wZ,NETWORKDAYS_INTL:()=>DZ,NOW:()=>OZ,QUARTER:()=>VZ,QUARTER_END:()=>UZ,QUARTER_START:()=>HZ,SECOND:()=>kZ,TIME:()=>AZ,TIMEVALUE:()=>jZ,TODAY:()=>MZ,WEEKDAY:()=>NZ,WEEKNUM:()=>PZ,WORKDAY:()=>FZ,WORKDAY_INTL:()=>IZ,YEAR:()=>LZ,YEARFRAC:()=>RZ,YEAR_END:()=>GZ,YEAR_START:()=>WZ}),dZ=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}(dZ||{});let fZ={description:P(`Converts year/month/day into a date.`),args:[U(`year (number)`,P(`The year component of the date.`)),U(`month (number)`,P(`The month component of the date.`)),U(`day (number)`,P(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(L(e,this.locale)),i=Math.trunc(L(t,this.locale)),a=Math.trunc(L(n,this.locale));if(r<0||r>9999)return new I(P(`The year (%s) must be between 0 and 9999 inclusive.`,r.toString()));r<1900&&(r+=1900);let o=Ga(new va(r,i-1,a));return o<0?new I(P(`The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.`)):{value:o,format:this.locale.dateFormat}},isExported:!0},pZ={description:P(`Calculates the number of days, months, or years between two dates.`),args:[U(`start_date (date)`,P(`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.`)),U(`end_date (date)`,P(`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.`)),U(`unit (string)`,P(`A text abbreviation for unit of time.`),[{value:`Y`,label:P(`The number of whole years between start_date and end_date`)},{value:`M`,label:P(`The number of whole months between start_date and end_date`)},{value:`D`,label:P(`The number of days between start_date and end_date`)},{value:`MD`,label:P(`The number of days between start_date and end_date after subtracting whole months`)},{value:`YM`,label:P(`The number of whole months between start_date and end_date after subtracting whole years`)},{value:`YD`,label:P(`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=R(n).toUpperCase();if(!Object.values(dZ).includes(r))return new I(zo(Object.values(dZ),R(n)));let i=Math.trunc(L(e,this.locale)),a=Math.trunc(L(t,this.locale)),o=Wa(i),s=Wa(a);if(a<i)return new I(P(`start_date (%s) should be on or before end_date (%s).`,o.toLocaleDateString(),s.toLocaleDateString()));switch(r){case`Y`:return eo(o,s);case`M`:return Qa(o,s);case`D`:return $a(o,s);case`YM`:return Qa(o,s)-eo(o,s)*12;case`MD`:let e=s.getDate()-o.getDate();return e<0&&(e=qa(new va(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case`YD`:{if(to(i,a))return $a(o,s);let e=new va(o.getFullYear(),s.getMonth(),s.getDate()),t=$a(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=$a(o,e)),t}}},isExported:!0},mZ={description:P(`Converts a date string to a date value.`),args:[U(`date_string (string)`,P(`The string representing the date.`))],compute:function(e){let t=R(e),n=Pa(t,this.locale);return n===null?new I(P(`The date_string (%s) cannot be parsed to date/time.`,t.toString())):Math.trunc(n.value)},isExported:!0},hZ={description:P(`Day of the month that a specific date falls on.`),args:[U(`date (string)`,P(`The date from which to extract the day.`))],compute:function(e){return Jo(e,this.locale).getDate()},isExported:!0},gZ={description:P(`Number of days between two dates.`),args:[U(`end_date (date)`,P(`The end of the date range.`)),U(`start_date (date)`,P(`The start of the date range.`))],compute:function(e,t){let n=Jo(e,this.locale),r=Jo(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/ba)},isExported:!0},_Z={description:P(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[U(`start_date (date)`,P(`The start date to consider in the calculation.`)),U(`end_date (date)`,P(`The end date to consider in the calculation.`)),U(`method (boolean, default=false)`,P(`An indicator of what day count method to use.`),[{value:!1,label:P(`U.S. NASD method (default)`)},{value:!0,label:P(`European method`)}])],compute:function(e,t,n={value:!1}){let r=Math.trunc(L(e,this.locale)),i=Math.trunc(L(t,this.locale)),a=Za(r,i,z(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},vZ={description:P(`Date a number of months before/after another date.`),args:[U(`start_date (date)`,P(`The date from which to calculate the result.`)),U(`months (number)`,P(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:Ga(Ya(Jo(e,this.locale),Math.trunc(L(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},yZ={description:P(`Last day of a month before or after a date.`),args:[U(`start_date (date)`,P(`The date from which to calculate the result.`)),U(`months (number)`,P(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=Jo(e,this.locale),r=Math.trunc(L(t,this.locale));return{value:Ga(new va(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},bZ={description:P(`Hour component of a specific time.`),args:[U(`time (date)`,P(`The time from which to calculate the hour component.`))],compute:function(e){return Jo(e,this.locale).getHours()},isExported:!0},xZ={description:P(`ISO week number of the year.`),args:[U(`date (date)`,P(`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=Jo(e,this.locale),n=t.getFullYear(),r=1;for(;new va(n,0,r).getDay()!==4;)r+=1;let i=new va(n,0,r-3),a=31;for(;new va(n,11,a).getDay()!==4;)--a;let o=new va(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 va(n,11,a+3+1);break;case-1:let e=1;for(;new va(n-1,0,e).getDay()!==4;)e+=1;c=new va(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/ba;return Math.floor(l/7)+1},isExported:!0},SZ={description:P(`Minute component of a specific time.`),args:[U(`time (date)`,P(`The time from which to calculate the minute component.`))],compute:function(e){return Jo(e,this.locale).getMinutes()},isExported:!0},CZ={description:P(`Month of the year a specific date falls in`),args:[U(`date (date)`,P(`The date from which to extract the month.`))],compute:function(e){return Jo(e,this.locale).getMonth()+1},isExported:!0},wZ={description:P(`Net working days between two provided days.`),args:[U(`start_date (date)`,P(`The start date of the period from which to calculate the number of net working days.`)),U(`end_date (date)`,P(`The end date of the period from which to calculate the number of net working days.`)),U(`holidays (date, range<date>, optional)`,P(`A range or array constant containing the date serial numbers to consider holidays.`))],compute:function(e,t,n){return DZ.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function TZ(e){let t=e?.value;if(typeof t==`string`){sS(t.length===7&&[...t].every(e=>e===`0`||e===`1`),P(`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 sS(1<=t&&t<=7||11<=t&&t<=17,P(`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 I(P(`The weekend must be a number or a string.`))}let EZ=[{value:1,label:P(`Saturday/Sunday are weekends`)},{value:2,label:P(`Sunday/Monday are weekends`)},{value:3,label:P(`Monday/Tuesday are weekends`)},{value:4,label:P(`Tuesday/Wednesday are weekends`)},{value:5,label:P(`Wednesday/Thursday are weekends`)},{value:6,label:P(`Thursday/Friday are weekends`)},{value:7,label:P(`Friday/Saturday are weekends`)},{value:11,label:P(`Sunday is the only weekend`)},{value:12,label:P(`Monday is the only weekend`)},{value:13,label:P(`Tuesday is the only weekend`)},{value:14,label:P(`Wednesday is the only weekend`)},{value:15,label:P(`Thursday is the only weekend`)},{value:16,label:P(`Friday is the only weekend`)},{value:17,label:P(`Saturday is the only weekend`)}],DZ={description:P(`Net working days between two dates (specifying weekends).`),args:[U(`start_date (date)`,P(`The start date of the period from which to calculate the number of net working days.`)),U(`end_date (date)`,P(`The end date of the period from which to calculate the number of net working days.`)),U(`weekend (any, default=1)`,P(`A number or string representing which days of the week are considered weekends.`),EZ),U(`holidays (date, range<date>, optional)`,P(`A range or array constant containing the dates to consider as holidays.`))],compute:function(e,t,n={value:1},r){let i=Jo(e,this.locale),a=Jo(t,this.locale),o=TZ(n),s=new Set;r!==void 0&&Zo([r],e=>{let t=Jo(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=va.fromTimestamp((c?i:a).getTime()),u=va.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},OZ={description:P(`Current date and time as a date value.`),args:[],compute:function(){let e=va.now(),t=e.getTime()-ya.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/ba)+n,format:av(this.locale)}},isExported:!0},kZ={description:P(`Minute component of a specific time.`),args:[U(`time (date)`,P(`The time from which to calculate the second component.`))],compute:function(e){return Jo(e,this.locale).getSeconds()},isExported:!0},AZ={description:P(`Converts hour/minute/second into a time.`),args:[U(`hour (number)`,P(`The hour component of the time.`)),U(`minute (number)`,P(`The minute component of the time.`)),U(`second (number)`,P(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(L(e,this.locale)),i=Math.trunc(L(t,this.locale)),a=Math.trunc(L(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 I(P(`The function [[FUNCTION_NAME]] result cannot be negative`)):{value:r/24+i/1440+a/(1440*60),format:this.locale.timeFormat}},isExported:!0},jZ={description:P(`Converts a time string into its serial number representation.`),args:[U(`time_string (string)`,P(`The string that holds the time representation.`))],compute:function(e){let t=R(e),n=Pa(t,this.locale);if(n===null)return new I(P(`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},MZ={description:P(`Current date as a date value.`),args:[],compute:function(){let e=va.now();return{value:Ga(new va(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},NZ={description:P(`Day of the week of the date provided (as number).`),args:[U(`date (date)`,P(`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.`)),U(`type (number, default=1)`,P(`A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.`),[{value:1,label:P(`Numbers 1 (Sunday) trough 7 (Saturday)`)},{value:2,label:P(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:3,label:P(`Numbers 0 (Monday) trough 6 (Sunday)`)},{value:11,label:P(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:12,label:P(`Numbers 1 (Tuesday) trough 7 (Monday)`)},{value:13,label:P(`Numbers 1 (Wednesday) trough 7 (Tuesday)`)},{value:14,label:P(`Numbers 1 (Thursday) trough 7 (Wednesday)`)},{value:15,label:P(`Numbers 1 (Friday) trough 7 (Thursday)`)},{value:16,label:P(`Numbers 1 (Saturday) trough 7 (Friday)`)},{value:17,label:P(`Numbers 1 (Sunday) trough 7 (Saturday)`)}])],compute:function(e,t={value:1}){let n=Jo(e,this.locale),r=Math.round(L(t,this.locale)),i=n.getDay();if(!(1<=r&&r<=3)&&!(11<=r&&r<=17))return new I(P(`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},PZ={description:P(`Week number of the year.`),args:[U(`date (date)`,P(`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.`)),U(`type (number, default=1)`,P(`A number representing the day that a week starts on. Sunday = 1.`),[{value:1,label:P(`Sunday`)},{value:2,label:P(`Monday`)},{value:11,label:P(`Monday`)},{value:12,label:P(`Tuesday`)},{value:13,label:P(`Wednesday`)},{value:14,label:P(`Thursday`)},{value:15,label:P(`Friday`)},{value:16,label:P(`Saturday`)},{value:17,label:P(`Sunday`)},{value:21,label:P(`ISO week number (Monday as first day of the week)`)}])],compute:function(e,t={value:1}){let n=Jo(e,this.locale),r=Math.round(L(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(r))return new I(P(`The type (%s) is out of range.`,r.toString()));if(r===21)return xZ.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 va(a,0,o);for(;s.getDay()!==i;)o+=1,s=new va(a,0,o);let c=(n.getTime()-s.getTime())/ba;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},FZ={description:P(`Date after a number of workdays.`),args:[U(`start_date (date)`,P(`The date from which to begin counting.`)),U(`num_days (number)`,P(`The number of working days to advance from start_date. If negative, counts backwards.`)),U(`holidays (date, range<date>, optional)`,P(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:null}){return IZ.compute.bind(this)(e,t,{value:1},n)},isExported:!0},IZ={description:P(`Date after a number of workdays (specifying weekends).`),args:[U(`start_date (date)`,P(`The date from which to begin counting.`)),U(`num_days (number)`,P(`The number of working days to advance from start_date. If negative, counts backwards.`)),U(`weekend (any, default=1)`,P(`A number or string representing which days of the week are considered weekends.`),EZ),U(`holidays (date, range<date>, optional)`,P(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:1},r){let i=Jo(e,this.locale),a=Math.trunc(L(t,this.locale));if(n.value===`1111111`)return new I(P(`The weekend must be different from '1111111'.`));let o=TZ(n),s=new Set;r!==void 0&&Zo([r],e=>{let t=Jo(e,this.locale);s.add(t.getTime())});let c=va.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-ya.getTime();return{value:Math.round(f/ba),format:this.locale.dateFormat}},isExported:!0},LZ={description:P(`Year specified by a given date.`),args:[U(`date (date)`,P(`The date from which to extract the year.`))],compute:function(e){return Jo(e,this.locale).getFullYear()},isExported:!0},RZ={description:P(`Exact number of years between two dates.`),args:[U(`start_date (date)`,P(`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.`)),U(`end_date (date)`,P(`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.`)),U(`day_count_convention (number, default=0)`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n={value:0}){let r=Math.trunc(L(e,this.locale)),i=Math.trunc(L(t,this.locale)),a=Math.trunc(L(n,this.locale));return r<0?new I(P(`The start_date (%s) must be positive or null.`,r)):i<0?new I(P(`The end_date (%s) must be positive or null.`,i)):0>a||a>4?new I(P(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,a)):Za(r,i,a)}},zZ={description:P(`First day of the month a date falls in.`),args:[U(`date (date)`,P(`The date from which to calculate the result.`))],compute:function(e){let t=Jo(e,this.locale);return{value:Ga(new va(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},BZ={description:P(`Last day of the month a date falls in.`),args:[U(`date (date)`,P(`The date from which to calculate the result.`))],compute:function(e){return yZ.compute.bind(this)(e,{value:0})}},VZ={description:P(`Quarter of the year a specific date falls in`),args:[U(`date (date)`,P(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((Jo(e,this.locale).getMonth()+1)/3)}},HZ={description:P(`First day of the quarter of the year a specific date falls in.`),args:[U(`date (date)`,P(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=VZ.compute.bind(this)(e);return{value:Ga(new va(LZ.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},UZ={description:P(`Last day of the quarter of the year a specific date falls in.`),args:[U(`date (date)`,P(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=VZ.compute.bind(this)(e);return{value:Ga(new va(LZ.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},WZ={description:P(`First day of the year a specific date falls in.`),args:[U(`date (date)`,P(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:Ga(new va(LZ.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},GZ={description:P(`Last day of the year a specific date falls in.`),args:[U(`date (date)`,P(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:Ga(new va(LZ.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var KZ=l({DELTA:()=>qZ});let qZ={description:P(`Compare two numeric values, returning 1 if they're equal.`),args:[U(`number1 (number)`,P(`The first number to compare.`)),U(`number2 (number, default=0)`,P(`The second number to compare.`))],compute:function(e,t={value:0}){return+(L(e,this.locale)===L(t,this.locale))},isExported:!0};var JZ=l({FILTER:()=>XZ,SORT:()=>ZZ,SORTN:()=>QZ,UNIQUE:()=>$Z});function YZ(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;sS(n[e]!==void 0,P(`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(z(_S(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(ht(s)&&(s.length>1||s[0].length>1))sS(s.length===1&&s[0].length===a,P(`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=L(_S(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:PV(`desc`),asc:PV(`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 XZ={description:P(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[U(`range (any, range<any>)`,P(`The data to be filtered.`)),U(`condition (boolean, range<boolean>, repeating)`,P(`Column or row containing true or false values corresponding to the range.`))],compute:function(e,...t){let n=B(e),r=t.map(e=>is(B(e),e=>e.value));for(let e of r)if(!lS(e))return new I(P(`The arguments condition must be a single column or row.`));if(!uS(...t))return new I(P(`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`?os(n):n,i.some(e=>e.length!==n.length))return new I(P(`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`?os(o):o:new Do(P(`No match found in FILTER evaluation`))},isExported:!1},ZZ={description:P(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[U(`range (range)`,P(`The data to be sorted.`)),U(`sort_column (any, range<number>, repeating, optional)`,P(`The index of the column in range or a range outside of range containing the value by which to sort.`)),U(`is_ascending (boolean, repeating, optional)`,P(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:P(`Ascending`)},{value:!1,label:P(`Descending`)}])],compute:function(e,...t){return os(YZ(os(e),this.locale,...t))},isExported:!0},QZ={description:P(`Returns the first n items in a data set after performing a sort.`),args:[U(`range (range)`,P(`The data to be sorted.`)),U(`n (number)`,P(`The number of items to return.`)),U(`display_ties_mode (number, default=0)`,P(`A number representing the way to display ties.`)),U(`sort_column (number, range<number>, repeating, optional)`,P(`The index of the column in range or a range outside of range containing the value by which to sort.`)),U(`is_ascending (boolean, repeating, optional)`,P(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:P(`Ascending`)},{value:!1,label:P(`Descending`)}])],compute:function(e,t,...n){let r=L(t?.value??1,this.locale),i=n.length%2==0?0:L(n[0]?.value,this.locale),a=n.length%2==0?n:n.slice(1);if(r<0)return new I(P(`Wrong value of 'n'. Expected a positive number. Got %s.`,r));if(i<0||i>3)return new I(P(`Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.`,i));let o=YZ(os(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 os(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return os(o.slice(0,e));return os(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 os(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 os(e)}}},isExported:!1},$Z={description:P(`Unique rows in the provided source range.`),args:[U(`range (any, range<any>)`,P(`The data to filter by unique entries.`)),U(`by_column (boolean, default=FALSE)`,P(`Whether to filter the data by columns or by rows.`),[{value:!0,label:P(`Return unique columns`)},{value:!1,label:P(`Return unique rows`)}]),U(`exactly_once (boolean, default=FALSE)`,P(`Whether to return only entries with no duplicates.`),[{value:!0,label:P(`Return items that appear exactly once`)},{value:!1,label:P(`Return every distinct item`)}])],compute:function(e={value:``},t,n){if(!ht(e))return[[e]];let r=z(t?.value)||!1,i=z(n?.value)||!1;r||(e=os(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:os(o):new I(P(`No unique values found`))},isExported:!0};var eQ=l({ACCRINTM:()=>aQ,AMORLINC:()=>oQ,COUPDAYBS:()=>cQ,COUPDAYS:()=>sQ,COUPDAYSNC:()=>lQ,COUPNCD:()=>uQ,COUPNUM:()=>dQ,COUPPCD:()=>fQ,CUMIPMT:()=>pQ,CUMPRINC:()=>mQ,DB:()=>hQ,DDB:()=>_Q,DISC:()=>vQ,DOLLARDE:()=>yQ,DOLLARFR:()=>bQ,DURATION:()=>xQ,EFFECT:()=>SQ,FV:()=>wQ,FVSCHEDULE:()=>TQ,INTRATE:()=>EQ,IPMT:()=>OQ,IRR:()=>AQ,ISPMT:()=>jQ,MDURATION:()=>MQ,MIRR:()=>NQ,NOMINAL:()=>PQ,NPER:()=>FQ,NPV:()=>LQ,PDURATION:()=>RQ,PMT:()=>BQ,PPMT:()=>HQ,PRICE:()=>WQ,PRICEDISC:()=>GQ,PRICEMAT:()=>KQ,PV:()=>UQ,RATE:()=>JQ,RECEIVED:()=>YQ,RRI:()=>XQ,SLN:()=>ZQ,SYD:()=>QQ,TBILLEQ:()=>t$,TBILLPRICE:()=>e$,TBILLYIELD:()=>n$,VDB:()=>r$,XIRR:()=>i$,XNPV:()=>a$,YIELD:()=>o$,YIELDDISC:()=>s$,YIELDMAT:()=>c$});let tQ=[{value:1,label:P(`Annual`)},{value:2,label:P(`Semi-annual`)},{value:4,label:P(`Quarterly`)}],nQ=[{value:0,label:P(`End of period (default)`)},{value:1,label:P(`Beginning of period`)}],rQ=[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`frequency (number)`,P(`The number of interest or coupon payments per year (1, 2, or 4).`),tQ),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)];function iQ(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)){sS(d<r&&a!==void 0,P(`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,sS(d<r,P(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let aQ={description:P(`Accrued interest of security paying at maturity.`),args:[U(`issue (date)`,P(`The date the security was initially issued.`)),U(`maturity (date)`,P(`The maturity date of the security.`)),U(`rate (number)`,P(`The annualized rate of interest.`)),U(`redemption (number)`,P(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(L(e,this.locale)),o=Math.trunc(L(t,this.locale)),s=L(r,this.locale),c=L(n,this.locale),l=Math.trunc(L(i,this.locale));if(a<0)return new I(DX(a));if(a>=o)return new I(jX(a,o));if(oZ(l))return new I(mX(l));if(s<=0)return new I(YX(s));if(c<=0)return new I(JX(c));let u=Za(a,o,l);return s*c*u},isExported:!0},oQ={description:P(`Depreciation for an accounting period.`),args:[U(`cost (number)`,P(`The initial cost of the asset.`)),U(`purchase_date (date)`,P(`The date the asset was purchased.`)),U(`first_period_end (date)`,P(`The date the first period ended.`)),U(`salvage (number)`,P(`The value of the asset at the end of depreciation.`)),U(`period (number)`,P(`The single period within life for which to calculate depreciation.`)),U(`rate (number)`,P(`The deprecation rate.`)),U(`day_count_convention (number, optional)`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=L(e,this.locale),c=Math.trunc(L(t,this.locale)),l=Math.trunc(L(n,this.locale)),u=L(r,this.locale),d=L(i,this.locale),f=L(a,this.locale),p=Math.trunc(L(o,this.locale));if(s<=0)return new I(fX(s));if(c<0)return new I(GX(c));if(u<0)return new I(XX(u));if(u>s)return new I(ZX(u,s));if(d<0)return new I(RX(d));if(f<=0)return new I(JX(f));if(oZ(p))return new I(mX(p));if(c>l)return new I(WX(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=Za(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},sQ={description:P(`Days in coupon period containing settlement date.`),args:rQ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(L(e,this.locale)),a=Math.trunc(L(t,this.locale)),o=Math.trunc(L(n,this.locale)),s=Math.trunc(L(r,this.locale));if(i>=a)return new I(jX(i,a));if(sZ(o))return new I(pX(o));if(oZ(s))return new I(mX(s));if(s===1){let i=fQ.compute.bind(this)(e,t,n,r).value,a=uQ.compute.bind(this)(e,t,n,r).value;return L(a,this.locale)-L(i,this.locale)}return(s===3?365:360)/o},isExported:!0},cQ={description:P(`Days from settlement until next coupon.`),args:rQ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(L(e,this.locale)),a=Math.trunc(L(t,this.locale)),o=Math.trunc(L(n,this.locale)),s=Math.trunc(L(r,this.locale));if(i>=a)return new I(jX(i,a));if(sZ(o))return new I(pX(o));if(oZ(s))return new I(mX(s));let c=fQ.compute.bind(this)(e,t,n,r).value,l=L(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=Za(l,i,s);return Math.round(e*360)}let u=Jo(i,this.locale),d=Jo(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&&Ja(d)&&Ja(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&Ja(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},lQ={description:P(`Days from settlement until next coupon.`),args:rQ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(L(e,this.locale)),a=Math.trunc(L(t,this.locale)),o=Math.trunc(L(n,this.locale)),s=Math.trunc(L(r,this.locale));if(i>=a)return new I(jX(i,a));if(sZ(o))return new I(pX(o));if(oZ(s))return new I(mX(s));let c=uQ.compute.bind(this)(e,t,n,r).value,l=L(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=Za(i,l,s);return Math.round(e*360)}let u=cQ.compute.bind(this)(e,t,n,r);return L(sQ.compute.bind(this)(e,t,n,r),this.locale)-L(u,this.locale)},isExported:!0},uQ={description:P(`Next coupon date after the settlement date.`),args:rQ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(L(e,this.locale)),a=Math.trunc(L(t,this.locale)),o=Math.trunc(L(n,this.locale)),s=Math.trunc(L(r,this.locale));if(i>=a)return new I(jX(i,a));if(sZ(o))return new I(pX(o));if(oZ(s))return new I(mX(s));let c=12/o,l=dQ.compute.bind(this)(e,t,n,r);return{value:Ga(Ya(Jo(a,this.locale),-(L(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},dQ={description:P(`Number of coupons between settlement and maturity.`),args:rQ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(L(e,this.locale)),a=Math.trunc(L(t,this.locale)),o=Math.trunc(L(n,this.locale)),s=Math.trunc(L(r,this.locale));if(i>=a)return new I(jX(i,a));if(sZ(o))return new I(pX(o));if(oZ(s))return new I(mX(s));let c=1,l=a,u=12/o;for(;l>i;)l=Ga(Ya(Jo(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},fQ={description:P(`Last coupon date prior to or on the settlement date.`),args:rQ,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(L(e,this.locale)),a=Math.trunc(L(t,this.locale)),o=Math.trunc(L(n,this.locale)),s=Math.trunc(L(r,this.locale));if(i>=a)return new I(jX(i,a));if(sZ(o))return new I(pX(o));if(oZ(s))return new I(mX(s));let c=12/o,l=dQ.compute.bind(this)(e,t,n,r);return{value:Ga(Ya(Jo(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},pQ={description:P(`Cumulative interest paid over a set of periods.`),args:[U(`rate (number)`,P(`The interest rate.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`present_value (number)`,P(`The current value of the annuity.`)),U(`first_period (number)`,P(`The number of the payment period to begin the cumulative calculation.`)),U(`last_period (number)`,P(`The number of the payment period to end the cumulative calculation.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r,i,a={value:0}){let o=L(r,this.locale),s=L(i,this.locale),c=L(e,this.locale),l=L(n,this.locale),u=L(t,this.locale),d=+!!z(a);if(u<=0)return new I(FX(u));if(o<=0)return new I(wX(o));if(s<=0)return new I(kX(s));if(o>s)return new I(CX(o,s));if(s>u)return new I(OX(s,u));if(c<=0)return new I(JX(c));if(l<=0)return new I(HX(l));let f=0;for(let e=o;e<=s;e++)f+=DQ(c,e,u,l,0,d);return f},isExported:!0},mQ={description:P(`Cumulative principal paid over a set of periods.`),args:[U(`rate (number)`,P(`The interest rate.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`present_value (number)`,P(`The current value of the annuity.`)),U(`first_period (number)`,P(`The number of the payment period to begin the cumulative calculation.`)),U(`last_period (number)`,P(`The number of the payment period to end the cumulative calculation.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r,i,a={value:0}){let o=L(r,this.locale),s=L(i,this.locale),c=L(e,this.locale),l=L(n,this.locale),u=L(t,this.locale),d=+!!z(a);if(u<=0)return new I(FX(u));if(o<=0)return new I(wX(o));if(s<=0)return new I(kX(s));if(o>s)return new I(CX(o,s));if(s>u)return new I(OX(s,u));if(c<=0)return new I(JX(c));if(l<=0)return new I(HX(l));let f=0;for(let e=o;e<=s;e++)f+=VQ(c,e,u,l,0,d);return f},isExported:!0},hQ={description:P(`Depreciation via declining balance method.`),args:[U(`cost (number)`,P(`The initial cost of the asset.`)),U(`salvage (number)`,P(`The value of the asset at the end of depreciation.`)),U(`life (number)`,P(`The number of periods over which the asset is depreciated.`)),U(`period (number)`,P(`The single period within life for which to calculate depreciation.`)),U(`month (number, optional)`,P(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=L(e,this.locale),o=L(t,this.locale),s=L(n,this.locale),c=Math.trunc(L(r,this.locale)),l=i.length?Math.trunc(L(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new I(dX(a));if(o<0)return new I(XX(o));if(c<=0)return new I(VX(c));if(s<=0)return new I(AX(s));if(1>l||l>12)return new I(MX(l));if(c>u)return new I(LX(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},gQ=`#,##0.00`,_Q={description:P(`Depreciation via double-declining balance method.`),args:[U(`cost (number)`,P(`The initial cost of the asset.`)),U(`salvage (number)`,P(`The value of the asset at the end of depreciation.`)),U(`life (number)`,P(`The number of periods over which the asset is depreciated.`)),U(`period (number)`,P(`The single period within life for which to calculate depreciation.`)),U(`factor (number, default=2)`,P(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=L(e,this.locale),o=L(t,this.locale),s=L(n,this.locale),c=L(r,this.locale),l=L(i,this.locale);if(a<0)return new I(dX(a));if(o<0)return new I(XX(o));if(c<=0)return new I(VX(c));if(s<=0)return new I(AX(s));if(c>s)return new I(BX(c,s));if(l<=0)return new I(hX(l));if(a===0||o>=a)return{value:0,format:gQ};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:gQ};if(c<=1)return{value:a*u,format:gQ};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:gQ}},isExported:!0},vQ={description:P(`Discount rate of a security based on price.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`price (number)`,P(`The price at which the security is bought per 100 face value.`)),U(`redemption (number)`,P(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(L(e,this.locale)),o=Math.trunc(L(t,this.locale)),s=L(n,this.locale),c=L(r,this.locale),l=Math.trunc(L(i,this.locale));if(a>=o)return new I(jX(a,o));if(oZ(l))return new I(mX(l));if(s<=0)return new I(UX(s));if(c<=0)return new I(YX(c));let u=Za(a,o,l);return(c-s)/c/u},isExported:!0},yQ={description:P(`Convert a decimal fraction to decimal value.`),args:[U(`fractional_price (number)`,P(`The price quotation given using fractional decimal conventions.`)),U(`unit (number)`,P(`The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=L(e,this.locale),r=Math.trunc(L(t,this.locale));if(r<=0)return new I(rZ(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},bQ={description:P(`Convert a decimal value to decimal fraction.`),args:[U(`decimal_price (number)`,P(`The price quotation given as a decimal value.`)),U(`unit (number)`,P(`The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=L(e,this.locale),r=Math.trunc(L(t,this.locale));if(r<=0)return new I(rZ(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},xQ={description:P(`Number of periods for an investment to reach a value.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,P(`The annualized rate of interest.`)),U(`yield (number)`,P(`The expected annual yield of the security.`)),U(`frequency (number)`,P(`The number of interest or coupon payments per year (1, 2, or 4).`),tQ),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(L(e,this.locale)),s=Math.trunc(L(t,this.locale)),c=L(n,this.locale),l=L(r,this.locale),u=Math.trunc(L(i,this.locale)),d=Math.trunc(L(a,this.locale));if(o>=s)return new I(jX(o,s));if(sZ(u))return new I(pX(u));if(oZ(d))return new I(mX(d));if(c<0)return new I(qX(c));if(l<0)return new I(iZ(l));let f=Za(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},SQ={description:P(`Annual effective interest rate.`),args:[U(`nominal_rate (number)`,P(`The nominal interest rate per year.`)),U(`periods_per_year (number)`,P(`The number of compounding periods per year.`))],compute:function(e,t){let n=L(e,this.locale),r=Math.trunc(L(t,this.locale));return n<=0?new I(NX(n)):r<=0?new I(zX(r)):(1+n/r)**+r-1},isExported:!0};function CQ(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 wQ={description:P(`Future value of an annuity investment.`),args:[U(`rate (number)`,P(`The interest rate.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`payment_amount (number)`,P(`The amount per period to be paid.`)),U(`present_value (number, default=0)`,P(`The current value of the annuity.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:CQ(L(e,this.locale),L(t,this.locale),L(n,this.locale),L(r,this.locale),+!!z(i)),format:`#,##0.00`}},isExported:!0},TQ={description:P(`Future value of principal from series of rates.`),args:[U(`principal (number)`,P(`The amount of initial capital or value to compound against.`)),U(`rate_schedule (number, range<number>)`,P(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=L(e,this.locale);return es([t],(e,t)=>e*(1+L(t,this.locale)),n)},isExported:!0},EQ={description:P(`Calculates effective interest rate.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`investment (number)`,P(`The amount invested in the security.`)),U(`redemption (number)`,P(`The amount to be received at maturity.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(L(e,this.locale)),o=Math.trunc(L(t,this.locale)),s=L(r,this.locale),c=L(n,this.locale),l=Math.trunc(L(i,this.locale));if(a>=o)return new I(jX(a,o));if(c<=0)return new I(EX(c));if(s<=0)return new I(YX(s));if(oZ(l))return new I(mX(l));let u=Za(a,o,l);return(s-c)/c/u},isExported:!0};function DQ(e,t,n,r,i,a){return zQ(e,n,r,i,a)-VQ(e,t,n,r,i,a)}let OQ={description:P(`Payment on the principal of an investment.`),args:[U(`rate (number)`,P(`The annualized rate of interest.`)),U(`period (number)`,P(`The amortization period, in terms of number of periods.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`present_value (number)`,P(`The current value of the annuity.`)),U(`future_value (number, default=0)`,P(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:DQ(L(e,this.locale),L(t,this.locale),L(n,this.locale),L(r,this.locale),L(i,this.locale),+!!z(a)),format:`#,##0.00`}},isExported:!0},kQ=.1,AQ={description:P(`Internal rate of return given periodic cashflows.`),args:[U(`cashflow_amounts (number, range<number>)`,P(`An array or range containing the income or payments associated with the investment.`)),U(`rate_guess (number, default=${kQ})`,P(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:kQ}){let n=L(t,this.locale);if(n<=-1)return new I(KX(n));let r=!1,i=!1,a=[];if(Qo([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new I(uX);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:iQ(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},jQ={description:P(`Returns the interest paid at a particular period of an investment.`),args:[U(`rate (number)`,P(`The interest rate.`)),U(`period (number)`,P(`The period for which you want to view the interest payment.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`present_value (number)`,P(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=L(e,this.locale),a=L(t,this.locale),o=L(n,this.locale),s=L(r,this.locale);return o===0?new I(PX(o)):-1*(s-a/o*s)*i},isExported:!0},MQ={description:P(`Modified Macaulay duration.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,P(`The annualized rate of interest.`)),U(`yield (number)`,P(`The expected annual yield of the security.`)),U(`frequency (number)`,P(`The number of interest or coupon payments per year (1, 2, or 4).`),tQ),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=xQ.compute.bind(this)(e,t,n,r,i,a),s=L(r,this.locale),c=Math.trunc(L(i,this.locale));return L(o,this.locale)/(1+s/c)},isExported:!0},NQ={description:P(`Modified internal rate of return.`),args:[U(`cashflow_amounts (range<number>)`,P(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),U(`financing_rate (number)`,P(`The interest rate paid on funds invested.`)),U(`reinvestment_return_rate (number)`,P(`The return (as a percentage) earned on reinvestment of income received from the investment.`))],compute:function(e,t,n){let r=L(t,this.locale),i=L(n,this.locale),a=os(e).flat().filter(e=>e.value!==null).map(e=>L(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 I(uX);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},PQ={description:P(`Annual nominal interest rate.`),args:[U(`effective_rate (number)`,P(`The effective interest rate per year.`)),U(`periods_per_year (number)`,P(`The number of compounding periods per year.`))],compute:function(e,t){let n=L(e,this.locale),r=Math.trunc(L(t,this.locale));return n<=0?new I(yX(n)):r<=0?new I(zX(r)):((n+1)**(1/r)-1)*r},isExported:!0},FQ={description:P(`Number of payment periods for an investment.`),args:[U(`rate (number)`,P(`The interest rate.`)),U(`payment_amount (number)`,P(`The amount of each payment made.`)),U(`present_value (number)`,P(`The current value of the annuity.`)),U(`future_value (number, default=0)`,P(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=L(e,this.locale),o=L(t,this.locale),s=L(n,this.locale),c=L(r,this.locale),l=+!!z(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 IQ(e,t,n,r){let i=0;return ts(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let LQ={description:P(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[U(`discount (number)`,P(`The discount rate of the investment over one period.`)),U(`cashflow (number, range<number>, repeating)`,P(`The future cash flows.`))],compute:function(e,...t){let n=L(e,this.locale);return n===-1?new I(gX(n)):{value:IQ(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},RQ={description:P(`Computes the number of periods needed for an investment to reach a value.`),args:[U(`rate (number)`,P(`The rate at which the investment grows each period.`)),U(`present_value (number)`,P(`The investment's current value.`)),U(`future_value (number)`,P(`The investment's desired future value.`))],compute:function(e,t,n){let r=L(e,this.locale),i=L(t,this.locale),a=L(n,this.locale);return r<=0?new I(JX(r)):i<=0?new I(HX(i)):a<=0?new I(TX(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function zQ(e,t,n,r,i){if(t<=0)throw new I(FX(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 BQ={description:P(`Periodic payment for an annuity investment.`),args:[U(`rate (number)`,P(`The annualized rate of interest.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`present_value (number)`,P(`The current value of the annuity.`)),U(`future_value (number, default=0)`,P(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r={value:0},i={value:0}){let a=L(t,this.locale),o=L(e,this.locale),s=+!!z(i),c=L(r,this.locale);return{value:zQ(o,a,L(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function VQ(e,t,n,r,i,a){if(n<=0)throw new I(FX(n));if(t<=0||t>n)throw new I(IX(n));let o=zQ(e,n,r,i,a);return a===1&&t===1?o:o+-CQ(e,a===0?t-1:t-2,o,r+o*a,0)*e}let HQ={description:P(`Payment on the principal of an investment.`),args:[U(`rate (number)`,P(`The annualized rate of interest.`)),U(`period (number)`,P(`The amortization period, in terms of number of periods.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`present_value (number)`,P(`The current value of the annuity.`)),U(`future_value (number, default=0)`,P(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=L(n,this.locale),s=L(e,this.locale),c=L(t,this.locale),l=+!!z(a),u=L(i,this.locale);return{value:VQ(s,c,o,L(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},UQ={description:P(`Present value of an annuity investment.`),args:[U(`rate (number)`,P(`The interest rate.`)),U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`payment_amount (number)`,P(`The amount per period to be paid.`)),U(`future_value (number, default=0)`,P(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=L(e,this.locale),o=L(t,this.locale),s=L(n,this.locale),c=L(r,this.locale),l=+!!z(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},WQ={description:P(`Price of a security paying periodic interest.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,P(`The annualized rate of interest.`)),U(`yield (number)`,P(`The expected annual yield of the security.`)),U(`redemption (number)`,P(`The redemption amount per 100 face value, or par.`)),U(`frequency (number)`,P(`The number of interest or coupon payments per year (1, 2, or 4).`),tQ),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(L(e,this.locale)),c=Math.trunc(L(t,this.locale)),l=L(n,this.locale),u=L(r,this.locale),d=L(i,this.locale),f=Math.trunc(L(a,this.locale)),p=Math.trunc(L(o,this.locale));if(s>=c)return new I(jX(s,c));if(sZ(f))return new I(pX(f));if(oZ(p))return new I(mX(p));if(l<0)return new I(qX(l));if(u<0)return new I(iZ(u));if(d<=0)return new I(YX(d));let m=Za(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 ee=0;for(let e=1;e<=h;e++)ee+=v/_**(e-1+g);return d/_**(h-1+g)+ee-v*(1-g)},isExported:!0},GQ={description:P(`Price of a discount security.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`discount (number)`,P(`The discount rate of the security at time of purchase.`)),U(`redemption (number)`,P(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(L(e,this.locale)),o=Math.trunc(L(t,this.locale)),s=L(n,this.locale),c=L(r,this.locale),l=Math.trunc(L(i,this.locale));if(a>=o)return new I(jX(a,o));if(oZ(l))return new I(mX(l));if(s<=0)return new I(_X(s));if(c<=0)return new I(YX(c));let u=Za(a,o,l);return c-s*c*u},isExported:!0},KQ={description:P(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`issue (date)`,P(`The date the security was initially issued.`)),U(`rate (number)`,P(`The annualized rate of interest.`)),U(`yield (number)`,P(`The expected annual yield of the security.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(L(e,this.locale)),s=Math.trunc(L(t,this.locale)),c=Math.trunc(L(n,this.locale)),l=L(r,this.locale),u=L(i,this.locale),d=Math.trunc(L(a,this.locale));if(o<=c)return new I(eZ(o,c));if(o>=s)return new I(jX(o,s));if(oZ(d))return new I(mX(d));if(l<0)return new I(qX(l));if(u<0)return new I(iZ(u));let f=Za(o,s,d),p=Za(o,c,d),m=100+Za(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},qQ=.1,JQ={description:P(`Interest rate of an annuity investment.`),args:[U(`number_of_periods (number)`,P(`The number of payments to be made.`)),U(`payment_per_period (number)`,P(`The amount per period to be paid.`)),U(`present_value (number)`,P(`The current value of the annuity.`)),U(`future_value (number, default=0)`,P(`The future value remaining after the final payment has been made.`)),U(`end_or_beginning (number, default=0)`,P(`The timing of the payment payments are due for each period.`),nQ),U(`rate_guess (number, default=${qQ})`,P(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:qQ}){let o=L(e,this.locale),s=L(t,this.locale),c=+!!z(i),l=L(a,this.locale)||qQ,u=L(r,this.locale),d=L(n,this.locale);return o<=0?new I(FX(o)):aZ([s,d,u])?l<=-1?new I(KX(l)):(u-=s*c,d+=s*c,{value:iQ(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 I(P(`There must be both positive and negative values in [payment_amount, present_value, future_value].`))},isExported:!0},YQ={description:P(`Amount received at maturity for a security.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`investment (number)`,P(`The amount invested (irrespective of face value of each security).`)),U(`discount (number)`,P(`The discount rate of the security invested in.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(L(e,this.locale)),o=Math.trunc(L(t,this.locale)),s=L(n,this.locale),c=L(r,this.locale),l=Math.trunc(L(i,this.locale));return a>=o?new I(jX(a,o)):oZ(l)?new I(mX(l)):s<=0?new I(EX(s)):c<=0?new I(_X(c)):s/(1-c*Za(a,o,l))},isExported:!0},XQ={description:P(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[U(`number_of_periods (number)`,P(`The number of periods.`)),U(`present_value (number)`,P(`The present value of the investment.`)),U(`future_value (number)`,P(`The future value of the investment.`))],compute:function(e,t,n){let r=L(e,this.locale),i=L(t,this.locale),a=L(n,this.locale);return r<=0?new I(FX(r)):(a/i)**(1/r)-1},isExported:!0},ZQ={description:P(`Depreciation of an asset using the straight-line method.`),args:[U(`cost (number)`,P(`The initial cost of the asset.`)),U(`salvage (number)`,P(`The value of the asset at the end of depreciation.`)),U(`life (number)`,P(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=L(e,this.locale),i=L(t,this.locale),a=L(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},QQ={description:P(`Depreciation via sum of years digit method.`),args:[U(`cost (number)`,P(`The initial cost of the asset.`)),U(`salvage (number)`,P(`The value of the asset at the end of depreciation.`)),U(`life (number)`,P(`The number of periods over which the asset is depreciated.`)),U(`period (number)`,P(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=L(e,this.locale),a=L(t,this.locale),o=L(n,this.locale),s=L(r,this.locale);if(s<=0)return new I(VX(s));if(o<=0)return new I(AX(o));if(s>o)return new I(BX(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function $Q(e,t,n){return 100*(1-n*Za(e,t,2))}let e$={description:P(`Price of a US Treasury bill.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`discount (number)`,P(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(L(e,this.locale)),i=Math.trunc(L(t,this.locale)),a=L(n,this.locale);return r>=i?new I(jX(r,i)):cZ(r,i,this.locale)?a<=0?new I(_X(a)):a>=1?new I(vX(a)):$Q(r,i,a):new I($X(r,i))},isExported:!0},t$={description:P(`Equivalent rate of return for a US Treasury bill.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`discount (number)`,P(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(L(e,this.locale)),i=Math.trunc(L(t,this.locale)),a=L(n,this.locale);if(r>=i)return new I(jX(r,i));if(!cZ(r,i,this.locale))return new I($X(r,i));if(a<=0)return new I(_X(a));if(a>=1)return new I(vX(a));let o=gZ.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=$Q(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},n$={description:P(`The yield of a US Treasury bill based on price.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`price (number)`,P(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(L(e,this.locale)),i=Math.trunc(L(t,this.locale)),a=L(n,this.locale);if(r>=i)return new I(jX(r,i));if(!cZ(r,i,this.locale))return new I($X(r,i));if(a<=0)return new I(UX(a));let o=Za(r,i,2);return(100-a)/a*(1/o)},isExported:!0},r$={description:P(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[U(`cost (number)`,P(`The initial cost of the asset.`)),U(`salvage (number)`,P(`The value of the asset at the end of depreciation.`)),U(`life (number)`,P(`The number of periods over which the asset is depreciated.`)),U(`start (number)`,P(`Starting period to calculate depreciation.`)),U(`end (number)`,P(`Ending period to calculate depreciation.`)),U(`factor (number, default=2)`,P(`The number of months in the first year of depreciation.`)),U(`no_switch (number, default=false)`,P(`Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.`),[{value:!1,label:P(`Switch to straight-line depreciation`)},{value:!0,label:P(`Do not switch to straight-line depreciation`)}])],compute:function(e,t,n,r,i,a={value:2},o={value:!1}){a||=0;let s=L(e,this.locale),c=L(t,this.locale),l=L(n,this.locale),u=Math.trunc(L(r,this.locale)),d=Math.trunc(L(i,this.locale)),f=L(a,this.locale),p=z(o);if(s<0)return new I(dX(s));if(c<0)return new I(XX(c));if(l<=0)return new I(AX(l));if(u<0)return new I(tZ(u));if(d<0)return new I(bX(d));if(u>d)return new I(nZ(u,d));if(d>l)return new I(xX(d,l));if(f<=0)return new I(hX(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},i$={description:P(`Internal rate of return given non-periodic cash flows.`),args:[U(`cashflow_amounts (range<number>)`,P(`An range containing the income or payments associated with the investment.`)),U(`cashflow_dates (range<number>)`,P(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),U(`rate_guess (number, default=${qQ})`,P(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:qQ}){let r=L(n,this.locale);if(!uS(e,t))return new I(lX);let i=e.flat().map(e=>L(e,this.locale)),a=t.flat().map(e=>L(e,this.locale));if(!aZ(i))return new I(uX);if(a.some(e=>e<a[0]))return new I(SX(a[0]));if(r<=-1)return new I(KX(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 iQ(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},a$={description:P(`Net present value given to non-periodic cash flows..`),args:[U(`discount (number)`,P(`The discount rate of the investment over one period.`)),U(`cashflow_amounts (number, range<number>)`,P(`An range containing the income or payments associated with the investment.`)),U(`cashflow_dates (number, range<number>)`,P(`An range with dates corresponding to the cash flows in cashflow_amounts.`))],compute:function(e,t,n){let r=L(e,this.locale);if(!uS(t,n))return new I(lX);let i=B(t).flat().map(e=>Ho(e,this.locale)),a=B(n).flat().map(e=>Ho(e,this.locale));if(a.some(e=>e<a[0]))return new I(SX(a[0]));if(r<=0)return new I(JX(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},o$={description:P(`Annual yield of a security paying periodic interest.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`rate (number)`,P(`The annualized rate of interest.`)),U(`price (number)`,P(`The price at which the security is bought per 100 face value.`)),U(`redemption (number)`,P(`The redemption amount per 100 face value, or par.`)),U(`frequency (number)`,P(`The number of interest or coupon payments per year (1, 2, or 4).`),tQ),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(L(e,this.locale)),c=Math.trunc(L(t,this.locale)),l=L(n,this.locale),u=L(r,this.locale),d=L(i,this.locale),f=Math.trunc(L(a,this.locale)),p=Math.trunc(L(o,this.locale));if(s>=c)return new I(jX(s,c));if(sZ(f))return new I(pX(f));if(oZ(p))return new I(mX(p));if(l<0)return new I(qX(l));if(u<=0)return new I(UX(u));if(d<=0)return new I(YX(d));let m=Za(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 ee(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 y(e){return v(u,g,h,e,_,d)}function b(e){return ee(u,g,h,e,_)}return(iQ(y,b,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},s$={description:P(`Annual yield of a discount security.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`price (number)`,P(`The price at which the security is bought per 100 face value.`)),U(`redemption (number)`,P(`The redemption amount per 100 face value, or par.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(L(e,this.locale)),o=Math.trunc(L(t,this.locale)),s=L(n,this.locale),c=L(r,this.locale),l=Math.trunc(L(i,this.locale));if(a>=o)return new I(jX(a,o));if(oZ(l))return new I(mX(l));if(s<=0)return new I(UX(s));if(c<=0)return new I(YX(c));let u=Za(a,o,l);return(c/s-1)/u},isExported:!0},c$={description:P(`Annual yield of a security paying interest at maturity.`),args:[U(`settlement (date)`,P(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),U(`maturity (date)`,P(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),U(`issue (date)`,P(`The date the security was initially issued.`)),U(`rate (number)`,P(`The annualized rate of interest.`)),U(`price (number)`,P(`The price at which the security is bought.`)),U(`day_count_convention (number, default=0 )`,P(`An indicator of what day count method to use.`),lZ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(L(e,this.locale)),s=Math.trunc(L(t,this.locale)),c=Math.trunc(L(n,this.locale)),l=L(r,this.locale),u=L(i,this.locale),d=Math.trunc(L(a,this.locale));if(o>=s)return new I(jX(o,s));if(oZ(d))return new I(mX(d));if(o<c)return new I(QX(o,c));if(l<0)return new I(qX(l));if(u<=0)return new I(UX(u));let f=Za(c,s,d),p=Za(c,o,d),m=Za(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0};var l$=l({CELL:()=>d$,ISBLANK:()=>y$,ISERR:()=>f$,ISERROR:()=>p$,ISFORMULA:()=>x$,ISLOGICAL:()=>m$,ISNA:()=>h$,ISNONTEXT:()=>g$,ISNUMBER:()=>_$,ISTEXT:()=>v$,NA:()=>b$});let u$=[{value:`address`,label:P(`Returns an absolute reference as plain text of the top left cell in reference.`)},{value:`col`,label:P(`Returns the column number of the cell in reference.`)},{value:`contents`,label:P(`Returns the value contained in the top left cell in reference.`)},{value:`format`,label:P(`Returns the format of the top left cell in reference.`)},{value:`row`,label:P(`Returns the row number of the top left cell in reference.`)},{value:`type`,label:P(`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.`)}],d$={description:P(`Gets information about a cell.`),args:[U(`info_type (string)`,P(`The type of information requested.`),u$),U(`reference (any, range<any>)`,P(`The reference to the cell.`))],compute:function(e,t){let n=R(e).toLowerCase();if(!u$.map(e=>e.value).includes(n))return new I(P(`The info_type should be one of %s.`,u$.join(`, `)));let r=B(t)[0][0],i=r.position;if(i===void 0)return new I(P(`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`:Fc(r.format)?`l`:typeof r.value==`number`||typeof r.value==`boolean`?`v`:`l`}return``},isExported:!0},f$={description:P(`Whether a value is an error other than #N/A.`),args:[U(`value (any)`,P(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return Po(t)&&t!==F.NotAvailable},isExported:!0},p$={description:P(`Whether a value is an error.`),args:[U(`value (any)`,P(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return Po(t)},isExported:!0},m$={description:P("Whether a value is `true` or `false`."),args:[U(`value (any)`,P(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},h$={description:P(`Whether a value is the error #N/A.`),args:[U(`value (any)`,P(`The value to be verified as an error type.`))],compute:function(e){return e?.value===F.NotAvailable},isExported:!0},g$={description:P(`Whether a value is non-textual.`),args:[U(`value (any)`,P(`The value to be checked.`))],compute:function(e){return!v$.compute.bind(this)(e)},isExported:!0},_$={description:P(`Whether a value is a number.`),args:[U(`value (any)`,P(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},v$={description:P(`Whether a value is text.`),args:[U(`value (any)`,P(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&Po(e?.value)===!1},isExported:!0},y$={description:P(`Whether the referenced cell is empty`),args:[U(`value (any)`,P(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},b$={description:P(`Returns the error value #N/A.`),args:[],compute:function(){return{value:F.NotAvailable}},isExported:!0},x$={description:P(`Checks whether there is a reference to a cell that contains a formula, and returns TRUE or FALSE.`),args:[U(`cell_reference (any)`,P(`A reference to a cell.`))],compute:function(e){return e?.position===void 0?new Eo(Lo):this.getters.getCell(e.position)?.isFormula??!1},isExported:!0};var S$=l({AND:()=>C$,FALSE:()=>w$,IF:()=>T$,IFERROR:()=>E$,IFNA:()=>D$,IFS:()=>O$,NOT:()=>k$,OR:()=>A$,SWITCH:()=>j$,TRUE:()=>M$,XOR:()=>N$});let C$={description:P("Logical `and` operator."),args:[U(`logical_expression (boolean, range<boolean>, repeating)`,P(`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}=rS(e);return n?t:new I(bs)},isExported:!0},w$={description:P("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},T$={description:P(`Returns value depending on logical expression.`),args:[U(`logical_expression (boolean, range<boolean>)`,P(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.`)),U(`value_if_true (any, range)`,P(`The value the function returns if logical_expression is TRUE.`)),U(`value_if_false (any, range, default=FALSE)`,P(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return yS(e)?Jc(this,al.get(`IF`),[e,t,n]):(z(_S(e))?t:n)??{value:0}},isExported:!0},E$={description:P(`Value if it is not an error, otherwise 2nd argument.`),args:[U(`value (any, range)`,P(`The value to return if value itself is not an error.`)),U(`value_if_error (any, range, default="empty")`,P(`The value the function returns if value is an error.`))],compute:function(e,t){return yS(e)?Jc(this,al.get(`IFERROR`),[e,t]):(Po(_S(e)?.value)?t:e)??{value:0}},isExported:!0},D$={description:P(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[U(`value (any, range)`,P(`The value to return if value itself is not #N/A an error.`)),U(`value_if_error (any, range, default="empty")`,P(`The value the function returns if value is an #N/A error.`))],compute:function(e,t){return yS(e)?Jc(this,al.get(`IFNA`),[e,t]):(_S(e)?.value===F.NotAvailable?t:e)??{value:0}},isExported:!0},O$={description:P(`Returns a value depending on multiple logical expressions.`),args:[U(`condition (any, range, repeating)`,P(`The condition to be evaluated. It can be a boolean, a number, an array, or a reference to any of those.`)),U(`value (any, range, repeating)`,P(`The value to be returned if its corresponding condition is TRUE.`))],compute:function(...e){if(e.length%2!=0)return new I(P(`Wrong number of arguments. Expected an even number of arguments.`));for(;e.length>0;){if(yS(e[0]))return Jc(this,al.get(`IFS`),e);let t=z(_S(e.shift())),n=e.shift();if(t)return n??{value:0}}return new I(P(`No match.`))},isExported:!0},k$={description:P(`Returns opposite of provided logical value.`),args:[U(`logical_expression (boolean)`,P(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!z(e)},isExported:!0},A$={description:P("Logical `or` operator."),args:[U(`logical_expression (boolean, range<boolean>, repeating)`,P(`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}=iS(e);return n?t:new I(bs)},isExported:!0},j$={description:P(`Returns a value by comparing cases to an expression.`),args:[U(`expression (number, boolean, string)`,P(`The value to be checked.`)),U(`case (any, repeating)`,P(`Case to be checked against expression.`)),U(`value (any, repeating)`,P(`Value to be returned if its corresponding case matches expression.`)),U(`default (any, default="empty")`,P(`An optional default value to be returned if none of the cases match expression.`))],compute:function(e,...t){let n=t.length%2==0?Fo(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&Po(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},M$={description:P("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},N$={description:P("Logical `xor` operator."),args:[U(`logical_expression (boolean, range<boolean>, repeating)`,P(`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 cs(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new I(bs)},isExported:!0};function P$(e,t){let n=t.getPivotId(e);if(!n)throw new I(P(`There is no pivot with id "%s"`,e));return n}function F$(e,t,n){let{measures:r}=n.getPivotCoreDefinition(e);if(!r.find(e=>e.id===t))throw new I(P(`The argument %s is not a valid measure. Here are the measures: %s`,t,`(${r.map(e=>e.id).join(`, `)})`))}function I$(e){if(e.length%2!=0)throw new I(P(`Function PIVOT takes an even number of arguments.`))}function L$(e,t,n){let r=[],i=e.getters.getPivotCoreDefinition(t);if(i.type===`SPREADSHEET`&&i.dataSet){let{sheetId:t,zone:n}=i.dataSet,a=Yn(n),o=e.getters.getRangeFromSheetXC(t,a);if(o===void 0||o.invalidXc||o.invalidSheetName)throw new Eo;if(e.__originCellPosition&&o.sheetId===e.__originSheetId&&sr(O(e.__originCellPosition),n))throw new To;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 R$=l({ADDRESS:()=>V$,CHOOSE:()=>i1,COLUMN:()=>H$,COLUMNS:()=>U$,DROP:()=>a1,FORMULATEXT:()=>s1,HLOOKUP:()=>W$,INDEX:()=>G$,INDIRECT:()=>K$,LOOKUP:()=>q$,MATCH:()=>J$,OFFSET:()=>r1,PIVOT:()=>n1,PIVOT_HEADER:()=>t1,PIVOT_VALUE:()=>e1,ROW:()=>Y$,ROWS:()=>X$,TAKE:()=>o1,VLOOKUP:()=>Z$,XLOOKUP:()=>$$});let z$=[{value:!0,label:P(`A1 style (default)`)},{value:!1,label:P(`R1C1 style`)}],B$=[{value:!0,label:P(`Approximate match (default)`)},{value:!1,label:P(`Exact match`)}],V$={description:P(`Returns a cell reference as a string. `),args:[U(`row (number)`,P(`The row number of the cell reference. `)),U(`column (number)`,P(`The column number (not name) of the cell reference. A is column number 1. `)),U(`absolute_relative_mode (number, default=1)`,P(`An indicator of whether the reference is row/column absolute.`),[{value:1,label:P(`Absolute row and column (e.g. $A$1)`)},{value:2,label:P(`Absolute row, relative column (e.g. A$1)`)},{value:3,label:P(`Relative row, absolute column (e.g. $A1)`)},{value:4,label:P(`Relative row and column (e.g. A1)`)}]),U(`use_a1_notation (boolean, default=TRUE)`,P(`A boolean indicating whether to use A1 style notation or R1C1 style notation.`),z$),U(`sheet (string, optional)`,P(`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=Wo(e,this.locale),o=Wo(t,this.locale);if(a<1)return new I(fS(a));if(o<1)return new I(fS(o));let s=Wo(n,this.locale);if(![1,2,3,4].includes(s))return new I(Ro(1,4,s));let c=z(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:yl(R(i),l)},isExported:!0},H$={description:P(`Column number of a specified cell.`),args:[U(`cell_reference (any, range<any>, default='this cell')`,P(`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 I(P(`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 I(P(`The range is out of bounds.`));if(n.position===void 0)return new Eo(Lo);let r=n.position.col;return t.length===1?r+1:rs(t.length,1,e=>({value:r+e+1}))},isExported:!0},U$={description:P(`Number of columns in a specified array or range.`),args:[U(`range (any, range<any>)`,P(`The range whose column count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new I(P(`The range is out of bounds.`)):t[0][0].value===F.InvalidReference?t[0][0]:t.length},isExported:!0},W$={description:P(`Horizontal lookup`),args:[U(`search_key (string, number, boolean)`,P(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`range (any, range)`,P(`The range to consider for the search. The first row in the range is searched for the key specified in search_key.`)),U(`index (number)`,P(`The row index of the value to be returned, where the first row in range is numbered 1.`)),U(`is_sorted (boolean, default=true)`,P(`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.`),B$)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(L(n?.value,this.locale)),a=B(t);if(1>i||i>a[0].length)return new I(P(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[t][0].value,s=a[z(r.value)?ps(a,e,`nextSmaller`,`asc`,a.length,o):ms(a,e,`wildcard`,a.length,o,this.lookupCaches)];return s===void 0?Fo(e):s[i-1]},isExported:!0},G$={description:P(`Returns the content of a cell, specified by row and column offset.`),args:[U(`reference (any, range)`,P(`The range of cells from which the values are returned.`)),U(`row (number, default=0)`,P(`The index of the row to be returned from within the reference range of cells.`)),U(`column (number, default=0)`,P(`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=L(t.value,this.locale),a=L(n.value,this.locale);return a<0||a-1>=r.length||i<0||i-1>=r[0].length?new I(P(`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},K$={description:P(`Returns the content of a cell, specified by a string.`),args:[U(`reference (string)`,P(`The range of cells from which the values are returned.`)),U(`use_a1_notation (boolean, default=TRUE)`,P(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`),z$)],compute:function(e,t={value:!0}){let n=e?.value?.toString();if(!n)return new Eo(P(`Reference should be defined.`));if(!z(t))return new I(P(`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 Eo;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},q$={description:P(`Look up a value.`),args:[U(`search_key (string, number, boolean)`,P(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`search_array (any, range)`,P(`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.`)),U(`result_range (any, range, optional)`,P(`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=ps(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?Fo(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 I(P(`The result_range must be a single row or a single column.`)):a>1?c>a-1?new I(P(`[[FUNCTION_NAME]] evaluates to an out of range row value %s.`,c+1)):i[c][0]:c>o-1?new I(P(`[[FUNCTION_NAME]] evaluates to an out of range column value %s.`,c+1)):i[0][c])},isExported:!0},J$={description:P(`Position of item in range that matches value.`),args:[U(`search_key (string, number, boolean)`,P(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`range (any, range)`,P(`The one-dimensional array to be searched.`)),U(`search_type (number, default=1)`,P(`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:P(`Ascending order (default)`)},{value:0,label:P(`Exact match`)},{value:-1,label:P(`Descending order`)}])],compute:function(e,t,n={value:1}){let r=L(n,this.locale),i=B(t),a=i.length,o=i[0].length;if(a!==1&&o!==1)return new I(P(`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=ps(i,e,`nextSmaller`,`asc`,l,c);break;case 0:s=ms(i,e,`wildcard`,l,c,this.lookupCaches);break;case-1:s=ps(i,e,`nextGreater`,`desc`,l,c);break}return a===1&&i[0][s]===void 0||a!==1&&i[s]===void 0?Fo(e):s+1},isExported:!0},Y$={description:P(`Row number of a specified cell.`),args:[U(`cell_reference (any, range<any>, default='this cell')`,P(`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 I(P(`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 I(P(`The range is out of bounds.`));if(n.position===void 0)return new Eo(Lo);let r=n.position.row;return t[0].length===1?r+1:rs(1,t[0].length,(e,t)=>({value:r+t+1}))},isExported:!0},X$={description:P(`Number of rows in a specified array or range.`),args:[U(`range (any, range<any>)`,P(`The range whose row count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new I(P(`The range is out of bounds.`)):t[0][0].value===F.InvalidReference?t[0][0]:t[0].length},isExported:!0},Z$={description:P(`Vertical lookup.`),args:[U(`search_key (string, number, boolean)`,P(`The value to search for. For example, 42, 'Cats', or I24.`)),U(`range (any, range)`,P(`The range to consider for the search. The first column in the range is searched for the key specified in search_key.`)),U(`index (number)`,P(`The column index of the value to be returned, where the first column in range is numbered 1.`)),U(`is_sorted (boolean, default=true)`,P(`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.`),B$)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(L(n?.value,this.locale)),a=B(t);if(1>i||i>a.length)return new I(P(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[0][t].value,s=z(r.value)?ps(a,e,`nextSmaller`,`asc`,a[0].length,o):ms(a,e,`wildcard`,a[0].length,o,this.lookupCaches),c=a[i-1][s];return c===void 0?Fo(e):c},isExported:!0},Q$={0:`strict`,1:`nextGreater`,"-1":`nextSmaller`,2:`wildcard`},$$={description:P(`Search a range for a match and return the corresponding item from a second range.`),args:[U(`search_key (string,number,boolean)`,P(`The value to search for.`)),U(`lookup_range (any, range)`,P(`The range to consider for the search. Should be a single column or a single row.`)),U(`return_range (any, range)`,P(`The range containing the return value. Should have the same dimensions as lookup_range.`)),U(`if_not_found (any, optional)`,P(`If a valid match is not found, return this value.`)),U(`match_mode (any, default=0)`,P(`Specifies how to match search_key with the items in lookup_range. `),[{value:0,label:P(`Exact match (default)`)},{value:-1,label:P(`Exact match or next smaller item`)},{value:1,label:P(`Exact match or next larger item`)},{value:2,label:P(`Wildcard character match`)}]),U(`search_mode (any, default=1)`,P(`Specifies the search mode to use. By default, a first to last search will be used.`),[{value:1,label:P(`Search first to last (default)`)},{value:-1,label:P(`Search last to first`)},{value:2,label:P(`Binary search (sorted ascending order)`)},{value:-2,label:P(`Binary search (sorted descending order)`)}])],compute:function(e,t,n,r,i={value:0},a={value:1}){let o=Math.trunc(L(i.value,this.locale)),s=Math.trunc(L(a.value,this.locale)),c=B(t),l=B(n);if(c.length!==1&&c[0].length!==1)return new I(P(`lookup_range should be either a single row or single column.`));if(![1,-1,2,-2].includes(s))return new I(P(`search_mode should be a value in [-1, 1, -2, 2].`));if(![-1,0,1,2].includes(o))return new I(P(`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 I(P(`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 I(P(`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=Q$[o],m=s===-1,h=s===2||s===-2?ps(c,e,p,s===2?`asc`:`desc`,f,d):ms(c,e,p,f,d,this.lookupCaches,m);return h===-1?r===void 0?Fo(e):[[r]]:u===`col`?l.map(e=>[e[h]]):[l[h]]},isExported:!0},e1={description:P(`Get the value from a pivot.`),args:[U(`pivot_id (number,string)`,P(`ID of the pivot.`)),U(`measure_name (string)`,P(`Name of the measure.`)),U(`domain_field_name (string,repeating,optional)`,P(`Field name.`)),U(`domain_value (number,string,boolean,repeating,optional)`,P(`Value.`))],compute:function(e,t,...n){let r=R(e),i=R(t),a=P$(r,this.getters);F$(a,i,this.getters),I$(n);let o=this.getters.getPivot(a),s=this.getters.getPivotCoreDefinition(a);L$(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=P(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${r})`);return{value:F.GenericError,message:P(`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)}},t1={description:P(`Get the header of a pivot.`),args:[U(`pivot_id (number,string)`,P(`ID of the pivot.`)),U(`domain_field_name (string,repeating,optional)`,P(`Field name.`)),U(`domain_value (number,string,value,repeating,optional)`,P(`Value.`))],compute:function(e,...t){let n=R(e),r=P$(n,this.getters);I$(t);let i=this.getters.getPivot(r);L$(this,r,[]),i.init({reload:i.needsReevaluation});let a=i.assertIsValid({throwOnError:!1});if(a)return a;if(!i.areDomainArgsFieldsValid(t)){let e=P(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${n})`);return{value:F.GenericError,message:P(`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(R(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}}},n1={description:P(`Get a pivot table.`),args:[U(`pivot_id (string)`,P(`ID of the pivot.`)),U(`row_count (number, optional)`,P(`number of rows`)),U(`include_total (boolean, default=TRUE)`,P(`Whether to include total/sub-totals or not.`)),U(`include_column_titles (boolean, default=TRUE)`,P(`Whether to include the column titles or not.`)),U(`column_count (number, optional)`,P(`number of columns`)),U(`include_measure_titles (boolean, default=TRUE)`,P(`Whether to include the measure titles row or not.`))],compute:function(e,t,n,r,i,a){let o=P$(R(e),this.getters),s=this.getters.getPivot(o),c=this.getters.getPivotCoreDefinition(o),l=DC(c,t,n,r,i,a,this.locale);if(l.numberOfRows<0)return new I(P(`The number of rows must be positive.`));if(l.numberOfColumns<0)return new I(P(`The number of columns must be positive.`));L$(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 I(K_(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(vC(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}},r1={description:P(`Returns a range reference shifted by a specified number of rows and columns from a starting cell reference.`),args:[U(`cell_reference (any, range<any>)`,P(`The starting point from which to count the offset rows and columns.`)),U(`offset_rows (number)`,P(`The number of rows to offset by.`)),U(`offset_columns (number)`,P(`The number of columns to offset by.`)),U(`height (number, default='height of cell_reference')`,P(`The number of rows of the range to return starting at the offset target.`)),U(`width (number, default='width of cell_reference')`,P(`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 Eo(Lo);let a=B(e),o=a[0][0];if(o===void 0)return new I(P(`The range is out of bounds.`));if(o.position===void 0)return new Eo(Lo);let s=a[0].length,c=a.length;if(r){let e=L(r,this.locale);if(e<1)return new I(P(`Height value is %(_height)s. It should be greater than or equal to 1.`,{_height:e}));s=e}if(i){let e=L(i,this.locale);if(e<1)return new I(P(`Width value is %(_width)s. It should be greater than or equal to 1.`,{_width:e}));c=e}let l=L(t,this.locale),u=L(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 Eo(P(`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 Eo:(d&&this.addDependencies?.(d,[g]),rs(c,s,(e,t)=>this.getFormulaResult({sheetId:h,col:f+e,row:p+t})))}},i1={description:P(`Returns an element from a list of choices based on index.`),args:[U(`index (number)`,P(`Which choice to return.`)),U(`choice (any, range<any>, repeating)`,P(`A potential value to return. May be a reference to a cell or an individual value.`))],compute:function(e,...t){let n=Math.floor(L(e,this.locale))-1;return n<0||n>=t.length?new I(P(`Index for CHOOSE is invalid. Valid values are between 1 and %(choices)s inclusive.`,{choices:t.length})):t[n]??new I(P(`Choice is undefined.`))},isExported:!0},a1={description:P(`Excludes a specified number of rows or columns from the start or end of an array.`),args:[U(`array (range)`,P(`The array from which to drop rows or columns`)),U(`rows (number)`,P(`The number of rows to drop. A negative value drops from the end of the array.`)),U(`columns (number, optional)`,P(`The number of columns to exclude. A negative value drops from the end of the array.`))],compute:function(e,t,n){let r=L(t,this.locale),i=L(n,this.locale),a=e;if(Math.abs(i)>=e.length||Math.abs(r)>=e[0].length)return new I(P(`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},o1={description:P(`Returns a specified number of contiguous rows or columns from the start or end of an array.`),args:[U(`array (range)`,P(`The array from which to take rows or columns.`)),U(`rows (number)`,P(`The number of rows to take. A negative value takes from the end of the array.`)),U(`columns (number, optional)`,P(`The number of columns to take. A negative value takes from the end of the array.`))],compute:function(e,t,n){let r=t?L(t,this.locale):e[0].length,i=L(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 I(P(`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},s1={description:P(`Returns a formula as a string.`),args:[U(`cell_reference (any)`,P(`A reference to a cell.`))],compute:function(e){if(e?.position===void 0)return new Eo(Lo);let t=this.getters.getCell(e.position);return t?.isFormula?t.compiledFormula.toFormulaString(this.getters):new Do(P(`The cell does not contain a formula.`))},isExported:!0};var c1=l({ADD:()=>l1,CONCAT:()=>u1,DIVIDE:()=>d1,EQ:()=>h1,GT:()=>v1,GTE:()=>y1,LT:()=>b1,LTE:()=>x1,MINUS:()=>S1,MULTIPLY:()=>C1,NE:()=>w1,POW:()=>T1,SPILLED_RANGE:()=>E1,UMINUS:()=>D1,UNARY_PERCENT:()=>O1,UPLUS:()=>k1});let l1={description:P(`Sum of two numbers.`),args:[U(`value1 (number)`,P(`The first addend.`)),U(`value2 (number)`,P(`The second addend.`))],compute:function(e,t){return{value:L(e,this.locale)+L(t,this.locale),format:e?.format||t?.format}}},u1={description:P(`Concatenation of two values.`),args:[U(`value1 (string)`,P(`The value to which value2 will be appended.`)),U(`value2 (string)`,P(`The value to append to value1.`))],compute:function(e,t){return R(e)+R(t)},isExported:!0},d1={description:P(`One number divided by another.`),args:[U(`dividend (number)`,P(`The number to be divided.`)),U(`divisor (number)`,P(`The number to divide by.`))],compute:function(e,t){let n=L(t,this.locale);return n===0?new Ao(P(`The divisor must be different from zero.`)):{value:L(e,this.locale)/n,format:e?.format||t?.format}}};function f1(e){return e===void 0||e.value===null}let p1={number:0,string:``,boolean:!1};function m1(e,t,n=2e-16){return Math.abs(e-t)<n}let h1={description:P(`Equal.`),args:[U(`value1 (string, number, boolean)`,P(`The first value.`)),U(`value2 (string, number, boolean)`,P(`The value to test against value1 for equality.`))],compute:function(e,t){if(Po(e?.value))return e;if(Po(t?.value))return t;let n=f1(e)?p1[typeof t?.value]:e?.value,r=f1(t)?p1[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:m1(n,r)}:{value:n===r}}};function g1(e,t,n){if(Po(e?.value))return e;if(Po(t?.value))return t;let r=f1(e)?p1[typeof t?.value]??``:e?.value,i=f1(t)?p1[typeof e?.value]??``:t?.value,a=_1[typeof r],o=_1[typeof i];if(a!==o)return{value:n(a,o)};switch(typeof r){case`string`:r=r.toUpperCase();break;case`boolean`:r=Number(r);break}switch(typeof i){case`string`:i=i.toUpperCase();break;case`boolean`:i=Number(i);break}return{value:n(r,i)}}let _1={number:0,string:1,boolean:2},v1={description:P(`Strictly greater than.`),args:[U(`value1 (number, string, boolean)`,P(`The value to test as being greater than value2.`)),U(`value2 (number, string, boolean)`,P(`The second value.`))],compute:function(e,t){return g1(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?!m1(e,t)&&e>t:e>t)}},y1={description:P(`Greater than or equal to.`),args:[U(`value1 (number, string, boolean)`,P(`The value to test as being greater than or equal to value2.`)),U(`value2 (number, string, boolean)`,P(`The second value.`))],compute:function(e,t){return g1(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?m1(e,t)||e>t:e>=t)}},b1={description:P(`Less than.`),args:[U(`value1 (number, string, boolean)`,P(`The value to test as being less than value2.`)),U(`value2 (number, string, boolean)`,P(`The second value.`))],compute:function(e,t){let n=y1.compute.bind(this)(e,t);return Po(n.value)?n:{value:!n.value}}},x1={description:P(`Less than or equal to.`),args:[U(`value1 (number, string, boolean)`,P(`The value to test as being less than or equal to value2.`)),U(`value2 (number, string, boolean)`,P(`The second value.`))],compute:function(e,t){let n=v1.compute.bind(this)(e,t);return Po(n.value)?n:{value:!n.value}}},S1={description:P(`Difference of two numbers.`),args:[U(`value1 (number)`,P(`The minuend, or number to be subtracted from.`)),U(`value2 (number)`,P(`The subtrahend, or number to subtract from value1.`))],compute:function(e,t){return{value:L(e,this.locale)-L(t,this.locale),format:e?.format||t?.format}}},C1={description:P(`Product of two numbers`),args:[U(`factor1 (number)`,P(`The first multiplicand.`)),U(`factor2 (number)`,P(`The second multiplicand.`))],compute:function(e,t){return{value:L(e,this.locale)*L(t,this.locale),format:e?.format||t?.format}}},w1={description:P(`Not equal.`),args:[U(`value1 (string, number, boolean)`,P(`The first value.`)),U(`value2 (string, number, boolean)`,P(`The value to test against value1 for inequality.`))],compute:function(e,t){let n=h1.compute.bind(this)(e,t);return Po(n.value)?n:{value:!n.value}}},T1={description:P(`A number raised to a power.`),args:[U(`base (number)`,P(`The number to raise to the exponent power.`)),U(`exponent (number)`,P(`The exponent to raise base to.`))],compute:function(e,t){return lJ.compute.bind(this)(e,t)}},E1={description:P(`Gets the spilled range of an array formula.`),args:[U(`ref (any, range<any>)`,P(`The reference to get the spilled range from.`))],compute:function(e){if(e===void 0)return new Eo(Lo);let t=B(e);if(t.length!==1||t[0].length!==1)return new I(P(`Only single-cell references are allowed to get the spilled range.`));let n=t[0][0];if(Po(n.value))return n;if(n.position===void 0)return new Eo(Lo);let r=this.__originCellPosition;r&&this.updateDependencies?.(r);let i=this.getters.getSpreadZone(n.position);if(i===void 0)return new Eo;let a=this.getters.getRangeFromZone(this.__originSheetId,i);return r&&this.addDependencies?.(r,[a]),rs(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},D1={description:P(`A number with the sign reversed.`),args:[U(`value (number)`,P(`The number to have its sign reversed. Equivalently, the number to multiply by -1.`))],compute:function(e){return{value:-L(e,this.locale),format:e?.format}}},O1={description:P(`Value interpreted as a percentage.`),args:[U(`percentage (number)`,P(`The value to interpret as a percentage.`))],compute:function(e){return L(e,this.locale)/100}},k1={description:P(`A specified number, unchanged.`),args:[U(`value (any)`,P(`The number to return.`))],compute:function(e={value:null}){return e}},$=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),A1={transform:e=>e,inverseTransform:e=>e},j1=1e-10,M1=.0254,N1=M1/72,P1=.3048,F1=.9144,I1=1609.34,L1=1852,R1=946073047258e4,z1={g:{...A1,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:{...A1,category:`distance`},km:{...$(1e3),category:`distance`},ang:{...$(j1),category:`distance`},Picapt:{...$(N1),category:`distance`},pica:{...$(M1/6),category:`distance`},in:{...$(M1),category:`distance`},ft:{...$(P1),category:`distance`},yd:{...$(F1),category:`distance`},ell:{...$(1.143),category:`distance`},mi:{...$(I1),category:`distance`},survey_mi:{...$(1609.34),category:`distance`},Nmi:{...$(L1),category:`distance`},ly:{...$(R1),category:`distance`},parsec:{...$(0x6da012f95c9fd0),category:`distance`},sec:{...A1,category:`time`},min:{...$(60),category:`time`},hr:{...$(3600),category:`time`},day:{...$(86400),category:`time`},yr:{...$(31556952),category:`time`},Pa:{...A1,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:{...A1,category:`force`},dyn:{...$(1e-5),category:`force`},pond:{...$(.00980665),category:`force`},lbf:{...$(4.44822),category:`force`},J:{...A1,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:{...A1,category:`power`},PS:{...$(735.499),category:`power`},HP:{...$(745.7),category:`power`},T:{...A1,category:`magnetism`},ga:{...$(1e-4),category:`magnetism`},K:{...A1,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":{...A1,category:`volume`,order:3},"ang^3":{...$(j1**3),category:`volume`,order:3},"Picapt^3":{...$(N1**3),category:`volume`,order:3},tsp:{...$(492892e-11),category:`volume`},tspm:{...$(5e-6),category:`volume`},tbs:{...$(14786764825785619e-21),category:`volume`},"in^3":{...$(M1**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":{...$(P1**3),category:`volume`,order:3},bushel:{...$(.0352390704),category:`volume`},barrel:{...$(.158987295),category:`volume`},"yd^3":{...$(F1**3),category:`volume`,order:3},MTON:{...$(1.13267386368),category:`volume`},GRT:{...$(2.83168),category:`volume`},"mi^3":{...$(I1**3),category:`volume`,order:3},"Nmi^3":{...$(L1**3),category:`volume`,order:3},"ly^3":{...$(R1**3),category:`volume`,order:3},"m^2":{...A1,category:`area`,order:2},"ang^2":{...$(j1**2),category:`area`,order:2},"Picapt^2":{...$(N1**2),category:`area`,order:2},"in^2":{...$(M1**2),category:`area`,order:2},"ft^2":{...$(P1**2),category:`area`,order:2},"yd^2":{...$(F1**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":{...$(I1**2),category:`area`,order:2},"Nmi^2":{...$(L1**2),category:`area`,order:2},"ly^2":{...$(R1**2),category:`area`,order:2},bit:{...A1,category:`information`},byte:{...$(8),category:`information`},"m/s":{...A1,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`}},B1={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`},V1={"":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},H1={weight:P(`Weight`),distance:P(`Distance`),time:P(`Time`),pressure:P(`Pressure`),force:P(`Force`),energy:P(`Energy`),power:P(`Power`),magnetism:P(`Magnetism`),temperature:P(`Temperature`),volume:P(`Volume`),area:P(`Area`),information:P(`Information`),speed:P(`Speed`)},U1=Object.entries(z1).map(([e,t])=>({value:e,label:W1(t.category)}));function W1(e){return H1[e]??``}function G1(e){for(let[t,n]of Object.entries(V1)){if(t&&!e.startsWith(t))continue;let r=e.slice(t.length),i=z1[r];if(!i&&B1[r]&&(i=z1[B1[r]]),i)return{...i,factor:i.order?n**+i.order:n}}}var K1=l({CONVERT:()=>q1});let q1={description:P(`Converts a numeric value to a different unit of measure.`),args:[U(`value (number)`,P(`the numeric value in start_unit to convert to end_unit`)),U(`start_unit (string)`,P(`The starting unit, the unit currently assigned to value`),U1),U(`end_unit (string)`,P(`The unit of measure into which to convert value`),U1)],compute:function(e,t,n){let r=L(e,this.locale),i=R(t),a=R(n),o=G1(i),s=G1(a);return o?s?o.category===s.category?{value:s.inverseTransform(o.factor*o.transform(r))/s.factor,format:e?.format}:{value:F.GenericError,message:P(`Incompatible units of measure ('%s' vs '%s')`,W1(o.category),W1(s.category))}:{value:F.GenericError,message:P(`Invalid units of measure ('%s')`,a)}:{value:F.GenericError,message:P(`Invalid units of measure ('%s')`,i)}},isExported:!0};var J1=l({CHAR:()=>Q1,CLEAN:()=>$1,CONCATENATE:()=>e0,EXACT:()=>t0,FIND:()=>n0,FORMAT_LARGE_NUMBER:()=>r0,JOIN:()=>i0,LEFT:()=>a0,LEN:()=>o0,LOWER:()=>s0,MID:()=>c0,PROPER:()=>l0,REGEXEXTRACT:()=>d0,REGEXREPLACE:()=>f0,REGEXTEST:()=>u0,REPLACE:()=>p0,RIGHT:()=>m0,SEARCH:()=>h0,SPLIT:()=>g0,SUBSTITUTE:()=>_0,TEXT:()=>S0,TEXTAFTER:()=>w0,TEXTBEFORE:()=>T0,TEXTJOIN:()=>v0,TEXTSPLIT:()=>y0,TRIM:()=>b0,UPPER:()=>x0,VALUE:()=>C0});let Y1=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,X1=[{value:0,label:P(`Case-sensitive (default)`)},{value:1,label:P(`Case-insensitive`)}],Z1=[{value:0,label:P(`Don't match to end (default)`)},{value:1,label:P(`Match to end`)}],Q1={description:P(`Gets character associated with number.`),args:[U(`table_number (number)`,P(`The number of the character to look up from the current Unicode table in decimal format.`))],compute:function(e){let t=Math.trunc(L(e,this.locale));return t<1?new I(P(`The table_number (%s) is out of range.`,t)):String.fromCharCode(t)},isExported:!0},$1={description:P(`Remove non-printable characters from a piece of text.`),args:[U(`text (string)`,P(`The text whose non-printable characters are to be removed.`))],compute:function(e){let t=R(e),n=``;for(let e of t)e&&e.charCodeAt(0)>31&&(n+=e);return n},isExported:!0},e0={description:P(`Appends strings to one another.`),args:[U(`string (string, range<string>, repeating)`,P(`String to append in sequence.`))],compute:function(...e){return es(e,(e,t)=>e+R(t),``)},isExported:!0},t0={description:P(`Tests whether two strings are identical.`),args:[U(`string1 (string)`,P(`The first string to compare.`)),U(`string2 (string)`,P(`The second string to compare.`))],compute:function(e,t){return R(e)===R(t)},isExported:!0},n0={description:P(`First position of string found in text, case-sensitive.`),args:[U(`search_for (string)`,P(`The string to look for within text_to_search.`)),U(`text_to_search (string)`,P(`The text to search for the first occurrence of search_for.`)),U(`starting_at (number, default=1)`,P(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=R(e),i=R(t),a=L(n,this.locale);if(i===``)return new I(P(`The text_to_search must be non-empty.`));if(a<1)return new I(P(`The starting_at (%s) must be greater than or equal to 1.`,a));let o=i.indexOf(r,a-1);return o===-1?new I(P(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)):o+1},isExported:!0},r0={description:P(`Apply a large number format`),args:[U(`value (number)`,P(`The number.`)),U(`unit (string, optional)`,P(`The formatting unit. Use 'k', 'm', or 'b' to force the unit`),[{value:`k`,label:P(`Thousand`)},{value:`m`,label:P(`Million`)},{value:`b`,label:P(`Billion`)}])],compute:function(e,t){return{value:L(e,this.locale),format:Dc(e,t,this.locale)}}},i0={description:P(`Concatenates elements of arrays with delimiter.`),args:[U(`delimiter (string)`,P(`The character or string to place between each concatenated value.`)),U(`value_or_array (string, range<string>, repeating)`,P(`Value to be appended using delimiter.`))],compute:function(e,...t){let n=R(e);return es(t,(e,t)=>(e?e+n:``)+R(t),``)}},a0={description:P(`Substring from beginning of specified string.`),args:[U(`text (string)`,P(`The string from which the left portion will be returned.`)),U(`number_of_characters (number, optional)`,P(`The number of characters to return from the left side of string.`))],compute:function(e,...t){let n=t.length?L(t[0],this.locale):1;return n<0?new I(P(`The number_of_characters (%s) must be positive or null.`,n)):R(e).substring(0,n)},isExported:!0},o0={description:P(`Length of a string.`),args:[U(`text (string)`,P(`The string whose length will be returned.`))],compute:function(e){return R(e).length},isExported:!0},s0={description:P(`Converts a specified string to lowercase.`),args:[U(`text (string)`,P(`The string to convert to lowercase.`))],compute:function(e){return R(e).toLowerCase()},isExported:!0},c0={description:P(`A segment of a string.`),args:[U(`text (string)`,P(`The string to extract a segment from.`)),U(`starting_at (number)`,P(`The index from the left of string from which to begin extracting. The first character in string has the index 1.`)),U(`extract_length (number)`,P(`The length of the segment to extract.`))],compute:function(e,t,n){let r=R(e),i=L(t,this.locale),a=L(n,this.locale);return i<1?new I(P(`The starting_at argument (%s) must be positive greater than one.`,i.toString())):a<0?new I(P(`The extract_length argument (%s) must be positive or null.`,a)):r.slice(i-1,i+a-1)},isExported:!0},l0={description:P(`Capitalizes each word in a specified string.`),args:[U(`text_to_capitalize (string)`,P(`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 R(e).replace(Y1,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},u0={description:P(`Checks whether a string matches the supplied regular expression.`),args:[U(`text (string)`,P(`The string to test.`)),U(`pattern (string)`,P(`The regular expression pattern to match against the text.`)),U(`case_sensitivity (number, default=0)`,P(`Whether the match is case-sensitive.`),[{value:0,label:P(`Case-sensitive`)},{value:1,label:P(`Case-insensitive`)}])],compute:function(e,t,n={value:0}){let r=R(e),i=R(t),a=L(n,this.locale);if(i===``)return!0;if(r===``)return!1;if(a!==0&&a!==1)return new I(P(`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 I(P(`Invalid regular expression`))}return s.test(r)},isExported:!0},d0={description:P(`Extract text from a string based on the supplied regular expression.`),args:[U(`text (string)`,P(`The string on which you want to extract text.`)),U(`pattern (string)`,P(`The regular expression pattern to match against the text.`)),U(`return_mode (number, default=0)`,P(`0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array.`),[{value:0,label:P(`First match`)},{value:1,label:P(`All matches`)},{value:2,label:P(`Capture groups of first match`)}]),U(`case_sensitivity (number, default=0)`,P(`Whether the match is case-sensitive.`),[{value:0,label:P(`Case-sensitive`)},{value:1,label:P(`Case-insensitive`)}])],compute:function(e,t,n={value:0},r={value:0}){let i=R(e),a=R(t),o=L(n,this.locale),s=L(r,this.locale);if(i===``||a===``)return{value:``};if(o<0||o>2)return new I(P(`The return_mode (%s) must be 0, 1 or 2.`,o));if(s!==0&&s!==1)return new I(P(`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 I(P(`Invalid regular expression`))}let u=[...i.matchAll(l)];return u.length===0?{value:F.NotAvailable,message:P(`No matches found.`)}:o===0?u[0][0]:o===1?u.map(e=>[e[0]]):u[0].length<2?new I(P(`No capturing groups found.`)):u[0].slice(1).map(e=>[e])},isExported:!0},f0={description:P(`Replace text in a string based on the supplied regular expression.`),args:[U(`text (string)`,P(`The string in which you want to replace text.`)),U(`pattern (string)`,P(`The regular expression pattern to match against the text.`)),U(`replacement (string)`,P(`The text to use as the replacement.`)),U(`occurrence (number, default=0)`,P(`0 = replace all matches. A negative number counts from the end.`)),U(`case_sensitivity (number, default=0)`,P(`Whether the match is case-sensitive.`),[{value:0,label:P(`Case-sensitive`)},{value:1,label:P(`Case-insensitive`)}])],compute:function(e,t,n,r={value:0},i={value:0}){let a=R(e),o=R(t),s=R(n),c=L(r,this.locale),l=L(i,this.locale);if(l!==0&&l!==1)return new I(P(`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 I(P(`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},p0={description:P(`Replaces part of a text string with different text.`),args:[U(`text (string)`,P(`The text, a part of which will be replaced.`)),U(`position (number)`,P(`The position where the replacement will begin (starting from 1).`)),U(`length (number)`,P(`The number of characters in the text to be replaced.`)),U(`new_text (string)`,P(`The text which will be inserted into the original text.`))],compute:function(e,t,n,r){let i=L(t,this.locale);if(i<1)return new I(P(`The position (%s) must be greater than or equal to 1.`,i));let a=L(n,this.locale);if(a<0)return new I(P(`The length (%s) must be positive or zero.`,a));let o=R(e),s=R(r);return o.substring(0,i-1)+s+o.substring(i-1+a)},isExported:!0},m0={description:P(`A substring from the end of a specified string.`),args:[U(`text (string)`,P(`The string from which the right portion will be returned.`)),U(`number_of_characters (number, optional)`,P(`The number of characters to return from the right side of string.`))],compute:function(e,...t){let n=t.length?L(t[0],this.locale):1;if(n<0)return new I(P(`The number_of_characters (%s) must be positive or zero.`,n));let r=R(e),i=r.length;return r.substring(i-n,i)},isExported:!0},h0={description:P(`First position of string found in text, ignoring case.`),args:[U(`search_for (string)`,P(`The string to look for within text_to_search.`)),U(`text_to_search (string)`,P(`The text to search for the first occurrence of search_for.`)),U(`starting_at (number, default=1)`,P(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=R(e).toLowerCase(),i=R(t).toLowerCase(),a=L(n,this.locale);if(i===``)return{value:F.GenericError,message:P(`The text_to_search must be non-empty.`)};if(a<1)return{value:F.GenericError,message:P(`The starting_at (%s) must be greater than or equal to 1.`,a)};let o=i.indexOf(r,a-1);return o===-1?{value:F.GenericError,message:P(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)}:{value:o+1}},isExported:!0},g0={description:P(`Split text by specific character delimiter(s).`),args:[U(`text (string)`,P(`The text to divide.`)),U(`delimiter (string)`,P(`The character or characters to use to split text.`)),U(`split_by_each (boolean, default=true})`,P(`Whether or not to divide text around each character contained in delimiter.`)),U(`remove_empty_text (boolean, default=true)`,P(`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=R(e),a=xt(R(t)),o=z(n),s=z(r);if(a.length<=0)return new I(P(`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!==``)),os([l])},isExported:!1},_0={description:P(`Replaces existing text with new text in a string.`),args:[U(`text_to_search (string)`,P(`The text within which to search and replace.`)),U(`search_for (string)`,P(`The string to search for within text_to_search.`)),U(`replace_with (string)`,P(`The string that will replace search_for.`)),U(`occurrence_number (number, optional)`,P(`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=L(r,this.locale);if(i<0)return new I(P(`The occurrenceNumber (%s) must be positive or null.`,i));let a=R(e),o=R(t);if(o===``)return a;let s=R(n),c=new RegExp(xt(o),`g`);if(i===0)return a.replace(c,s);let l=0;return a.replace(c,e=>++l===i?s:e)},isExported:!0},v0={description:P(`Combines text from multiple strings and/or arrays.`),args:[U(`delimiter (string)`,P(`A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.`)),U(`ignore_empty (boolean)`,P(`A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.`),[{value:!0,label:P(`Ignore empty cells`)},{value:!1,label:P(`Include empty cells (default)`)}]),U(`texts (string, range<string>, repeating)`,P(`Text item to join.`))],compute:function(e,t={value:!0},...n){let r=R(e),i=z(t),a=0;return es(n,(e,t)=>i&&R(t)===``?e:(a++?e+r:``)+R(t),``)},isExported:!0},y0={description:P(`Splits text into rows or columns using specified column and row delimiters.`),args:[U(`text (string)`,P(`The text to split.`)),U(`col_delimiter (string, range<string>)`,P(`Character or string to split columns by.`)),U(`row_delimiter (string, range<string>, optional)`,P(`Character or string to split rows by.`)),U(`ignore_empty (boolean, default=false)`,P(`Whether to ignore empty cells.`),[{value:!1,label:P(`Include empty cells (default)`)},{value:!0,label:P(`Ignore empty cells`)}]),U(`match_mode (number, default=0)`,P(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),X1),U(`pad_with (string, default="${F.NotAvailable}")`,P(`The value to use for padding empty cells.`))],compute:function(e,t,n,r={value:!1},i={value:0},a=new Do){let o=R(e);if(o.length<=0)return new I(P(`No text to split.`));if(t===void 0&&n===void 0)return new I(P(`At least one delimiter must be provided.`));let s=B(t).flat().map(e=>xt(R(e))),c=B(n).flat().map(e=>xt(R(e)));if(s.some(e=>e===``)||c.some(e=>e===``))return new I(P(`The delimiters cannot be empty values.`));let l=z(r),u=L(i,this.locale);if(![0,1].includes(u))return new I(P(`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 os(d)},isExported:!0},b0={description:P(`Removes space characters.`),args:[U(`text (string)`,P(`The text or reference to a cell containing text to be trimmed.`))],compute:function(e){return ln(R(e))},isExported:!0},x0={description:P(`Converts a specified string to uppercase.`),args:[U(`text (string)`,P(`The string to convert to uppercase.`))],compute:function(e){return R(e).toUpperCase()},isExported:!0},S0={description:P(`Converts a number to text according to a specified format.`),args:[U(`number (number)`,P(`The number, date or time to format.`)),U(`format (string)`,P(`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(L(e,this.locale),{format:R(t),locale:this.locale})},isExported:!0},C0={description:P(`Converts a string to a numeric value.`),args:[U(`value (number)`,P(`the string to be converted`))],compute:function(e){return L(e,this.locale)},isExported:!0},w0={description:P(`Returns text that occurs after a given substring or delimiter.`),args:[U(`text (string)`,P(`The source text.`)),U(`delimiter (string)`,P(`The substring after which text will be returned.`)),U(`instance_num (number, default=1)`,P(`The desired instance of the delimiter after which we extract the text. A negative number searches from the end.`)),U(`match_mode (number, default=0)`,P(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),X1),U(`match_end (number, default=0))`,P(`Whether to treat the end of text as a delimiter.`),Z1),U(`if_not_found (string, default="${F.NotAvailable}")`,P(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Do){let o=R(e),s=L(n,this.locale),c=L(r,this.locale),l=L(i,this.locale);if(s===0)return new I(P(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new I(P(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new I(P(`match_end should have a value of 0 or 1.`));let u=R(t);if(u===``)return Math.sign(s)>0?{value:o}:{value:``};let d=c===1?`gi`:`g`,f=xt(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+u.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},T0={description:P(`Returns text that occurs before a given substring or delimiter.`),args:[U(`text (string)`,P(`The source text.`)),U(`delimiter (string)`,P(`The substring after which text will be returned.`)),U(`instance_num (number, default=1)`,P(`The desired instance of the delimiter before which we extract the text. A negative number searches from the end.`)),U(`match_mode (number, default=0)`,P(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),X1),U(`match_end (number, default=0))`,P(`Whether to match a delimiter against the end of the text.`),Z1),U(`if_not_found (string, default="${F.NotAvailable}")`,P(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Do){let o=R(e),s=L(n,this.locale),c=L(r,this.locale),l=L(i,this.locale);if(s===0)return new I(P(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new I(P(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new I(P(`match_end should have a value of 0 or 1.`));let u=R(t);if(u===``)return Math.sign(s)>0?{value:``}:{value:o};let d=c===1?`gi`:`g`,f=xt(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+u.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 E0=l({HYPERLINK:()=>D0});let D0={description:P(`Creates a hyperlink in a cell.`),args:[U(`url (string)`,P(`The full URL of the link enclosed in quotation marks.`)),U(`link_label (string, optional)`,P(`The text to display in the cell, enclosed in quotation marks.`))],compute:function(e,t){let n=R(e).trim(),r=R(t)||n;return n===``?r:Pt(r,n)},isExported:!0},O0=[{name:P(`Array`),functions:UK},{name:P(`Database`),functions:JY},{name:P(`Date`),functions:uZ},{name:P(`Filter`),functions:JZ},{name:P(`Financial`),functions:eQ},{name:P(`Info`),functions:l$},{name:P(`Lookup`),functions:R$},{name:P(`Logical`),functions:S$},{name:P(`Math`),functions:yq},{name:P(`Operator`),functions:c1},{name:P(`Statistical`),functions:FJ},{name:P(`Text`),functions:J1},{name:P(`Engineering`),functions:KZ},{name:P(`Web`),functions:E0},{name:P(`Parser`),functions:K1}];for(let e of O0){let t=e.functions;for(let n in t){let r=t[n];r.category=r.category||e.name,n=n.replace(/_/g,`.`),al.add(n,{isExported:!1,...r})}}let k0={},A0={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},j0={autoCompleteProviders:iA,autofillModifiersRegistry:eB,autofillRulesRegistry:tB,cellMenuRegistry:FI,colMenuRegistry:$I,errorTypes:Co,functionRegistry:al,featurePluginRegistry:eH,iconsOnCellRegistry:Pz,statefulUIPluginRegistry:tH,coreViewsPluginRegistry:nH,corePluginRegistry:$V,rowMenuRegistry:oL,sidePanelRegistry:tF,figureRegistry:j_,chartSidePanelComponentRegistry:AA,chartDataSourceSidePanelComponentRegistry:CE,chartComponentRegistry:s_,chartTypeRegistry:Tb,chartSubtypeRegistry:Hg,chartDataSourceRegistry:wb,topbarMenuRegistry:OH,topbarComponentRegistry:qH,topBarToolBarRegistry:YU,clickableCellRegistry:rH,otRegistry:TB,inverseCommandRegistry:oH,urlRegistry:Vd,cellPopoverRegistry:cw,numberFormatMenuRegistry:wH,repeatLocalCommandTransformRegistry:wV,repeatCommandTransformRegistry:CV,clipboardHandlersRegistries:ZL,pivotRegistry:qN,pivotTimeAdapterRegistry:LS,pivotSidePanelRegistry:cP,pivotNormalizationValueRegistry:hC,supportedPivotPositionalFormulaRegistry:AR,pivotToFunctionValueRegistry:gC,migrationStepRegistry:PC,chartJsExtensionRegistry:Wr,onIterationEndEvaluationRegistry:wz,specificRangeTransformRegistry:EB},M0={arg:U,isEvaluationError:Po,toBoolean:z,toJsDate:Jo,toNumber:L,toString:R,toNormalizedPivotValue:dC,toFunctionPivotValue:pC,toXC:E,toZone:Wn,toUnboundedZone:Un,toCartesian:Nn,numberToLetters:wn,lettersToNumber:Tn,UuidGenerator:G,formatValue:H,createCurrencyFormat:bc,ColorGenerator:jp,computeTextWidth:bf,createEmptyWorkbookData:ew,createEmptySheet:$C,createEmptyExcelSheet:tw,doesCellContainFunction:bn,rgbaToHex:rp,colorToRGBA:ip,positionToZone:O,isDefined:w,isMatrix:ht,lazy:Gt,genericRepeat:KH,createAction:xe,createActions:_e,transformRangeData:Nr,deepEquals:T,overlap:ir,union:er,isInside:or,deepCopy:x,expandZoneOnInsertion:Xn,reduceZoneOnDeletion:$n,unquote:wt,getMaxObjectId:rC,getFirstPivotFunction:QN,getNumberOfPivotFunctions:eP,parseDimension:oC,isDateOrDatetimeField:sC,makeFieldProposal:tP,periodYearToComparable:IS,insertTokenAfterArgSeparator:rP,insertTokenAfterLeftParenthesis:iP,mergeContiguousZones:Ar,getPivotHighlights:WM,pivotTimeAdapter:RS,UNDO_REDO_PIVOT_COMMANDS:Zz,createPivotFormula:uC,areDomainArgsFieldsValid:lC,splitReference:vl,sanitizeSheetName:Et,getUniqueText:_n,isNumber:uo,isDateTime:Ma,createCustomFields:SC,schemeToColorScale:jC,isDateTimeFormat:pc,jsDateToNumber:Ka,numberToJsDate:Wa,DateTime:va,parseFormat:Ls,isFormula:vn,domainToColRowDomain:vN,collapseHierarchicalDisplayName:OC,getCanonicalSymbolName:Tt,fuzzyLookup:rA,PositionMap:aF,replaceSymbolInFormula:Zu},N0={isMarkdownLink:Mt,parseMarkdownLink:Ft,markdownLink:Pt,openLink:Kd,urlRepresentation:Gd},P0={Checkbox:wE,Section:Z,Select:T_,RoundColorPicker:QE,ChartDataSeries:IE,ChartErrorSection:BE,ChartLabelRange:LE,ChartRangeDataSourceComponent:hk,ChartTitle:YE,ChartPanel:PA,ChartFigure:k_,ChartJsComponent:Rh,ClickableCellSortIcon:jR,ZoomableChartJsComponent:$g,Grid:kR,GridOverlay:rR,ScorecardChart:ag,GaugeChartComponent:a_,LineConfigPanel:hA,BarConfigPanel:HE,PieChartDesignPanel:vA,GenericChartConfigPanel:VE,ChartWithAxisDesignPanel:aD,GenericZoomableChartDesignPanel:oD,LineChartDesignPanel:gA,GaugeChartConfigPanel:Nk,GaugeChartDesignPanel:uA,ScorecardChartConfigPanel:xA,ScorecardChartDesignPanel:SA,GeoChartDesignPanel:pA,RadarChartDesignPanel:yA,WaterfallChartDesignPanel:kA,ComboChartDesignPanel:Ak,FunnelChartDesignPanel:Mk,SunburstChartDesignPanel:CA,TreeMapChartDesignPanel:OA,ChartTypePicker:MA,FigureComponent:M_,MenuPopover:w_,Popover:b_,SelectionInput:FE,StandaloneComposer:lA,ValidationMessages:zE,AddDimensionButton:oN,PivotDimensionGranularity:cN,PivotDimensionOrder:lN,PivotDimension:rN,PivotLayoutConfigurator:pN,PivotHTMLRenderer:NR,PivotDeferUpdate:KM,PivotTitleSection:mN,CogWheelMenu:xE,TextInput:mE,SidePanelCollapsible:WE,RadioSelection:ZE,GeoChartRegionSelectSection:dA,ChartMenu:D_,FullScreenFigure:MR,NumberInput:KE,TopBar:XU,Composer:Wk},F0={useDragAndDropListItems:oE,useHighlights:LA,useHighlightsOnHover:IA},I0={Component:A,useExternalListener:Ii,EnvPlugin:Ri,App:Ui},L0={useStoreProvider:qi,DependencyContainer:Gi,CellPopoverStore:lw,ComposerFocusStore:Ur,CellComposerStore:LL,FindAndReplaceStore:wj,HighlightStore:ME,DelayedHoveredCellStore:N_,HoveredTableStore:eR,ModelStore:Ir,NotificationStore:aA,RendererStore:Br,SelectionInputStore:PE,SpreadsheetStore:Vr,useStore:j,useLocalStore:Ji,SidePanelStore:rF,PivotSidePanelStore:oP,PivotMeasureDisplayPanelStore:HM,ClientFocusStore:cL,GridRenderer:fR};function R0(e,t){return al.add(e,t),{addFunction:(e,t)=>R0(e,t)}}let z0={DEFAULT_LOCALE:V,HIGHLIGHT_COLOR:De,PIVOT_STATIC_TABLE_CONFIG:st,PIVOT_INSERT_TABLE_STYLE_ID:ct,ChartTerms:L_,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2,CHART_TYPES:AC,DARK_MODE_FILTER_STRING:hp},B0={...mk,...PR};e.AbstractCellClipboardHandler=pV,e.AbstractChart=zh,e.AbstractFigureClipboardHandler=sK,e.BadExpressionError=wo,e.CHART_TYPES=AC,e.CellErrorType=F,e.CellValueType=yd,e.CircularDependencyError=To,e.ClientDisconnectedError=sV,e.ClipboardMIMEType=uw,e.CommandResult=zd,e.CompiledFormula=fd,e.CorePlugin=lv,e.CoreViewPlugin=oF,e.DEFAULT_LOCALE=V,e.DEFAULT_LOCALES=Ss,e.DEFAULT_LOCALE_DIGIT_GROUPING=`[3,0]`,e.DIRECTION=_t,e.DispatchResult=Ld,e.DivisionByZeroError=Ao,e.EvaluationError=I,e.InvalidReferenceError=Eo,e.LocalTransportService=JH,e.Model=iK,e.NEXT_VALUE=F_,e.NotAvailableError=Do,e.NumberTooLargeError=jo,e.OrderedLayers=Rr,e.PREVIOUS_VALUE=P_,e.PivotRuntimeDefinition=qM,e.Registry=k,e.Revision=oV,e.SPREADSHEET_DIMENSIONS=A0,e.SplillBlockedError=ko,e.Spreadsheet=$U,e.SpreadsheetPivotTable=FN,e.UIPlugin=fB,e.UnknownFunctionError=Oo,e.__info__=k0,e.addFunction=R0,e.addRenderingLayer=zr,e.astToFormula=NL,e.availableConditionalFormatOperators=lj,e.availableDataValidationOperators=xj,e.availableFiltersOperators=YM,e.borderPositions=gt,e.borderStyles=mt,e.canExecuteInReadonly=Id,e.categories=O0,e.chartHelpers=B0,e.compatibility=I0,e.components=P0,e.composerFocusTypes=vt,e.constants=z0,e.convertAstNodes=pu,e.coreTypes=Pd,e.createAutocompleteArgumentsProvider=TK,e.errorTypes=Co,e.filterDateCriterionOperators=QM,e.filterNumberCriterionOperators=ZM,e.filterTextCriterionOperators=XM,e.findCellInNewZone=_r,e.functionCache=ud,e.getCaretDownSvg=Dy,e.getCaretUpSvg=Oy,e.helpers=M0,e.hooks=F0,e.invalidSubtotalFormulasCommands=jd,e.invalidateBordersCommands=Ad,e.invalidateCFEvaluationCommands=kd,e.invalidateChartEvaluationCommands=Dd,e.invalidateDependenciesCommands=Od,e.invalidateEvaluationCommands=Ed,e.isCoreCommand=Fd,e.isHeadersDependant=xd,e.isMatrix=ht,e.isPositionDependent=wd,e.isRangeDependant=Cd,e.isSheetDependent=bd,e.isTargetDependent=Sd,e.isZoneDependent=Td,e.iterateAstNodes=mu,e.links=N0,e.load=zC,e.lockedSheetAllowedCommands=Nd,e.parse=du,e.parseTokens=fu,e.readonlyAllowedCommands=Md,e.registries=j0,e.schemeToColorScale=jC,e.setDefaultSheetViewSize=at,e.setTranslationMethod=bo,e.stores=L0,e.tokenColors=pt,e.tokenize=Al,k0.version=`19.4.4`,k0.date=`2026-07-23T07:49:22.265Z`,k0.hash=`6b3c312`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|