@odoo/o-spreadsheet 19.1.0-alpha.6 → 19.1.0-alpha.7
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-engine.esm.js +4 -4
- package/dist/o-spreadsheet-engine.iife.js +4 -4
- package/dist/o-spreadsheet-engine.min.iife.js +1 -1
- package/dist/o_spreadsheet.esm.js +6 -6
- package/dist/o_spreadsheet.iife.js +6 -6
- package/dist/o_spreadsheet.min.iife.js +1 -1
- package/dist/o_spreadsheet.xml +3 -3
- package/package.json +1 -2
|
@@ -840,4 +840,4 @@
|
|
|
840
840
|
offset="offset"
|
|
841
841
|
direction="'vertical'"
|
|
842
842
|
onScroll.bind="onScroll"
|
|
843
|
-
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){const{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{y:e}=this.env.model.getters.getMainViewportRect();return{top:`${this.props.topOffset+e}px`,right:"0px",width:"15px",bottom:By()?"15px":"0"}}onScroll(e){const{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:t,offsetY:e})}}class RU extends t.Component{static template="o-spreadsheet-Selection";static props={};static components={Highlight:CU};get highlightProps(){const 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:l}}}function xU({refName:e}){const s=t.useRef(e);t.useEffect(e=>{e?.focus()},()=>[s.el])}class TU extends t.Component{static template="o-spreadsheet-TextInput";static props={value:String,onChange:Function,class:{type:String,optional:!0},id:{type:String,optional:!0},placeholder:{type:String,optional:!0},autofocus:{type:Boolean,optional:!0},alwaysShowBorder:{type:Boolean,optional:!0}};inputRef=t.useRef("input");setup(){t.useExternalListener(window,"click",e=>{e.target!==this.inputRef.el&&this.inputRef.el?.value!==this.props.value&&this.save()},{capture:!0}),this.props.autofocus&&xU({refName:"input"})}onKeyDown(e){switch(e.key){case"Enter":this.save(),e.preventDefault(),e.stopPropagation();break;case"Escape":this.inputRef.el&&(this.inputRef.el.value=this.props.value,this.inputRef.el.blur()),e.preventDefault(),e.stopPropagation()}}save(){const e=(this.inputRef.el?.value||"").trim();e!==this.props.value&&this.props.onChange(e),this.inputRef.el?.blur()}onMouseDown(e){e.target!==document.activeElement&&(e.preventDefault(),e.stopPropagation())}onMouseUp(e){const t=e.target;t!==document.activeElement&&(t.focus(),t.select(),e.preventDefault(),e.stopPropagation())}get inputClass(){return[this.props.class,this.props.alwaysShowBorder?"o-input-border":void 0].filter(Te).join(" ")}}class AU extends t.Component{static template="o-spreadsheet-ActionButton";static props={action:Object,hasTriangleDownIcon:{type:Boolean,optional:!0},selectedColor:{type:String,optional:!0},class:{type:String,optional:!0},onClick:{type:Function,optional:!0}};actionButton=jf(this.props.action);setup(){t.onWillUpdateProps(e=>{e.action!==this.props.action&&(this.actionButton=jf(e.action))})}get isVisible(){return this.actionButton.isVisible(this.env)}get isEnabled(){return this.actionButton.isEnabled(this.env)}get isActive(){return this.actionButton.isActive?.(this.env)}get title(){const e=this.actionButton.name(this.env),t=this.actionButton.description(this.env);return e+(t?` (${t})`:"")}get iconTitle(){return this.actionButton.icon(this.env)}onClick(e){this.isEnabled&&(this.props.onClick?.(e),this.actionButton.execute?.(this.env))}get buttonStyle(){return this.props.selectedColor?Ey({"border-bottom":`4px solid ${this.props.selectedColor}`,height:"16px","margin-top":"2px"}):""}}class DU extends t.Component{static template="o-spreadsheet-ColorPickerWidget";static props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={ColorPicker:rM};colorPickerButtonRef=t.useRef("colorPickerButton");get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:"border-bottom-style: hidden"}get colorPickerAnchorRect(){const e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}}class _U extends t.Component{static template="o-spreadsheet-FontSizeEditor";static props={currentFontSize:Number,onFontSizeChanged:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String};static defaultProps={onFocusInput:()=>{}};static components={Popover:DF};fontSizes=K;dropdown=t.useState({isOpen:!1});inputRef=t.useRef("inputFontSize");rootEditorRef=t.useRef("FontSizeEditor");fontSizeListRef=t.useRef("fontSizeList");setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}get popoverProps(){const{x:e,y:t,width:s,height:o}=this.rootEditorRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:s,height:o},positioning:"bottom-left",verticalOffset:0}}onExternalClick(e){Dy(this.fontSizeListRef.el,e)||Dy(this.rootEditorRef.el,e)||this.closeFontList()}toggleFontList(){this.dropdown.isOpen?this.closeFontList():(this.props.onToggle?.(),this.inputRef.el.focus())}closeFontList(){this.dropdown.isOpen=!1}setSize(e){const t=ue(Math.floor(parseFloat(e)),1,400);this.props.onFontSizeChanged(t),this.closeFontList()}setSizeFromInput(e){this.setSize(e.target.value)}setSizeFromList(e){this.setSize(e)}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if("Enter"===e.key||"Escape"===e.key){this.closeFontList();const t=e.target;"Escape"===e.key&&(t.value=`${this.props.currentFontSize}`),this.props.onToggle?.()}}}class OU extends t.Component{static template="o-spreadsheet.TextStyler";static components={ColorPickerWidget:DU,ActionButton:AU,FontSizeEditor:_U};static props={style:Object,updateStyle:{type:Function,optional:!0},defaultStyle:{type:Object,optional:!0},hasVerticalAlign:{type:Boolean,optional:!0},hasHorizontalAlign:{type:Boolean,optional:!0},hasBackgroundColor:{type:Boolean,optional:!0},class:{type:String,optional:!0}};openedEl=null;setup(){t.useExternalListener(window,"click",this.onExternalClick)}state=t.useState({activeTool:""});updateFontSize(e){this.props.updateStyle?.({...this.props.style,fontSize:e})}toggleDropdownTool(e,t){const s=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=s?"":e,this.openedEl=s?null:t.target}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onTextColorChange(e){this.props.updateStyle?.({...this.props.style,color:e}),this.closeMenus()}onFillColorChange(e){this.props.updateStyle?.({...this.props.style,fillColor:e}),this.closeMenus()}updateAlignment(e){this.props.updateStyle?.({...this.props.style,align:e}),this.closeMenus()}updateVerticalAlignment(e){this.props.updateStyle?.({...this.props.style,verticalAlign:e}),this.closeMenus()}toggleBold(){this.props.updateStyle?.({...this.props.style,bold:!this.bold})}toggleItalic(){this.props.updateStyle?.({...this.props.style,italic:!this.italic})}closeMenus(){this.state.activeTool="",this.openedEl=null}get align(){return this.props.style.align??this.props.defaultStyle?.align}get verticalAlign(){return this.props.style.verticalAlign||this.props.defaultStyle?.verticalAlign}get bold(){return this.props.style.bold??this.props.defaultStyle?.bold}get italic(){return this.props.style.italic??this.props.defaultStyle?.italic}get currentFontSize(){return this.props.style.fontSize??this.props.defaultStyle?.fontSize??P.fontSize}get boldButtonAction(){return{name:fs("Bold"),execute:()=>this.toggleBold(),isActive:()=>this.bold||!1,icon:"o-spreadsheet-Icon.BOLD"}}get italicButtonAction(){return{name:fs("Italic"),execute:()=>this.toggleItalic(),isActive:()=>this.italic||!1,icon:"o-spreadsheet-Icon.ITALIC"}}get horizontalAlignButtonAction(){let e="o-spreadsheet-Icon.ALIGN_LEFT";return"center"===this.align?e="o-spreadsheet-Icon.ALIGN_CENTER":"right"===this.align&&(e="o-spreadsheet-Icon.ALIGN_RIGHT"),{name:fs("Horizontal alignment"),icon:e}}get horizontalAlignActions(){return[{name:fs("Left"),execute:()=>this.updateAlignment("left"),isActive:()=>"left"===this.align,icon:"o-spreadsheet-Icon.ALIGN_LEFT"},{name:fs("Center"),execute:()=>this.updateAlignment("center"),isActive:()=>"center"===this.align,icon:"o-spreadsheet-Icon.ALIGN_CENTER"},{name:fs("Right"),execute:()=>this.updateAlignment("right"),isActive:()=>"right"===this.align,icon:"o-spreadsheet-Icon.ALIGN_RIGHT"}]}get verticalAlignButtonAction(){let e="o-spreadsheet-Icon.ALIGN_MIDDLE";return"top"===this.verticalAlign?e="o-spreadsheet-Icon.ALIGN_TOP":"bottom"===this.verticalAlign&&(e="o-spreadsheet-Icon.ALIGN_BOTTOM"),{name:fs("Vertical alignment"),icon:e}}get verticalAlignActions(){return[{name:fs("Top"),execute:()=>this.updateVerticalAlignment("top"),isActive:()=>"top"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_TOP"},{name:fs("Middle"),execute:()=>this.updateVerticalAlignment("middle"),isActive:()=>"middle"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},{name:fs("Bottom"),execute:()=>this.updateVerticalAlignment("bottom"),isActive:()=>"bottom"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"}]}}class FU extends t.Component{static template="o-spreadsheet-CogWheelMenu";static components={MenuPopover:PF};static props={items:Array};buttonRef=t.useRef("button");menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});menuId=this.env.model.uuidGenerator.uuidv4();toggleMenu(e){e.closedMenuId!==this.menuId&&(this.menuState.isOpen=!this.menuState.isOpen,this.menuState.anchorRect=Fy(this.buttonRef.el),this.menuState.menuItems=qf(this.props.items))}}class PU extends t.Component{static template="o-spreadsheet-CarouselPanel";static props={onCloseSidePanel:Function,figureId:String};static components={Section:aM,TextInput:TU,TextStyler:OU,CogWheelMenu:FU};DEFAULT_CAROUSEL_TITLE_STYLE=te;dragAndDrop=cM();previewListRef=t.useRef("previewList");setup(){let e=[...this.carouselItems];t.onWillUpdateProps(()=>{Me(this.carouselItems,e)||this.dragAndDrop.cancel(),e=[...this.carouselItems]})}get carouselItems(){return this.env.model.getters.getCarousel(this.props.figureId).items}get title(){return this.env.model.getters.getCarousel(this.props.figureId).title}get carousel(){return this.env.model.getters.getCarousel(this.props.figureId)}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[this.getItemId(e)]||""}getItemId(e){return"chart"===e.type?e.chartId:"transparent-carousel"}addNewChartToCarousel(){this.env.model.dispatch("ADD_NEW_CHART_TO_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId})}get hasDataView(){return this.carouselItems.some(e=>"carouselDataView"===e.type)}isCarouselItemActive(e){return Me(this.env.model.getters.getSelectedCarouselItem(this.props.figureId),e)}addDataViewToCarousel(){const e=this.env.model.getters.getCarousel(this.props.figureId);this.updateItems([...e.items,{type:"carouselDataView"}])}activateCarouselItem(e){this.env.model.dispatch("UPDATE_CAROUSEL_ACTIVE_ITEM",{figureId:this.props.figureId,sheetId:this.carouselSheetId,item:e})}editCarouselItem(e){"chart"===e.type&&(this.activateCarouselItem(e),this.env.model.dispatch("SELECT_FIGURE",{figureId:this.props.figureId}),this.env.openSidePanel("ChartPanel",{chartId:e.chartId}))}renameCarouselItem(e,t){const s=t.trim();if(!s||s===this.getItemTitle(e).toString())return;const o=[...this.carouselItems],i=this.carouselItems.findIndex(t=>Me(t,e));-1!==i&&(o[i]={...e,title:s},this.updateItems(o))}deleteCarouselItem(e){const t=this.env.model.getters.getCarousel(this.props.figureId).items.filter(t=>!Me(t,e));this.updateItems(t)}popOutCarouselItem(e){"chart"===e.type&&this.env.model.dispatch("POPOUT_CHART_FROM_CAROUSEL",{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId})}onDragHandleMouseDown(e,t){if(0!==t.button)return;const s=Array.from(this.previewListRef.el.children).map(e=>Fy(e)),o=this.carouselItems.map((e,t)=>({id:this.getItemId(e),size:s[t].height,position:s[t].y}));this.dragAndDrop.start("vertical",{draggedItemId:this.getItemId(e),initialMousePosition:t.clientY,items:o,scrollableContainerEl:this.previewListRef.el,onDragEnd:(t,s)=>this.onDragEnd(e,s)})}onDragEnd(e,t){const s=this.carouselItems.findIndex(t=>Me(t,e));if(-1===s||s===t)return;const o=[...this.env.model.getters.getCarousel(this.props.figureId).items];o.splice(s,1),o.splice(t,0,e),this.updateItems(o)}getItemTitle(e){return b_(this.env.model.getters,e)}getItemPreview(e){return function(e,t){if("carouselDataView"===t.type)return"o-spreadsheet-Icon.DATA";const s=e.getChartDefinition(t.chartId);return(f_.getAll().find(e=>e.matcher?.(s))||f_.get(s.type)).preview}(this.env.model.getters,e)}updateItems(e){this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...this.carousel,items:e}})}updateTitleText(e){const t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,text:e}}})}updateTitleStyle(e){const t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,...e}}})}get carouselAddChartInfoMessage(){return fs("Add a chart to the carousel. You can also add a chart by dragging and dropping it over the carousel figure.")}getCogWheelMenuItems(e){const t=[];return"chart"===e.type&&(t.push({name:fs("Edit chart"),execute:()=>this.editCarouselItem(e),icon:"o-spreadsheet-Icon.EDIT"}),t.push({name:fs("Pop out chart"),execute:()=>this.popOutCarouselItem(e),icon:"o-spreadsheet-Icon.EXTERNAL"})),t.push({name:fs("Delete item"),execute:()=>this.deleteCarouselItem(e),icon:"o-spreadsheet-Icon.TRASH"}),t}get carouselSheetId(){const e=this.env.model.getters.getFigureSheetId(this.props.figureId);if(!e)throw new Error("Could not find the sheetId of the carousel figure");return e}get carouselDataViewMessage(){return fs("The data view makes the carousel transparent, revealing the data underneath.")}}class MU extends t.Component{static template="o-spreadsheet.ChartDataSeries";static components={SelectionInput:fM,Section:aM};static props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},onSelectionChanged:Function,onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},onSelectionConfirmed:Function,title:{type:String,optional:!0},maxNumberOfUsedRanges:{type:Number,optional:!0},datasetOrientation:{type:String,optional:!0},canChangeDatasetOrientation:{type:Boolean,optional:!0},onFlipAxis:{type:Function,optional:!0}};get ranges(){return this.props.ranges.map(e=>e.dataRange)}get disabledRanges(){return this.props.ranges.map((e,t)=>!!this.props.maxNumberOfUsedRanges&&t>=this.props.maxNumberOfUsedRanges)}get colors(){return this.props.ranges.map(e=>e.backgroundColor)}get title(){return this.props.title?this.props.title:this.props.hasSingleRange?fs("Data range"):fs("Data series")}}class NU extends t.Component{static template="o-spreadsheet.ChartErrorSection";static components={Section:aM,ValidationMessages:JV};static props={messages:{type:Array,element:String}}}class LU extends t.Component{static template="o-spreadsheet.ChartLabelRange";static components={SelectionInput:fM,Checkbox:IM,Section:aM};static props={title:{type:String,optional:!0},range:String,isInvalid:Boolean,onSelectionChanged:Function,onSelectionConfirmed:Function,options:{type:Array,optional:!0}};static defaultProps={title:fs("Categories / Labels"),options:[]}}class kU extends t.Component{static template="o-spreadsheet-GenericChartConfigPanel";static components={ChartDataSeries:MU,ChartLabelRange:LU,Section:aM,Checkbox:IM,ChartErrorSection:NU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};state=t.useState({datasetDispatchResult:void 0,labelsDispatchResult:void 0});dataSets=[];labelRange;datasetOrientation=void 0;chartTerms=Ig;setup(){this.dataSets=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange,this.datasetOrientation=this.computeDatasetOrientation()}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[]].filter(e=>"NoChanges"!==e).map(e=>Ig.Errors[e]||Ig.Errors.Unexpected)}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause("InvalidDataSet")}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause("InvalidLabelRange")}get dataSetsHaveTitleLabel(){return"rows"===this.datasetOrientation?fs("Use col %(column_name)s as headers",{column_name:it(this.calculateHeaderPosition()||0)}):fs("Use row %(row_position)s as headers",{row_position:this.calculateHeaderPosition()||""})}getLabelRangeOptions(){const e=this.props.definition;return[{name:"aggregated",label:this.chartTerms.AggregatedChart,value:("aggregated"in e&&e.aggregated)??!1,onChange:this.onUpdateAggregated.bind(this)},{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.chartId,{dataSetsHaveTitle:e})}get canChangeDatasetOrientation(){const e=new Set,t=[],s=this.env.model.getters.getActiveSheetName(),o=this.dataSets.map(e=>e.dataRange);this.labelRange&&o.push(this.labelRange);for(const i of o){if(!Et(i))return!1;const o=tr(i),n=It(o.xc);if(void 0===n.bottom||void 0===n.right)return!1;if(t.push(n),e.add(o.sheetName||s),e.size>1)return!1}const i=es(t);if(1!==i.length)return!1;const{left:n,right:r,top:a,bottom:l}=i[0];return!t.some(e=>!(e.top===a&&e.bottom===l||e.left===n&&e.right===r))}computeDatasetOrientation(){let e=!1,t=!1;for(const s of this.dataSets){if(!Et(s.dataRange))return;const o=It(s.dataRange);if(void 0===o.bottom||void 0===o.right)return;o.top===o.bottom&&(e=!0),o.left===o.right&&(t=!0)}return e&&!t?"rows":!e&&t?"columns":void 0}setDatasetOrientation(e){const t=this.props.definition.dataSets.map(e=>e.dataRange),s=this.transposeDataSet([this.props.definition.labelRange,...t],e);if(0===s.length)return;const o=s.length>1?s.shift().dataRange:"";this.props.updateChart(this.props.chartId,{labelRange:o,dataSets:s}),this.dataSets=s,this.labelRange=o,this.datasetOrientation=e}onDataSeriesRangesChanged(e){this.dataSets=e.map((e,t)=>({...this.dataSets?.[t],dataRange:e})),this.state.datasetDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesReordered(e){const t=KC({dataSets:this.dataSets},this.dataSets.length);this.datasetOrientation=void 0;const s=this.dataSets.map(e=>t.next());this.dataSets=e.map(e=>({backgroundColor:s[e],...this.dataSets[e]})),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesRemoved(e){const t=KC({dataSets:this.dataSets},this.dataSets.length),s=this.dataSets.map(e=>t.next());this.dataSets=this.dataSets.map((e,t)=>({backgroundColor:s[t],...e})).filter((t,s)=>s!==e),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesConfirmed(){this.dataSets=this.splitRanges,this.datasetOrientation=this.computeDatasetOrientation(),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets}),this.state.datasetDispatchResult.isSuccessful&&(this.dataSets=this.env.model.getters.getChartDefinition(this.props.chartId).dataSets)}get splitRanges(){const e=[];for(const t of this.dataSets){const s=t.dataRange;if(!this.env.model.getters.isRangeValid(s)){e.push(t);continue}const{sheetName:o}=tr(s),i=o?`${o}!`:"",n=It(s);if(n.bottom!==n.top&&n.left!==n.right){if("rows"!==this.datasetOrientation){if(void 0!==n.right)for(let s=n.left;s<=n.right;++s){const o=s===n.left?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Tt({left:s,right:s,top:n.top,bottom:n.bottom})}`})}else if(void 0!==n.bottom)for(let s=n.top;s<=n.bottom;++s){const o=s===n.top?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Tt({left:n.left,right:n.right,top:s,bottom:s})}`})}}else if(void 0!==n.bottom)for(let s=n.top;s<=n.bottom;++s){const o=s===n.top?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Tt({left:n.left,right:n.right,top:s,bottom:s})}`})}else if(void 0!==n.right)for(let s=n.left;s<=n.right;++s){const o=s===n.left?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Tt({left:s,right:s,top:n.top,bottom:n.bottom})}`})}}else e.push(t)}return e}getDataSeriesRanges(){return this.dataSets}onLabelRangeChanged(e){this.labelRange=e[0],this.state.labelsDispatchResult=this.props.canUpdateChart(this.props.chartId,{labelRange:this.labelRange})}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.chartId,{labelRange:this.labelRange})}getLabelRange(){return this.labelRange||""}onUpdateAggregated(e){this.props.updateChart(this.props.chartId,{aggregated:e})}calculateHeaderPosition(){if(this.isDatasetInvalid||this.isLabelInvalid)return;const e=this.env.model.getters,t=e.getActiveSheetId(),s=Rb(e,t,this.labelRange),o=eC(e,this.dataSets,t,this.props.definition.dataSetsHaveTitle);return o.length?"rows"===this.datasetOrientation?o[0].dataRange.zone.left:o[0].dataRange.zone.top+1:s?s.zone.top+1:void 0}get maxNumberOfUsedRanges(){return $y.get(this.props.definition.type).dataSeriesLimit}transposeDataSet(e,t){const s=this.env.model.getters;if(void 0===t)return e.filter(Te).map(e=>({dataRange:e}));const o={},i=[],n=s.getFigureIdFromChartId(this.props.chartId),r=s.getFigureSheetId(n);let a=s.getActiveSheet().name;r&&(a=s.getSheet(r).name);for(const t of e){if(!t)continue;if(!Et(t))return e.filter(Te).map(e=>({dataRange:e}));let{sheetName:s,xc:i}=tr(t);s=s??a,o[s]||(o[s]=[]),o[s].push(wt(i))}for(const e in o){const s=es(o[e]);if("columns"===t)for(const t of s)for(let s=t.left;s<=t.right;s++){const o=`${e===a?"":e+"!"}${Tt({...t,left:s,right:s})}`;i.push({dataRange:o})}else for(const t of s)for(let s=t.top;s<=t.bottom;s++){const o=`${e===a?"":e+"!"}${Tt({...t,top:s,bottom:s})}`;i.push({dataRange:o})}}return i}}class VU extends kU{static template="o-spreadsheet-BarConfigPanel";get stackedLabel(){return this.props.definition.horizontal?this.chartTerms.StackedBarChart:this.chartTerms.StackedColumnChart}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}}class UU extends t.Component{static template="o-spreadsheet.BadgeSelection";static props={choices:Array,onChange:Function,selectedValue:String}}class HU extends t.Component{static template="o-spreadsheet.ChartTitle";static components={Section:aM,TextStyler:OU};static props={title:{type:String,optional:!0},placeholder:{type:String,optional:!0},updateTitle:Function,name:{type:String},style:Object,defaultStyle:{type:Object,optional:!0},updateStyle:Function};static defaultProps={title:"",placeholder:""};updateTitle(e){this.props.updateTitle(e.target.value)}}class zU extends t.Component{static template="o-spreadsheet-AxisDesignEditor";static components={Section:aM,ChartTitle:HU,BadgeSelection:UU};static props={chartId:String,definition:Object,updateChart:Function,axesList:Array};state=t.useState({currentAxis:"x"});defaultFontSize=12;get axisTitleStyle(){return this.props.definition.axesDesign?.[this.state.currentAxis]?.title??{}}get badgeAxes(){return this.props.axesList.map(e=>({value:e.id,label:e.name}))}updateAxisEditor(e){this.state.currentAxis=e.target.value}getAxisTitle(){const e=this.props.definition.axesDesign??{};return e[this.state.currentAxis]?.title.text||""}updateAxisTitle(e){const t=ae(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:{...t?.[this.state.currentAxis]?.title,text:e}},this.props.updateChart(this.props.chartId,{axesDesign:t})}updateAxisTitleStyle(e){const t=ae(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:e},this.props.updateChart(this.props.chartId,{axesDesign:t})}}class BU extends t.Component{static template="o-spreadsheet.RadioSelection";static props={choices:Array,onChange:Function,selectedValue:{optional:!1},name:String,direction:{type:String,optional:!0}};static defaultProps={direction:"horizontal"}}class GU extends t.Component{static template="o-spreadsheet-GeneralDesignEditor";static components={RoundColorPicker:lM,ChartTitle:HU,Section:aM,SidePanelCollapsible:DP,RadioSelection:BU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function,defaultChartTitleFontSize:{type:Number,optional:!0},slots:{type:Object,optional:!0}};static defaultProps={defaultChartTitleFontSize:R};state;setup(){this.state=t.useState({activeTool:""})}get title(){return this.props.definition.title}toggleDropdownTool(e,t){const s=this.state.activeTool===e;this.state.activeTool=s?"":e}updateBackgroundColor(e){this.props.updateChart(this.props.chartId,{background:e})}updateTitle(e){const t={...this.title,text:e};this.props.updateChart(this.props.chartId,{title:t})}updateChartTitleStyle(e){const t={...this.title,...e};this.props.updateChart(this.props.chartId,{title:t}),this.state.activeTool=""}}class WU extends t.Component{static template="o-spreadsheet-ChartHumanizeNumbers";static components={Checkbox:IM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function}}class $U extends t.Component{static template="o-spreadsheet-ChartLegend";static components={Section:aM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e.target.value})}}class qU extends t.Component{static template="o-spreadsheet-SeriesDesignEditor";static components={SidePanelCollapsible:DP,Section:aM,RoundColorPicker:lM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function,slots:{type:Object,optional:!0}};state=t.useState({index:0});getDataSeries(){const e=this.env.model.getters.getChartRuntime(this.props.chartId);return e&&"chartJsConfig"in e?e.chartJsConfig.data.datasets.filter(e=>!fC(e.xAxisID??"")).map(e=>e.label):[]}updateEditedSeries(e){this.state.index=e.target.selectedIndex}updateDataSeriesColor(e){const t=this.props.definition.dataSets;t?.[this.state.index]&&(t[this.state.index]={...t[this.state.index],backgroundColor:e},this.props.updateChart(this.props.chartId,{dataSets:t}))}getDataSeriesColor(){const e=this.props.definition.dataSets;if(!e?.[this.state.index])return"";const t=e[this.state.index].backgroundColor;return t?bv(t):zv(this.state.index,Bv(this.props.definition.dataSets.length))}updateDataSeriesLabel(e){const t=e.target.value,s=this.props.definition.dataSets;s?.[this.state.index]&&(s[this.state.index]={...s[this.state.index],label:t},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSeriesLabel(){const e=this.props.definition.dataSets;return e[this.state.index]?.label||this.getDataSeries()[this.state.index]}}class ZU extends t.Component{static template="o-spreadsheet-SeriesWithAxisDesignEditor";static components={SeriesDesignEditor:qU,Checkbox:IM,RadioSelection:BU,Section:aM,RoundColorPicker:lM};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function,slots:{type:Object,optional:!0}};axisChoices=gC;updateDataSeriesAxis(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],yAxisId:"left"===t?"y":"y1"},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSerieAxis(e){const t=this.props.definition.dataSets;return t?.[e]&&"y1"===t[e].yAxisId?"right":"left"}get canHaveTwoVerticalAxis(){return!("horizontal"in this.props.definition&&this.props.definition.horizontal)}toggleDataTrend(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],trend:{type:"polynomial",order:1,...s[e].trend,display:t}},this.props.updateChart(this.props.chartId,{dataSets:s}))}getTrendLineConfiguration(e){const t=this.props.definition.dataSets;return t?.[e]?.trend}getTrendType(e){return e?"polynomial"===e.type&&1===e.order?"linear":e.type:""}onChangeTrendType(e,t){const s=t.target.value;let o;switch(s){case"linear":case"polynomial":o={type:"polynomial",order:"linear"===s?1:this.getMaxPolynomialDegree(e)};break;case"exponential":case"logarithmic":case"trailingMovingAverage":o={type:s};break;default:return}this.updateTrendLineValue(e,o)}getPolynomialDegrees(e){return ge(1,this.getMaxPolynomialDegree(e)+1)}onChangePolynomialDegree(e,t){const s=t.target;this.updateTrendLineValue(e,{order:parseInt(s.value)})}getMaxPolynomialDegree(e){const t=this.env.model.getters.getChartRuntime(this.props.chartId);return Math.min(10,t.chartJsConfig.data.datasets[e].data.length-1)}get defaultWindowSize(){return 2}onChangeMovingAverageWindow(e,t){const s=t.target;let o=parseInt(s.value)||2;o<=1&&(o=2),this.updateTrendLineValue(e,{window:o})}getDataSeriesColor(e){const t=this.props.definition.dataSets;if(!t?.[e])return"";const s=t[e].backgroundColor;return s?bv(s):zv(e,Bv(this.props.definition.dataSets.length))}getTrendLineColor(e){return this.getTrendLineConfiguration(e)?.color??_v(this.getDataSeriesColor(e),.5)}updateTrendLineColor(e,t){this.updateTrendLineValue(e,{color:t})}updateTrendLineValue(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],trend:{...s[e].trend,...t}},this.props.updateChart(this.props.chartId,{dataSets:s}))}}class jU extends t.Component{static template="o-spreadsheet-ChartShowValues";static components={Checkbox:IM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function,defaultValue:{type:Boolean,optional:!0}}}class YU extends t.Component{static template="o-spreadsheet-ChartWithAxisDesignPanel";static components={GeneralDesignEditor:GU,SidePanelCollapsible:DP,Section:aM,AxisDesignEditor:zU,SeriesWithAxisDesignEditor:ZU,ChartLegend:$U,ChartShowValues:jU,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function};get axesList(){const{useLeftAxis:e,useRightAxis:t}=hC(this.props.definition),s=[{id:"x",name:fs("Horizontal axis")}];return e&&s.push({id:"y",name:fs(t?"Left axis":"Vertical axis")}),t&&s.push({id:"y1",name:fs(e?"Right axis":"Vertical axis")}),s}}class XU extends t.Component{static template="o-spreadsheet-ChartShowDataMarkers";static components={Checkbox:IM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function}}class KU extends YU{static template="o-spreadsheet-GenericZoomableChartDesignPanel";static components={...YU.components,Checkbox:IM};onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}}class JU extends KU{static template="o-spreadsheet-ComboChartDesignPanel";static components={...KU.components,ChartShowDataMarkers:XU,RadioSelection:BU};seriesTypeChoices=[{value:"bar",label:fs("Bar")},{value:"line",label:fs("Line")}];updateDataSeriesType(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],type:t},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSeriesType(e){const t=this.props.definition.dataSets;return t?.[e]?t[e].type??"line":"bar"}}class QU extends t.Component{static template="o-spreadsheet-FunnelChartDesignPanel";static components={ChartShowValues:jU,GeneralDesignEditor:GU,SidePanelCollapsible:DP,RoundColorPicker:lM,Section:aM,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};getFunnelColorItems(){const e=this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig.data.labels||[],t=BC(e,this.props.definition.funnelColors);return e.map((e,s)=>({label:e||fs("Value %s",s+1),color:t[s]}))}updateFunnelItemColor(e,t){const s=je(this.props.definition.funnelColors||[],t,e);this.props.updateChart(this.props.chartId,{funnelColors:s})}}class eH extends t.Component{static template="o-spreadsheet-GaugeChartConfigPanel";static components={ChartErrorSection:NU,ChartDataSeries:MU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};state=t.useState({dataRangeDispatchResult:void 0});dataRange=this.props.definition.dataRange;get configurationErrorMessages(){return[...this.state.dataRangeDispatchResult?.reasons||[]].map(e=>Ig.Errors[e]||Ig.Errors.Unexpected)}get isDataRangeInvalid(){return!!this.state.dataRangeDispatchResult?.isCancelledBecause("InvalidGaugeDataRange")}onDataRangeChanged(e){this.dataRange=e[0],this.state.dataRangeDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataRange:this.dataRange})}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.chartId,{dataRange:this.dataRange})}getDataRange(){return{dataRange:this.dataRange||""}}}class tH extends t.Component{static template="o-spreadsheet-GaugeChartDesignPanel";static components={SidePanelCollapsible:DP,Section:aM,RoundColorPicker:lM,GeneralDesignEditor:GU,ChartErrorSection:NU,StandaloneComposer:JP,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};state;setup(){this.state=t.useState({sectionRuleCancelledReasons:this.checkSectionRuleFormulasAreValid(this.props.definition.sectionRule),sectionRule:ae(this.props.definition.sectionRule)})}get designErrorMessages(){return[...this.state.sectionRuleCancelledReasons||[]].map(e=>Ig.Errors[e]||Ig.Errors.Unexpected)}get isRangeMinInvalid(){return!(!this.state.sectionRuleCancelledReasons?.includes("EmptyGaugeRangeMin")&&!this.state.sectionRuleCancelledReasons?.includes("GaugeRangeMinNaN"))}get isRangeMaxInvalid(){return!(!this.state.sectionRuleCancelledReasons?.includes("EmptyGaugeRangeMax")&&!this.state.sectionRuleCancelledReasons?.includes("GaugeRangeMaxNaN"))}get isLowerInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.includes("GaugeLowerInflectionPointNaN")}get isUpperInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.includes("GaugeUpperInflectionPointNaN")}updateSectionColor(e,t){const s=ae(this.state.sectionRule);s.colors[e]=t,this.updateSectionRule(s)}updateSectionRule(e){this.state.sectionRuleCancelledReasons=[],this.state.sectionRuleCancelledReasons.push(...this.checkSectionRuleFormulasAreValid(this.state.sectionRule));const t=this.props.updateChart(this.props.chartId,{sectionRule:e});t.isSuccessful?this.state.sectionRule=ae(e):this.state.sectionRuleCancelledReasons.push(...t.reasons)}onConfirmGaugeRange(e,t){this.state.sectionRule={...this.state.sectionRule,[e]:t},this.updateSectionRule(this.state.sectionRule)}getGaugeInflectionComposerProps(e){const t="lowerColor"===e?"lowerInflectionPoint":"upperInflectionPoint",s=this.state.sectionRule[t];return{onConfirm:e=>{this.state.sectionRule={...this.state.sectionRule,[t]:{...s,value:e}},this.updateSectionRule(this.state.sectionRule)},composerContent:s.value,invalid:"lowerColor"===e?this.isLowerInflectionPointInvalid:this.isUpperInflectionPointInvalid,defaultRangeSheetId:this.sheetId,class:t,placeholder:fs("Value"),title:fs("Value or formula")}}checkSectionRuleFormulasAreValid(e){const t=[];return this.valueIsValidNumber(e.rangeMin)||t.push("GaugeRangeMinNaN"),this.valueIsValidNumber(e.rangeMax)||t.push("GaugeRangeMaxNaN"),this.valueIsValidNumber(e.lowerInflectionPoint.value)||t.push("GaugeLowerInflectionPointNaN"),this.valueIsValidNumber(e.upperInflectionPoint.value)||t.push("GaugeUpperInflectionPointNaN"),t}valueIsValidNumber(e){const t=this.env.model.getters.getLocale();if(!e.startsWith("="))return void 0!==So(e,t);const s=this.env.model.getters.evaluateFormula(this.sheetId,e);return!bi(s)&&void 0!==So(fi(s),t)}get sheetId(){const e=this.env.model.getters.getChart(this.props.chartId);if(!e)throw new Error("Chart not found with id "+this.props.chartId);return e.sheetId}}class sH extends t.Component{static template="o-spreadsheet-GeoChartRegionSelectSection";static components={Section:aM};static props={chartId:String,definition:Object,updateChart:Function};updateSelectedRegion(e){const t=e.target.value;this.props.updateChart(this.props.chartId,{region:t})}get availableRegions(){return this.env.model.getters.getGeoChartAvailableRegions()}get selectedRegion(){return this.props.definition.region||this.availableRegions[0]?.id}}class oH extends kU{static template="o-spreadsheet-GeoChartConfigPanel";static components={...kU.components,GeoChartRegionSelectSection:sH};get dataRanges(){return this.getDataSeriesRanges()}get disabledRanges(){return this.props.definition.dataSets.map((e,t)=>t>0)}getLabelRangeOptions(){return[{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}}const iH={minColor:"#FFF5EB",midColor:"#FD8D3C",maxColor:"#7F2704"};class nH extends YU{static template="o-spreadsheet-GeoChartDesignPanel";static components={...YU.components,RoundColorPicker:lM};colorScalesChoices=Ig.GeoChart.ColorScales;updateColorScaleType(e){const t=e.target.value;"custom"===t?this.updateColorScale(iH):this.updateColorScale(t)}updateColorScale(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}updateLegendPosition(e){const t=e.target.value;this.props.updateChart(this.props.chartId,{legendPosition:t})}get selectedColorScale(){return"object"==typeof this.props.definition.colorScale?"custom":this.props.definition.colorScale||"oranges"}get selectedMissingValueColor(){return this.props.definition.missingValueColor||"#ffffff"}get customColorScale(){if("object"==typeof this.props.definition.colorScale)return this.props.definition.colorScale}getCustomColorScaleColor(e){return this.customColorScale?.[e]??""}setCustomColorScaleColor(e,t){t||"midColor"===e||(t="#fff");const s=this.customColorScale;s&&this.updateColorScale({...s,[e]:t})}}class rH extends kU{static template="o-spreadsheet-HierarchicalChartConfigPanel";static components={...kU.components};getLabelRangeOptions(){return[{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}}class aH extends kU{static template="o-spreadsheet-LineConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.chartId);return!!(e&&e instanceof JO)&&HI(e.getDefinition(),e.dataSets,e.labelRange,this.env.model.getters)}get stackedLabel(){return this.props.definition.fillArea?this.chartTerms.StackedAreaChart:this.chartTerms.StackedLineChart}getLabelRangeOptions(){const e=super.getLabelRangeOptions();return this.canTreatLabelsAsText&&e.push({name:"labelsAsText",value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}onUpdateLabelsAsText(e){this.props.updateChart(this.props.chartId,{labelsAsText:e})}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}}class lH extends KU{static template="o-spreadsheet-LineChartDesignPanel";static components={...KU.components,ChartShowDataMarkers:XU}}class cH extends t.Component{static template="o-spreadsheet.PieHoleSize";static components={Section:aM};static props={onValueChange:Function,value:Number};debouncedOnChange=De(this.onChange.bind(this),100);onChange(e){isNaN(Number(e))||this.props.onValueChange(ue(Number(e),0,95))}}class hH extends t.Component{static template="o-spreadsheet-PieChartDesignPanel";static components={GeneralDesignEditor:GU,Section:aM,ChartLegend:$U,ChartShowValues:jU,PieHoleSize:cH,Checkbox:IM,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}get defaultHoleSize(){return 50}}class dH extends t.Component{static template="o-spreadsheet-RadarChartDesignPanel";static components={GeneralDesignEditor:GU,SeriesDesignEditor:qU,Section:aM,ChartLegend:$U,ChartShowValues:jU,ChartShowDataMarkers:XU,Checkbox:IM,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function}}class uH extends ny{dataSets;labelRange;background;legendPosition;labelsAsText;aggregated;type="scatter";dataSetsHaveTitle;dataSetDesign;axesDesign;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=eC(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.zoomable=e.zoomable}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static transformDefinition(e,t,s){return iC(e,t,s)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"scatter",labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues,zoomable:e.zoomable,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"scatter",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,zoomable:this.zoomable,humanize:this.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new uH(i,this.sheetId,this.getters)}getDefinitionForExcel(){const e=this.dataSets.map(e=>sC(this.getters,e)).filter(e=>""!==e.range),t=oC(this.getters,this.labelRange,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:e,labelRange:t,verticalAxis:hC(s)}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new uH(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new uH(t,e,this.getters)}}class gH extends t.Component{static template="o-spreadsheet-ScorecardChartConfigPanel";static components={SelectionInput:fM,ChartErrorSection:NU,Section:aM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};state=t.useState({keyValueDispatchResult:void 0,baselineDispatchResult:void 0});keyValue=this.props.definition.keyValue;baseline=this.props.definition.baseline;get errorMessages(){return[...this.state.keyValueDispatchResult?.reasons||[],...this.state.baselineDispatchResult?.reasons||[]].map(e=>Ig.Errors[e]||Ig.Errors.Unexpected)}get isKeyValueInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause("InvalidScorecardKeyValue")}get isBaselineInvalid(){return!!this.state.keyValueDispatchResult?.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.target.value})}}class pH extends t.Component{static template="o-spreadsheet-ScorecardChartDesignPanel";static components={GeneralDesignEditor:GU,RoundColorPicker:lM,SidePanelCollapsible:DP,Section:aM,Checkbox:IM,ChartTitle:HU,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};get colorsSectionTitle(){return"progress"===this.props.definition.baselineMode?fs("Progress bar colors"):fs("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})}}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){const 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){const t={...this.baselineStyle,...e};this.props.updateChart(this.props.chartId,{baselineDescr:t})}}class mH extends t.Component{static template="o-spreadsheet-SunburstChartDesignPanel";static components={GeneralDesignEditor:GU,Section:aM,SidePanelCollapsible:DP,ChartShowValues:jU,Checkbox:IM,TextStyler:OU,RoundColorPicker:lM,ChartLegend:$U,PieHoleSize:cH};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};defaults=Ew;get showValues(){return this.props.definition.showValues??Ew.showValues}get showLabels(){return this.props.definition.showLabels??Ew.showLabels}get groupColors(){const e=this.props.chartId,t=this.env.model.getters.getChartRuntime(e).chartJsConfig.data.datasets[0];return t?.groupColors||[]}onGroupColorChanged(e,t){const s=ae(this.props.definition.groupColors)??[];s[e]=t,this.props.updateChart(this.props.chartId,{groupColors:s})}onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}}class fH extends t.Component{static template="o-spreadsheet-TreeMapCategoryColors";static components={Checkbox:IM,RoundColorPicker:lM};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){const e=this.props.definition.coloringOptions??CC.coloringOptions;if("categoryColor"!==e.type)throw new Error("Coloring options is not solid color");return e}getTreeGroupAndColors(){const e=this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig;return e.data.datasets[0]?.groupColors||[]}onGroupColorChanged(e,t){const s=ae(this.coloringOptions);s.colors[e]=t||void 0,this.props.onColorChanged(s)}useValueBasedGradient(e){if("categoryColor"!==this.coloringOptions.type)throw new Error("Coloring options is not solid color");this.props.onColorChanged({...this.coloringOptions,useValueBasedGradient:e})}}class vH extends t.Component{static template="o-spreadsheet-TreeMapColorScale";static components={RoundColorPicker:lM};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){const e=this.props.definition.coloringOptions??CC.coloringOptions;if("colorScale"!==e.type)throw new Error("Coloring options is not a color scale");return e}setColorScaleColor(e,t){this.props.onColorChanged({...this.coloringOptions,[e]:t})}}const bH={type:"colorScale",minColor:"#FFF5EB",midColor:"#FD8D3C",maxColor:"#7F2704"},SH={type:"categoryColor",colors:[],useValueBasedGradient:!0};class CH extends t.Component{static template="o-spreadsheet-TreeMapChartDesignPanel";static components={GeneralDesignEditor:GU,Section:aM,SidePanelCollapsible:DP,ChartShowValues:jU,Checkbox:IM,TextStyler:OU,RoundColorPicker:lM,BadgeSelection:UU,TreeMapCategoryColors:fH,TreeMapColorScale:vH};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};savedColors={categoryColors:SH,colorScale:bH};defaults=CC;get showHeaders(){return this.props.definition.showHeaders??CC.showHeaders}get showValues(){return this.props.definition.showValues??CC.showValues}get showLabels(){return this.props.definition.showLabels??CC.showLabels}get coloringOptions(){return this.props.definition.coloringOptions??CC.coloringOptions}changeColoringOption(e){const t="categoryColor"===e?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:fs("Category color"),value:"categoryColor"},{label:fs("Color scale"),value:"colorScale"}]}}class yH extends t.Component{static template="o-spreadsheet-WaterfallChartDesignPanel";static components={GeneralDesignEditor:GU,ChartShowValues:jU,Checkbox:IM,SidePanelCollapsible:DP,Section:aM,RoundColorPicker:lM,AxisDesignEditor:zU,RadioSelection:BU,ChartLegend:$U,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};axisChoices=gC;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:fs("Horizontal axis")},{id:"y",name:fs("Vertical axis")}]}get positiveValuesColor(){return this.props.definition.positiveValuesColor||m}get negativeValuesColor(){return this.props.definition.negativeValuesColor||f}get subTotalValuesColor(){return this.props.definition.subTotalValuesColor||v}updateVerticalAxisPosition(e){this.props.updateChart(this.props.chartId,{verticalAxisPosition:e})}onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}}const IH=new Og;IH.add("line",{configuration:aH,design:lH}).add("scatter",{configuration:class extends kU{static template="o-spreadsheet-ScatterConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.chartId);return!!(e&&e instanceof uH)&&HI(e.getDefinition(),e.dataSets,e.labelRange,this.env.model.getters)}onUpdateLabelsAsText(e){this.props.updateChart(this.props.chartId,{labelsAsText:e})}getLabelRangeOptions(){const e=super.getLabelRangeOptions();return this.canTreatLabelsAsText&&e.push({name:"labelsAsText",value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}},design:KU}).add("bar",{configuration:VU,design:KU}).add("combo",{configuration:kU,design:JU}).add("pie",{configuration:kU,design:hH}).add("gauge",{configuration:eH,design:tH}).add("scorecard",{configuration:gH,design:pH}).add("waterfall",{configuration:kU,design:yH}).add("pyramid",{configuration:kU,design:YU}).add("radar",{configuration:kU,design:dH}).add("sunburst",{configuration:rH,design:mH}).add("geo",{configuration:oH,design:nH}).add("funnel",{configuration:class extends kU{getLabelRangeOptions(){const e=this.props.definition;return[{name:"aggregated",label:this.chartTerms.AggregatedChart,value:e.aggregated??!1,onChange:this.onUpdateAggregated.bind(this)},{name:"cumulative",label:this.chartTerms.CumulativeData,value:e.cumulative??!1,onChange:this.onUpdateCumulative.bind(this)},{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}},design:QU}).add("treemap",{configuration:rH,design:CH});const wH={line:fs("Line"),column:fs("Column"),bar:fs("Bar"),area:fs("Area"),pie:fs("Pie"),hierarchical:fs("Hierarchical"),misc:fs("Miscellaneous")};class EH extends t.Component{static template="o-spreadsheet-ChartTypePicker";static components={Section:aM,Popover:DF};static props={chartId:String,chartPanelStore:Object};categories=wH;chartTypeByCategories={};popoverRef=t.useRef("popoverRef");selectRef=t.useRef("selectRef");state=t.useState({popoverProps:void 0,popoverStyle:""});setup(){t.useExternalListener(window,"pointerdown",this.onExternalClick,{capture:!0});for(const e of f_.getAll())this.chartTypeByCategories[e.category]?this.chartTypeByCategories[e.category].push(e):this.chartTypeByCategories[e.category]=[e]}onExternalClick(e){Dy(this.popoverRef.el?.parentElement,e)||Dy(this.selectRef.el,e)||this.closePopover()}onTypeChange(e){this.props.chartPanelStore.changeChartType(this.props.chartId,e),this.closePopover()}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}getSelectedChartSubtypeProperties(){const e=this.getChartDefinition(this.props.chartId);return f_.getAll().find(t=>t.matcher?.(e)||!1)||f_.get(e.type)}onPointerDown(e){if(this.state.popoverProps)return void this.closePopover();const t=e.currentTarget,{bottom:s,right:o,width:i}=t.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:o,y:s,width:0,height:0},positioning:"top-right",verticalOffset:0},this.state.popoverStyle=Ey({width:`${i}px`})}closePopover(){this.state.popoverProps=void 0}}class RH extends hv{mutators=["activatePanel","changeChartType"];panel="configuration";creationContexts={};activatePanel(e){this.panel=e}changeChartType(e,t){const s=this.getters.getContextCreationChart(e),o=this.creationContexts[e]||{};let i=s?.range;i?.every((e,t)=>Me(e,o.range?.[t]))&&(i=Object.assign([],o.range,s?.range)),this.creationContexts[e]={...o,...s,range:i};const n=this.getters.getFigureIdFromChartId(e),r=this.getters.getFigureSheetId(n);if(!r)return;const a=this.getChartDefinitionFromContextCreation(e,t);this.model.dispatch("UPDATE_CHART",{definition:a,chartId:e,figureId:n,sheetId:r})}getChartDefinitionFromContextCreation(e,t){const s=f_.get(t);return{...$y.get(s.chartType).getChartDefinitionFromContextCreation(this.creationContexts[e]),...s.subtypeDefinition}}}class xH extends t.Component{static template="o-spreadsheet-ChartPanel";static components={Section:aM,ChartTypePicker:EH};static props={onCloseSidePanel:Function,chartId:String};panelContentRef;scrollPositions={configuration:0,design:0};store;get chartId(){return this.props.chartId}setup(){this.store=tv(RH),this.panelContentRef=t.useRef("panelContent"),t.useEffect(()=>{const e=this.panelContentRef.el,t=this.store.panel;e&&(e.scrollTop=this.scrollPositions[t])},()=>[this.store.panel])}switchPanel(e){const t=this.panelContentRef.el;t&&(this.scrollPositions[this.store.panel]=t.scrollTop),this.store.activatePanel(e)}updateChart(e,t){const s=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId)return;const o={...this.getChartDefinition(this.chartId),...t};return this.env.model.dispatch("UPDATE_CHART",{definition:o,chartId:e,figureId:s,sheetId:this.env.model.getters.getFigureSheetId(s)})}canUpdateChart(e,t){const s=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId||!this.env.model.getters.isChartDefined(e))return;const o={...this.getChartDefinition(this.chartId),...t};return this.env.model.canDispatch("UPDATE_CHART",{definition:o,chartId:e,figureId:s,sheetId:this.env.model.getters.getFigureSheetId(s)})}onTypeChange(e){this.chartId&&this.store.changeChartType(this.chartId,e)}get chartPanel(){if(!this.chartId)throw new Error("Chart not defined.");const e=this.env.model.getters.getChartType(this.chartId);if(!e)throw new Error("Chart not defined.");const t=IH.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}}class TH extends t.Component{static template="o-spreadsheet-IconPicker";static props={onIconPicked:Function};icons=gR;iconSets=pR;onIconClick(e){e&&this.props.onIconPicked(e)}}function AH(e,s){const o=function(e){const s=t.useState({hovered:!1});return eU(e,"mouseenter",()=>s.hovered=!0),eU(e,"mouseleave",()=>s.hovered=!1),s}(e);DH({get highlights(){return o.hovered?s.highlights:[]}})}function DH(e){const s=Qf(),o=tv(ZP);t.onMounted(()=>{o.register(e)});let i=e.highlights;t.useEffect(e=>{Me(e,i)||(i=e,s.trigger("store-updated"))},()=>[e.highlights])}class _H extends t.Component{static template="o-spreadsheet-ConditionalFormatPreview";icons=gR;ref=t.useRef("cfPreview");setup(){AH(this.ref,this)}getPreviewImageStyle(){const e=this.props.conditionalFormat.rule;if("CellIsRule"===e.type)return Ey(Iy(e.style));if("ColorScaleRule"===e.type){const t=fv(e.minimum.color),s=e.midpoint?fv(e.midpoint.color):null,o=fv(e.maximum.color),i="background-image: linear-gradient(to right, ";return s?i+t+", "+s+", "+o+")":i+t+", "+o+")"}if("DataBarRule"===e.type){return`background-image: linear-gradient(to right, ${fv(e.color)} 50%, white 50%)`}return""}getDescription(){const e=this.props.conditionalFormat;switch(e.rule.type){case"CellIsRule":return QT.get(e.rule.operator).getPreview({...e.rule,type:e.rule.operator},this.env.model.getters);case"ColorScaleRule":return yg.ColorScale;case"IconSetRule":return yg.IconSet;case"DataBarRule":return yg.DataBar}}deleteConditionalFormat(){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:this.props.conditionalFormat.id,sheetId:this.env.model.getters.getActiveSheetId()})}onMouseDown(e){this.props.onMouseDown(e)}get highlights(){const e=this.env.model.getters.getActiveSheetId();return this.props.conditionalFormat.ranges.map(t=>({range:this.env.model.getters.getRangeFromSheetXC(e,t),color:o,fillAlpha:.06}))}}_H.props={conditionalFormat:Object,onPreviewClick:Function,onMouseDown:Function,class:String};class OH extends t.Component{static template="o-spreadsheet-ConditionalFormatPreviewList";static props={conditionalFormats:Array,onPreviewClick:Function,onAddConditionalFormat:Function};static components={ConditionalFormatPreview:_H};icons=gR;dragAndDrop=cM();cfListRef=t.useRef("cfList");setup(){t.onWillUpdateProps(e=>{Me(this.props.conditionalFormats,e.conditionalFormats)||this.dragAndDrop.cancel()})}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[e.id]||""}onPreviewMouseDown(e,t){if(0!==t.button)return;const s=Array.from(this.cfListRef.el.children).map(e=>Fy(e)),o=this.props.conditionalFormats.map((e,t)=>({id:e.id,size:s[t].height,position:s[t].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.id,initialMousePosition:t.clientY,items:o,scrollableContainerEl:this.cfListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const s=this.props.conditionalFormats.findIndex(t=>t.id===e)-t;0!==s&&this.env.model.dispatch("CHANGE_CONDITIONAL_FORMAT_PRIORITY",{cfId:e,delta:s,sheetId:this.env.model.getters.getActiveSheetId()})}}class FH extends t.Component{static template="o-spreadsheet-ConditionalFormattingEditor";static props={editedCf:Object,onCancel:Function,onExit:Function,isNewCf:Boolean};static components={SelectionInput:fM,IconPicker:TH,ColorPickerWidget:DU,ConditionalFormatPreviewList:OH,Section:aM,RoundColorPicker:lM,StandaloneComposer:JP,BadgeSelection:UU,ValidationMessages:JV,SelectMenu:CM};icons=gR;iconSets=pR;getTextDecoration=yy;colorNumberToHex=fv;state;setup(){switch(this.state=t.useState({errors:[],currentCFType:this.props.editedCf.rule.type,ranges:this.props.editedCf.ranges,rules:this.getDefaultRules(),hasEditedCf:this.props.isNewCf}),this.props.editedCf.rule.type){case"CellIsRule":this.state.rules.cellIs=this.props.editedCf.rule;break;case"ColorScaleRule":this.state.rules.colorScale=this.props.editedCf.rule;break;case"IconSetRule":this.state.rules.iconSet=this.props.editedCf.rule;break;case"DataBarRule":this.state.rules.dataBar=this.props.editedCf.rule}t.useExternalListener(window,"click",this.closeMenus)}get isRangeValid(){return this.state.errors.includes("EmptyRange")}get errorMessages(){return this.state.errors.map(e=>yg.Errors[e]||yg.Errors.Unexpected)}get cfTypesValues(){return[{value:"CellIsRule",label:fs("Single color")},{value:"ColorScaleRule",label:fs("Color scale")},{value:"IconSetRule",label:fs("Icon set")},{value:"DataBarRule",label:fs("Data bar")}]}updateConditionalFormat(e){const t=e.ranges||this.state.ranges;if(this.state.ranges.some(e=>!e.match(Xn)))return e.suppressErrors||(this.state.errors=["InvalidRange"]),["InvalidRange"];const s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getLocale(),i=e.rule||this.getEditedRule(this.state.currentCFType),n=this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:nh(i,o),id:this.props.editedCf.id},ranges:t.map(e=>this.env.model.getters.getRangeDataFromXc(s,e)),sheetId:s});n.isSuccessful&&(this.state.hasEditedCf=!0);const r=n.reasons.filter(e=>"NoChanges"!==e);return e.suppressErrors||(this.state.errors=r),r}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}}onSave(){0===this.updateConditionalFormat({}).length&&this.props.onExit()}onCancel(){this.state.hasEditedCf?this.props.onCancel():this.props.onExit()}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"isNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:KR("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}}}changeRuleType(e){this.state.currentCFType!==e&&(this.state.errors=[],this.state.currentCFType=e,this.updateConditionalFormat({rule:this.getEditedRule(e),suppressErrors:!0}))}onRangeUpdate(e){this.state.ranges=e}onRangeConfirmed(){this.updateConditionalFormat({ranges:this.state.ranges})}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){return this.state.errors.includes("FirstArgMissing")||this.state.errors.includes("ValueCellIsInvalidFormula")}get isValue2Invalid(){return this.state.errors.includes("SecondArgMissing")}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}onKeydown(e){if("F4"===e.key){const t=e.target,s=WP({start:t.selectionStart??0,end:t.selectionEnd??0},t.value,this.env.model.getters.getLocale());if(!s)return;t.value=s.content,t.setSelectionRange(s.selection.start,s.selection.end),t.dispatchEvent(new Event("input"))}}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,this.updateConditionalFormat({rule:this.state.rules.cellIs,suppressErrors:!0}),this.closeMenus()}get cfCriterionMenuItems(){return SM(e=>this.editOperator(e),pI)}get selectedCriterionName(){return QT.get(this.state.rules.cellIs.operator).name}get criterionComponent(){return bM.get(this.state.rules.cellIs.operator).component}get genericCriterion(){return{type:this.state.rules.cellIs.operator,values:this.state.rules.cellIs.values}}onRuleValuesChanged(e){this.state.rules.cellIs.values=e.values,this.updateConditionalFormat({rule:{...this.state.rules.cellIs,values:e.values}})}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes("MinInvalidFormula")||this.state.errors.includes("MinBiggerThanMid")||this.state.errors.includes("MinBiggerThanMax")||this.state.errors.includes("MinNaN");case"midpoint":return this.state.errors.includes("MidInvalidFormula")||this.state.errors.includes("MidNaN")||this.state.errors.includes("MidBiggerThanMax");case"maximum":return this.state.errors.includes("MaxInvalidFormula")||this.state.errors.includes("MaxNaN");default:return!1}}setColorScaleColor(e,t){if(!Sv(t))return;const s=this.state.rules.colorScale[e];s&&(s.color=vv(t)),this.updateConditionalFormat({rule:this.state.rules.colorScale}),this.closeMenus()}getPreviewGradient(){const e=this.state.rules.colorScale,t=fv(e.minimum.color),s=fv(e.midpoint?.color||h),o=fv(e.maximum.color),i="background-image: linear-gradient(to right, ";return void 0===e.midpoint?i+t+", "+o+")":i+t+", "+s+", "+o+")"}getThresholdColor(e){return fv(e?e.color:h)}onMidpointChange(e){const t=e.target.value,s=this.state.rules.colorScale;s.midpoint="none"===t?void 0:{color:h,value:"",...s.midpoint,type:t},this.updateConditionalFormat({rule:s,suppressErrors:!0})}updateThresholdType(e,t){this.state.rules.colorScale[e].type=t,this.updateConditionalFormat({rule:this.state.rules.colorScale,suppressErrors:!0})}updateThresholdValue(e,t){this.state.rules.colorScale[e].value=t,this.updateConditionalFormat({rule:this.state.rules.colorScale})}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes("ValueLowerInflectionNaN")||this.state.errors.includes("ValueLowerInvalidFormula")||this.state.errors.includes("LowerBiggerThanUpper");case"upperInflectionPoint":return this.state.errors.includes("ValueUpperInflectionNaN")||this.state.errors.includes("ValueUpperInvalidFormula")||this.state.errors.includes("LowerBiggerThanUpper");default:return!0}}reverseIcons(){const 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){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIcon(e,t){this.state.rules.iconSet.icons[e]=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionOperator(e,t){this.state.rules.iconSet[e].operator=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionValue(e,t){this.state.rules.iconSet[e].value=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionType(e,t,s){this.state.rules.iconSet[e].type=t,this.updateConditionalFormat({rule:this.state.rules.iconSet,suppressErrors:!0})}getColorScaleComposerProps(e){const t=this.state.rules.colorScale[e];if(!t)throw new Error("Threshold not found");const s=this.isValueInvalid(e);return{onConfirm:e=>{t.value=e,this.updateConditionalFormat({rule:this.state.rules.colorScale})},composerContent:t.value||"",placeholder:fs("Formula"),defaultStatic:!0,invalid:s,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getColorIconSetComposerProps(e){const t=this.state.rules.iconSet[e],s=this.isInflectionPointInvalid(e);return{onConfirm:e=>{t.value=e,this.updateConditionalFormat({rule:this.state.rules.iconSet})},composerContent:t.value||"",placeholder:fs("Formula"),defaultStatic:!0,invalid:s,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getRangeValues(){return[this.state.rules.dataBar.rangeValues||""]}updateDataBarColor(e){Sv(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})}}class PH extends t.Component{static template="o-spreadsheet-ConditionalFormattingPanel";static props={selection:{type:Object,optional:!0},onCloseSidePanel:Function};static components={ConditionalFormatPreviewList:OH,ConditionalFormattingEditor:FH,Section:aM};activeSheetId;originalEditedCf=void 0;state=t.useState({mode:"list"});setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId();const e=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===s.length){const e=this.conditionalFormats.find(e=>e.id===s[0]);e&&this.editConditionalFormat(e)}t.onWillUpdateProps(e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===s.length){const e=this.conditionalFormats.find(e=>e.id===s[0]);e&&this.editConditionalFormat(e)}else this.switchToList()}else this.editedCF||this.switchToList()})}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId()).map(e=>({...e,rule:rh(e.rule,this.env.model.getters.getLocale())}))}switchToList(){this.state.mode="list",this.state.editedCfId=void 0,this.originalEditedCf=void 0}addConditionalFormat(){const e=this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,ranges:this.env.model.getters.getSelectedZones().map(e=>this.env.model.getters.getRangeDataFromZone(this.activeSheetId,e)),cf:{id:e,rule:{type:"CellIsRule",operator:"isNotEmpty",style:{fillColor:"#b6d7a8"},values:[]}}}),this.state.editedCfId=e,this.state.mode="edit",this.originalEditedCf=void 0}editConditionalFormat(e){this.state.mode="edit",this.state.editedCfId=e.id,this.originalEditedCf=e}cancelEdition(){this.originalEditedCf?this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,ranges:this.originalEditedCf.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.activeSheetId,e)),cf:this.originalEditedCf}):this.state.editedCfId&&this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,id:this.state.editedCfId}),this.switchToList()}get editedCF(){return this.conditionalFormats.find(e=>e.id===this.state.editedCfId)}}const MH=new Og;class NH extends t.Component{static template="o-spreadsheet-CustomCurrencyPanel";static components={Section:aM,Checkbox:IM};static props={onCloseSidePanel:Function};availableCurrencies;state;setup(){this.availableCurrencies=[],this.state=t.useState({selectedCurrencyIndex:0,currencyCode:"",currencySymbol:"",selectedFormatIndex:0,isAccountingFormat:!1}),t.onWillStart(()=>this.updateAvailableCurrencies())}get formatProposals(){const e=this.availableCurrencies[this.state.selectedCurrencyIndex],t=e.position,s="before"===e.position?"after":"before",o=this.state.currencySymbol.trim()?this.state.currencySymbol:"",i=this.state.currencyCode.trim()?this.state.currencyCode:"",n=e.decimalPlaces;if(!o&&!i)return[];const r=[{symbol:o,position:t,decimalPlaces:0},{symbol:o,position:t,decimalPlaces:n},{symbol:o,position:t,decimalPlaces:0,code:i},{symbol:o,position:t,decimalPlaces:n,code:i},{symbol:o,position:s,decimalPlaces:0},{symbol:o,position:s,decimalPlaces:n},{symbol:o,position:s,decimalPlaces:0,code:i},{symbol:o,position:s,decimalPlaces:n,code:i}],a=new Set,l=this.env.model.getters.getLocale();return r.map(e=>{const t=Dn(e);if((e.symbol||e.code)&&!a.has(t))return a.add(t),{format:t,accountingFormat:_n(e),example:pn(1e3,{format:t,locale:l})}}).filter(Te)}get isSameFormat(){return!!this.selectedFormat&&this.selectedFormat===this.getCommonFormat()}async updateAvailableCurrencies(){if(0===MH.getAll().length){(await(this.env.loadCurrencies?.())||[]).forEach((e,t)=>{MH.add(t.toString(),e)})}const e={name:wg.Custom,code:"",symbol:"",decimalPlaces:2,position:"after"};this.availableCurrencies=[e,...MH.getAll()]}updateSelectCurrency(e){const t=e.target;this.state.selectedCurrencyIndex=parseInt(t.value,10);const s=this.availableCurrencies[this.state.selectedCurrencyIndex];this.state.currencyCode=s.code,this.state.currencySymbol=s.symbol}updateCode(e){const t=e.target;this.state.currencyCode=t.value,this.initAvailableCurrencies()}updateSymbol(e){const t=e.target;this.state.currencySymbol=t.value,this.initAvailableCurrencies()}updateSelectFormat(e){const t=e.target;this.state.selectedFormatIndex=parseInt(t.value,10)}apply(){this.env.model.dispatch("SET_FORMATTING_WITH_PIVOT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),format:this.selectedFormat})}initAvailableCurrencies(){this.state.selectedCurrencyIndex=0}getCommonFormat(){const e=this.env.model.getters.getSelectedZones(),t=this.env.model.getters.getActiveSheetId(),s=e.map(e=>this.env.model.getters.getEvaluatedCellsInZone(t,e)).flat(),o=s[0].format;return s.every(e=>e.format===o)?o:void 0}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:"")}toggleAccountingFormat(){this.state.isAccountingFormat=!this.state.isAccountingFormat}getFormatExamples(){const e=this.selectedFormat,t=this.env.model.getters.getLocale();return[{label:fs("positive")+":",value:pn(1234.56,{format:e,locale:t})},{label:fs("negative")+":",value:pn(-1234.56,{format:e,locale:t})},{label:fs("zero")+":",value:pn(0,{format:e,locale:t})}]}get selectedFormat(){const e=this.formatProposals[this.state.selectedFormatIndex];return this.state.isAccountingFormat?e?.accountingFormat:e?.format}}class LH extends t.Component{static template="o-spreadsheet-DataValidationEditor";static components={SelectionInput:fM,SelectMenu:CM,Section:aM,ValidationMessages:JV};static props={rule:{type:Object,optional:!0},onExit:Function,onCloseSidePanel:{type:Function,optional:!0}};state=t.useState({rule:this.defaultDataValidationRule,errors:[]});editingSheetId;setup(){this.editingSheetId=this.env.model.getters.getActiveSheetId(),this.props.rule&&(this.state.rule={...this.props.rule,ranges:this.props.rule.ranges.map(e=>this.env.model.getters.getRangeString(e,this.editingSheetId))},this.state.rule.criterion.type=this.props.rule.criterion.type)}onCriterionTypeChanged(e){this.state.rule.criterion.type=e}onRangesChanged(e){this.state.rule.ranges=e}onCriterionChanged(e){this.state.rule.criterion=e}changeRuleIsBlocking(e){const t=e.target.value;this.state.rule.isBlocking="true"===t}onSave(){if(this.state.rule){const e=this.env.model.dispatch("ADD_DATA_VALIDATION_RULE",this.dispatchPayload);e.isSuccessful?this.props.onExit():this.state.errors=e.reasons}}get dispatchPayload(){const e={...this.state.rule,ranges:void 0},t=this.env.model.getters.getLocale(),s=e.criterion,o=QT.get(s.type),i=s.values.slice(0,o.numberOfValues(s)).map(e=>e?.trim()).filter(e=>""!==e&&void 0!==e).map(e=>Jc(e,t));return e.criterion={...s,values:i},{sheetId:this.editingSheetId,ranges:this.state.rule.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.editingSheetId,e)),rule:e}}get dvCriterionMenuItems(){return SM(e=>this.onCriterionTypeChanged(e),mI)}get selectedCriterionName(){const e=this.state.rule.criterion.type;return QT.get(e).name}get defaultDataValidationRule(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones().map(t=>Tt(this.env.model.getters.getUnboundedZone(e,t)));return{id:this.env.model.uuidGenerator.smallUuid(),criterion:{type:"containsText",values:[""]},ranges:t}}get criterionComponent(){return bM.get(this.state.rule.criterion.type).component}get errorMessages(){return this.state.errors.map(e=>Ag.Errors[e]||Ag.Errors.Unexpected)}}class kH extends t.Component{static template="o-spreadsheet-DataValidationPreview";static props={onClick:Function,rule:Object};ref=t.useRef("dvPreview");setup(){AH(this.ref,this)}deleteDataValidation(){const 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:o,fillAlpha:.06}))}get rangesString(){const e=this.env.model.getters.getActiveSheetId();return this.props.rule.ranges.map(t=>this.env.model.getters.getRangeString(t,e)).join(", ")}get descriptionString(){return QT.get(this.props.rule.criterion.type).getPreview(this.props.rule.criterion,this.env.model.getters)}}class VH extends t.Component{static template="o-spreadsheet-DataValidationPanel";static props={onCloseSidePanel:Function};static components={DataValidationPreview:kH,DataValidationEditor:LH};state=t.useState({mode:"list",activeRule:void 0});onPreviewClick(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getDataValidationRule(t,e);s&&(this.state.mode="edit",this.state.activeRule=s)}addDataValidationRule(){this.state.mode="edit",this.state.activeRule=void 0}onExitEditMode(){this.state.mode="list",this.state.activeRule=void 0}localizeDVRule(e){if(!e)return e;return ah(e,this.env.model.getters.getLocale())}get validationRules(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getDataValidationRules(e)}}const UH="#8B008B";var HH;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(HH||(HH={}));class zH extends hv{mutators=["updateSearchOptions","updateSearchContent","searchFormulas","selectPreviousMatch","selectNextMatch","replace"];allSheetsMatches=[];activeSheetMatches=[];specificRangeMatches=[];currentSearchRegex=null;initialShowFormulaState;preserveSelectedMatchIndex=!1;irreplaceableMatchCount=0;isSearchDirty=!1;shouldFinalizeUpdateSelection=!1;notificationStore=this.get(jP);selectedMatchIndex=null;toSearch="";toReplace="";searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1,searchScope:"activeSheet",specificRange:void 0};constructor(e){super(e),this.initialShowFormulaState=this.model.getters.shouldShowFormulas(),this.searchOptions.searchFormulas=this.initialShowFormulaState;const t=e(ZP);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(HH.previous,{jumpToMatchSheet:!0,updateSelection:!0})}selectNextMatch(){this.selectNextCell(HH.next,{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;break;case"REPLACE_SEARCH":for(const 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}}finalize(){this.isSearchDirty&&(this.refreshSearch({jumpToMatchSheet:!1,updateSelection:this.shouldFinalizeUpdateSelection}),this.shouldFinalizeUpdateSelection=!1,this.isSearchDirty=!1)}get allSheetMatchesCount(){return this.allSheetsMatches.length}get activeSheetMatchesCount(){return this.activeSheetMatches.length}get specificRangeMatchesCount(){return this.specificRangeMatches.length}_updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null),this.toSearch=e,this.currentSearchRegex=Xe(this.toSearch,this.searchOptions),this.refreshSearch({jumpToMatchSheet:!0,updateSelection:!0})}refreshSearch(e){this.preserveSelectedMatchIndex||(this.selectedMatchIndex=null),this.findMatches(),this.selectNextCell(HH.current,e)}getSheetsInSearchOrder(){switch(this.searchOptions.searchScope){case"allSheets":const 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":const s=this.searchOptions.specificRange;return s&&s?[s.sheetId]:[]}}findMatches(){const e=[];if(this.toSearch)for(const t of this.getters.getSheetIds())e.push(...this.findMatchesInSheet(t));if(this.allSheetsMatches=e,this.activeSheetMatches=e.filter(e=>e.sheetId===this.getters.getActiveSheetId()),this.searchOptions.specificRange){const{sheetId:t,zone:s}=this.searchOptions.specificRange;this.specificRangeMatches=e.filter(e=>e.sheetId===t&&kt(e.col,e.row,s))}else this.specificRangeMatches=[]}findMatchesInSheet(e){const t=[],{left:s,right:o,top:i,bottom:n}=this.getters.getSheetZone(e);for(let r=i;r<=n;r++)for(let i=s;i<=o;i++){const s=this.getters.isColHidden(e,i),o=this.getters.isRowHidden(e,r);if(s||o)continue;const n={sheetId:e,col:i,row:r};if(this.currentSearchRegex?.test(this.getSearchableString(n))){const s={sheetId:e,col:i,row:r};t.push(s)}}return t}selectNextCell(e,t){const s=this.searchMatches;if(!s.length)return void(this.selectedMatchIndex=null);let o;if(null===this.selectedMatchIndex){let e=-1;for(const t of this.getSheetsInSearchOrder())if(e=s.findIndex(e=>e.sheetId===t),-1!==e)break;o=e}else o=this.selectedMatchIndex+e;o=(o+s.length)%s.length,this.selectedMatchIndex=o;const i=s[o];t.jumpToMatchSheet&&this.getters.getActiveSheetId()!==i.sheetId&&(this.preserveSelectedMatchIndex=!0,this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:i.sheetId}),this.preserveSelectedMatchIndex=!1,this.isSearchDirty=!1),this.model.selection.getBackToDefault(),t.updateSelection&&this.model.selection.selectCell(i.col,i.row)}replace(){null!==this.selectedMatchIndex&&(this.preserveSelectedMatchIndex=!0,this.shouldFinalizeUpdateSelection=!0,this.model.dispatch("REPLACE_SEARCH",{searchString:this.toSearch,replaceWith:this.toReplace,matches:[this.searchMatches[this.selectedMatchIndex]],searchOptions:this.searchOptions}),this.preserveSelectedMatchIndex=!1)}replaceAll(){this.model.dispatch("REPLACE_SEARCH",{searchString:this.toSearch,replaceWith:this.toReplace,matches:this.searchMatches,searchOptions:this.searchOptions})}showReplaceWarningMessage(e,t){const s=e-t;0===s?this.notificationStore.notifyUser({type:"warning",sticky:!1,text:fs("Match(es) cannot be replaced as they are part of a formula.")}):this.notificationStore.notifyUser({type:"warning",sticky:!1,text:fs("%(replaceable_count)s match(es) replaced. %(irreplaceable_count)s match(es) cannot be replaced as they are part of a formula.",{replaceable_count:s,irreplaceable_count:t})})}replaceMatch(e,t,s,o){const i=this.getters.getCell(e);if(!i?.content)return;if(i?.isFormula&&!o.searchFormulas)return void this.irreplaceableMatchCount++;const n=Xe(t,o),r=new RegExp(n.source,n.flags+"g"),a=Kc(this.getters.getCellText(e,{showFormula:o.searchFormulas}).replace(r,s),this.getters.getLocale());this.model.dispatch("UPDATE_CELL",{...e,content:a})}getSearchableString(e){return this.getters.getCellText(e,{showFormula:this.searchOptions.searchFormulas})}get highlights(){const e=[],t=this.getters.getActiveSheetId();for(const[s,o]of this.searchMatches.entries()){if(o.sheetId!==t)continue;const i=Zt(o),n=this.getters.expandZone(t,i),{width:r,height:a}=this.getters.getVisibleRect(n);r>0&&a>0&&e.push({range:this.model.getters.getRangeFromZone(t,n),color:UH,noBorder:s!==this.selectedMatchIndex,thinLine:!0,fillAlpha:.2})}if("specificRange"===this.searchOptions.searchScope){const s=this.searchOptions.specificRange;s&&s.sheetId===t&&e.push({range:s,color:UH,noFill:!0,thinLine:!0})}return e}}class BH extends t.Component{static template="o-spreadsheet-FindAndReplacePanel";static components={SelectionInput:fM,Section:aM,Checkbox:IM,ValidationMessages:JV};static props={onCloseSidePanel:Function};searchInput=t.useRef("searchInput");store;state;updateSearchContent;get hasSearchResult(){return null!==this.store.selectedMatchIndex}get searchOptions(){return this.store.searchOptions}get allSheetsMatchesCount(){return fs("%s matches in all sheets",this.store.allSheetMatchesCount)}get currentSheetMatchesCount(){return fs("%(matches)s matches in %(sheetName)s",{matches:this.store.activeSheetMatchesCount,sheetName:this.env.model.getters.getSheetName(this.env.model.getters.getActiveSheetId())})}get specificRangeMatchesCount(){const e=this.searchOptions.specificRange;if(!e)return"";const{sheetId:t,zone:s}=e;return fs("%(matches)s matches in range %(range)s of %(sheetName)s",{matches:this.store.specificRangeMatchesCount,range:Tt(s),sheetName:this.env.model.getters.getSheetName(t)})}get searchInfo(){return this.store.toSearch?[this.specificRangeMatchesCount,this.currentSheetMatchesCount,this.allSheetsMatchesCount]:[]}setup(){this.store=tv(zH),this.state=t.useState({dataRange:""}),t.onMounted(()=>this.searchInput.el?.focus()),t.onWillUnmount(()=>this.updateSearchContent.stopDebounce()),this.updateSearchContent=De(this.store.updateSearchContent,200),t.useExternalListener(window,"keydown",e=>{const t=ky(e);"Ctrl+F"!==t&&"Ctrl+H"!==t||(this.searchInput.el?.focus(),e.preventDefault(),e.stopPropagation())},{capture:!0})}onFocusSearch(){this.updateDataRange()}onSearchInput(e){this.updateSearchContent(e.target.value)}onKeydownSearch(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),e.shiftKey?this.store.selectPreviousMatch():this.store.selectNextMatch())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),this.store.replace())}searchFormulas(e){this.store.searchFormulas(e)}searchExactMatch(e){this.store.updateSearchOptions({exactMatch:e})}searchMatchCase(e){this.store.updateSearchOptions({matchCase:e})}changeSearchScope(e){const t=e.target.value;this.store.updateSearchOptions({searchScope:t})}onSearchRangeChanged(e){this.state.dataRange=e[0]}updateDataRange(){if(!this.state.dataRange||"specificRange"!==this.searchOptions.searchScope)return;const e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.dataRange);this.store.updateSearchOptions({specificRange:e})}get pendingSearch(){return this.updateSearchContent.isDebouncePending()}}const GH=qf([Zk,jk,Yk,Xk,Kk,Jk,Qk,eV,tV,Hk,zk,Bk,Gk,Wk,$k]);class WH extends t.Component{static template="o-spreadsheet-MoreFormatsPanel";static props={onCloseSidePanel:Function};get dateFormatsActions(){return GH}}class $H extends hv{pivotId;initialMeasure;mutators=["cancelMeasureDisplayEdition","updateMeasureDisplayType","updateMeasureDisplayField","updateMeasureDisplayValue"];measureDisplay;constructor(e,t,s){super(e),this.pivotId=t,this.initialMeasure=s,this.measureDisplay=s.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){const t=ae(this.model.getters.getPivotCoreDefinition(this.pivotId)),s=this.getMeasureIndex(this.initialMeasure.id,t),o={...t.measures[s],display:e};t.measures[s]=o;this.model.dispatch("UPDATE_PIVOT",{pivot:t,pivotId:this.pivotId}).isSuccessful&&(this.measureDisplay=e)}getMeasureDisplay(e,t,s){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||(t=this.fields[0]?.nameWithGranularity),{type:e,fieldNameWithGranularity:t};case"%_of":case"difference_from":case"%_difference_from":t||(t=this.fields[0]?.nameWithGranularity);const o=this.getPossibleValues(t);return void 0!==s&&o.find(e=>e.value===s)||(s=fI),{type:e,fieldNameWithGranularity:t,value:s??fI}}}getMeasureIndex(e,t){const s=t.measures.findIndex(t=>t.id===e);if(-1===s)throw new Error(`Measure with id ${e} not found in pivot.`);return s}get doesDisplayNeedsField(){return["%_of_parent_total","running_total","%_running_total","rank_asc","rank_desc"].includes(this.measureDisplay.type)||this.doesDisplayNeedsValue}get fields(){const e=this.getters.getPivot(this.pivotId).definition;return[...e.columns,...e.rows].map(e=>({...e,displayName:dp(e)}))}get doesDisplayNeedsValue(){return this.isDisplayValueDependant(this.measureDisplay)}isDisplayValueDependant(e){return["%_of","difference_from","%_difference_from"].includes(e.type)}get values(){const e=this.measureDisplay;return this.isDisplayValueDependant(e)?this.getPossibleValues(e.fieldNameWithGranularity):[]}getPossibleValues(e){const t=[{value:fI,label:fs("(previous)")},{value:vI,label:fs("(next)")}],s=this.fields.find(t=>t.nameWithGranularity===e);if(!s)return[];return[...t,...this.getters.getPivot(this.pivotId).getPossibleFieldValues(s)]}cancelMeasureDisplayEdition(){const e=ae(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})}}class qH extends t.Component{static template="o-spreadsheet-PivotMeasureDisplayPanel";static props={onCloseSidePanel:Function,pivotId:String,measure:Object};static components={Section:aM,Checkbox:IM,RadioSelection:BU};measureDisplayTypeLabels=_g.labels;measureDisplayDescription=_g.documentation;store;setup(){this.store=tv($H,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}))}}function ZH(e,t){const s=e.getActiveSheetId(),i=function(e,t){const s=[],o=e.getActiveSheetId();for(const i of e.getSheetViewVisibleCols())for(const n of e.getSheetViewVisibleRows()){const r={sheetId:o,col:i,row:n};t===e.getPivotIdFromPosition(r)&&s.push(r)}return s}(e,t);return es(i.map(Zt)).map(t=>({range:e.getRangeFromZone(s,t),noFill:!0,color:o}))}class jH extends t.Component{static template="o-spreadsheet-PivotDeferUpdate";static props={deferUpdate:Boolean,isDirty:Boolean,toggleDeferUpdate:Function,discard:Function,apply:Function};static components={Section:aM,Checkbox:IM};get deferUpdatesLabel(){return fs("Defer updates")}get deferUpdatesTooltip(){return fs("Changing the pivot definition requires to reload the data. It may take some time.")}}class YH extends t.Component{static template="o-spreadsheet-PivotCustomGroupsCollapsible";static props={pivotId:String,customField:Object,onCustomFieldUpdated:Function};static components={SidePanelCollapsible:DP,TextInput:TU,Checkbox:IM};get groups(){return this.props.customField.groups.sort((e,t)=>e.isOtherGroup||t.isOtherGroup?e.isOtherGroup?1:-1:0)}get hasOthersGroup(){return this.props.customField.groups.some(e=>e.isOtherGroup)}addOthersGroup(){if(this.hasOthersGroup)return;const e={name:pp(fs("Others"),this.props.customField),values:[],isOtherGroup:!0},t=[...this.props.customField.groups,e];this.updateCustomField({...this.props.customField,groups:t})}onDeleteGroup(e){const t=[...this.props.customField.groups];t.splice(e,1),this.updateCustomField({...this.props.customField,groups:t})}onRenameGroup(e,t){const s=ae(this.props.customField.groups),o=s[e];o&&(o.name=pp(t,this.props.customField),this.updateCustomField({...this.props.customField,groups:s}))}updateCustomField(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.props.onCustomFieldUpdated({customFields:{...t.customFields,[e.name]:e}})}}function XH(e,t,s,o){const i=[];e=e.toLowerCase();for(const n of e){const e=t.toLocaleLowerCase().indexOf(n);-1!==e&&(i.push({value:t.slice(0,e),color:""},{value:t[e],color:s,classes:[o]}),t=t.slice(e+1))}return i.push({value:t}),i.filter(e=>e.value)}class KH extends t.Component{static template="o-spreadsheet-AddDimensionButton";static components={Popover:DF,TextValueProvider:MP};static props={onFieldPicked:Function,fields:Array,slots:{type:Object,optional:!0}};buttonRef=t.useRef("button");popover=t.useState({isOpen:!1});search=t.useState({input:""});autoComplete;setup(){this.autoComplete=tv(YP),this.autoComplete.useProvider(this.getProvider()),t.useExternalListener(window,"click",e=>{e.target!==this.buttonRef.el&&(this.popover.isOpen=!1)}),xU({refName:"autofocus"})}getProvider(){return{proposals:this.proposals,autoSelectFirstProposal:!1,selectProposal:e=>{const t=this.props.fields.find(t=>t.string===e);t&&this.pickField(t)}}}get proposals(){let e;return e=this.search.input?tS(this.search.input,this.props.fields,e=>e.string):this.props.fields,e.map(e=>{const t=e.string;return{text:t,fuzzySearchKey:t,htmlContent:XH(this.search.input,t,g,"o-semi-bold")}})}get popoverProps(){const{x:e,y:t,width:s,height:o}=this.buttonRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:s,height:o},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":const t=this.autoComplete.provider?.proposals;1===t?.length&&this.autoComplete.provider?.selectProposal(t[0].text||"");const s=this.autoComplete.selectedProposal;this.autoComplete.provider?.selectProposal(s?.text||"");break;case"ArrowUp":case"ArrowDown":this.autoComplete.moveSelection("ArrowDown"===e.key?"next":"previous");break;case"Escape":this.popover.isOpen=!1}}}class JH extends t.Component{static template="o-spreadsheet-PivotDimension";static props={dimension:Object,onRemoved:{type:Function,optional:!0},onNameUpdated:{type:Function,optional:!0},slots:{type:Object,optional:!0}};static components={CogWheelMenu:FU,TextInput:TU};updateName(e){this.props.onNameUpdated?.(this.props.dimension,""===e||e.startsWith("=")?void 0:e)}}class QH extends t.Component{static template="o-spreadsheet-PivotDimensionGranularity";static props={dimension:Object,onUpdated:Function,availableGranularities:Set,allGranularities:Array};periods=Jg}class ez extends t.Component{static template="o-spreadsheet-PivotDimensionOrder";static props={dimension:Object,onUpdated:Function}}class tz extends t.Component{static template="o-spreadsheet-PivotMeasureEditor";static components={PivotDimension:JH,StandaloneComposer:JP};static props={definition:Object,measure:Object,onMeasureUpdated:Function,onRemoved:Function,generateMeasureId:Function,aggregators:Object,pivotId:String};getMeasureAutocomplete(){return e=this.props.definition,t=this.props.measure,{sequence:0,autoSelectFirstProposal:!0,getProposals(s){const o=e.measures.filter(e=>e!==t).map(e=>{const t=he(e.id);return{text:t,description:e.displayName,htmlContent:[{value:t,color:x}],fuzzySearchKey:e.displayName+t+e.fieldName}}),i=e.rows.concat(e.columns).map(e=>{const t=he(e.nameWithGranularity);return{text:t,description:e.displayName,htmlContent:[{value:t,color:x}],fuzzySearchKey:e.displayName+t+e.fieldName}});return o.concat(i)},selectProposal(e,t){let s=e.end;"SYMBOL"===e.type&&(s=e.start);const o=e.end;this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}};var e,t}updateMeasureFormula(e){this.props.onMeasureUpdated({...this.props.measure,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:"="===e[0]?e:"="+e}})}updateAggregator(e){this.props.onMeasureUpdated({...this.props.measure,aggregator:e,id:this.props.generateMeasureId(this.props.measure.fieldName,e)})}updateName(e,t){this.props.measure.computedBy&&t?this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t,id:this.props.generateMeasureId(t,this.props.measure.aggregator),fieldName:t}):this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t})}toggleMeasureVisibility(){this.props.onMeasureUpdated({...this.props.measure,isHidden:!this.props.measure.isHidden})}openShowValuesAs(){this.env.replaceSidePanel("PivotMeasureDisplayPanel",`pivot_key_${this.props.pivotId}`,{pivotId:this.props.pivotId,measure:this.props.measure})}getColoredSymbolToken(e){if("SYMBOL"!==e.type)return;const t=ce(e.value,"'");return this.props.definition.columns.some(e=>e.nameWithGranularity===t)||this.props.definition.rows.some(e=>e.nameWithGranularity===t)||this.props.definition.measures.some(e=>e.id===t&&e.id!==this.props.measure.id)?x:void 0}get isCalculatedMeasureInvalid(){return sE(this.props.measure.computedBy?.formula??"").isBadExpression}}class sz extends t.Component{static template="o-spreadsheet-PivotSortSection";static components={Section:aM};static props={definition:Object,pivotId:String};get hasValidSort(){const e=this.env.model.getters.getPivot(this.props.pivotId);return!!this.props.definition.sortedColumn&&gp(this.props.definition.sortedColumn,e)}get sortDescription(){const e="asc"===this.props.definition.sortedColumn?.order?fs("ascending"):fs("descending");return fs("Sorted on column (%(ascOrDesc)s):",{ascOrDesc:e})}get sortValuesAndFields(){const e=this.props.definition.sortedColumn;if(!e)return[];const t=this.env.model.getters.getPivot(this.props.pivotId),s=this.env.model.getters.getLocale(),o=[],i=[];for(const n of e.domain){o.push(n);const{value:e,format:r}=t.getPivotHeaderValueAndFormat(o),a=pn(e,{format:r,locale:s}),l=t.definition.getDimension(n.field);i.push({field:dp(l),value:a})}0===e.domain.length&&i.push({value:fs("Total")});const n=t.getMeasure(e.measure).displayName;return i.push({value:n,field:fs("Measure")}),i}}class oz extends t.Component{static template="o-spreadsheet-PivotLayoutConfigurator";static components={AddDimensionButton:KH,PivotDimension:JH,PivotDimensionOrder:ez,PivotDimensionGranularity:QH,PivotMeasureEditor:tz,PivotSortSection:sz,PivotCustomGroupsCollapsible:YH};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=t.useRef("pivot-dimensions");dragAndDrop=cM();AGGREGATORS=Yg;composerFocus;isDateOrDatetimeField=tp;setup(){this.composerFocus=ev(uv)}startDragAndDrop(e,t){if(0!==t.button||"SELECT"===t.target.tagName)return;const s=this.getDimensionElementsRects(),o=this.props.definition,{columns:i,rows:n}=o,r=[...i.map(e=>e.nameWithGranularity),"__rows_title__",...n.map(e=>e.nameWithGranularity)],a=i.concat(n),l=r.map((e,t)=>({id:e,size:s[t+1].height,position:s[t+1].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:l,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{const s=r.findIndex(t=>t===e);if(s===t)return;const o=[...r];o.splice(s,1),o.splice(t,0,e);const i=o.slice(0,o.indexOf("__rows_title__")),n=o.slice(o.indexOf("__rows_title__")+1);this.props.onDimensionsUpdated({columns:i.map(e=>a.find(t=>t.nameWithGranularity===e)).filter(Te),rows:n.map(e=>a.find(t=>t.nameWithGranularity===e)).filter(Te)})}})}getGranularitiesFor(e){return tp(e)?"date"===e.type?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(0!==t.button||"SELECT"===t.target.tagName||"INPUT"===t.target.tagName||"inactive"!==this.composerFocus.focusMode)return;const s=this.getDimensionElementsRects(),o=this.props.definition,{measures:i,columns:n,rows:r}=o,a=i.map(e=>e.id),l=3+n.length+r.length,c=a.map((e,t)=>({id:e,size:s[t+l].height,position:s[t+l].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{const s=a.findIndex(t=>t===e);if(s===t)return;const o=[...a];o.splice(s,1),o.splice(t,0,e),this.props.onDimensionsUpdated({measures:o.map(e=>i.find(t=>t.id===e)).filter(Te)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{const t=getComputedStyle(e),s=e.getBoundingClientRect();return{x:s.x,y:s.y,width:s.width+parseInt(t.marginLeft||"0")+parseInt(t.marginRight||"0"),height:s.height+parseInt(t.marginTop||"0")+parseInt(t.marginBottom||"0")}})}removeDimension(e){const{columns:t,rows:s}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:s.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){const{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){const{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:"asc"}])})}addRowDimension(e){const{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:"asc"}])})}addMeasureDimension(e){const{measures:t}=this.props.definition,s=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,s),fieldName:e,aggregator:s}])})}updateMeasure(e,t){const{measures:s}=this.props.definition,o={measures:s.map(s=>s.id===e.id?t:s)};this.props.definition.sortedColumn?.measure===e.id&&(o.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(o)}getMeasureId(e,t){const s=e.replaceAll("'","")+(t?`:${t}`:"");let o=s,i=2;for(;this.props.definition.measures.some(e=>e.id===o);)o=`${s}:${i}`,i++;return o}getDefaultMeasureAggregator(e){const t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:"count"}addCalculatedMeasure(){const{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,"sum"),fieldName:t,aggregator:"sum",computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:"=0"}}])})}getCustomField(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);return t.customFields?.[e.nameWithGranularity]}updateOrder(e,t){const{rows:s,columns:o}=this.props.definition;this.props.onDimensionsUpdated({rows:s.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,order:t||void 0}:s),columns:o.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,order:t||void 0}:s)})}updateGranularity(e,t){const{rows:s,columns:o}=this.props.definition;this.props.onDimensionsUpdated({rows:s.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,granularity:t}:s),columns:o.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,granularity:t}:s)})}getMeasureDescription(e){const t=e.display;if(!t||"no_calculations"===t.type)return"";const s=this.env.model.getters.getPivot(this.props.pivotId),o=[...s.definition.columns,...s.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=o?dp(o):"";return _g.descriptions[t.type](i)}getHugeDimensionErrorMessage(e){const t=this.env.model.getters.getPivot(this.props.pivotId).getPossibleFieldValues(e);return t.length>100?fs("This dimension contains a lot of values (%s), and might slow down the pivot table.",t.length):void 0}}class iz extends t.Component{static template="o-spreadsheet-PivotTitleSection";static components={CogWheelMenu:FU,Section:aM,TextInput:TU};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:fs("Flip axes"),icon:"o-spreadsheet-Icon.EXCHANGE",execute:this.props.flipAxis},{name:fs("Duplicate"),icon:"o-spreadsheet-Icon.COPY",execute:()=>this.duplicatePivot()},{name:fs("Delete"),icon:"o-spreadsheet-Icon.TRASH",execute:()=>this.delete()}]}get name(){return this.env.model.getters.getPivotName(this.props.pivotId)}get displayName(){return this.env.model.getters.getPivotDisplayName(this.props.pivotId)}duplicatePivot(){const e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),s=this.env.model.dispatch("DUPLICATE_PIVOT_IN_NEW_SHEET",{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t});let o;o=s.isSuccessful?fs("Pivot duplicated."):s.isCancelledBecause("PivotInError")?fs("Cannot duplicate a pivot in error."):fs("Pivot duplication failed.");const i=s.isSuccessful?"success":"danger";this.env.notifyUser({text:o,sticky:!1,type:i}),s.isSuccessful&&this.env.openSidePanel("PivotSidePanel",{pivotId:e})}delete(){this.env.askConfirmation(fs("Are you sure you want to delete this pivot?"),()=>{this.env.model.dispatch("REMOVE_PIVOT",{pivotId:this.props.pivotId})})}onNameChanged(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch("UPDATE_PIVOT",{pivotId:this.props.pivotId,pivot:{...t,name:e}})}}class nz extends hv{pivotId;mutators=["reset","deferUpdates","applyUpdate","discardPendingUpdate","update"];updatesAreDeferred;draft=null;notification=this.get(jP);alreadyNotified=!1;alreadyNotifiedForPivotSize=!1;constructor(e,t){super(e),this.pivotId=t,this.updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){if("UPDATE_PIVOT"===e.type)e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){const e=XD.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){const e=[{name:"__count",string:fs("Count"),type:"integer",aggregator:"sum"}],t=this.fields;for(const s in t){const o=t[s];o&&(XD.get(this.pivot.type).isMeasureCandidate(o)&&e.push(o))}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){const e=[],t=this.fields;for(const s in t){const o=t[s];o&&(XD.get(this.pivot.type).isGroupable(o)&&e.push(o))}const{columns:s,rows:o,measures:i}=this.definition,n=i.concat(o).concat(s).map(e=>e.fieldName),r=this.unusedGranularities;return e.filter(e=>tp(e)?!n.includes(e.name)||r[e.name].size>0:!n.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return XD.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return XD.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this.updatesAreDeferred=!0,this.draft=null}deferUpdates(e){!1===e&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this.updatesAreDeferred=e}applyUpdate(){if(this.draft){if(this.model.dispatch("UPDATE_PIVOT",{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot()){const e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:"info",text:fs("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})}const e=this.getters.getPivot(this.pivotId),t=e.isValid()?e.getExpandedTableStructure().numberOfCells:0;!this.alreadyNotifiedForPivotSize&&t>Q&&(this.alreadyNotifiedForPivotSize=!0,this.notification.notifyUser({type:"warning",text:yP(t,this.getters.getLocale()),sticky:!0}))}}discardPendingUpdate(){this.draft=null}update(e){const t=this.getters.getPivotCoreDefinition(this.pivotId),s={...t,...this.draft,...e},o={...s,columns:s.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:s.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:s.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display})),sortedColumn:this.shouldKeepSortedColumn(s)?s.sortedColumn:void 0};if(o.collapsedDomains){const{COL:e,ROW:t}=o.collapsedDomains;o.collapsedDomains={COL:e.filter(e=>this.areDomainFieldsValid(e,o.columns)),ROW:t.filter(e=>this.areDomainFieldsValid(e,o.rows))}}if(!this.draft&&Me(t,o))return;const i=this.addDefaultDateTimeGranularity(this.fields,o);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0;const t=this.getters.getPivotFormulaId(this.pivotId);for(const s of this.getters.getVisibleCellPositions()){const o=this.getters.getCell(s);if(o?.isFormula){const s=MD(o.compiledFormula.tokens),i=s?.args[0]?.value;if(s&&t===i.toString()){if("PIVOT"===s.functionName)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){const{columns:s,rows:o}=t,i=ae(s),n=ae(o),r=this.getUnusedGranularities(e,t);for(const t of i.concat(n)){const s=e[t.fieldName]?.type;if(("date"===s||"datetime"===s)&&!t.granularity){const e=r[t.fieldName]?.values().next().value||"year";r[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:n}}getUnusedGranularities(e,t){const{columns:s,rows:o,measures:i}=t,n=s.concat(o).concat(i).filter(t=>{const s=e[t.fieldName]?.type;return"date"===s||"datetime"===s}),r={};for(const t of n)r[t.fieldName]=new Set("date"===e[t.fieldName]?.type?this.dateGranularities:this.datetimeGranularities);for(const e of n)r[e.fieldName].delete(e.granularity||"month");return r}shouldKeepSortedColumn(e){const{sortedColumn:t}=e;if(!t)return!0;const s=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find(e=>e.id===t.measure)&&Me(s.columns,e.columns)}areDomainFieldsValid(e,t){const s=t.map(({fieldName:e,granularity:t})=>e+(t?`:${t}`:""));for(let t=0;t<e.length;t++)if(e[t].field!==s[t])return!1;return!0}}class rz extends t.Component{static template="o-spreadsheet-PivotSpreadsheetSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:oz,Section:aM,SelectionInput:fM,Checkbox:IM,PivotDeferUpdate:jH,PivotTitleSection:iz};store;state;pivotSidePanelRef=t.useRef("pivotSidePanel");setup(){this.store=tv(nz,this.props.pivotId),this.state=t.useState({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return(!this.store.isDirty||!this.state.rangeHasChanged)&&this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,"forceSheetReference")]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){const e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;const t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){const{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}}const az=new Og;az.add("SPREADSHEET",{editor:rz});class lz extends t.Component{static template="o-spreadsheet-PivotSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:oz,Section:aM};setup(){DH(this)}get sidePanelEditor(){const e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw new Error("pivotId does not correspond to a pivot.");return az.get(e.type).editor}get highlights(){return ZH(this.env.model.getters,this.props.pivotId)}}class cz extends t.Component{static template="o-spreadsheet-RemoveDuplicatesPanel";static components={ValidationMessages:JV,Section:aM,Checkbox:IM};static props={onCloseSidePanel:Function};state=t.useState({hasHeader:!1,columns:{}});setup(){this.updateColumns(),t.onWillUpdateProps(()=>this.updateColumns())}toggleHasHeader(){this.state.hasHeader=!this.state.hasHeader}toggleAllColumns(){const e=!this.isEveryColumnSelected;for(const t in this.state.columns)this.state.columns[t]=e}toggleColumn(e){this.state.columns[e]=!this.state.columns[e]}onRemoveDuplicates(){this.env.model.dispatch("REMOVE_DUPLICATES",{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()})}getColLabel(e){const t=parseInt(e);let s=fs("Column %s",it(t));if(this.state.hasHeader){const e=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSelectedZone().top,i=this.env.model.getters.getEvaluatedCell({sheetId:e,col:t,row:o});"empty"!==i.type&&(s+=` - ${i.value}`)}return s}get isEveryColumnSelected(){return Object.values(this.state.columns).every(e=>e)}get errorMessages(){const e=this.env.model.canDispatch("REMOVE_DUPLICATES",{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()}).reasons,t=new Set;for(const s of e)t.add(Tg.Errors[s]||Tg.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){const e=Ut(this.env.model.getters.getSelectedZone());return fs("%(row_count)s rows and %(column_count)s columns selected",{row_count:e.numberOfRows,column_count:e.numberOfCols})}get canConfirm(){return 0===this.errorMessages.length}updateColumns(){const e=this.env.model.getters.getSelectedZone(),t=this.state.columns,s={};for(let o=e.left;o<=e.right;o++)s[o]=!(o in t)||t[o];this.state.columns=s}getColsToAnalyze(){return Object.keys(this.state.columns).filter(e=>this.state.columns[e]).map(e=>parseInt(e))}}class hz extends t.Component{static template="o-spreadsheet-SettingsPanel";static components={Section:aM,ValidationMessages:JV,BadgeSelection:UU};static props={onCloseSidePanel:Function};loadedLocales=[];setup(){t.onWillStart(()=>this.loadLocales())}onLocaleChange(e){const t=this.loadedLocales.find(t=>t.code===e);t&&this.env.model.dispatch("UPDATE_LOCALE",{locale:t})}async loadLocales(){this.loadedLocales=(await this.env.loadLocales()).filter(e=>{const t=Xc(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t}).sort((e,t)=>e.name.localeCompare(t.name))}get numberFormatPreview(){return pn(1234567.89,{format:"#,##0.00",locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){const e=this.env.model.getters.getLocale();return pn(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){const e=this.env.model.getters.getLocale();return pn(1.6,{format:hh(e),locale:e})}get firstDayOfWeek(){const e=this.env.model.getters.getLocale().weekStart;return un[e%7]}get currentLocale(){return this.env.model.getters.getLocale()}get supportedLocales(){const e=this.currentLocale,t=this.loadedLocales.find(t=>t.code===e.code);if(!t)return[...this.loadedLocales,e].sort((e,t)=>e.name.localeCompare(t.name));if(!Me(e,t)){const s=this.loadedLocales.indexOf(t),o=[...this.loadedLocales];return o[s]=e,o.sort((e,t)=>e.name.localeCompare(t.name)),o}return this.loadedLocales}}const dz={SplitIsDestructive:fs("This will overwrite data in the subsequent columns. Split anyway?")};const uz=[{name:fs("Detect automatically"),value:"auto"},{name:fs("Custom separator"),value:"custom"},{name:fs("Space"),value:" "},{name:fs("Comma"),value:","},{name:fs("Semicolon"),value:";"},{name:fs("Line Break"),value:X}];class gz extends t.Component{static template="o-spreadsheet-SplitIntoColumnsPanel";static components={ValidationMessages:JV,Section:aM,Checkbox:IM};static props={onCloseSidePanel:Function};state=t.useState({separatorValue:"auto",addNewColumns:!1,customSeparator:""});setup(){const e=ev(uv);t.useEffect(e=>{"inactive"!==e&&this.props.onCloseSidePanel()},()=>[e.focusMode]),t.onMounted(()=>{e.activeComposer.stopEdition()})}onSeparatorChange(e){this.state.separatorValue=e}updateCustomSeparator(e){e.target&&(this.state.customSeparator=e.target.value)}updateAddNewColumnsCheckbox(e){this.state.addNewColumns=e}confirm(){(function(e,t,s){let o=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:s});return o.isCancelledBecause("SplitWillOverwriteContent")&&e.askConfirmation(dz.SplitIsDestructive,()=>{o=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:s,force:!0})}),o})(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){const e=this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(const s of e)switch(s){case"SplitWillOverwriteContent":case"EmptySplitSeparator":break;default:t.add(xg.Errors[s]||xg.Errors.Unexpected)}return Array.from(t)}get warningMessages(){const e=[];return this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes("SplitWillOverwriteContent")&&e.push(xg.Errors.SplitWillOverwriteContent),e}get separatorValue(){return"custom"===this.state.separatorValue?this.state.customSeparator:"auto"===this.state.separatorValue?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return uz}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}}function pz(e,t,s,o){e.resetTransform(),function(e,t,s,o){e.save();for(let i=0;i<5;i++)for(let n=0;n<5;n++)e.fillStyle=t.styles[i][n].fillColor||"#fff",e.fillRect(i*s,n*o,s,o);e.restore()}(e,t,s,o),function(e,t,s,o){e.save(),e.translate(0,.5),e.lineWidth=1;for(let i=0;i<5;i++)for(let n=0;n<5;n++){const r=t.borders[i][n];r.top&&(e.strokeStyle=r.top.color,e.beginPath(),e.moveTo(i*s,n*o),e.lineTo(i*s+s,n*o),e.stroke()),r.bottom&&(e.strokeStyle=r.bottom.color,e.beginPath(),e.moveTo(i*s,n*o+o),e.lineTo(i*s+s,n*o+o),e.stroke())}e.resetTransform(),e.translate(.5,0);for(let i=0;i<5;i++)for(let n=0;n<5;n++){const r=t.borders[i][n];r.left&&(e.strokeStyle=r.left.color,e.beginPath(),e.moveTo(i*s,n*o),e.lineTo(i*s,n*o+o),e.stroke()),r.right&&(e.strokeStyle=r.right.color,e.beginPath(),e.moveTo(i*s+s,n*o),e.lineTo(i*s+s,n*o+o+1),e.stroke())}e.restore()}(e,t,s,o),function(e,t,s,o){e.save(),e.translate(0,.5),e.lineWidth=1;const i=Math.floor(s/4),n=Math.floor(o/2);for(let r=0;r<5;r++)for(let a=0;a<5;a++)e.strokeStyle=t.styles[r][a].textColor||"#000",e.beginPath(),e.moveTo(r*s+i+1,a*o+n),e.lineTo(r*s+s-i,a*o+n),e.stroke();e.restore()}(e,t,s,o)}class mz extends t.Component{static template="o-spreadsheet-TableStylePreview";static components={MenuPopover:PF};static props={tableConfig:Object,tableStyle:Object,class:String,styleId:{type:String,optional:!0},selected:{type:Boolean,optional:!0},onClick:{type:Function,optional:!0}};canvasRef=t.useRef("canvas");menu=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});setup(){t.onWillUpdateProps(e=>{Me(this.props.tableConfig,e.tableConfig)&&Me(this.props.tableStyle,e.tableStyle)||this.drawTable(e)}),t.onMounted(()=>this.drawTable(this.props))}drawTable(e){const t=this.canvasRef.el.getContext("2d"),{width:s,height:o}=this.canvasRef.el.getBoundingClientRect();this.canvasRef.el.width=s,this.canvasRef.el.height=o;pz(t,AA(e.tableConfig,e.tableStyle,5,5),(s-1)/5,(o-1)/5)}onContextMenu(e){var t,s;this.props.styleId&&(this.menu.menuItems=(t=this.env,s=this.props.styleId,t.model.getters.isTableStyleEditable(s)?qf([{id:"editTableStyle",name:fs("Edit table style"),execute:e=>e.openSidePanel("TableStyleEditorPanel",{styleId:s}),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.EDIT"},{id:"deleteTableStyle",name:fs("Delete table style"),execute:e=>e.model.dispatch("REMOVE_TABLE_STYLE",{tableStyleId:s}),icon:"o-spreadsheet-Icon.TRASH"}]):[]),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.env.model.getters.getTableStyle(this.props.styleId).displayName:""}get isStyleEditable(){return!!this.props.styleId&&this.env.model.getters.isTableStyleEditable(this.props.styleId)}editTableStyle(){this.env.openSidePanel("TableStyleEditorPanel",{styleId:this.props.styleId})}}class fz extends t.Component{static template="o-spreadsheet-TableStylesPopover";static components={Popover:DF,TableStylePreview:mz};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0}};categories=cE;tableStyleListRef=t.useRef("tableStyleList");state=t.useState({selectedCategory:this.initialSelectedCategory});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!Dy(this.tableStyleListRef.el,e)&&(this.props.closePopover(),e.hasClosedTableStylesPopover=!0)}get displayedStyles(){const e=this.env.model.getters.getTableStyles();return Object.keys(e).filter(t=>e[t].category===this.state.selectedCategory)}get initialSelectedCategory(){return this.props.selectedStyleId?this.env.model.getters.getTableStyle(this.props.selectedStyleId).category:"medium"}newTableStyle(){this.props.closePopover(),this.env.openSidePanel("TableStyleEditorPanel",{onStylePicked:this.props.onStylePicked})}}class vz extends t.Component{static template="o-spreadsheet-TableStylePicker";static components={TableStylesPopover:fz,TableStylePreview:mz};static props={table:Object};state=t.useState({popoverProps:void 0});getDisplayedTableStyles(){const e=this.env.model.getters.getTableStyles(),t=e[this.props.table.config.styleId].category,s=Object.keys(e).filter(s=>e[s].category===t),o=s.indexOf(this.props.table.config.styleId);if(-1===o)return o;const i=4*Math.floor(o/4);return s.slice(i)}onStylePicked(e){const t=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("UPDATE_TABLE",{sheetId:t,zone:this.props.table.range.zone,config:{styleId:e}}),this.closePopover()}onArrowButtonClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps)return void this.closePopover();const t=e.currentTarget,{bottom:s,right:o}=t.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:o,y:s,width:0,height:0},positioning:"top-right",verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}}class bz extends t.Component{static template="o-spreadsheet-TablePanel";static components={TableStylePicker:vz,SelectionInput:fM,ValidationMessages:JV,Checkbox:IM,Section:aM};static props={onCloseSidePanel:Function,table:Object};state;setup(){const e=this.env.model.getters.getActiveSheetId();this.state=t.useState({tableZoneErrors:[],tableXc:this.env.model.getters.getRangeString(this.props.table.range,e),filtersEnabledIfPossible:this.props.table.config.hasFilters})}updateHasFilters(e){this.state.filtersEnabledIfPossible=e,this.updateTableConfig("hasFilters",e)}updateTableConfig(e,t){const s=this.env.model.getters.getActiveSheetId();return this.env.model.dispatch("UPDATE_TABLE",{sheetId:s,zone:this.props.table.range.zone,config:{[e]:t}})}updateHasHeaders(e){const t=e?1:0;this.updateNumberOfHeaders(t)}updateTableIsDynamic(e){const t=e?"dynamic":"forceStatic";if(t===this.props.table.type)return;const s=this.env.model.getters.getTable(RA(this.props.table));if(!s)return;const o=this.env.model.getters.getActiveSheetId(),i=this.env.model.dispatch("UPDATE_TABLE",{sheetId:o,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(s.range),tableType:t}),n=this.env.model.getters.getCoreTable(RA(this.props.table));if(i.isSuccessful&&n){const e=n.range;this.state.tableXc=this.env.model.getters.getRangeString(e,o),this.state.tableZoneErrors=[]}}onChangeNumberOfHeaders(e){const t=e.target,s=parseInt(t.value);this.updateNumberOfHeaders(s).isSuccessful||(t.value=this.props.table.config.numberOfHeaders.toString())}updateNumberOfHeaders(e){const t=e>0&&(this.tableConfig.hasFilters||this.state.filtersEnabledIfPossible);return this.env.model.dispatch("UPDATE_TABLE",{sheetId:this.env.model.getters.getActiveSheetId(),zone:this.props.table.range.zone,config:{numberOfHeaders:e,hasFilters:t}})}onRangeChanged(e){const t=this.env.model.getters.getActiveSheetId();this.state.tableXc=e[0];const s=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(s.zone)}).reasons}onRangeConfirmed(){const e=this.env.model.getters.getActiveSheetId();let t=this.env.model.getters.getRangeFromSheetXC(e,this.state.tableXc);if(1===Kt(t.zone)){const s=this.env.model.getters.getContiguousZone(e,t.zone);t=this.env.model.getters.getRangeFromZone(e,s)}const s=t.zone,o=this.props.table.range.zone,i=s.top===o.top&&s.left===o.left?"RESIZE_TABLE":"UPDATE_TABLE",n=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)}),r={sheetId:e,col:t.zone.left,row:t.zone.top},a=this.env.model.getters.getCoreTable(r);if(n.isSuccessful&&a){const t=RA(a);this.env.model.selection.selectZone({zone:Zt(t),cell:t});const s=a.range;this.state.tableXc=this.env.model.getters.getRangeString(s,e)}}deleteTable(){const e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("REMOVE_TABLE",{sheetId:e,target:[this.props.table.range.zone]})}getNewTableType(e){if("forceStatic"===this.props.table.type)return"forceStatic";const t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.canCreateDynamicTableOnZones(t,[e])?"dynamic":"static"}get tableConfig(){return this.props.table.config}get errorMessages(){return(this.state.tableZoneErrors||[]).map(e=>Dg.Errors[e]||Dg.Errors.Unexpected)}getCheckboxLabel(e){return Dg.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:Dg.Tooltips.filterWithoutHeader}get canBeDynamic(){const e=this.env.model.getters.getActiveSheetId();return"dynamic"===this.props.table.type||this.env.model.getters.canCreateDynamicTableOnZones(e,[this.props.table.range.zone])}get dynamicTableTooltip(){return Dg.Tooltips.isDynamic}}const Sz="#3C78D8";class Cz extends t.Component{static template="o-spreadsheet-TableStyleEditorPanel";static components={Section:aM,RoundColorPicker:lM,TableStylePreview:mz};static props={onCloseSidePanel:Function,onStylePicked:{type:Function,optional:!0},styleId:{type:String,optional:!0}};state=t.useState(this.getInitialState());setup(){t.useExternalListener(window,"click",()=>this.state.pickerOpened=!1)}getInitialState(){const e=this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId):null;return{pickerOpened:!1,primaryColor:e?.primaryColor||Sz,selectedTemplateName:e?.templateName||"lightColoredText",styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=Sv(e)?e:Sz,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){const e=this.props.styleId||this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch("CREATE_TABLE_STYLE",{tableStyleId:e,tableStyleName:this.state.styleName,templateName:this.state.selectedTemplateName,primaryColor:this.state.primaryColor}),this.props.onStylePicked?.(e),this.props.onCloseSidePanel()}onCancel(){this.props.onCloseSidePanel()}onDelete(){this.props.styleId&&(this.env.model.dispatch("REMOVE_TABLE_STYLE",{tableStyleId:this.props.styleId}),this.props.onCloseSidePanel())}get colorPreviewStyle(){return Ey({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(TE).filter(e=>"none"!==e)}get previewTableConfig(){return{bandedColumns:!1,bandedRows:!0,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,totalRow:!0,hasFilters:!0,styleId:""}}get selectedStyle(){return this.computeTableStyle(this.state.selectedTemplateName)}computeTableStyle(e){return AE(this.state.styleName,e,this.state.primaryColor)}}const yz=new Og;yz.add("ConditionalFormatting",{title:fs("Conditional formatting"),Body:PH}),yz.add("ChartPanel",{title:fs("Chart"),Body:xH,computeState:(e,t)=>{const s=e.getSelectedFigureId(),o=s?e.getChartIdFromFigureId(s):t.chartId;return o&&e.isChartDefined(o)?{isOpen:!0,props:{chartId:o}}:{isOpen:!1}}}),yz.add("FindAndReplace",{title:fs("Find and Replace"),Body:BH}),yz.add("CustomCurrency",{title:fs("Custom currency format"),Body:NH}),yz.add("SplitToColumns",{title:fs("Split text into columns"),Body:gz}),yz.add("Settings",{title:fs("Spreadsheet settings"),Body:hz}),yz.add("RemoveDuplicates",{title:fs("Remove duplicates"),Body:cz}),yz.add("DataValidation",{title:fs("Data validation"),Body:VH}),yz.add("DataValidationEditor",{title:fs("Data validation"),Body:LH}),yz.add("MoreFormats",{title:fs("More date formats"),Body:WH}),yz.add("TableSidePanel",{title:fs("Edit table"),Body:bz,computeState:e=>{const t=e.getFirstTableInSelection();if(!t)return{isOpen:!1};return{isOpen:!0,props:{table:e.getCoreTable(RA(t))},key:t.id}}}),yz.add("TableStyleEditorPanel",{title:fs("Create custom table style"),Body:Cz,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??"new"})}),yz.add("PivotSidePanel",{title:(e,t)=>fs("Pivot #%s",e.model.getters.getPivotFormulaId(t.pivotId)),Body:lz,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),yz.add("PivotMeasureDisplayPanel",{title:(e,t)=>{const s=e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id);return fs('Measure "%s" options',s.displayName)},Body:qH,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(e){return{isOpen:!1}}}}),yz.add("CarouselPanel",{title:fs("Carousel"),Body:PU,computeState:(e,t)=>{const s=t.figureId||e.getSelectedFigureId();return s&&e.doesCarouselExist(s)?{isOpen:!0,props:{figureId:s}}:{isOpen:!1}}});class Iz{mutators=["setSmallThreshhold"];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}}const wz=350,Ez=150;class Rz extends hv{mutators=["open","replace","toggle","close","changePanelSize","resetPanelSize","togglePinPanel","closeMainPanel","changeSpreadsheetWidth","toggleCollapsePanel"];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(Iz);get isMainPanelOpen(){return!(!this.mainPanel||!this.mainPanel.componentTag)&&this.computeState(this.mainPanel).isOpen}get isSecondaryPanelOpen(){return!(!this.secondaryPanel||!this.secondaryPanel.componentTag)&&this.computeState(this.secondaryPanel).isOpen}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){const t=this.computeState(e);return t.isOpen?t.props??{}:{}}getPanelKey(e){const t=this.computeState(e);if(t.isOpen)return t.key}open(e,t={}){if(this.screenWidthStore.isSmall)return;const s={initialPanelProps:t,componentTag:e,size:wz},o=this.computeState(s);if(!o.isOpen)return;if(!this.mainPanel||!this.mainPanel.isPinned||this.mainPanelKey===o.key)return void this._openPanel("mainPanel",s,o);const i=this.mainPanel.isCollapsed?wz:this.mainPanel.size;!this.secondaryPanel&&i+wz>this.availableWidth?this.get(jP).notifyUser({sticky:!1,type:"warning",text:fs("The window is too small to display multiple side panels.")}):this._openPanel("secondaryPanel",s,o)}replace(e,t,s={}){const o={initialPanelProps:s,componentTag:e,size:wz},i=this.computeState(o);if(!i.isOpen)return;const n=()=>{this.mainPanel?.isCollapsed&&this.toggleCollapsePanel("mainPanel")},r=this.mainPanelKey===i.key,a=this.secondaryPanelKey===i.key;if(r&&this.secondaryPanel)return this.close(),void n();if(a)return this.closeMainPanel(),this.togglePinPanel(),void n();const l=this.mainPanelKey===t?"mainPanel":"secondaryPanel";this._openPanel(l,o,i)}_openPanel(e,t,s){const o=this[e];o&&t.componentTag!==o.componentTag&&o.initialPanelProps?.onCloseSidePanel?.(),this[e]={initialPanelProps:s.props??{},componentTag:t.componentTag,size:o?.size||wz,isCollapsed:o?.isCollapsed||!1,isPinned:!(!o||!("isPinned"in o))&&o.isPinned},this[e].isCollapsed&&this.toggleCollapsePanel(e)}toggle(e,t){const s=this.mainPanel?.isPinned?this.secondaryPanel:this.mainPanel;s&&e===s.componentTag?this.close():this.open(e,t)}close(){this.mainPanel?.isPinned?this.secondaryPanel&&(this.secondaryPanel.initialPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0):(this.mainPanel?.initialPanelProps.onCloseSidePanel?.(),this.mainPanel=void 0)}closeMainPanel(){this.mainPanel?.initialPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel||void 0,this.secondaryPanel=void 0}changePanelSize(e,t){const s=this[e];if(!s||"isCollapsed"in s&&s.isCollapsed)return;t=Math.max(t,wz);let o="mainPanel"===e?this.secondaryPanel?.size||0:this.mainPanel?.size||0;t>this.availableWidth-o&&("mainPanel"===e&&this.secondaryPanel&&(this.secondaryPanel.size=Math.max(this.availableWidth-t,wz),o=this.secondaryPanel.size),t=Math.max(this.availableWidth-o,wz)),s.size=t}resetPanelSize(e){this[e]&&(this[e].size=wz)}togglePinPanel(){this.mainPanel&&(this.mainPanel.isPinned=!this.mainPanel.isPinned,!this.mainPanel.isPinned&&this.secondaryPanel&&(this.secondaryPanel?.initialPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel,this.secondaryPanel=void 0))}toggleCollapsePanel(e){const t=this[e];t&&(t.isCollapsed?(t.isCollapsed=!1,this.changePanelSize(e,wz)):(t.isCollapsed=!0,t.size=45))}computeState({componentTag:e,initialPanelProps:t}){const s=yz.get(e).computeState,o=s?s(this.getters,t):{isOpen:!0,props:t};return o.isOpen?{...o,key:o.key||e}:o}changeSpreadsheetWidth(e){this.availableWidth=e-Ez,this.secondaryPanel&&e-this.totalPanelSize<Ez&&(this.secondaryPanel?.initialPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0),this.mainPanel&&e-this.totalPanelSize<Ez&&(this.mainPanel.size=Math.max(e-Ez,wz))}}class xz extends t.Component{static template="o-spreadsheet-TableResizer";static props={table:Object};state=t.useState({highlightZone:void 0});dragNDropGrid=VV(this.env);setup(){DH(this)}get containerStyle(){const e=this.props.table.range.zone,t={...e,left:e.right,top:e.bottom},s=this.env.model.getters.getVisibleRect(t);return 0===s.height||0===s.width?Ey({display:"none"}):Ey({top:s.y+s.height-6+"px",left:s.x+s.width-6+"px"})}onMouseDown(e){const t=this.props.table.range.zone,s={col:t.left,row:t.top};document.body.style.cursor="nwse-resize";this.dragNDropGrid.start(e,(e,t,o)=>{this.state.highlightZone={left:s.col,top:s.row,right:Math.max(e,s.col),bottom:Math.max(t,s.row)}},()=>{document.body.style.cursor="";const e=this.state.highlightZone;if(!e)return;const t=this.props.table.range.sheetId;this.env.model.dispatch("RESIZE_TABLE",{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0})}get highlights(){return this.state.highlightZone?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:"#777",noFill:!0}]:[]}}const Tz={ROW:NV,COL:DV,CELL:vk,GROUP_HEADERS:PV,UNGROUP_HEADERS:MV};class Az extends t.Component{static template="o-spreadsheet-Grid";static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:qV,GridOverlay:rU,GridPopover:aU,HeadersOverlay:gU,MenuPopover:PF,Autofill:HV,ClientTag:BV,Highlight:CU,Popover:DF,VerticalScrollBar:EU,HorizontalScrollBar:wU,TableResizer:xz,Selection:RU};HEADER_HEIGHT=A;HEADER_WIDTH=D;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=VV(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=ev(ZP),this.menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.hoveredCell=ev(HF),this.composerFocusStore=ev(uv),this.DOMFocusableElementStore=ev(OP),this.sidePanel=ev(Rz),this.paintFormatStore=ev(sU),this.clientFocusStore=ev(kV),ev(LV),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),t.useExternalListener(document.body,"cut",this.copy.bind(this,!0)),t.useExternalListener(document.body,"copy",this.copy.bind(this,!1)),t.useExternalListener(document.body,"paste",this.paste),t.onMounted(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),mU("canvas",this.env.model,()=>this.env.model.getters.getSheetViewDimensionWithHeaders()),this.onMouseWheel=vU((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=ev(wP),t.useEffect((e,t)=>{e||t||this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),fU(this.gridRef,this.moveCanvas.bind(this),()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){return Ey({top:"26px",left:"48px",height:"calc(100% - 41px)",width:"calc(100% - 63px)"})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>{this.env.model.getters.getActiveCell().type===_d.empty?this.onComposerCellFocused():this.onComposerContentFocused()},Tab:()=>this.env.model.selection.moveAnchorCell("right",1),"Shift+Tab":()=>this.env.model.selection.moveAnchorCell("left",1),F2:()=>{this.env.model.getters.getActiveCell().type===_d.empty?this.onComposerCellFocused():this.onComposerContentFocused()},Delete:()=>{this.env.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch("CLEAN_CLIPBOARD_HIGHLIGHT")},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch("REQUEST_UNDO"),"Ctrl+Y":()=>this.env.model.dispatch("REQUEST_REDO"),F4:()=>this.env.model.dispatch("REQUEST_REDO"),"Ctrl+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>uN(this.env),"Alt+=":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:s}=this.env.model.getters.getSelection(),o=this.env.model.getters.getAutomaticSums(e,t,s.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&o.length<=1){const t=o[0]?.zone,s=t?this.env.model.getters.zoneToXC(e,o[0].zone):"",i=`=SUM(${s})`;this.onComposerCellFocused(i,{start:5,end:5+s.length})}else this.env.model.dispatch("SUM_SELECTION")},"Alt+Enter":()=>{const e=this.env.model.getters.getActiveCell();e.link&&Wf(e.link,this.env)},"Ctrl+Home":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:s}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,s)},"Ctrl+End":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),s=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,s)},"Shift+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},s=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:s,zone:t})},"Ctrl+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},s=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:s,zone:t})},"Ctrl+D":async()=>this.env.model.dispatch("COPY_PASTE_CELLS_ABOVE"),"Ctrl+R":async()=>this.env.model.dispatch("COPY_PASTE_CELLS_ON_LEFT"),"Ctrl+H":()=>this.sidePanel.open("FindAndReplace",{}),"Ctrl+F":()=>this.sidePanel.open("FindAndReplace",{}),"Ctrl+Shift+E":()=>this.setHorizontalAlign("center"),"Ctrl+Shift+L":()=>this.setHorizontalAlign("left"),"Ctrl+Shift+R":()=>this.setHorizontalAlign("right"),"Ctrl+Shift+V":()=>rN(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{const e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),s=1===this.env.model.getters.getSelectedZones().length,o=e.size>0&&s,i=t.size>0&&s;o&&!i?hN(this.env):i&&!o&&cN(this.env)},"Ctrl+Alt+-":()=>{const e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&0===t.length?this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:"COL",elements:e}):t.length>0&&0===e.length&&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")},PageDown:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PageUp:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"Ctrl+K":()=>gN(this.env),"Alt+Shift+ArrowRight":()=>this.processHeaderGroupingKey("right"),"Alt+Shift+ArrowLeft":()=>this.processHeaderGroupingKey("left"),"Alt+Shift+ArrowUp":()=>this.processHeaderGroupingKey("up"),"Alt+Shift+ArrowDown":()=>this.processHeaderGroupingKey("down")};focusDefaultElement(){this.env.model.getters.getSelectedFigureId()||"inactive"!==this.composerFocusStore.activeComposer.editionMode||this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw new Error("Grid el is not defined.");return this.gridRef.el}getAutofillPosition(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-4,top:t.y+t.height-4}}get isAutofillVisible(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(0===t.width||0===t.height)}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t-D,height:e-A,gridOffsetX:D,gridOffsetY:A})}moveCanvas(e,t){const{scrollX:s,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s+e,offsetY:o+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(){return{...Oy(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,s,o){if(o.preventDefault(),"editing"===this.composerFocusStore.activeComposer.editionMode&&this.composerFocusStore.activeComposer.stopEdition(),s.expandZone?this.env.model.selection.setAnchorCorner(e,t):s.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t),this.env.isMobile())return;let i=e,n=t;this.dragNDropGrid.start(o,(e,t,s)=>{s.preventDefault(),(e!==i&&-1!==e||t!==n&&-1!==t)&&(i=-1===e?i:e,n=-1===t?n:t,this.env.model.selection.setAnchorCorner(i,n))},()=>{this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){const s=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:s,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:s,col:e,row:t}).type===_d.empty?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),PP(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){const t=ky(e),s=this.keyDownMapping[t];if(s)return e.preventDefault(),e.stopPropagation(),void s();" "!==t?e.key.startsWith("Arrow")&&this.processArrows(e):this.processSpaceKey(e)}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:s,top:o}=t;let i="CELL";this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(s)?i="COL":this.env.model.getters.getActiveRows().has(o)&&(i="ROW");const{x:n,y:r,width:a}=this.env.model.getters.getVisibleRect(t),l=this.getGridRect();this.toggleContextMenu(i,l.x+n+a,l.y+r)}onCellRightClicked(e,t,{x:s,y:o}){const i=this.env.model.getters.getSelectedZones();let n="CELL";kt(e,t,i[i.length-1])?this.env.model.getters.getActiveCols().has(e)?n="COL":this.env.model.getters.getActiveRows().has(t)&&(n="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(n,s,o)}toggleContextMenu(e,t,s){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.anchorRect={x:t,y:s,width:0,height:0},this.menuState.menuItems=Tz[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement))return;if("inactive"!==this.composerFocusStore.activeComposer.editionMode)return;e?YN(this.env):this.env.model.dispatch("COPY");const s=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(s),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();const t=e.clipboardData;if(!t)return;const s=[...t.files]?.find(e=>S_.includes(e.type)),o={content:{[gI.PlainText]:t?.getData(gI.PlainText),[gI.Html]:t?.getData(gI.Html)}};s&&(o.content[s.type]=s);const i=this.env.model.getters.getSelectedZones(),n=this.env.model.getters.isCutOperation(),r=this.env.model.getters.getClipboardId(),a=w_(o.content),l=a.data?.clipboardId;r===l?tN(this.env,i):await sN(this.env,i,a),n&&await this.env.clipboard.write({[gI.PlainText]:""})}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(1!==this.env.model.getters.getSelectedZones().length)return;const t=this.env.model.getters.getActiveRows().size>0,s=this.env.model.getters.getActiveCols().size>0;s&&t?this.processHeaderGroupingEventOnWholeSheet(e):s?this.processHeaderGroupingEventOnHeaders(e,"COL"):t?this.processHeaderGroupingEventOnHeaders(e,"ROW"):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){const s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSelectedZone(),i="COL"===t?o.left:o.top,n="COL"===t?o.right:o.bottom;switch(e){case"right":this.env.model.dispatch("GROUP_HEADERS",{sheetId:s,dimension:t,start:i,end:n});break;case"left":this.env.model.dispatch("UNGROUP_HEADERS",{sheetId:s,dimension:t,start:i,end:n});break;case"down":this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:s,dimension:t,zone:o});break;case"up":this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:s,dimension:t,zone:o})}}processHeaderGroupingEventOnWholeSheet(e){const t=this.env.model.getters.getActiveSheetId();"up"===e?(this.env.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"ROW"}),this.env.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"COL"})):"down"===e&&(this.env.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"ROW"}),this.env.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"COL"}))}processHeaderGroupingEventOnGrid(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getSelectedZone();switch(e){case"down":this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"ROW",zone:s}),this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"COL",zone:s});break;case"up":this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"ROW",zone:s}),this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"COL",zone:s});break;case"right":{const{x:e,y:t,width:o}=this.env.model.getters.getVisibleRect(s),i=this.getGridRect();this.toggleContextMenu("GROUP_HEADERS",e+o+i.x,t+i.y);break}case"left":{if(!jN(this.env,"COL")&&!jN(this.env,"ROW"))return;const{x:e,y:t,width:o}=this.env.model.getters.getVisibleRect(s),i=this.getGridRect();this.toggleContextMenu("UNGROUP_HEADERS",e+o+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:"cellFocus"})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:"contentFocus"})}get staticTables(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(TA)}get displaySelectionHandler(){return this.env.isMobile()&&"inactive"===this.composerFocusStore.activeComposer.editionMode}}function Dz(e,t){const s=`"${t?`${e.name}:${t}`:e.name}"`,o=e.string!==e.name?e.string+s:s;return{text:s,description:e.string+(e.help?` (${e.help})`:""),htmlContent:[{value:s,color:ie.STRING}],fuzzySearchKey:o}}function _z(e){const t=e.functionContext?.args[0];if(t&&["STRING","NUMBER"].includes(t.type))return t.value}const Oz=new Og;Oz.add("SPREADSHEET",!1);class Fz extends t.Component{static template="o-spreadsheet-ClickableCellSortIcon";static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=ev(oU)}get style(){const e=this.env.model.getters.getCellComputedStyle(this.props.position);return Ey({color:e.textColor||I,"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){const t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?function(e,t){const s=Ev(t),o=Ev(e),i=s.a+o.a*(1-s.a);return wv({r:Math.round((s.r*s.a+o.r*o.a*(1-s.a))/i),g:Math.round((s.g*s.a+o.g*o.a*(1-s.a))/i),b:Math.round((s.b*s.a+o.b*o.a*(1-s.a))/i),a:i})}(e.fillColor||"#FFFFFF",t):e.fillColor||"#FFFFFF"}}class Pz extends t.Component{static template="o-spreadsheet-FullScreenFigure";static props={};static components={ChartFigure:LF};fullScreenFigureStore;ref=t.useRef("fullScreenFigure");spreadsheetRect=AF();figureRegistry=VF;setup(){this.fullScreenFigureStore=ev(EF);const e=ev(iS);let s;t.onWillUpdateProps(()=>{s!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+"-fullscreen"),s=this.figureUI?.id}),t.useEffect(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){"Escape"===e.key&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return VF.get(this.figureUI.tag).Component}}class Mz extends t.Component{static template="o_spreadsheet.PivotHTMLRenderer";static components={Checkbox:IM};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=t.useState({showMissingValuesOnly:!1});setup(){const e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;const e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){const t=this.pivot.getExpandedTableStructure().rows,s=[...t[e].values];if(s.length<=1)return[e];s.pop();const o=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(s));return[e].concat(this.addRecursiveRow(o))}buildColumnsMissing(e){const t=[];for(const e of this.data.columns){const s=[];for(const t in e)for(let o=0;o<e[t].span;o++)s.push(parseInt(t,10));t.push(s)}for(let s=t[t.length-1].length;s>=0;s--)if(!e.includes(s))for(const e of t)e.splice(s,1);const s=[];for(const e in t){const o=[];let i,n=1;for(let s=0;s<t[e].length;s++)i!==t[e][s]?(void 0!==i&&o.push(Object.assign({},this.data.columns[e][i],{span:n})),i=t[e][s],n=1):n++;void 0!==i&&o.push(Object.assign({},this.data.columns[e][i],{span:n})),s.push(o)}return s}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){const s=e.map(()=>[]);for(const o of t)for(const t in e)s[t].push(this.data.values[e[t]][o]);return s}getColumnsIndexes(){const e=new Set;for(let t=0;t<this.data.columns.length;t++){const s=[];for(let e=0;e<this.data.columns[t].length;e++)for(let o=0;o<this.data.columns[t][e].span;o++)s.push(this.data.columns[t][e]);for(let t=0;t<s.length;t++)s[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++){this.data.values[t].find(e=>e.isMissing)&&e.add(t)}return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){const e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(const s of this.data.values)s[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){const s=[];for(const o of t.columns){const t=[];for(const s of o){const o=[];for(let e=0;e<s.fields.length;e++)o.push({value:s.fields[e]},{value:s.values[e]});const i=this.pivot.parseArgsToPivotDomain(o),n=this.env.model.getters.getLocale();if("measure"===i.at(-1)?.field){const{value:o,format:r}=this.pivot.getPivotMeasureValue(Eo(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${sp(e,i).join(",")})`,value:pn(o,{format:r,locale:n}),span:s.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{const{value:o,format:r}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${sp(e,i).join(",")})`,value:pn(o,{format:r,locale:n}),span:s.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}s.push(t)}const o=s[s.length-1];return s[s.length-1]=o.map(e=>(e.isMissing||(e.style="color: #756f6f;"),e)),s}_buildRowHeaders(e,t){const s=[];for(const o of t.rows){const t=[];for(let e=0;e<o.fields.length;e++)t.push({value:o.fields[e]},{value:o.values[e]});const i=this.pivot.parseArgsToPivotDomain(t),{value:n,format:r}=this.pivot.getPivotHeaderValueAndFormat(i),a=this.env.model.getters.getLocale(),l={formula:`=PIVOT.HEADER(${sp(e,i).join(",")})`,value:pn(n,{format:r,locale:a}),isMissing:!this.tracker?.isHeaderPresent(i)};o.indent>1&&(l.style=`padding-left: ${o.indent-10}px`),s.push(l)}return s}_buildValues(e,t){const s=[];for(const o of t.columns.at(-1)||[]){const i=[],n=Eo(o.values[o.values.length-1]);for(const s of t.rows){const t=[];for(let e=0;e<s.fields.length;e++)t.push({value:s.fields[e]},{value:s.values[e]});for(let e=0;e<o.fields.length-1;e++)t.push({value:o.fields[e]},{value:o.values[e]});const r=this.pivot.parseArgsToPivotDomain(t),{value:a,format:l}=this.pivot.getPivotCellValueAndFormat(n,r),c=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${sp(e,r,n).join(",")})`,value:pn(a,{format:l,locale:c}),isMissing:!this.tracker?.isValuePresent(n,r)})}s.push(i)}return s}}class Nz{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,s="copyPaste"){}paste(e,t,s){}isPasteAllowed(e,t,s,o){return"Success"}isCutAllowed(e){return"Success"}getPasteTarget(e,t,s,o){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}}class Lz extends Nz{copy(e,t,s="copyPaste"){}pasteFromCopy(e,t,s,o){if(1===t.length)for(const i of I_(t,s))this.pasteZone(e,i.left,i.top,s,o);else for(const i of ft(t))for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++)this.pasteZone(e,t,n,s,o)}pasteZone(e,t,s,o,i){}}class kz extends Lz{isCutAllowed(e){return 1!==e.zones.length?"WrongCutSelection":"Success"}copy(e,t,s="copyPaste"){const o=e.sheetId,{clippedZones:i,rowsIndexes:n,columnsIndexes:r}=e,a=[],l=1===n.length&&1===r.length;for(const t of n){const i=[];for(const a of r){const c={col:a,row:t,sheetId:o};let h=this.getters.getCell(c);const d=this.getters.getEvaluatedCell(c),u=this.getters.getPivotIdFromPosition(c),g=this.getters.getArrayFormulaSpreadingOn(c);if("shiftCells"!==s&&u&&g){const t=this.getters.getSpreadZone(g);if((!Me(g,c)||!l)&&t&&!e.zones.some(e=>Vt(t,e))){const e=this.getters.getPivotCellFromPosition(c),t=ip(this.getters.getPivotFormulaId(u),e);h={id:h?.id||"",style:h?.style,format:h?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if("shiftCells"!==s&&g&&!Me(g,c)){const e=n.includes(g.row)&&r.includes(g.col)?"":pn(d.value,{locale:this.getters.getLocale()});h={id:h?.id||"",style:h?.style,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:h?.content??"",style:h?.style,format:h?.format,tokens:h?.isFormula?h.compiledFormula.tokens.map(({value:e,type:t})=>({value:e,type:t})):[],border:this.getters.getCellBorder(c)||void 0,evaluatedCell:d,position:c})}a.push(i)}return{cells:a,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,s,o){if(!s.cells)return"Success";if(o?.isCutOperation&&void 0!==o?.pasteOption)return"WrongPasteOption";if(t.length>1&&(s.cells.length>1||s.cells[0].length>1))return"WrongPasteSelection";const i=s.cells.length,n=s.cells[0].length;for(const o of I_(t,s.cells))if(this.getters.doesIntersectMerge(e,o)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*n!==1))return"WillRemoveExistingMerge";return"Success"}paste(e,t,s){const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t,s):this.pasteFromCopy(i,o,t.cells,s)}getPasteTarget(e,t,s,o){const i=s.cells[0].length,n=s.cells.length;return o?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+n-1}]}:1===i&&1===n?{zones:[],sheetId:e}:{sheetId:e,zones:I_(t,s.cells)}}pasteFromCut(e,t,s,o){this.clearClippedZones(s);const i=t[0];this.pasteZone(e,i.left,i.top,s.cells,o)}clearClippedZones(e){this.dispatch("CLEAR_CELLS",{sheetId:e.sheetId,target:e.zones}),this.dispatch("CLEAR_FORMATTING",{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){if(!a)continue;const r={col:t+o,row:s+n,sheetId:e};this.pasteCell(a,r,i)}}pasteCell(e,t,s){const{sheetId:o,col:i,row:n}=t,r=this.getters.getEvaluatedCell(t),a=e?.format||e.evaluatedCell.format;if("asValue"===s?.pasteOption)return void this.dispatch("UPDATE_CELL",{...t,content:e.evaluatedCell.value?.toString()||"",format:a});if("onlyFormat"===s?.pasteOption)return void this.dispatch("UPDATE_CELL",{...t,style:e?.style??null,format:a??r.format});let l=e?.content;e?.tokens&&e.tokens.length>0&&!s?.isCutOperation?l=this.getters.getTranslatedCellFormula(o,i-e.position.col,n-e.position.row,e.tokens):e?.tokens&&e.tokens.length>0&&(l=this.getters.getFormulaMovedInSheet(e.position.sheetId,o,e.tokens)),""!==l||e?.format||e?.style?this.dispatch("UPDATE_CELL",{...t,content:l,style:e?.style||null,format:e?.format}):r&&this.dispatch("CLEAR_CELL",t)}convertTextToClipboardData(e){const t=this.getters.getLocale(),s={cells:[]},o=[];let i=0;for(const[t,s]of e.replace(/\r/g,"").split("\n").entries())o.push(s.split("\t")),o[t].length>i&&(i=o[t].length);for(const e of o){const o=[];for(let s=0;s<i;s++){const i=eh(e[s]||"",t);o.push({content:i,evaluatedCell:{formattedValue:i}})}s.cells.push(o)}return s}}function Vz(e,t){for(let s=0;s<t.length;s++){const o=t[s].proposalValues;if(void 0===o||0===o.length)continue;const i=t=>{const i=t.functionContext;if(!i||i.parent.toUpperCase()!==e.toUpperCase()||i.argPosition!==s)return;const n=[];let r="";for(const{value:e,label:t}of o){switch(typeof e){case"string":r=`"${e}"`;break;case"number":r=e.toString();break;case"boolean":r=e?"TRUE":"FALSE"}n.push({text:r,description:t,htmlContent:[{value:r,color:"string"==typeof e?ie.STRING:ie.NUMBER}],fuzzySearchKey:r,alwaysExpanded:!0})}return n};$P.add(`${e}_function_${t[s].name}_argument_proposals`,{sequence:50,autoSelectFirstProposal:!0,selectProposal:Uz,getProposals:i})}}function Uz(e,t){let s=e.end;const o=e.end;["LEFT_PAREN","ARG_SEPARATOR"].includes(e.type)||(s=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}F_.add("data_cleanup",class extends Ir{allowDispatch(e){return"REMOVE_DUPLICATES"===e.type?this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique)):"Success"}handle(e){switch(e.type){case"REMOVE_DUPLICATES":this.removeDuplicates(e.columns,e.hasHeader);break;case"TRIM_WHITESPACE":this.trimWhitespace()}}removeDuplicates(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.getSelectedZone();t&&(o.top+=1);const i=this.getUniqueRowsIndexes(s,o.top,o.bottom,e),n=i.length;if(n===Ut(o).numberOfRows)return void this.notifyRowsRemovedAndRemaining(0,n);const r=i.map(e=>({left:o.left,top:e,right:o.right,bottom:e})),a=new kz(this.getters,this.dispatch),l=a.copy(C_(s,r),!1);if(!l)return;this.dispatch("CLEAR_CELLS",{target:[o],sheetId:s});const c={left:o.left,top:o.top,right:o.left,bottom:o.top};a.paste({zones:[c],sheetId:s},l,{isCutOperation:!1});const h={left:o.left,top:o.top-(t?1:0),right:o.right,bottom:o.top+n-1};this.selection.selectZone({cell:{col:h.left,row:h.top},zone:h});const d=o.bottom-o.top+1-n;this.notifyRowsRemovedAndRemaining(d,n)}getUniqueRowsIndexes(e,t,s,o){const i=new Map;for(const n of wC(t,s+1)){const t=o.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).value);!Object.values(i).some(e=>xC(e,t))&&(i[n]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:"info",text:fs("%s duplicate rows found and removed.\n%s unique rows remain.",e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return 1!==this.getters.getSelectedZones().length?"MoreThanOneRangeSelected":"Success"}checkNoMergeInZone(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?"WillRemoveExistingMerge":"Success"}checkRangeContainsValues(e){const t=this.getters.getActiveSheetId(),s=this.getters.getSelectedZone();e.hasHeader&&(s.top+=1);return this.getters.getEvaluatedCellsInZone(t,s).every(e=>"empty"===e.type)?"EmptyTarget":"Success"}checkNoColumnProvided(e){return 0===e.columns.length?"NoColumnsProvided":"Success"}checkColumnsIncludedInZone(e){const t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?"ColumnsNotIncludedInZone":"Success"}checkColumnsAreUnique(e){return e.columns.length!==new Set(e.columns).size?"DuplicatesColumnsSelected":"Success"}trimWhitespace(){const e=ft(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId();let s=0;for(const{col:o,row:i}of e.map(Bt).flat()){const e=this.getters.getCell({col:o,row:i,sheetId:t});if(!e)continue;const n=_C(e.content);n!==e.content&&(s+=1,this.dispatch("UPDATE_CELL",{sheetId:t,col:o,row:i,content:n}))}const o=s?fs("Trimmed whitespace from %s cells.",s):fs("No selected cells had whitespace trimmed.");this.ui.notifyUI({type:"info",text:o,sticky:!1})}}),$P.add("dataValidation",{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(ot(t))return[];if(!this.composer.currentEditedCell)return[];const s=this.composer.currentEditedCell,o=this.getters.getValidationRuleForCell(s);if(!o||"isValueInList"!==o.criterion.type&&"isValueInRange"!==o.criterion.type)return[];const i=this.composer.currentEditedCell.sheetId,n="isValueInRange"===o.criterion.type?this.getters.getDataValidationRangeValues(i,o.criterion):o.criterion.values.map(e=>({label:e,value:e}));if(!("chip"===o.criterion.displayStyle))return n.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));const r=o.criterion.colors;return n.map(e=>{const t=r?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:t?Pv(t):void 0,backgroundColor:t||C,classes:["badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start"]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t),this.composer.stopEdition()}}),$P.add("functions",{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if("SYMBOL"!==e.type)return[];const t=e.value;if(!ot(this.composer.currentContent))return[];const s=Object.entries(uf.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:s}])=>({text:e,description:s,htmlContent:XH(t,e,g,"o-semi-bold")})).sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text));return s},selectProposal(e,t){let s=e.end,o=e.end;["SYMBOL","FUNCTION"].includes(e.type)&&(s=e.start);const i=this.composer.currentTokens;t+="(";const n=i.map(e=>e.start).indexOf(e.start);if(n+1<i.length){const e=i[n+1];"LEFT_PAREN"===e?.type&&o++}this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}}),uf.getAll().forEach(e=>Vz(e.name,e.args)),$P.add("pivot_ids",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!["PIVOT.VALUE","PIVOT.HEADER","PIVOT"].includes(t.parent.toUpperCase())||0!==t.argPosition)return;const s=this.getters.getPivotIds();return s.includes(e.value)?void 0:s.map(e=>{const t=this.getters.getPivotCoreDefinition(e),s=`${this.getters.getPivotFormulaId(e)}`;return{text:s,description:t.name,htmlContent:[{value:s,color:ie.NUMBER}],fuzzySearchKey:s+t.name,alwaysExpanded:!0}}).filter(Te)},selectProposal:Uz}),$P.add("pivot_measures",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if("PIVOT.VALUE"!==t?.parent.toUpperCase()||1!==t.argPosition)return[];const s=_z(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return[];const i=this.getters.getPivot(o);return i.init(),i.isValid()?i.definition.measures.map(e=>{if("__count"===e.fieldName){const e='"__count"';return{text:e,description:fs("Count"),htmlContent:[{value:e,color:ie.STRING}],fuzzySearchKey:fs("Count")+e}}return function(e){const t=`"${e.id}"`,s=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:ie.STRING}],fuzzySearchKey:s}}(e)}).filter(Te):[]},selectProposal:Uz}),$P.add("pivot_group_fields",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!function(e){const t=e.functionContext;return"PIVOT.VALUE"===t?.parent.toUpperCase()&&t.argPosition>=2&&t.argPosition%2==0}(e)&&!function(e){const t=e.functionContext;return"PIVOT.HEADER"===t?.parent.toUpperCase()&&t.argPosition>=1&&t.argPosition%2==1}(e))return;const s=_z(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return;const i=this.getters.getPivot(o);i.init();const n=i.getFields(),{columns:r,rows:a}=i.definition;let l=t.args;"PIVOT.VALUE"===t?.parent.toUpperCase()?(l=l.filter((e,t)=>t%2==0),l=l.slice(1,t.argPosition)):l=l.filter((e,t)=>t%2==1);const c=l.map(e=>e?.value).filter(Te),h=r.map(e=>e.nameWithGranularity),d=a.map(e=>e.nameWithGranularity),u=[];let g=["ARG_SEPARATOR","SPACE"].includes(e.type)?c.at(-1):c.at(-2);const p=Oz.get(i.type);if(p&&g?.startsWith("#")&&(g=g.slice(1)),void 0===g&&(u.push(h[0]),u.push(d[0])),d.includes(g)){const e=d[d.indexOf(g)+1];u.push(e),u.push(h[0])}if(h.includes(g)){const e=h[h.indexOf(g)+1];u.push(e)}const m=u.filter(Te);return m.map(e=>{const[t,s]=e.split(":"),o=n[t];return o?Dz(o,s):void 0}).concat(m.map(e=>{if(!p)return;const t=e.split(":")[0],s=n[t];if(!s)return;const o=`"#${e}"`;return{text:o,description:fs("%s (positional)",s.string)+(s.help?` (${s.help})`:""),htmlContent:[{value:o,color:ie.STRING}],fuzzySearchKey:s.string+o}})).filter(Te)},selectProposal:Uz}),$P.add("pivot_group_values",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!e||!function(e){const t=e.functionContext;return"PIVOT.VALUE"===t?.parent.toUpperCase()&&t.argPosition>=2&&t.argPosition%2==1}(e)&&!function(e){const t=e.functionContext;return"PIVOT.HEADER"===t?.parent.toUpperCase()&&t.argPosition>=1&&t.argPosition%2==0}(e))return;const s=_z(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return;const i=this.getters.getPivot(o);if(!i.isValid())return;const n=t.argPosition,r=e.functionContext?.args[n-1]?.value;if(!r)return;let a;try{a=i.definition.getDimension(r)}catch(e){return}return"month_number"===a.granularity?Object.values(dn).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:ie.NUMBER}]})):"quarter_number"===a.granularity?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:fs("Quarter %s",e),htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"day_of_month"===a.granularity?ge(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"iso_week_number"===a.granularity?ge(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"day_of_week"===a.granularity?ge(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"hour_number"===a.granularity?ge(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"minute_number"===a.granularity?ge(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"second_number"===a.granularity?ge(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):i.getPossibleFieldValues(a).map(({value:e,label:t})=>{const s="string"==typeof e,o=s?`"${e}"`:e.toString(),i=t===e?"":t;return{text:o,description:i,htmlContent:[{value:o,color:s?ie.STRING:ie.NUMBER}],fuzzySearchKey:o+i}})},selectProposal:Uz}),$P.add("sheet_names",{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return"SYMBOL"===e.type||"UNKNOWN"===e.type&&e.value.startsWith("'")?this.getters.getSheetIds().map(e=>{const t=he(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith("'")?t:"'"+t}}):[]},selectProposal(e,t){const s=e.start,o=e.end;this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t+"!")}});const Hz=new Og;Hz.add("link",{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,s)=>Wf(t.model.getters.getEvaluatedCell(e).link,t,s),title:(e,t)=>{const s=t.getEvaluatedCell(e).link;return s?s.isExternal?fs("Go to url: %(url)s",{url:s.url}):fs("Go to %(label)s",{label:s.label}):""},sequence:5}),Hz.add("dashboard_pivot_sorting",{condition:(e,t)=>{if(!t.isDashboard())return!1;const s=t.getPivotCellFromPosition(e);return gk(t,e)&&"MEASURE_HEADER"===s.type},execute:(e,t)=>{pk(t,e,function(e,t){return zz[e.getPivotCellSortDirection(t)??"none"]}(t.model.getters,e))},component:Fz,componentProps:(e,t)=>({position:e,sortDirection:t.getPivotCellSortDirection(e)}),sequence:2});const zz={none:"asc",asc:"desc",desc:"none"};vD.add("filter_icon",(e,t)=>{if(e.isFilterHeader(t)){const s=e.isFilterActive(t),o=Iv(e.getCellComputedStyle(t).fillColor||"#fff")<.45;return{type:"filter_icon",svg:uR(s,o,!1),hoverSvg:uR(s,o,!0),priority:3,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const s=t.getStore(wP),o=s.persistentCellPopover;o.isOpen&&o.col===e.col&&o.row===e.row&&"FilterMenu"===o.type?s.close():s.open(e,"FilterMenu")}}}});const Bz=new Og;Bz.add("format_number_automatic",{..._k,id:"format_number_automatic",sequence:10}).add("format_number_plain_text",{...Ok,id:"format_number_plain_text",sequence:15,separator:!0}).add("format_number_number",{...Fk,id:"format_number_number",sequence:20}).add("format_number_percent",{...Mk,id:"format_number_percent",sequence:30,separator:!0}).add("format_number_currency",{...Nk,id:"format_number_currency",sequence:40}).add("format_number_accounting",{...kk,id:"format_number_accounting",sequence:45}).add("format_number_currency_rounded",{...Lk,id:"format_number_currency_rounded",sequence:50}).add("format_custom_currency",{...Uk,id:"format_custom_currency",sequence:60,separator:!0}).add("format_number_date",{...Hk,id:"format_number_date",sequence:70}).add("format_number_time",{...zk,id:"format_number_time",sequence:80}).add("format_number_date_time",{...Bk,id:"format_number_date_time",sequence:90}).add("format_number_duration",{...Gk,id:"format_number_duration",sequence:100,separator:!0}).add("more_formats",{...qk,id:"more_formats",sequence:120});const Gz=$e(e=>wn(e)?"date":e.includes("[$")?"currency":"number"),Wz={name:fs("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[e=>{const t=function(e){const t=new Set(Bz.getAll().map(t=>"function"==typeof t.format?t.format(e):t.format)),s=new Map;for(const o of e.model.getters.getSheetIds()){const i=e.model.getters.getEvaluatedCells(o);for(const e in i){const o=i[e];if(o.format&&!s.has(o.format)&&!t.has(o.format)){const e=Gz(o.format);"date"!==e&&"currency"!==e||s.set(o.format,Dk({descriptionValue:"currency"===e?1e3:Vk,format:o.format,name:o.format}))}}}return[...s.values()]}(e).map(e=>({...e,sequence:110}));return t.length>0&&(t[t.length-1].separator=!0),qf([...Bz.getAll(),...t])}]};const $z=new kM;$z.add("file",{name:fs("File"),sequence:10}).addChild("settings",["file"],{name:fs("Settings"),sequence:200,execute:e=>e.openSidePanel("Settings"),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.COG"}).add("edit",{name:fs("Edit"),sequence:20}).addChild("undo",["edit"],{...KN,sequence:10}).addChild("redo",["edit"],{...JN,sequence:20,separator:!0}).addChild("copy",["edit"],{...QN,sequence:30}).addChild("cut",["edit"],{...eL,sequence:40}).addChild("paste",["edit"],{...tL,sequence:50}).addChild("paste_special",["edit"],{...sL,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...oL,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{...iL,sequence:20}).addChild("edit_table",["edit"],{...vL,isVisible:mN,sequence:60}).addChild("find_and_replace",["edit"],{...nL,sequence:65,separator:!0}).addChild("delete",["edit"],{name:fs("Delete"),icon:"o-spreadsheet-Icon.TRASH",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...rL,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...aL,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...hL,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{...pL,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...mL,sequence:50}).addChild("edit_unhide_columns",["edit"],{...RN,sequence:80}).addChild("edit_unhide_rows",["edit"],{...AN,sequence:80}).add("view",{name:fs("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...DN,sequence:4}).addChild("freeze_panes",["view"],{..._N,sequence:5}).addChild("unfreeze_rows",["view","freeze_panes"],{...ON,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...FN,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...PN,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...MN,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...NN,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...LN,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...kN,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...VN,sequence:40}).addChild("group_headers",["view"],{name:fs("Group"),sequence:15,separator:!0,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",isVisible:vN}).addChild("group_columns",["view","group_headers"],{...BN,sequence:5}).addChild("ungroup_columns",["view","group_headers"],{...WN,isVisible:e=>jN(e,"COL"),sequence:10}).addChild("group_rows",["view","group_headers"],{...GN,sequence:15}).addChild("ungroup_rows",["view","group_headers"],{...$N,isVisible:e=>jN(e,"ROW"),sequence:20}).addChild("show",["view"],{name:fs("Show"),sequence:1,icon:"o-spreadsheet-Icon.SHOW"}).addChild("view_gridlines",["view","show"],{...UN,sequence:5}).addChild("view_formulas",["view","show"],{...zN,sequence:10}).addChild("view_irregularity_map",["view"],{...HN,sequence:40,separator:!0}).add("insert",{name:fs("Insert"),sequence:40}).addChild("insert_row",["insert"],{...yL,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...wL,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...xL,sequence:20}).addChild("insert_column",["insert"],{...TL,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...DL,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...FL,sequence:20}).addChild("insert_cell",["insert"],{...PL,sequence:30}).addChild("insert_cell_down",["insert","insert_cell"],{...ML,name:fs("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...NL,name:fs("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...KL,sequence:40,separator:!0}).addChild("insert_chart",["insert"],{...LL,sequence:50}).addChild("insert_carousel",["insert"],{...kL,sequence:51}).addChild("insert_pivot",["insert"],{...VL,sequence:52}).addChild("insert_image",["insert"],{...UL,sequence:55}).addChild("insert_table",["insert"],{...HL,sequence:57}).addChild("insert_function",["insert"],{...zL,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...BL,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...GL,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{...WL,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...$L,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...qL,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...ZL,sequence:50}).addChild("categories_function_list",["insert","insert_function"],()=>{const e=uf.content;return[...new Set(uf.getAll().filter(e=>!e.hidden).map(e=>e.category))].filter(Te).sort().map((t,s)=>{const o=Object.keys(e).filter(s=>e[s].category===t&&!e[s].hidden);return{name:t,children:JL(o)}})}).addChild("insert_link",["insert"],{...jL,separator:!0,sequence:70}).addChild("insert_checkbox",["insert"],{...YL,sequence:80}).addChild("insert_dropdown",["insert"],{...XL,separator:!0,sequence:90}).add("format",{name:fs("Format"),sequence:50}).addChild("format_number",["format"],{...Wz,name:fs("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{...iV,sequence:20}).addChild("format_italic",["format"],{...nV,sequence:30}).addChild("format_underline",["format"],{...rV,sequence:40}).addChild("format_strikethrough",["format"],{...aV,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...lV,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...cV,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...dV,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...uV,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...gV,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{...mV,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...fV,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{...vV,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...bV,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...CV,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...yV,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...IV,sequence:30}).addChild("format_cf",["format"],{...wV,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...EV,sequence:100,separator:!0}).add("data",{name:fs("Data"),sequence:60}).addChild("sort_range",["data"],{...bk,sequence:10,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...Sk,sequence:10}).addChild("sort_descending",["data","sort_range"],{...wk,sequence:20}).addChild("data_cleanup",["data"],{...Ck,sequence:15}).addChild("remove_duplicates",["data","data_cleanup"],{...yk,sequence:10}).addChild("trim_whitespace",["data","data_cleanup"],{...Ik,sequence:20}).addChild("split_to_columns",["data"],{...xk,sequence:20}).addChild("data_validation",["data"],{name:fs("Data Validation"),execute:e=>{e.openSidePanel("DataValidation")},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.DATA_VALIDATION",sequence:30,separator:!0}).addChild("add_remove_data_filter",["data"],{...Ek,sequence:40,separator:!0}).addChild("pivot_data_sources",["data"],e=>{const t=e.model.getters.getPivotIds().length;return e.model.getters.getPivotIds().map((s,o)=>{const i={get highlights(){return ZH(e.model.getters,s)}};return{id:`item_pivot_${e.model.getters.getPivotFormulaId(s)}`,name:e.model.getters.getPivotDisplayName(s),sequence:50+o/t,isReadonlyAllowed:!0,execute:e=>e.openSidePanel("PivotSidePanel",{pivotId:s}),isEnabled:e=>!e.isSmall,onStartHover:e=>e.getStore(ZP).register(i),onStopHover:e=>e.getStore(ZP).unRegister(i),icon:"o-spreadsheet-Icon.PIVOT",separator:o===e.model.getters.getPivotIds().length-1,secondaryIcon:e=>e.model.getters.isPivotUnused(s)?"o-spreadsheet-Icon.UNUSED_PIVOT_WARNING":void 0}})}).addChild("reinsert_dynamic_pivot",["data"],Tk).addChild("reinsert_static_pivot",["data"],Ak);const qz=[Zz,function(e,t){return"target"in t&&Array.isArray(t.target)?{...ae(t),target:e.getSelectedZones()}:t},Yz,function(e,t){return"ranges"in t?{...ae(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}];function Zz(e,t){return"sheetId"in t?{...ae(t),sheetId:e.getActiveSheetId()}:t}function jz(e,t){return"zone"in t?{...ae(t),zone:e.getSelectedZone()}:t}function Yz(e,t){if(!("row"in t)||!("col"in t))return t;const{col:s,row:o}=e.getActivePosition();return{...ae(t),col:s,row:o}}const Xz=new lr;function Kz(e,t){const s=e.getSelectedZone();return{...Zz(e,t),elements:"COL"===t.dimension?ge(s.left,s.right+1):ge(s.top,s.bottom+1)}}function Jz(e,t){const s=e.getSelectedZone();return{...ae(t),zone:s}}function Qz(e,t){const s=ae(t),o=e.getSelectedZone(),{top:i,bottom:n,left:r,right:a}=o;return"cols"in s?s.cols=ge(r,a+1):"rows"in s&&(s.rows=ge(i,n+1)),s}function eB(e,t){const s=e.getSelectedZone();return{...Zz(e,t),start:"COL"===t.dimension?s.left:s.top,end:"COL"===t.dimension?s.right:s.bottom}}function tB(e,t){let s=IC(t);for(const t of qz)s=t(e,s);return s}u_.add("UPDATE_CELL",tB),u_.add("CLEAR_CELL",tB),u_.add("CLEAR_CELLS",tB),u_.add("DELETE_CONTENT",tB),u_.add("ADD_MERGE",tB),u_.add("REMOVE_MERGE",tB),u_.add("SET_FORMATTING",tB),u_.add("CLEAR_FORMATTING",tB),u_.add("SET_BORDER",tB),u_.add("CREATE_TABLE",tB),u_.add("REMOVE_TABLE",tB),u_.add("HIDE_SHEET",tB),u_.add("ADD_COLUMNS_ROWS",function(e,t){const s=e.getActivePosition();return{...Zz(e,t),base:"COL"===t.dimension?s.col:s.row}}),u_.add("REMOVE_COLUMNS_ROWS",Kz),u_.add("HIDE_COLUMNS_ROWS",Kz),u_.add("RESIZE_COLUMNS_ROWS",Kz),u_.add("CREATE_SHEET",function(e,t){const s=ae(t);s.sheetId=Xz.smallUuid();const o=t.name||e.getSheet(e.getActiveSheetId()).name,i=o.match(/(.+?)\d*$/)?.[1]||o;return s.name=e.getNextSheetName(i),s}),u_.add("CREATE_FIGURE",function(e,t){const s=Yz(e,Zz(e,t));return s.figureId=Xz.smallUuid(),s}),u_.add("CREATE_CHART",function(e,t){const s=Xz.smallUuid();return{...Zz(e,t),figureId:s,chartId:s}}),u_.add("CREATE_IMAGE",function(e,t){return{...Zz(e,t),figureId:Xz.smallUuid()}}),u_.add("GROUP_HEADERS",eB),u_.add("UNGROUP_HEADERS",eB),u_.add("UNFOLD_HEADER_GROUPS_IN_ZONE",jz),u_.add("FOLD_HEADER_GROUPS_IN_ZONE",jz),g_.add("PASTE",function(e,t){return{type:"REPEAT_PASTE",pasteOption:ae(t.pasteOption),target:e.getSelectedZones()}}),g_.add("INSERT_CELL",Jz),g_.add("DELETE_CELL",Jz),g_.add("AUTORESIZE_COLUMNS",Qz),g_.add("AUTORESIZE_ROWS",Qz),g_.add("SORT_CELLS",function(e,t){const s=e.getSelectedZone();return{...Zz(e,t),col:s.left,row:s.top,zone:s}}),g_.add("SUM_SELECTION",tB),g_.add("SET_DECIMAL",tB),g_.add("DELETE_UNFILTERED_CONTENT",tB);const sB=new class extends Og{mapping={};uuidGenerator=new lr;replace(e,t){const s={...t,id:this.uuidGenerator.uuidv4()};return super.replace(e,s)}getAllOrdered(){return this.getAll().sort((e,t)=>e.sequence-t.sequence)}};class oB{fileStore;constructor(e){this.fileStore=e}async requestImage(){const e=await this.userImageUpload(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}async uploadFile(e){const t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}userImageUpload(){return new Promise((e,t)=>{const s=document.createElement("input");s.setAttribute("type","file"),s.setAttribute("accept","image/*"),s.addEventListener("change",async()=>{null===s.files||1!==s.files.length?t():e(s.files[0])}),s.click()})}getImageOriginalSize(e){return new Promise((t,s)=>{const o=new Image;o.addEventListener("load",()=>{const e={width:o.width,height:o.height};t(e)}),o.addEventListener("error",s),o.src=e})}}const iB=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];class nB extends t.Component{static template="o-spreadsheet-RippleEffect";static props={x:String,y:String,color:String,opacity:Number,duration:Number,width:Number,height:Number,offsetY:Number,offsetX:Number,allowOverflow:Boolean,onAnimationEnd:Function,style:String};rippleRef=t.useRef("ripple");setup(){let e;t.onMounted(()=>{const t=this.rippleRef.el;t&&t.animate&&(e=t.animate(iB,{duration:this.props.duration,easing:"ease-out"}),e.addEventListener("finish",this.props.onAnimationEnd))}),t.onWillUnmount(()=>{e?.removeEventListener("finish",this.props.onAnimationEnd)})}get rippleStyle(){const{x:e,y:t,width:s,height:o}=this.props;return Ey({transform:"scale(0)",left:e,top:t,"margin-left":`${-s/2+(this.props.offsetX||0)}px`,"margin-top":`${-o/2+(this.props.offsetY||0)}px`,width:`${s}px`,height:`${o}px`,background:this.props.color,"border-radius":"100%",opacity:`${this.props.opacity}`})}}class rB extends t.Component{static template="o-spreadsheet-Ripple";static props={color:{type:String,optional:!0},opacity:{type:Number,optional:!0},duration:{type:Number,optional:!0},ignoreClickPosition:{type:Boolean,optional:!0},width:{type:Number,optional:!0},height:{type:Number,optional:!0},offsetY:{type:Number,optional:!0},offsetX:{type:Number,optional:!0},allowOverflow:{type:Boolean,optional:!0},enabled:{type:Boolean,optional:!0},onAnimationEnd:{type:Function,optional:!0},slots:Object,class:{type:String,optional:!0}};static components={RippleEffect:nB};static defaultProps={color:"#aaaaaa",opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:""};childContainer=t.useRef("childContainer");state=t.useState({ripples:[]});currentId=1;onClick(e){if(!this.props.enabled)return;if(!this.childContainer.el)return;const t=this.getRippleChildRectInfo(),{x:s,y:o,width:i,height:n}=t,r=Math.max(i,n),a={x:e.clientX-s,y:e.clientY-o,width:this.props.width||2.85*r,height:this.props.height||2.85*r};this.state.ripples.push({rippleRect:a,id:this.currentId++})}getRippleStyle(){const e=this.childContainer.el;if(!e||1!==e.childElementCount||!e.firstElementChild)return"";const t=this.getRippleChildRectInfo();return Ey({top:t.marginTop+"px",left:t.marginLeft+"px",width:t.width+"px",height:t.height+"px"})}getRippleChildRectInfo(){const e=this.childContainer.el;if(!e)throw new Error("No child container element found");if(1!==e.childElementCount||!e.firstElementChild){return{...Fy(e),marginLeft:0,marginTop:0}}const t=e.firstElementChild,s=function(e){const t=window.getComputedStyle(e);return{top:parseInt(t.marginTop,10)||0,bottom:parseInt(t.marginBottom,10)||0,left:parseInt(t.marginLeft,10)||0,right:parseInt(t.marginRight,10)||0}}(t);return{...Fy(t),marginLeft:s.left,marginTop:s.top}}removeRipple(e){const t=this.state.ripples.findIndex(t=>t.id===e);-1!==t&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){const t=this.state.ripples.find(t=>t.id===e)?.rippleRect;if(!t)throw new Error("Cannot find a ripple with the id "+e);return{color:this.props.color,opacity:this.props.opacity,duration:this.props.duration,x:this.props.ignoreClickPosition?"50%":t.x+"px",y:this.props.ignoreClickPosition?"50%":t.y+"px",width:t.width,height:t.height,offsetX:this.props.offsetX||0,offsetY:this.props.offsetY||0,allowOverflow:this.props.allowOverflow||!1,style:this.getRippleStyle(),onAnimationEnd:()=>this.removeRipple(e)}}}class aB extends t.Component{static template="o-spreadsheet-BottomBarSheet";static props={sheetId:String,openContextMenu:Function,style:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0}};static components={Ripple:rB,ColorPicker:rM};static defaultProps={onMouseDown:()=>{},style:""};state=t.useState({isEditing:!1,pickerOpened:!1});sheetDivRef=t.useRef("sheetDiv");sheetNameRef=t.useRef("sheetNameSpan");editionState="initializing";DOMFocusableElementStore;setup(){t.onPatched(()=>{this.sheetNameRef.el&&this.state.isEditing&&"initializing"===this.editionState&&(this.editionState="editing",this.focusInputAndSelectContent())}),this.DOMFocusableElementStore=ev(OP),t.useExternalListener(window,"click",()=>this.state.pickerOpened=!1),t.useEffect(e=>{this.props.sheetId===e&&this.scrollToSheet()},()=>[this.env.model.getters.getActiveSheetId()])}focusInputAndSelectContent(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.sheetNameRef.el.focus();const e=window.getSelection();e&&this.sheetNameRef.el.firstChild&&e.setBaseAndExtent(this.sheetNameRef.el.firstChild,0,this.sheetNameRef.el.firstChild,this.sheetNameRef.el.textContent?.length||0)}scrollToSheet(){this.sheetDivRef.el?.scrollIntoView?.({behavior:"smooth",inline:"nearest"})}onFocusOut(){this.state.isEditing&&"initializing"!==this.editionState&&this.stopEdition()}onClick(){this.env.isMobile()&&this.activateSheet()}onMouseDown(e){this.env.isMobile()||(this.activateSheet(),this.props.onMouseDown(e))}activateSheet(){this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:this.props.sheetId}),this.scrollToSheet()}onDblClick(){this.env.model.getters.isReadonly()||this.startEdition()}onKeyDown(e){this.state.isEditing&&("Enter"===e.key&&(e.preventDefault(),this.stopEdition(),this.DOMFocusableElementStore.focus()),"Escape"===e.key&&(this.cancelEdition(),this.DOMFocusableElementStore.focus()))}onMouseEventSheetName(e){this.state.isEditing&&e.stopPropagation()}startEdition(){this.state.isEditing=!0,this.editionState="initializing"}stopEdition(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el.blur();const e=this.getInputContent()||"";!function(e,t,s,o){const i=e.model.dispatch("RENAME_SHEET",{sheetId:t,newName:s,oldName:e.model.getters.getSheetName(t)});i.reasons.includes("MissingSheetName")?e.raiseError(fs("The sheet name cannot be empty."),o):i.reasons.includes("DuplicatedSheetName")?e.raiseError(fs("A sheet with the name %s already exists. Please select another name.",s),o):i.reasons.includes("ForbiddenCharactersInSheetName")&&e.raiseError(fs("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",$.join(" ")),o)}(this.env,this.props.sheetId,e,()=>this.startEdition())}cancelEdition(){this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el?.blur(),this.setInputContent(this.sheetName)}onIconClick(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}onContextMenu(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}getInputContent(){return this.sheetNameRef.el?.textContent}setInputContent(e){this.sheetNameRef.el&&(this.sheetNameRef.el.textContent=e)}onColorPicked(e){this.state.pickerOpened=!1,this.env.model.dispatch("COLOR_SHEET",{sheetId:this.props.sheetId,color:e})}get colorPickerAnchorRect(){return Fy(this.sheetDivRef.el)}get contextMenuRegistry(){return function(e){const t=new kM;return t.add("delete",{..._M,sequence:10}).add("hide_sheet",{...LM,sequence:20}).add("duplicate",{...OM,sequence:30,separator:!0}).add("rename",{...FM(e),sequence:40}).add("change_color",{...PM(e),sequence:50,separator:!0}).add("move_right",{...MM,sequence:60}).add("move_left",{...NM,sequence:70}),t}({renameSheetCallback:()=>{this.scrollToSheet(),this.startEdition()},openSheetColorPickerCallback:()=>{this.state.pickerOpened=!0}})}get isSheetActive(){return this.env.model.getters.getActiveSheetId()===this.props.sheetId}get sheetName(){return this.env.model.getters.getSheetName(this.props.sheetId)}get sheetColorStyle(){return Ey({background:this.env.model.getters.getSheet(this.props.sheetId).color||""})}}const lB=[{name:fs("Sum"),types:[_d.number],compute:(e,t)=>Er([[e]],t)},{name:fs("Avg"),types:[_d.number],compute:(e,t)=>Ga([[e]],t)},{name:fs("Min"),types:[_d.number],compute:(e,t)=>Za([[e]],t).value},{name:fs("Max"),types:[_d.number],compute:(e,t)=>qa([[e]],t).value},{name:fs("Count"),types:[_d.number,_d.text,_d.boolean,_d.error],compute:e=>$a([[e]])},{name:fs("Count Numbers"),types:[_d.number,_d.text,_d.boolean,_d.error],compute:(e,t)=>Wa([[e]],t)}];class cB extends hv{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)})}handle(e){switch((cr.has(e.type)||"UPDATE_CELL"===e.type&&("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.statisticFnResults=this._computeStatisticFnResults())}handleEvent(){this.getters.isGridSelectionActive()&&(this.statisticFnResults=this._computeStatisticFnResults())}_computeStatisticFnResults(){const e=this.getters,t=e.getActiveSheetId(),s=[],o=ft(e.getSelectedZones(),[]),i=this.getters.getSheetSize(t).numberOfRows-1,n=this.getters.getSheetSize(t).numberOfCols-1;for(const r of o)for(let o=r.left;o<=(r.right??n);o++)for(let n=r.top;n<=(r.bottom??i);n++){if(e.isRowHidden(t,n)||e.isColHidden(t,o))continue;const i=e.getEvaluatedCell({sheetId:t,col:o,row:n});i.type!==_d.empty&&s.push(i)}const r=e.getLocale(),a={},l=$e(e=>{const t=e.split(",");return s.filter(e=>t.includes(e.type))});for(const e of lB){let t;const s=l(e.types.sort().join(","));s.length&&(t=Oe(()=>e.compute(s,r))),a[e.name]=t}return a}}class hB extends t.Component{static template="o-spreadsheet-BottomBarStatistic";static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:rB};selectedStatisticFn="";store;setup(){this.store=ev(cB),t.onWillUpdateProps(()=>{Object.values(this.store.statisticFnResults).every(e=>void 0===e)&&this.props.closeContextMenu()})}getSelectedStatistic(){if(!Object.values(this.store.statisticFnResults).every(e=>void 0===e))return""===this.selectedStatisticFn&&(this.selectedStatisticFn=Object.keys(this.store.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn)}listSelectionStatistics(e){const t=new kM;let s=0;for(const[e]of Object.entries(this.store.statisticFnResults))t.add(e,{name:()=>this.getComposedFnName(e),sequence:s,isReadonlyAllowed:!0,execute:()=>{this.selectedStatisticFn=e}}),s++;const o=e.currentTarget,{top:i,left:n,width:r}=o.getBoundingClientRect();this.props.openContextMenu(n+r,i,t)}getComposedFnName(e){const t=this.env.model.getters.getLocale(),s=this.store.statisticFnResults[e];return e+": "+(void 0!==s?pn(s(),{locale:t}):"__")}}class dB extends t.Component{static template="o-spreadsheet-BottomBar";static props={onClick:Function};static components={MenuPopover:PF,Ripple:rB,BottomBarSheet:aB,BottomBarStatistic:hB};bottomBarRef=t.useRef("bottomBar");sheetListRef=t.useRef("sheetList");dragAndDrop=cM();targetScroll=void 0;state=t.useState({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=t.useState({isOpen:!1,menuId:void 0,anchorRect:null,menuItems:[]});sheetList=this.getVisibleSheets();setup(){t.onWillUpdateProps(()=>{this.updateScrollState();const e=this.getVisibleSheets();Me(this.sheetList,e)||this.dragAndDrop.cancel(),this.sheetList=e})}clickAddSheet(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getSheetIds().findIndex(e=>e===t)+1,o=this.env.model.uuidGenerator.smallUuid(),i=this.env.model.getters.getNextSheetName(fs("Sheet"));this.env.model.dispatch("CREATE_SHEET",{sheetId:o,position:s,name:i}),this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map(e=>{const t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}})}clickListSheets(e){const t=new kM,s=this.env.model.getters.getActiveSheetId();let o=0;for(const e of this.env.model.getters.getSheetIds()){const i=this.env.model.getters.getSheet(e);t.add(e,{name:i.name,sequence:o,isReadonlyAllowed:!0,textColor:i.isVisible?void 0:"#808080",execute:t=>{this.env.model.getters.isSheetVisible(e)||this.env.model.dispatch("SHOW_SHEET",{sheetId:e}),t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:s,sheetIdTo:e})},isEnabled:e=>!e.model.getters.isReadonly()||i.isVisible,icon:i.color?"o-spreadsheet-Icon.SMALL_DOT_RIGHT_ALIGN":void 0,iconColor:i.color}),o++}const i=e.currentTarget,{left:n}=i.getBoundingClientRect(),r=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(n,r,"listSheets",t)}openContextMenu(e,t,s,o){this.menuState.isOpen=!0,this.menuState.menuId=s,this.menuState.menuItems=o.getMenuItems(),this.menuState.anchorRect={x:e,y:t,width:0,height:0}}onSheetContextMenu(e,t,s){const o=s.currentTarget,{top:i,left:n}=o.getBoundingClientRect();s.closedMenuId!==e?this.openContextMenu(n,i,e,t):this.closeMenu()}closeMenu(){this.menuState.isOpen=!1,this.menuState.menuId=void 0,this.menuState.menuItems=[],this.menuState.anchorRect=null}closeContextMenuWithId(e){this.menuState.menuId===e&&this.closeMenu()}onWheel(e){this.targetScroll=void 0;e.currentTarget.scrollLeft+=.5*e.deltaY}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll+this.sheetListWidth;this.scrollSheetListTo(Math.min(this.sheetListMaxScroll,t))}updateScrollState(){this.state.isSheetListScrollableLeft=this.sheetListCurrentScroll>0,this.state.isSheetListScrollableRight=this.sheetListCurrentScroll<this.sheetListMaxScroll}scrollSheetListTo(e){this.sheetListRef.el&&(this.targetScroll=e,this.sheetListRef.el.scrollTo({top:0,left:e,behavior:"smooth"}))}onSheetMouseDown(e,t){if(0!==t.button||this.env.model.getters.isReadonly())return;if(this.closeMenu(),this.env.isMobile())return;const s=this.getVisibleSheets(),o=this.getSheetItemRects(),i=s.map((e,t)=>({id:e.id,size:o[t].width,position:o[t].x}));this.dragAndDrop.start("horizontal",{draggedItemId:e,initialMousePosition:t.clientX,items:i,scrollableContainerEl:this.sheetListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const s=t-this.getVisibleSheets().findIndex(t=>t.id===e);e&&0!==s&&this.env.model.dispatch("MOVE_SHEET",{sheetId:e,delta:s})}getSheetStyle(e){return this.dragAndDrop.itemsStyle[e]||""}getSheetItemRects(){return Array.from(this.bottomBarRef.el.querySelectorAll(".o-sheet")).map(e=>e.getBoundingClientRect()).map(e=>({x:e.x,width:e.width-1,y:e.y,height:e.height}))}get sheetListCurrentScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollLeft:0}get sheetListWidth(){return this.sheetListRef.el?this.sheetListRef.el.clientWidth:0}get sheetListMaxScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollWidth-this.sheetListRef.el.clientWidth:0}}class uB extends hv{_clickableCells=t.markRaw({});_registryItems=t.markRaw(Hz.getAll().sort((e,t)=>e.sequence-t.sequence));handle(e){(cr.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this._clickableCells=t.markRaw({}),this._registryItems=t.markRaw(Hz.getAll().sort((e,t)=>e.sequence-t.sequence)))}getClickableItem(e){const{sheetId:t,col:s,row:o}=e,i=this._clickableCells,n=mt(s,o);if(i[t]||(i[t]={}),!(n in i[t])){const s=this.findClickableItem(e);i[t][n]=s}return i[t][n]}findClickableItem(e){const t=this.getters;for(const s of this._registryItems)if(s.condition(e,t))return s}get clickableCells(){const e=[],t=this.getters,s=t.getActiveSheetId();for(const o of this.getters.getVisibleCellPositions()){const i=this.getClickableItem(o);if(!i)continue;const n="function"==typeof i.title?i.title(o,t):i.title,r=t.expandZone(s,Zt(o));e.push({coordinates:t.getVisibleRect(r),position:o,action:i.execute,title:n||"",component:i.component,componentProps:i.componentProps?.(o,t)??{}})}return e}}class gB extends t.Component{static template="o-spreadsheet-SpreadsheetDashboard";static props={getGridSize:Function};static components={GridOverlay:rU,GridPopover:aU,Popover:DF,VerticalScrollBar:EU,HorizontalScrollBar:wU};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;gridRef;setup(){this.gridRef=t.useRef("grid"),this.hoveredCell=ev(HF),this.clickableCellsStore=ev(uB),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),mU("canvas",this.env.model,()=>this.env.model.getters.getSheetViewDimension()),this.onMouseWheel=vU((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=ev(wP),fU(this.gridRef,this.moveCanvas.bind(this),()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0})}get gridContainer(){const e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e),{end:s}=this.env.model.getters.getColDimensions(e,t);return Ey({"max-width":`${s}px`})}get gridOverlayDimensions(){return Ey({height:"100%",width:"100%"})}getCellClickableStyle(e){return Ey({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){return t.toRaw(this.clickableCellsStore.clickableCells)}selectClickableCell(e,t){const{position:s,action:o}=t;o(s,this.env,Hy(e))}onClosePopover(){this.cellPopovers.close()}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:0,gridOffsetY:0})}moveCanvas(e,t){const{scrollX:s,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s+e,offsetY:o+t})}getGridRect(){return{...Oy(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}}class pB extends t.Component{static template="o-spreadsheet-HeaderGroup";static props={group:Object,layerOffset:Number,openContextMenu:Function};toggleGroup(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group;OV(this.env,e,this.dimension,t,s)}get groupBoxStyle(){const e=this.groupBox;return Ey({top:`${e.groupRect.y}px`,left:`${e.groupRect.x}px`,width:`${e.groupRect.width}px`,height:`${e.groupRect.height}px`})}get groupButtonStyle(){return Ey({"background-color":this.isGroupFolded?"#333":"#fff",color:this.isGroupFolded?"#fff":"#333"})}get groupButtonIcon(){return this.isGroupFolded?"o-spreadsheet-Icon.PLUS":"o-spreadsheet-Icon.MINUS"}get isGroupFolded(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.group;return this.env.model.getters.isGroupFolded(e,this.dimension,t.start,t.end)}onContextMenu(e){const t=this.env.model.getters.getActiveSheetId(),s={x:e.clientX,y:e.clientY},o=this.props.group,i=function(e,t,s,o){const i=qf([{id:"toggle_group",name:e=>{const i=e.model.getters.getActiveSheetId(),n=e.model.getters.isGroupFolded(i,t,s,o);return fs(n?"ROW"===t?"Expand row group":"Expand column group":"ROW"===t?"Collapse row group":"Collapse column group")},execute:e=>{const i=e.model.getters.getActiveSheetId();OV(e,i,t,s,o)},icon:e=>{const i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,s,o)?"o-spreadsheet-Icon.EXPAND":"o-spreadsheet-Icon.COLLAPSE"}},{id:"remove_group",name:fs("ROW"===t?"Remove row group":"Remove column group"),execute:e=>{const i=e.model.getters.getActiveSheetId();e.model.dispatch("UNGROUP_HEADERS",{sheetId:i,dimension:t,start:s,end:o})},icon:"o-spreadsheet-Icon.TRASH",separator:!0}]);return[...i,...FV(e,t)]}(t,this.dimension,o.start,o.end);this.props.openContextMenu(s,i)}}class mB extends pB{dimension="ROW";get groupBorderStyle(){const e=this.groupBox;return 0===this.groupBox.groupRect.height?"":Ey({top:e.headerRect.height/2+"px",left:"calc(50% - 1px)",width:"30%",height:`calc(100% - ${e.headerRect.height/2}px)`,"border-left":"1px solid","border-bottom":e.isEndHidden?"":"1px solid"})}get groupHeaderStyle(){return Ey({width:"100%",height:`${this.groupBox.headerRect.height}px`})}get groupBox(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group,o=this.env.model.getters.getRowDimensions(e,t).start,i=this.env.model.getters.getRowDimensions(e,s).end;let n=0,r=A;if(0!==t){const s=this.env.model.getters.getRowDimensions(e,t-1);n=A+s.start,r=s.end-s.start}const a={x:this.props.layerOffset,y:n,width:F,height:r};return{headerRect:a,groupRect:{x:this.props.layerOffset,y:a.y,width:F,height:a.height+(i-o)},isEndHidden:this.env.model.getters.isRowHidden(e,s)}}}class fB extends pB{dimension="COL";get groupBorderStyle(){const e=this.groupBox;return 0===e.groupRect.width?"":Ey({top:"calc(50% - 1px)",left:e.headerRect.width/2+"px",width:`calc(100% - ${e.headerRect.width/2}px)`,height:"30%","border-top":"1px solid","border-right":e.isEndHidden?"":"1px solid"})}get groupHeaderStyle(){return Ey({width:`${this.groupBox.headerRect.width}px`,height:"100%"})}get groupBox(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group,o=this.env.model.getters.getColDimensions(e,t).start,i=this.env.model.getters.getColDimensions(e,s).end;let n=0,r=D;if(0!==t){const s=this.env.model.getters.getColDimensions(e,t-1);n=D+s.start,r=s.end-s.start}const a={x:n,y:this.props.layerOffset,width:r,height:F};return{headerRect:a,groupRect:{x:a.x,y:this.props.layerOffset,width:a.width+(i-o),height:F},isEndHidden:this.env.model.getters.isColHidden(e,s)}}}class vB extends t.Component{static template="o-spreadsheet-HeaderGroupContainer";static props={dimension:String,layers:Array};static components={RowGroup:mB,ColGroup:fB,MenuPopover:PF};menu=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});getLayerOffset(e){return e*F}onContextMenu(e){const t=this.env.model.getters.getActiveSheetId(),s={x:e.clientX,y:e.clientY},o=FV(t,this.props.dimension);this.openContextMenu(s,o)}openContextMenu(e,t){this.menu.isOpen=!0,this.menu.anchorRect={...e,width:0,height:0},this.menu.menuItems=t}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get groupComponent(){return"ROW"===this.props.dimension?mB:fB}get hasFrozenPane(){const e=this.env.model.getters.getMainViewportCoordinates();return"COL"===this.props.dimension?e.x>0:e.y>0}get scrollContainerStyle(){const{scrollX:e,scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo(),s={};return"COL"===this.props.dimension?s.left=-e-this.frozenPaneContainerSize+"px":s.top=-t-this.frozenPaneContainerSize+"px",Ey(s)}get frozenPaneContainerStyle(){const e={};return"COL"===this.props.dimension?e.width=`${this.frozenPaneContainerSize}px`:e.height=`${this.frozenPaneContainerSize}px`,Ey(e)}get frozenPaneContainerSize(){if(!this.hasFrozenPane)return 0;const e=this.env.model.getters.getMainViewportCoordinates();return"COL"===this.props.dimension?D+e.x:A+e.y}}class bB extends t.Component{static template="o-spreadsheet-SidePanel";static props={panelContent:Object,panelProps:Object,onCloseSidePanel:Function,onStartHandleDrag:Function,onResetPanelSize:Function,isPinned:{type:Boolean,optional:!0},onTogglePinPanel:{type:Function,optional:!0},onToggleCollapsePanel:{type:Function,optional:!0},isCollapsed:{type:Boolean,optional:!0}};spreadsheetRect=AF();getTitle(){const e=this.props.panelContent;return"function"==typeof e.title?e.title(this.env,this.props.panelProps):e.title}get pinInfoMessage(){return fs("Pin this panel to allow to open another side panel beside it.")}}class SB extends t.Component{static template="o-spreadsheet-SidePanels";static props={};static components={SidePanel:bB};sidePanelStore;spreadsheetRect=AF();setup(){this.sidePanelStore=ev(Rz),t.useEffect(()=>{this.sidePanelStore.mainPanel&&!this.sidePanelStore.isMainPanelOpen&&this.sidePanelStore.closeMainPanel(),this.sidePanelStore.secondaryPanel&&!this.sidePanelStore.isSecondaryPanelOpen&&this.sidePanelStore.close()},()=>[this.sidePanelStore.isMainPanelOpen,this.sidePanelStore.isSecondaryPanelOpen])}startHandleDrag(e,t){const s=document.body.style.cursor,o="mainPanel"===e?this.sidePanelStore.mainPanel:this.sidePanelStore.secondaryPanel;if(!o)return;const i=o.size,n=t.clientX;iM(t=>{document.body.style.cursor="col-resize";const s=i+n-t.clientX;this.sidePanelStore.changePanelSize(e,s)},()=>{document.body.style.cursor=s})}get mainPanelProps(){const e=this.sidePanelStore.mainPanelProps;if(this.sidePanelStore.mainPanel&&e)return{panelContent:yz.get(this.sidePanelStore.mainPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.closeMainPanel(),onTogglePinPanel:()=>this.sidePanelStore.togglePinPanel(),onStartHandleDrag:e=>this.startHandleDrag("mainPanel",e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize("mainPanel"),isPinned:this.sidePanelStore.mainPanel?.isPinned,onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel("mainPanel"),isCollapsed:this.sidePanelStore.mainPanel?.isCollapsed}}get secondaryPanelProps(){const e=this.sidePanelStore.secondaryPanelProps;if(this.sidePanelStore.secondaryPanel&&e)return{panelContent:yz.get(this.sidePanelStore.secondaryPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.close(),onStartHandleDrag:e=>this.startHandleDrag("secondaryPanel",e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize("secondaryPanel"),onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel("secondaryPanel"),isCollapsed:this.sidePanelStore.secondaryPanel?.isCollapsed}}get panelList(){return[{key:this.sidePanelStore.secondaryPanelKey,props:this.secondaryPanelProps,style:this.sidePanelStore.secondaryPanel?Ey({width:`${this.sidePanelStore.secondaryPanel.size}px`}):""},{key:this.sidePanelStore.mainPanelKey,props:this.mainPanelProps,style:this.sidePanelStore.mainPanel?Ey({width:`${this.sidePanelStore.mainPanel.size}px`}):""}].filter(e=>e.key&&e.props)}}class CB extends t.Component{static template="o-spreadsheet-RibbonMenu";static props={onClose:Function};static components={Menu:RF};rootItems=$z.getMenuItems();menuRef=t.useRef("menu");containerRef=t.useRef("container");state=t.useState({menuItems:this.rootItems,title:fs("Menu Bar"),parentState:void 0});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.onMounted(this.updateShadows)}onExternalClick(e){this.menuRef.el?.contains(e.target)||this.props.onClose()}onClickMenu(e){const t=e.children(this.env);t.length?(this.state.parentState={...this.state},this.state.menuItems=t,this.state.title=e.name(this.env),this.containerRef.el?.scrollTo({top:0})):(this.state.menuItems=this.rootItems,this.state.title=void 0,this.state.parentState=void 0,e.execute?.(this.env),this.props.onClose())}get menuProps(){return{menuItems:this.state.menuItems,onClose:this.props.onClose,onClickMenu:this.onClickMenu.bind(this)}}get style(){return Ey({height:`${this.props.height}px`})}updateShadows(){if(!this.containerRef.el)return;this.containerRef.el.classList.remove("scroll-top","scroll-bottom");const e=this.containerRef.el.scrollHeight-this.containerRef.el.clientHeight||0;this.containerRef.el.scrollTop<e-1&&this.containerRef.el.classList.add("scroll-bottom"),this.containerRef.el.scrollTop>0&&this.containerRef.el.classList.add("scroll-top")}onClickBack(){this.state.parentState?(this.state.menuItems=this.state.parentState.menuItems,this.state.title=this.state.parentState.title,this.state.parentState=this.state.parentState.parentState,this.containerRef.el?.scrollTo({top:0})):this.props.onClose()}get backTitle(){return this.state.parentState?fs("Go to previous menu"):fs("Close menu bar")}}class yB extends t.Component{static components={Composer:zP,BottomBar:dB,Ripple:rB,RibbonMenu:CB};static template="o-spreadsheet-SmallBottomBar";static props={onClick:Function};composerFocusStore;composerStore;composerInterface;composerRef=t.useRef("bottombarComposer");menuState=t.useState({isOpen:!1});setup(){this.composerFocusStore=ev(uv);const e=ev(WV);this.composerStore=e,this.composerInterface={id:"bottombarComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},t.useEffect(()=>{this.env.isMobile()&&!this.menuState.isOpen&&"inactive"!==this.composerStore.editionMode&&this.composerFocusStore.activeComposer!==this.composerInterface&&this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"})})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get showFxIcon(){return"inactive"===this.focus&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get rect(){return this.composerRef.el?Fy(this.composerRef.el):{x:0,y:0,width:0,height:0}}get composerProps(){const{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,composerStore:this.composerStore,onComposerContentFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus",selection:e}),isDefaultFocus:!1,inputStyle:Ey({height:"inactive"===this.focus?"26px":"fit-content","max-height":"130px"}),showAssistant:!Gy(),placeholder:this.composerStore.placeholder}}get symbols(){return["=","(",")",":","-","/","*",",","+","$","."]}insertSymbol(e){this.composerStore.replaceComposerCursorSelection(e),this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"})}toggleRibbon(){this.composerStore.cancelEdition(),this.menuState.isOpen=!this.menuState.isOpen}}class IB extends t.Component{static template="o-spreadsheet-TopBarComposer";static props={};static components={Composer:zP};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=ev(uv);const e=ev(WV);this.composerStore=e,this.composerInterface={id:"topbarComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition}}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get showFxIcon(){return"inactive"===this.focus&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get composerStyle(){const e={padding:"5px 0px 5px 8px","max-height":"300px","line-height":"24px"};return e.height="inactive"===this.focus?"34px":"fit-content",Ey(e)}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}}class wB{mutators=["closeDropdowns","openDropdown"];_currentDropdown=null;closeDropdowns(){this._currentDropdown=null}openDropdown(e){this._currentDropdown=e}get currentDropdown(){return this._currentDropdown}}function EB(){const e=t.useComponent(),s=ev(wB);return t.onWillUnmount(()=>{e===s.currentDropdown&&s.closeDropdowns()}),{closeDropdowns:()=>s.closeDropdowns(),openDropdown:()=>{s.openDropdown(e)},get isActive(){return s.currentDropdown===e}}}const RB=[[["all","o-spreadsheet-Icon.BORDERS"],["hv","o-spreadsheet-Icon.BORDER_HV"],["h","o-spreadsheet-Icon.BORDER_H"],["v","o-spreadsheet-Icon.BORDER_V"],["external","o-spreadsheet-Icon.BORDER_EXTERNAL"]],[["left","o-spreadsheet-Icon.BORDER_LEFT"],["top","o-spreadsheet-Icon.BORDER_TOP"],["right","o-spreadsheet-Icon.BORDER_RIGHT"],["bottom","o-spreadsheet-Icon.BORDER_BOTTOM"],["clear","o-spreadsheet-Icon.BORDER_CLEAR"]]];class xB extends t.Component{static template="o-spreadsheet-BorderEditor";static props={class:{type:String,optional:!0},currentBorderColor:{type:String,optional:!1},currentBorderStyle:{type:String,optional:!1},currentBorderPosition:{type:String,optional:!0},onBorderColorPicked:Function,onBorderStylePicked:Function,onBorderPositionPicked:Function,maxHeight:{type:Number,optional:!0},anchorRect:Object};static components={ColorPickerWidget:DU,Popover:DF};BORDER_POSITIONS=RB;lineStyleButtonRef=t.useRef("lineStyleButton");borderStyles=As;state=t.useState({activeTool:void 0});toggleDropdownTool(e){const t=this.state.activeTool===e;this.state.activeTool=t?void 0:e}closeDropdown(){this.state.activeTool=void 0}setBorderPosition(e){this.props.onBorderPositionPicked(e),this.closeDropdown()}setBorderColor(e){this.props.onBorderColorPicked(e),this.closeDropdown()}setBorderStyle(e){this.props.onBorderStylePicked(e),this.closeDropdown()}get lineStylePickerPopoverProps(){return{anchorRect:this.lineStylePickerAnchorRect,positioning:"bottom-left",verticalOffset:0}}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"bottom-left",verticalOffset:0}}get lineStylePickerAnchorRect(){const e=this.lineStyleButtonRef.el;if(null===e)return{x:0,y:0,width:0,height:0};const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}}class TB extends t.Component{static template="o-spreadsheet-BorderEditorWidget";static props={disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={BorderEditor:xB};topBarToolStore;borderEditorButtonRef=t.useRef("borderEditorButton");state=t.useState({currentColor:U,currentStyle:V,currentPosition:void 0});setup(){this.topBarToolStore=EB(),t.onWillUpdateProps(()=>{this.isActive||(this.state.currentPosition=void 0)})}get dropdownMaxHeight(){return this.env.model.getters.getSheetViewDimension().height}get borderEditorAnchorRect(){const e=this.borderEditorButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}onBorderPositionPicked(e){this.state.currentPosition=e,this.updateBorder()}onBorderColorPicked(e){this.state.currentColor=e,this.updateBorder()}onBorderStylePicked(e){this.state.currentStyle=e,this.updateBorder()}get isActive(){return this.topBarToolStore.isActive}toggleBorderEditor(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}updateBorder(){void 0!==this.state.currentPosition&&this.env.model.dispatch("SET_ZONE_BORDERS",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),border:{position:this.state.currentPosition,color:this.state.currentColor,style:this.state.currentStyle}})}}class AB extends t.Component{static template="o-spreadsheet-PaintFormatButton";static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=ev(sU)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}}class DB extends t.Component{static template="o-spreadsheet-TableDropdownButton";static components={TableStylesPopover:fz,ActionButton:AU};static props={class:{type:String,optional:!0}};topBarToolStore;state=t.useState({popoverProps:void 0});setup(){this.topBarToolStore=EB()}onStylePicked(e){const t=this.env.model.getters.getActiveSheetId(),s={...this.tableConfig,styleId:e};oN(this.env,t,s).isSuccessful&&this.env.openSidePanel("TableSidePanel",{}),this.closePopover()}onClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps)return void this.closePopover();if(this.env.model.getters.getFirstTableInSelection())return this.topBarToolStore.closeDropdowns(),void this.env.toggleSidePanel("TableSidePanel",{});const t=e.currentTarget,{left:s,bottom:o}=t.getBoundingClientRect();this.topBarToolStore.openDropdown(),this.state.popoverProps={anchorRect:{x:s,y:o,width:0,height:0},positioning:"bottom-left",verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}get action(){return{name:e=>e.model.getters.getFirstTableInSelection()?fs("Edit table"):fs("Insert table"),icon:e=>e.model.getters.getFirstTableInSelection()?"o-spreadsheet-Icon.EDIT_TABLE":"o-spreadsheet-Icon.PAINT_TABLE"}}get tableConfig(){return{...hE,numberOfHeaders:1,bandedRows:!0}}}class _B extends t.Component{static components={ColorPickerWidget:DU};static props={class:String,style:String,icon:String,title:String};static template="o-spreadsheet-ColorEditor";topBarToolStore;state=t.useState({isOpen:!1});setup(){this.topBarToolStore=EB()}get currentColor(){return this.env.model.getters.getCurrentStyle()[this.props.style]||("textColor"===this.props.style?"#000000":"#ffffff")}setColor(e){nN(this.env,{[this.props.style]:e}),this.state.isOpen=!1}get isMenuOpen(){return this.topBarToolStore.isActive}onClick(){this.isMenuOpen?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}}class OB extends t.Component{static template="o-spreadsheet-DropdownAction";static components={ActionButton:AU,Popover:DF};static props={parentAction:Object,childActions:Array,class:String,childClass:String};topBarToolStore;actionRef=t.useRef("actionRef");setup(){this.topBarToolStore=EB()}toggleDropdown(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}get popoverProps(){return{anchorRect:this.actionRef.el?this.actionRef.el.getBoundingClientRect():{x:0,y:0,width:0,height:0},positioning:"bottom-left",verticalOffset:0,class:"rounded"}}}class FB extends t.Component{static components={FontSizeEditor:_U};static props={class:String};static template="o-spreadsheet-TopBarFontSizeEditor";topBarToolStore;setup(){this.topBarToolStore=EB()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||L}setFontSize(e){nN(this.env,{fontSize:e})}onToggle(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}}class PB extends t.Component{static template="o-spreadsheet-NumberFormatsTool";static components={MenuPopover:PF,ActionButton:AU};static props={class:String};formatNumberMenuItemSpec=Wz;topBarToolStore;buttonRef=t.useRef("buttonRef");state=t.useState({anchorRect:{x:0,y:0,width:0,height:0},menuItems:[]});setup(){this.topBarToolStore=EB()}toggleMenu(){if(this.isActive)this.topBarToolStore.closeDropdowns();else{const e=jf(this.formatNumberMenuItemSpec);this.state.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.anchorRect=Fy(this.buttonRef.el),this.topBarToolStore.openDropdown()}}get isActive(){return this.topBarToolStore.isActive}}const MB=new class{content={};add(e){if(e in this.content)throw new Error(`${e} is already present in this registry!`);return this.content[e]=[],this}addChild(e,t){return this.content[e].push(t),this}getEntries(e){return this.content[e].sort((e,t)=>e.sequence-t.sequence)}getCategories(){return Object.keys(this.content)}};MB.add("edit").addChild("edit",{component:AU,props:{action:KN,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("edit",{component:AU,props:{action:JN,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("edit",{component:AB,props:{class:"o-hoverable-button o-toolbar-button o-mobile-disabled"},sequence:3}).addChild("edit",{component:AU,props:{action:EV,class:"o-hoverable-button o-toolbar-button"},sequence:4}).add("numberFormat").addChild("numberFormat",{component:AU,props:{action:Pk,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("numberFormat",{component:AU,props:{action:oV,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("numberFormat",{component:AU,props:{action:sV,class:"o-hoverable-button o-toolbar-button"},sequence:3}).addChild("numberFormat",{component:PB,props:{class:"o-menu-item-button o-hoverable-button o-toolbar-button"},sequence:4}).add("fontSize").addChild("fontSize",{component:FB,props:{class:"o-hoverable-button o-toolbar-button"},sequence:3}).add("textStyle").addChild("textStyle",{component:AU,props:{action:iV,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("textStyle",{component:AU,props:{action:nV,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("textStyle",{component:AU,props:{action:aV,class:"o-hoverable-button o-toolbar-button"},sequence:3}).addChild("textStyle",{component:_B,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button",style:"textColor",icon:"o-spreadsheet-Icon.TEXT_COLOR",title:fs("Text Color")},sequence:4}).add("cellStyle").addChild("cellStyle",{component:_B,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button",style:"fillColor",icon:"o-spreadsheet-Icon.FILL_COLOR",title:fs("Fill Color")},sequence:1}).addChild("cellStyle",{component:TB,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:2}).addChild("cellStyle",{component:AU,props:{action:fL,class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:3}).add("alignment").addChild("alignment",{component:OB,props:{parentAction:hV,childActions:[dV,uV,gV],class:"o-hoverable-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:1}).addChild("alignment",{component:OB,props:{parentAction:pV,childActions:[mV,fV,vV],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:2}).addChild("alignment",{component:OB,props:{parentAction:SV,childActions:[CV,yV,IV],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:3}).add("misc").addChild("misc",{component:DB,props:{class:"o-toolbar-button o-hoverable-button o-menu-item-button o-mobile-disabled"},sequence:1}).addChild("misc",{component:AU,props:{action:Rk,class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:2});class NB extends t.Component{static template="o-spreadsheet-TopBar";static props={onClick:Function,dropdownMaxHeight:Number};static components={MenuPopover:PF,TopBarComposer:IB,Popover:DF};toolsCategories=MB.getCategories();state=t.useState({menuState:{isOpen:!1,anchorRect:null,menuItems:[]},invisibleToolsCategories:[],toolsPopoverState:{isOpen:!1}});isSelectingMenu=!1;openedEl=null;menus=[];toolbarMenuRegistry=MB;formatNumberMenuItemSpec=Wz;isntToolbarMenu=!1;composerFocusStore;fingerprints;topBarToolStore;toolBarContainerRef=t.useRef("toolBarContainer");toolbarRef=t.useRef("toolBar");moreToolsContainerRef=t.useRef("moreToolsContainer");moreToolsButtonRef=t.useRef("moreToolsButton");spreadsheetRect=AF();setup(){this.composerFocusStore=ev(uv),this.fingerprints=ev(yN),this.topBarToolStore=ev(wB),t.useExternalListener(window,"click",this.onExternalClick),t.onWillStart(()=>this.updateCellState()),t.onWillUpdateProps(()=>this.updateCellState()),t.useEffect(()=>{this.state.toolsPopoverState.isOpen=!1,this.setVisibilityToolsGroups()},()=>[this.spreadsheetRect.width])}setVisibilityToolsGroups(){if(this.env.model.getters.isReadonly())return;const e=[],{x:t}=this.toolbarRef.el.getBoundingClientRect(),{x:s}=this.toolBarContainerRef.el.getBoundingClientRect();this.moreToolsContainerRef.el?.classList.remove("d-none");const o=this.moreToolsButtonRef.el?.getBoundingClientRect().width||0,i=Math.round(this.spreadsheetRect.width)-o-(t-s)-16,n=document.querySelectorAll(".tool-container");let r=0;for(let t=0;t<n.length;t++){const s=n[t];s.classList.remove("d-none");const{width:o}=s.getBoundingClientRect();r+=o,r>i&&(s.classList.add("d-none"),e.push(this.toolsCategories[t]))}this.state.invisibleToolsCategories=e,e.length||this.moreToolsContainerRef.el?.classList.add("d-none")}get topbarComponents(){return sB.getAllOrdered().filter(e=>!e.isVisible||e.isVisible(this.env))}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||L}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.isntToolbarMenu&&this.openMenu(e,t)}toggleContextMenu(e,t){this.state.menuState.isOpen&&this.isntToolbarMenu?this.closeMenus():(this.openMenu(e,t),this.isntToolbarMenu=!0)}openMenu(e,t){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!0,this.state.menuState.anchorRect=Fy(t.currentTarget),this.state.menuState.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.composerFocusStore.activeComposer.stopEdition()}closeMenus(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){this.menus=$z.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){nN(this.env,{[e]:t}),this.onClick()}setFontSize(e){nN(this.env,{fontSize:e})}toggleMoreTools(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!this.state.toolsPopoverState.isOpen}get toolsPopoverProps(){return{anchorRect:this.moreToolsButtonRef.el?Fy(this.moreToolsButtonRef.el):{x:0,y:0,width:0,height:0},positioning:"bottom-left",verticalOffset:0,class:"rounded",maxWidth:300}}showDivider(e){return e<this.toolsCategories.length-1||this.state.invisibleToolsCategories.length>0}}class LB{clipboard;constructor(e){this.clipboard=e}async write(e){if(this.clipboard?.write)try{await(this.clipboard?.write(this.getClipboardItems(e)))}catch(t){console.log("Failed to write on the clipboard, falling back to plain/html text. Error %s",t);try{await(this.clipboard?.write([new ClipboardItem({[gI.PlainText]:this.getBlob(e,gI.PlainText),[gI.Html]:this.getBlob(e,gI.Html)})]))}catch(e){}}else await this.writeText(e[gI.PlainText]??"")}async writeText(e){try{this.clipboard?.writeText(e)}catch(e){}}async read(){let e;try{e=await navigator.permissions.query({name:"clipboard-read"})}catch(e){}if(!this.clipboard?.read)return{status:"ok",content:{[gI.PlainText]:await(this.clipboard?.readText())}};try{const e=await this.clipboard.read(),t={};for(const s of e)for(const e of s.types){const o=await s.getType(e);if(S_.includes(e))t[e]=o;else{const s=await o.text();t[e]=s}}return{status:"ok",content:t}}catch(t){return{status:"denied"===e?.state?"permissionDenied":"notImplemented"}}}getClipboardItems(e){const t={};for(const s of Object.keys(e))t[s]=this.getBlob(e,s);return[new ClipboardItem(t)]}getBlob(e,t){const s=e[t];return s instanceof Blob||s instanceof File?s:new Blob([e[t]||""],{type:t})}}class kB extends t.Component{static template="o-spreadsheet-Spreadsheet";static props={model:Object,notifyUser:{type:Function,optional:!0},raiseError:{type:Function,optional:!0},askConfirmation:{type:Function,optional:!0}};static components={TopBar:NB,Grid:Az,BottomBar:dB,SmallBottomBar:yB,SidePanels:SB,SpreadsheetDashboard:gB,HeaderGroupContainer:vB,FullScreenFigure:Pz};sidePanel;spreadsheetRef=t.useRef("spreadsheet");spreadsheetRect=AF();_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){const e={};this.env.isDashboard()?e["grid-template-rows"]="auto":e["grid-template-rows"]="min-content auto min-content";const t=this.sidePanel.mainPanel?`${this.sidePanel.totalPanelSize||wz}px`:"auto";return e["grid-template-columns"]=`auto ${t}`,Ey(e)}setup(){if(!("isSmall"in this.env)){const e=function(){const e=AF();return{get isSmall(){return e.width<768}}}();t.useSubEnv({get isSmall(){return e.isSmall}})}const e=Qf();e.inject(nv,this.model);const s=this.env;e.get(Iz).setSmallThreshhold(()=>s.isSmall),this.notificationStore=ev(jP),this.composerFocusStore=ev(uv),this.sidePanel=ev(Rz);const o=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:o?new oB(o):void 0,loadCurrencies:this.model.config.external.loadCurrencies,loadLocales:this.model.config.external.loadLocales,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.sidePanel.open.bind(this.sidePanel),replaceSidePanel:this.sidePanel.replace.bind(this.sidePanel),toggleSidePanel:this.sidePanel.toggle.bind(this.sidePanel),clipboard:this.env.clipboard||new LB(navigator.clipboard),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,s)=>this.notificationStore.askConfirmation(e,t,s),raiseError:(e,t)=>this.notificationStore.raiseError(e,t),isMobile:Wy}),this.notificationStore.updateNotificationCallbacks({...this.props}),t.useEffect(()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()},()=>[this.env.model.getters.getActiveSheetId()]),t.useExternalListener(window,"resize",()=>this.render(!0)),t.useExternalListener(document.body,"wheel",()=>{}),this.bindModelEvents(),t.onWillUpdateProps(e=>{if(e.model!==this.props.model)throw new Error("Changing the props model is not supported at the moment.");e.notifyUser===this.props.notifyUser&&e.askConfirmation===this.props.askConfirmation&&e.raiseError===this.props.raiseError||this.notificationStore.updateNotificationCallbacks({...e})});const i=function(e){let t=!1;return async(...s)=>{t||(t=!0,await Promise.resolve(),t=!1,e(...s))}}(this.render.bind(this,!0));t.onMounted(()=>{this.checkViewportSize(),e.on("store-updated",this,i),n.observe(this.spreadsheetRef.el)}),t.onWillUnmount(()=>{this.unbindModelEvents(),e.off("store-updated",this),n.disconnect(),function(){if(window.Chart)for(const e of sS.getAll())e.unregister(window.Chart)}()}),t.onPatched(()=>{this.checkViewportSize()});const n=new ResizeObserver(()=>{this.sidePanel.changeSpreadsheetWidth(this.spreadsheetRect.width)})}bindModelEvents(){this.model.on("update",this,()=>this.render(!0)),this.model.on("notify-ui",this,e=>this.notificationStore.notifyUser(e)),this.model.on("raise-error-ui",this,({text:e})=>this.notificationStore.raiseError(e))}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this),this.model.off("raise-error-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(isFinite(e)&&isFinite(t))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.notificationStore.notifyUser({text:fs("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),type:"warning",sticky:!1}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}focusGrid(){this._focusGrid&&this._focusGrid()}get gridHeight(){return this.env.model.getters.getSheetViewDimension().height}get gridContainerStyle(){const e=F*this.rowLayers.length,t=F*this.colLayers.length;return Ey({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`})}get rowLayers(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,"ROW")}get colLayers(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,"COL")}getGridSize(){const e=this.spreadsheetRef.el?.querySelector(".o-spreadsheet-topbar-wrapper")?.getBoundingClientRect().height||0,t=this.spreadsheetRef.el?.querySelector(".o-spreadsheet-bottombar-wrapper")?.getBoundingClientRect().height||0,s=this.spreadsheetRef.el?.querySelector(".o-grid")?.getBoundingClientRect().width||0,o=(this.spreadsheetRef.el?.getBoundingClientRect().height||0)-(this.spreadsheetRef.el?.querySelector(".o-column-groups")?.getBoundingClientRect().height||0)-e-t;return{width:Math.max(s-O,0),height:Math.max(o-O,0)}}}class VB extends ny{dataSets;labelRange;background;legendPosition;aggregated;dataSetsHaveTitle;dataSetDesign;axesDesign;type="combo";showValues;hideDataMarkers;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers,this.zoomable=e.zoomable}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId),type:this.dataSetDesign?.[t]?.type??(t?"line":"bar")});return{type:"combo",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,zoomable:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:e,labelRange:t,verticalAxis:hC(s)}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new VB(i,this.sheetId,this.getters)}static getDefinitionFromContextCreation(e){const t=(e.range??[]).map((e,t)=>({...e,type:t?"line":"bar"}));return{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated,legendPosition:e.legendPosition??"top",title:e.title||{text:""},labelRange:e.auxiliaryRange||void 0,type:"combo",axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new VB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new VB(t,e,this.getters)}}class UB extends ny{dataSets;labelRange;background;legendPosition;aggregated;type="funnel";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;showValues;funnelColors;cumulative;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.horizontal=!0,this.funnelColors=e.funnelColors,this.cumulative=e.cumulative}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:"none",title:e.title||{text:""},type:"funnel",labelRange:e.auxiliaryRange||void 0,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new UB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new UB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"funnel",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,horizontal:this.horizontal,axesDesign:this.axesDesign,showValues:this.showValues,funnelColors:this.funnelColors,cumulative:this.cumulative,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new UB(i,this.sheetId,this.getters)}}class HB extends ny{dataSets;labelRange;background;legendPosition;type="geo";dataSetsHaveTitle;dataSetDesign;colorScale;missingValueColor;region;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.colorScale=e.colorScale,this.missingValueColor=e.missingValueColor,this.region=e.region}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"geo",labelRange:e.auxiliaryRange||void 0,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new HB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new HB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"geo",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,colorScale:this.colorScale,missingValueColor:this.missingValueColor,region:this.region,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new HB(i,this.sheetId,this.getters)}}class zB extends ny{dataSets;labelRange;background;legendPosition;aggregated;type="pyramid";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;stacked=!0;showValues;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"pyramid",labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new zB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new zB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"pyramid",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,horizontal:!0,stacked:!0,showValues:this.showValues,humanize:this.humanize}}getDefinitionForExcel(e){const{dataSets:t,labelRange:s}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),o=this.getDefinition(),i=_I(o,this.dataSets,this.labelRange,e),{dataSetsValues:n}=i,r=Math.max(...n.map(e=>Math.max(...e.data.map(Math.abs))));return{...o,horizontal:!0,backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:t,labelRange:s,verticalAxis:hC(o),maxValue:r}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new zB(i,this.sheetId,this.getters)}}class BB extends ny{dataSets;labelRange;background;legendPosition;stacked;aggregated;type="radar";dataSetsHaveTitle;dataSetDesign;fillArea;showValues;hideDataMarkers;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.fillArea=e.fillArea,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"radar",labelRange:e.auxiliaryRange||void 0,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new BB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new BB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"radar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated,fillArea:this.fillArea,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,humanize:this.humanize}}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new BB(i,this.sheetId,this.getters)}}class GB extends ny{dataSets;labelRange;background;legendPosition;type="sunburst";dataSetsHaveTitle;showValues;showLabels;valuesDesign;groupColors;pieHolePercentage;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.groupColors=e.groupColors,this.pieHolePercentage=e.pieHolePercentage}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static getDefinitionFromContextCreation(e){const t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"sunburst",labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){const e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}getDefinitionWithSpecificDataSets(e,t,s){return{type:"sunburst",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,showValues:this.showValues,showLabels:this.showLabels,valuesDesign:this.valuesDesign,groupColors:this.groupColors,pieHolePercentage:this.pieHolePercentage,humanize:this.humanize}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new GB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new GB(t,e,this.getters)}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new GB(i,this.sheetId,this.getters)}}class WB extends ny{static defaults={background:c,legendPosition:"top",dataSetsHaveTitle:!1,showHeaders:!0,headersColor:"#000000"};dataSets;labelRange;background;legendPosition;type="treemap";dataSetsHaveTitle;showHeaders;headerDesign;showValues;showLabels;valuesDesign;coloringOptions;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showHeaders=e.showHeaders,this.headerDesign=e.headerDesign,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.coloringOptions=e.coloringOptions}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static getDefinitionFromContextCreation(e){const t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"treemap",labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions,humanize:e.humanize}}getContextCreation(){const e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new WB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new WB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)}));return{type:"treemap",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,showValues:this.showValues,showHeaders:this.showHeaders,headerDesign:this.headerDesign,showLabels:this.showLabels,valuesDesign:this.valuesDesign,coloringOptions:this.coloringOptions,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new WB(i,this.sheetId,this.getters)}}$y.add("bar",{match:e=>"bar"===e,createChart:(e,t,s)=>new qw(e,t,s),getChartRuntime:Zw,validateChartDefinition:qw.validateChartDefinition,transformDefinition:qw.transformDefinition,getChartDefinitionFromContextCreation:qw.getDefinitionFromContextCreation,sequence:10}),$y.add("combo",{match:e=>"combo"===e,createChart:(e,t,s)=>new VB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=DI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:VC(s,o)},options:{...nI,layout:QI(0,o),scales:dw(s,o),plugins:{title:Dw(s,t),legend:nw(s),tooltip:Pw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}},validateChartDefinition:VB.validateChartDefinition,transformDefinition:VB.transformDefinition,getChartDefinitionFromContextCreation:VB.getDefinitionFromContextCreation,sequence:15}),$y.add("line",{match:e=>"line"===e,createChart:(e,t,s)=>new JO(e,t,s),getChartRuntime:QO,validateChartDefinition:JO.validateChartDefinition,transformDefinition:JO.transformDefinition,getChartDefinitionFromContextCreation:JO.getDefinitionFromContextCreation,sequence:20}),$y.add("pie",{match:e=>"pie"===e,createChart:(e,t,s)=>new eF(e,t,s),getChartRuntime:tF,validateChartDefinition:eF.validateChartDefinition,transformDefinition:eF.transformDefinition,getChartDefinitionFromContextCreation:eF.getDefinitionFromContextCreation,sequence:30}),$y.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,s)=>new gy(e,t,s),getChartRuntime:my,validateChartDefinition:gy.validateChartDefinition,transformDefinition:gy.transformDefinition,getChartDefinitionFromContextCreation:gy.getDefinitionFromContextCreation,sequence:40}),$y.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,s)=>new ZO(e,t,s),getChartRuntime:jO,validateChartDefinition:ZO.validateChartDefinition,transformDefinition:ZO.transformDefinition,getChartDefinitionFromContextCreation:ZO.getDefinitionFromContextCreation,sequence:50}),$y.add("scatter",{match:e=>"scatter"===e,createChart:(e,t,s)=>new uH(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=OI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"line",data:{labels:o.labels,datasets:LC(s,o)},options:{...nI,layout:QI(0,o),scales:gw(s,o),plugins:{title:Dw(s,t),legend:iw(s),tooltip:Mw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}},validateChartDefinition:uH.validateChartDefinition,transformDefinition:uH.transformDefinition,getChartDefinitionFromContextCreation:uH.getDefinitionFromContextCreation,sequence:60}),$y.add("waterfall",{match:e=>"waterfall"===e,createChart:(e,t,s)=>new sF(e,t,s),getChartRuntime:oF,validateChartDefinition:sF.validateChartDefinition,transformDefinition:sF.transformDefinition,getChartDefinitionFromContextCreation:sF.getDefinitionFromContextCreation,sequence:70}),$y.add("pyramid",{match:e=>"pyramid"===e,createChart:(e,t,s)=>new zB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=_I(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:PC(s,o)},options:{...nI,indexAxis:"y",layout:QI(0,o),scales:mw(s,o),plugins:{title:Dw(s,t),legend:tw(s),tooltip:kw(s,o),chartShowValuesPlugin:Tw(s,o)}}},background:e.background||c}},validateChartDefinition:zB.validateChartDefinition,transformDefinition:zB.transformDefinition,getChartDefinitionFromContextCreation:zB.getDefinitionFromContextCreation,sequence:80,dataSeriesLimit:2}),$y.add("radar",{match:e=>"radar"===e,createChart:(e,t,s)=>new BB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=PI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"radar",data:{labels:o.labels,datasets:UC(s,o)},options:{...nI,layout:QI(0,o),scales:fw(s,o),plugins:{title:Dw(s,t),legend:aw(s),tooltip:Vw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}},validateChartDefinition:BB.validateChartDefinition,transformDefinition:BB.transformDefinition,getChartDefinitionFromContextCreation:BB.getDefinitionFromContextCreation,sequence:80}),$y.add("geo",{match:e=>"geo"===e,createChart:(e,t,s)=>new HB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=MI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"choropleth",data:{datasets:HC(s,o)},options:{...nI,layout:QI(0,o),scales:vw(s,o),plugins:{title:Dw(s,t),tooltip:Uw(s,o),legend:{display:!1}}}},background:e.background||c}},validateChartDefinition:HB.validateChartDefinition,transformDefinition:HB.transformDefinition,getChartDefinitionFromContextCreation:HB.getDefinitionFromContextCreation,sequence:90,dataSeriesLimit:1}),$y.add("funnel",{match:e=>"funnel"===e,createChart:(e,t,s)=>new UB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=NI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"funnel",data:{labels:o.labels,datasets:zC(s,o)},options:{...nI,indexAxis:"y",layout:QI(0,o),scales:bw(0,o),plugins:{title:Dw(s,t),legend:{display:!1},tooltip:Hw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}},validateChartDefinition:UB.validateChartDefinition,transformDefinition:UB.transformDefinition,getChartDefinitionFromContextCreation:UB.getDefinitionFromContextCreation,sequence:100,dataSeriesLimit:1}),$y.add("sunburst",{match:e=>"sunburst"===e,createChart:(e,t,s)=>new GB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=LI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"doughnut",data:{datasets:GC(s,o)},options:{cutout:void 0===e.pieHolePercentage?"25%":`${e.pieHolePercentage}%`,...nI,layout:QI(0,o),plugins:{title:Dw(s,t),legend:lw(s),tooltip:zw(s,o),sunburstLabelsPlugin:xw(s,o),sunburstHoverPlugin:{enabled:!0}}}},background:e.background||c}},validateChartDefinition:GB.validateChartDefinition,transformDefinition:GB.transformDefinition,getChartDefinitionFromContextCreation:GB.getDefinitionFromContextCreation,sequence:30}),$y.add("treemap",{match:e=>"treemap"===e,createChart:(e,t,s)=>new WB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=LI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"treemap",data:{labels:o.labels,datasets:ZC(s,o)},options:{...nI,layout:QI(0,o),plugins:{title:Dw(s,t),legend:{display:!1},tooltip:Bw(s,o)}}},background:e.background||c}},validateChartDefinition:WB.validateChartDefinition,transformDefinition:WB.transformDefinition,getChartDefinitionFromContextCreation:WB.getDefinitionFromContextCreation,sequence:100}),f_.add("line",{matcher:e=>"line"===e.type&&!e.stacked&&!e.fillArea,displayName:fs("Line"),chartType:"line",chartSubtype:"line",subtypeDefinition:{stacked:!1,fillArea:!1},category:"line",preview:"o-spreadsheet-ChartPreview.LINE_CHART"}).add("stacked_line",{matcher:e=>"line"===e.type&&!e.fillArea&&!!e.stacked,displayName:fs("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=>"line"===e.type&&!e.stacked&&!!e.fillArea,displayName:fs("Area"),chartType:"line",chartSubtype:"area",subtypeDefinition:{stacked:!1,fillArea:!0},category:"area",preview:"o-spreadsheet-ChartPreview.AREA_CHART"}).add("stacked_area",{matcher:e=>"line"===e.type&&e.stacked&&!!e.fillArea,displayName:fs("Stacked Area"),chartType:"line",chartSubtype:"stacked_area",subtypeDefinition:{stacked:!0,fillArea:!0},category:"area",preview:"o-spreadsheet-ChartPreview.STACKED_AREA_CHART"}).add("scatter",{displayName:fs("Scatter"),chartType:"scatter",chartSubtype:"scatter",category:"misc",preview:"o-spreadsheet-ChartPreview.SCATTER_CHART"}).add("column",{matcher:e=>"bar"===e.type&&!e.stacked&&!e.horizontal,displayName:fs("Column"),chartType:"bar",chartSubtype:"column",subtypeDefinition:{stacked:!1,horizontal:!1},category:"column",preview:"o-spreadsheet-ChartPreview.COLUMN_CHART"}).add("stacked_column",{matcher:e=>"bar"===e.type&&e.stacked&&!e.horizontal,displayName:fs("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=>"bar"===e.type&&!e.stacked&&!!e.horizontal,displayName:fs("Bar"),chartType:"bar",chartSubtype:"bar",subtypeDefinition:{horizontal:!0,stacked:!1},category:"bar",preview:"o-spreadsheet-ChartPreview.BAR_CHART"}).add("stacked_bar",{matcher:e=>"bar"===e.type&&e.stacked&&!!e.horizontal,displayName:fs("Stacked Bar"),chartType:"bar",chartSubtype:"stacked_bar",subtypeDefinition:{horizontal:!0,stacked:!0},category:"bar",preview:"o-spreadsheet-ChartPreview.STACKED_BAR_CHART"}).add("combo",{displayName:fs("Combo"),chartSubtype:"combo",chartType:"combo",category:"line",preview:"o-spreadsheet-ChartPreview.COMBO_CHART"}).add("pie",{matcher:e=>"pie"===e.type&&!e.isDoughnut,displayName:fs("Pie"),chartSubtype:"pie",chartType:"pie",subtypeDefinition:{isDoughnut:!1},category:"pie",preview:"o-spreadsheet-ChartPreview.PIE_CHART"}).add("doughnut",{matcher:e=>"pie"===e.type&&!!e.isDoughnut,displayName:fs("Doughnut"),chartSubtype:"doughnut",chartType:"pie",subtypeDefinition:{isDoughnut:!0},category:"pie",preview:"o-spreadsheet-ChartPreview.DOUGHNUT_CHART"}).add("gauge",{displayName:fs("Gauge"),chartSubtype:"gauge",chartType:"gauge",category:"misc",preview:"o-spreadsheet-ChartPreview.GAUGE_CHART"}).add("scorecard",{displayName:fs("Scorecard"),chartSubtype:"scorecard",chartType:"scorecard",category:"misc",preview:"o-spreadsheet-ChartPreview.SCORECARD_CHART"}).add("waterfall",{displayName:fs("Waterfall"),chartSubtype:"waterfall",chartType:"waterfall",category:"misc",preview:"o-spreadsheet-ChartPreview.WATERFALL_CHART"}).add("pyramid",{displayName:fs("Population Pyramid"),chartSubtype:"pyramid",chartType:"pyramid",category:"misc",preview:"o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART"}).add("radar",{matcher:e=>"radar"===e.type&&!e.fillArea,displayName:fs("Radar"),chartSubtype:"radar",chartType:"radar",subtypeDefinition:{fillArea:!1},category:"misc",preview:"o-spreadsheet-ChartPreview.RADAR_CHART"}).add("filled_radar",{matcher:e=>"radar"===e.type&&!!e.fillArea,displayName:fs("Filled Radar"),chartType:"radar",chartSubtype:"filled_radar",subtypeDefinition:{fillArea:!0},category:"misc",preview:"o-spreadsheet-ChartPreview.FILLED_RADAR_CHART"}).add("geo",{displayName:fs("Geo Chart"),chartSubtype:"geo",chartType:"geo",category:"misc",preview:"o-spreadsheet-ChartPreview.GEO_CHART"}).add("funnel",{displayName:fs("Funnel"),chartSubtype:"funnel",chartType:"funnel",category:"misc",preview:"o-spreadsheet-ChartPreview.FUNNEL_CHART"}).add("sunburst",{matcher:e=>"sunburst"===e.type,displayName:fs("Sunburst"),chartSubtype:"sunburst",chartType:"sunburst",category:"hierarchical",preview:"o-spreadsheet-ChartPreview.SUNBURST_CHART"}).add("treemap",{matcher:e=>"treemap"===e.type,displayName:fs("Tree Map"),chartType:"treemap",chartSubtype:"treemap",category:"hierarchical",preview:"o-spreadsheet-ChartPreview.TREE_MAP_CHART"});class $B extends Nz{copy(e){}}T_.figureHandlers.add("chart",class extends $B{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);if("chart"!==s.tag)return;const o={...s},i=this.getters.getChartFromFigureId(e.figureId);if(!i)throw new Error(`No chart for the given id: ${e.figureId}`);const n=i.copyInSheetId(t);return{figureId:e.figureId,copiedFigure:o,copiedChart:n}}getPasteTarget(e,t,s,o){return{zones:[],figureId:(new lr).smallUuid(),sheetId:e}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=e.sheetId,{width:r,height:a}=t.copiedFigure,l=t.copiedChart.copyInSheetId(n),c=this.getters.getMaxAnchorOffset(n,a,r);let{left:h,top:d}=o[0];const u={x:0,y:0};h>c.col&&(h=c.col,u.x=c.offset.x),d>c.row&&(d=c.row,u.y=c.offset.y),this.dispatch("CREATE_CHART",{figureId:i,chartId:(new lr).smallUuid(),sheetId:n,definition:l.getDefinition(),col:h,row:d,offset:u,size:{height:a,width:r}}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}).add("image",class extends $B{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);const o={...s};if("image"!==s.tag)return;const i=ae(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:o,copiedImage:i,sheetId:t}}getPasteTarget(e,t,s,o){return{sheetId:e,zones:[],figureId:(new lr).smallUuid()}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=this.getters.getActiveSheetId(),{width:r,height:a}=t.copiedFigure,l=ae(t.copiedImage),c=this.getters.getMaxAnchorOffset(n,a,r);let{left:h,top:d}=o[0];const u={x:0,y:0};h>c.col&&(h=c.col,u.x=c.offset.x),d>c.row&&(d=c.row,u.y=c.offset.y),this.dispatch("CREATE_IMAGE",{figureId:i,sheetId:n,col:h,row:d,offset:u,size:{height:a,width:r},definition:l}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}).add("carousel",class extends $B{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);if("carousel"!==s.tag)return;const o={...s},i=this.getters.getCarousel(e.figureId),n={};for(const e of i.items)if("chart"===e.type){const s=this.getters.getChart(e.chartId);if(!s)throw new Error(`No chart for the given id: ${e.chartId}`);n[e.chartId]=s.copyInSheetId(t)}return{figureId:e.figureId,copiedFigure:o,copiedCarousel:i,copiedCharts:n,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:(new lr).smallUuid(),sheetId:e}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=e.sheetId,{width:r,height:a}=t.copiedFigure,l=this.getters.getMaxAnchorOffset(n,a,r);let{left:c,top:h}=o[0];const d={x:0,y:0};c>l.col&&(c=l.col,d.x=l.offset.x),h>l.row&&(h=l.row,d.y=l.offset.y),this.dispatch("CREATE_CAROUSEL",{figureId:i,sheetId:n,definition:{items:[]},col:c,row:h,offset:d,size:{height:a,width:r}});const u=new lr,g=ae(t.copiedCarousel.items);for(const e of g){if("chart"!==e.type)continue;const s=t.copiedCharts[e.chartId],o=u.smallUuid(),r=s.copyInSheetId(n).getDefinition();this.dispatch("CREATE_CHART",{figureId:i,chartId:o,sheetId:n,definition:r}),e.chartId=o}this.dispatch("UPDATE_CAROUSEL",{sheetId:n,figureId:i,definition:{...t.copiedCarousel,items:g}}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}),T_.cellHandlers.add("dataValidation",class extends Lz{uuidGenerator=new lr;queuedChanges={};copy(e){const{rowsIndexes:t,columnsIndexes:s}=e,o=e.sheetId,i=[];for(const e of t){const t=[];for(const i of s){const s={sheetId:o,col:i,row:e},n=this.getters.getValidationRuleForCell(s);t.push({position:s,rule:n})}i.push(t)}return{dvRules:i}}paste(e,t,s){if(this.queuedChanges={},s.pasteOption)return;const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t):this.pasteFromCopy(i,o,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,s){const o=t[0];this.pasteZone(e,o.left,o.top,s.dvRules,{isCutOperation:!0})}pasteZone(e,t,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){const r={col:t+o,row:s+n,sheetId:e};this.pasteDataValidation(a,r,i?.isCutOperation)}}pasteDataValidation(e,t,s){if(e){const o=Zt(t),i=Zt(e.position),n=e.rule;if(!n){const e=this.getters.getValidationRuleForCell(t);return void(e&&this.adaptDataValidationRule(t.sheetId,e,[],[o]))}const r=[];if(s&&r.push(i),e.position.sheetId===t.sheetId){const s=this.getDataValidationRuleToCopyTo(t.sheetId,n,!1);this.adaptDataValidationRule(e.position.sheetId,s,[o],r)}else{const s=this.getters.getValidationRuleForCell(e.position);s&&this.adaptDataValidationRule(e.position.sheetId,s,[],r);const i=this.getDataValidationRuleToCopyTo(t.sheetId,n);this.adaptDataValidationRule(t.sheetId,i,[o],[])}}}getDataValidationRuleToCopyTo(e,t,s=!0){let o=this.getters.getDataValidationRules(e).find(e=>Me(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking);const i=this.queuedChanges[e];return!o&&i&&(o=i.find(e=>Me(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),o||{...t,id:s?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,s,o){this.queuedChanges[e]||(this.queuedChanges[e]=[]);const i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...s),i.toRemove.push(...o)):this.queuedChanges[e].push({toAdd:s,toRemove:o,rule:t})}executeQueuedChanges(){for(const e in this.queuedChanges)for(const{toAdd:t,toRemove:s,rule:o}of this.queuedChanges[e]){const i=o.ranges.map(e=>e.zone),n=ft(i,s),r=ft([...n,...t],[]);0!==r.length?this.dispatch("ADD_DATA_VALIDATION_RULE",{rule:{id:o.id,criterion:o.criterion,isBlocking:o.isBlocking},ranges:r.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e}):this.dispatch("REMOVE_DATA_VALIDATION_RULE",{sheetId:e,id:o.id})}}}).add("cell",kz).add("sheet",class extends Lz{isPasteAllowed(e,t,s,o){if(!("cells"in s))return"Success";const{xSplit:i,ySplit:n}=this.getters.getPaneDivisions(e);return Jt(I_(t,s.cells),i,n)?"FrozenPaneOverlap":"Success"}}).add("merge",class extends Lz{copy(e){const t=this.getters.getActiveSheetId(),{rowsIndexes:s,columnsIndexes:o}=e,i=[];for(const e of s){const s=[];for(const i of o){const o={col:i,row:e,sheetId:t};s.push(this.getters.getMerge(o))}i.push(s)}return{merges:i,sheetId:t}}paste(e,t,s){if(s.isCutOperation){const e=t.merges.flat().filter(Te);this.dispatch("REMOVE_MERGE",{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,s)}pasteZone(e,t,s,o){for(const[i,n]of o.entries())for(const[o,r]of n.entries()){const n={col:t+o,row:s+i,sheetId:e};this.pasteMerge(r,n)}}pasteMerge(e,t){if(!e)return;if(this.getters.isInMerge(t))return;const{sheetId:s,col:o,row:i}=t;this.dispatch("ADD_MERGE",{sheetId:s,force:!0,target:[{left:o,top:i,right:o+e.right-e.left,bottom:i+e.bottom-e.top}]})}}).add("table",class extends Lz{copy(e,t,s="copyPaste"){const o=e.sheetId,{rowsIndexes:i,columnsIndexes:n,zones:r}=e,a=new Set,l=[];for(const e of i){const c=[];l.push(c);for(const l of n){const n={col:l,row:e,sheetId:o},h=this.getters.getTable(n);if(!h){c.push({});continue}const d=this.getters.getCoreTable(n),u=d?.range.zone;let g;if(!a.has(h.id)&&d&&u&&r.some(e=>Vt(u,e))){a.add(h.id);let{numberOfRows:e}=Ut(u);for(let s=u.top;s<=u.bottom;s++)t||i.includes(s)||e--;const s=d.range,o=this.getters.extendRange(d.range,"ROW",s.zone.top+e-1-s.zone.bottom);g={range:this.getters.getRangeData(o),config:d.config,type:d.type}}"shiftCells"!==s&&c.push({table:g,style:this.getTableStyleToCopy(n),isWholeTableCopied:a.has(h.id)})}}return{tableCells:l,sheetId:e.sheetId}}getTableStyleToCopy(e){const t=this.getters.getCellTableStyle(e),s=this.getters.getCellStyle(e),o=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Ve(s)},border:{...o,...Ve(i)}}}paste(e,t,s){const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t,s):this.pasteFromCopy(i,o,t.tableCells,s)}pasteFromCut(e,t,s,o){for(const e of s.tableCells)for(const t of e)t.table&&this.dispatch("REMOVE_TABLE",{sheetId:s.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});const i=t[0];this.pasteZone(e,i.left,i.top,s.tableCells,o)}pasteZone(e,t,s,o,i){for(let n=0;n<o.length;n++){const r=o[n];for(let o=0;o<r.length;o++){const a=r[o];if(!a)continue;const l={col:t+o,row:s+n,sheetId:e};this.pasteTableCell(e,a,l,i)}}if(1===o.length)for(let i=0;i<o[0].length;i++)this.dispatch("AUTOFILL_TABLE_COLUMN",{col:t+i,row:s,sheetId:e})}pasteTableCell(e,t,s,o){if(t.table&&!o?.pasteOption){const{range:o}=t.table,i=Ut(this.getters.getRangeFromRangeData(o).zone),n={left:s.col,top:s.row,right:s.col+i.numberOfCols-1,bottom:s.row+i.numberOfRows-1};this.dispatch("CREATE_TABLE",{sheetId:s.sheetId,ranges:[this.getters.getRangeDataFromZone(e,n)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(s)||"asValue"===o?.pasteOption||(o?.pasteOption||t.isWholeTableCopied)&&"onlyFormat"!==o?.pasteOption||(t.style?.style&&this.dispatch("UPDATE_CELL",{...s,style:t.style.style}),t.style?.border&&this.dispatch("SET_BORDER",{...s,border:t.style.border}))}}).add("conditionalFormat",class extends Lz{uuidGenerator=new lr;queuedChanges={};copy(e){if(!e.zones.length)return;const{rowsIndexes:t,columnsIndexes:s}=e,o=e.sheetId,i=[];for(const e of t){const t=[];for(const i of s){const s=Array.from(this.getters.getRulesByCell(o,i,e));t.push({position:{col:i,row:e,sheetId:o},rules:s})}i.push(t)}return{cfRules:i}}paste(e,t,s){if(this.queuedChanges={},"asValue"===s.pasteOption)return;const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t):this.pasteFromCopy(i,o,t.cfRules,s),this.executeQueuedChanges()}pasteFromCut(e,t,s){const o=t[0];this.pasteZone(e,o.left,o.top,s.cfRules,{isCutOperation:!0})}pasteZone(e,t,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){const r={col:t+o,row:s+n,sheetId:e};this.pasteCf(a,r,i?.isCutOperation)}}pasteCf(e,t,s){if(e?.rules&&e.rules.length>0){const o=Zt(e.position),i=Zt(t);for(const n of e.rules){const r=[];if(s&&r.push(o),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,n,[i],r);else{this.adaptCFRules(e.position.sheetId,n,[],r);const s=this.getCFToCopyTo(t.sheetId,n);this.adaptCFRules(t.sheetId,s,[i],[])}}}}adaptCFRules(e,t,s,o){this.queuedChanges[e]||(this.queuedChanges[e]=[]);const i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...s),i.toRemove.push(...o)):this.queuedChanges[e].push({toAdd:s,toRemove:o,cf:t})}executeQueuedChanges(){for(const e in this.queuedChanges)for(const{toAdd:t,toRemove:s,cf:o}of this.queuedChanges[e]){const i=this.getters.getAdaptedCfRanges(e,o,t,s);i&&(0!==i.length?this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:o.id,rule:o.rule,stopIfTrue:o.stopIfTrue},ranges:i,sheetId:e}):this.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:o.id,sheetId:e}))}}getCFToCopyTo(e,t){let s=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&Me(e.rule,t.rule));const o=this.queuedChanges[e];return!s&&o&&(s=o.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&Me(e.cf.rule,t.rule))?.cf),s||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}}).add("references",class extends Lz{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,s){if(s.isCutOperation){const s=e.zones[0];this.dispatch("MOVE_RANGES",{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:s.left,row:s.top})}}}).add("border",class extends Lz{copy(e){const t=e.sheetId;if(0===e.zones.length)return;const s=[];let o=0;for(const i of EC(e.columnsIndexes)){let n=0;for(const r of EC(e.rowsIndexes)){const e={left:i[0],right:i[i.length-1],top:r[0],bottom:r[r.length-1]};s.push(...this.getters.getBorders(t,e).map(({zone:t,style:s})=>({zone:{left:t.left-e.left+o,right:t.right&&t.right-e.left+o,top:t.top-e.top+n,bottom:t.bottom&&t.bottom-e.top+n},style:s}))),n+=r.length}o+=i.length}return{borders:s,width:e.columnsIndexes.length,height:e.rowsIndexes.length}}paste(e,t,s){const o=e.sheetId;if("asValue"===s.pasteOption)return;const i=e.zones;if(s.isCutOperation){const{left:e,top:s}=i[0];this.pasteBorderZone(o,e,s,t.borders)}else for(const e of i)for(const s of y_(e,t.width,t.height))this.pasteBorderZone(o,s.left,s.top,t.borders)}pasteBorderZone(e,t,s,o){for(const i of o){const o={left:i.zone.left+t,right:i.zone.right&&i.zone.right+t||i.zone.left+t,top:i.zone.top+s,bottom:i.zone.bottom&&i.zone.bottom+s||i.zone.top+s};for(const[t,s]of this.getOptimalBorderCommands(i.style))s&&this.dispatch("SET_ZONE_BORDERS",{sheetId:e,target:[o],border:{position:t,...s}})}}getOptimalBorderCommands(e){const t=xC(e.horizontal,e.vertical),s=xC(e.left,e.right,e.top,e.bottom);return t&&s&&xC(e.horizontal,e.left)?[["all",e.top]]:t&&s?[["hv",e.horizontal],["external",e.top]]:s?[["h",e.horizontal],["v",e.vertical],["external",e.top]]:t?[["hv",e.horizontal],["top",e.top],["bottom",e.bottom],["left",e.left],["right",e.right]]:[["h",e.horizontal],["v",e.vertical],["top",e.top],["bottom",e.bottom],["left",e.left],["right",e.right]]}});const qB={},ZB={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:A,HEADER_WIDTH:D,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:_,SCROLLBAR_WIDTH:O},jB={autoCompleteProviders:$P,autofillModifiersRegistry:e_,autofillRulesRegistry:t_,cellMenuRegistry:vk,colMenuRegistry:DV,errorTypes:Ss,linkMenuRegistry:VM,functionRegistry:uf,featurePluginRegistry:F_,iconsOnCellRegistry:vD,statefulUIPluginRegistry:P_,coreViewsPluginRegistry:M_,corePluginRegistry:O_,rowMenuRegistry:NV,sidePanelRegistry:yz,figureRegistry:VF,chartSidePanelComponentRegistry:IH,chartComponentRegistry:wF,chartRegistry:$y,chartSubtypeRegistry:f_,topbarMenuRegistry:$z,topbarComponentRegistry:sB,clickableCellRegistry:Hz,otRegistry:aE,inverseCommandRegistry:GE,urlRegistry:Uf,cellPopoverRegistry:IP,numberFormatMenuRegistry:Bz,repeatLocalCommandTransformRegistry:g_,repeatCommandTransformRegistry:u_,clipboardHandlersRegistries:T_,pivotRegistry:XD,pivotTimeAdapterRegistry:Fg,pivotSidePanelRegistry:az,pivotNormalizationValueRegistry:cp,supportedPivotPositionalFormulaRegistry:Oz,pivotToFunctionValueRegistry:hp,migrationStepRegistry:LT,chartJsExtensionRegistry:sS},YB={arg:as,isEvaluationError:mo,toBoolean:To,toJsDate:Ao,toNumber:bo,toString:Eo,toNormalizedPivotValue:np,toFunctionPivotValue:ap,toXC:mt,toZone:wt,toUnboundedZone:It,toCartesian:pt,numberToLetters:it,lettersToNumber:nt,UuidGenerator:lr,formatValue:pn,createCurrencyFormat:Dn,ColorGenerator:Gv,computeTextWidth:zb,createEmptyWorkbookData:ZT,createEmptySheet:qT,createEmptyExcelSheet:jT,rgbaToHex:wv,colorToRGBA:Ev,positionToZone:Zt,isDefined:Te,isMatrix:Ds,lazy:Oe,genericRepeat:tB,createAction:jf,createActions:qf,transformRangeData:os,deepEquals:Me,overlap:Lt,union:Ft,isInside:kt,deepCopy:ae,expandZoneOnInsertion:At,reduceZoneOnDeletion:Ot,unquote:ce,getMaxObjectId:Kg,getFunctionsFromTokens:kf,getFirstPivotFunction:MD,getNumberOfPivotFunctions:ND,parseDimension:ep,isDateOrDatetimeField:tp,makeFieldProposal:Dz,insertTokenAfterArgSeparator:function(e,t){let s=e.end;const o=e.end;"ARG_SEPARATOR"!==e.type&&(s=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)},insertTokenAfterLeftParenthesis:function(e,t){let s=e.end;const o=e.end;"LEFT_PAREN"!==e.type&&(s=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)},mergeContiguousZones:es,getPivotHighlights:ZH,pivotTimeAdapter:Pg,UNDO_REDO_PIVOT_COMMANDS:JD,createPivotFormula:ip,areDomainArgsFieldsValid:op,splitReference:tr,sanitizeSheetName:de,getUniqueText:st,isNumber:lo,isDateTime:$s,createCustomFields:fp},XB={isMarkdownLink:Se,parseMarkdownLink:Ie,markdownLink:ye,openLink:Wf,urlRepresentation:Gf},KB={Checkbox:IM,Section:aM,RoundColorPicker:lM,ChartDataSeries:MU,ChartErrorSection:NU,ChartLabelRange:LU,ChartTitle:HU,ChartPanel:xH,ChartFigure:LF,ChartJsComponent:iy,ClickableCellSortIcon:Fz,ZoomableChartJsComponent:mF,Grid:Az,GridOverlay:rU,ScorecardChart:Cy,GaugeChartComponent:yF,LineConfigPanel:aH,BarConfigPanel:VU,PieChartDesignPanel:hH,GenericChartConfigPanel:kU,ChartWithAxisDesignPanel:YU,GenericZoomableChartDesignPanel:KU,LineChartDesignPanel:lH,GaugeChartConfigPanel:eH,GaugeChartDesignPanel:tH,ScorecardChartConfigPanel:gH,ScorecardChartDesignPanel:pH,GeoChartDesignPanel:nH,RadarChartDesignPanel:dH,WaterfallChartDesignPanel:yH,ComboChartDesignPanel:JU,FunnelChartDesignPanel:QU,SunburstChartDesignPanel:mH,TreeMapChartDesignPanel:CH,ChartTypePicker:EH,FigureComponent:UF,MenuPopover:PF,Popover:DF,SelectionInput:fM,ValidationMessages:JV,AddDimensionButton:KH,PivotDimensionGranularity:QH,PivotDimensionOrder:ez,PivotDimension:JH,PivotLayoutConfigurator:oz,PivotHTMLRenderer:Mz,PivotDeferUpdate:jH,PivotTitleSection:iz,CogWheelMenu:FU,TextInput:TU,SidePanelCollapsible:DP,RadioSelection:BU,GeoChartRegionSelectSection:sH,ChartDashboardMenu:MF,FullScreenFigure:Pz},JB={useDragAndDropListItems:cM,useHighlights:DH,useHighlightsOnHover:AH},QB={useStoreProvider:Qf,DependencyContainer:Xf,CellPopoverStore:wP,ComposerFocusStore:uv,CellComposerStore:WV,FindAndReplaceStore:zH,HighlightStore:ZP,DelayedHoveredCellStore:HF,HoveredTableStore:oU,ModelStore:nv,NotificationStore:jP,RendererStore:cv,SelectionInputStore:mM,SpreadsheetStore:hv,useStore:ev,useLocalStore:tv,SidePanelStore:Rz,PivotSidePanelStore:nz,PivotMeasureDisplayPanelStore:$H,ClientFocusStore:kV,GridRenderer:pU};const eG={DEFAULT_LOCALE:Oc,HIGHLIGHT_COLOR:o,PIVOT_TABLE_CONFIG:J,ChartTerms:Ig,FIGURE_ID_SPLITTER:z,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2},tG={...iF,...$w};e.AbstractCellClipboardHandler=Lz,e.AbstractChart=ny,e.AbstractFigureClipboardHandler=$B,e.CellErrorType=bs,e.ClientDisconnectedError=zE,e.CorePlugin=XT,e.CoreViewPlugin=MA,e.DEFAULT_LOCALE=Oc,e.DEFAULT_LOCALES=_c,e.DispatchResult=br,e.EvaluationError=Cs,e.LocalTransportService=nE,e.Model=class extends Yf{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},s=[],o=new lr,i=!1){const n=performance.now();console.debug("##### Model creation #####"),super(),gs===ds&&ps===us&&(ps=()=>!0),s=WT(e,s);const r=zT(e,i);this.state=new V_,this.uuidGenerator=o,this.config=this.setupConfig(t),this.session=this.setupSession(r.revisionId),this.coreGetters={},this.range=new N_(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.adaptFormulaStringDependencies=this.range.adaptFormulaStringDependencies.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.getters={isReadonly:()=>"readonly"===this.config.mode||"dashboard"===this.config.mode,isDashboard:()=>"dashboard"===this.config.mode},this.selection=new k_(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(const e of O_.getAll())this.setupCorePlugin(e,r);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(s);for(const e of M_.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(const e of P_.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(const e of F_.getAll()){const t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.joinSession(),t.snapshotRequested||e["[Content_Types].xml"]&&!this.getters.isReadonly()){const e=performance.now();console.debug("Snapshot requested"),this.session.snapshot(this.exportData()),this.garbageCollectExternalResources(),console.debug("Snapshot taken in",performance.now()-e,"ms")}console.debug("Model created in",performance.now()-n,"ms"),console.debug("######")}joinSession(){this.session.join(this.config.client)}async leaveSession(){const e=this.getters.isReadonly()?void 0:Oe(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(const s of e.getters){if(!(s in t))throw new Error(`Invalid getter name: ${s} for plugin ${t.constructor}`);if(s in this.getters)throw new Error(`Getter "${s}" is already defined.`);this.getters[s]=t[s].bind(t)}for(const s of e.layers)this.renderers[s]||(this.renderers[s]=[]),this.renderers[s].push(t);return t}setupCoreViewPlugin(e){const t=new e(this.coreViewPluginConfig);for(const s of e.getters){if(!(s in t))throw new Error(`Invalid getter name: ${s} for plugin ${t.constructor}`);if(s in this.getters)throw new Error(`Getter "${s}" is already defined.`);this.getters[s]=t[s].bind(t)}return t}setupCorePlugin(e,t){const s=new e(this.corePluginConfig);for(const t of e.getters){if(!(t in s))throw new Error(`Invalid getter name: ${t} for plugin ${s.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=s[t].bind(s)}s.import(t),this.corePlugins.push(s),this.coreHandlers.push(s),this.handlers.push(s)}onRemoteRevisionReceived({commands:e}){for(const t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new BE(JE({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{this.checkDispatchAllowed(e).isSuccessful?(this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1):this.dispatchToHandlers(this.coreHandlers,{type:"UNDO",commands:[e]})}}),this.config.transportService,e)}setupSessionEvents(){this.session.on("remote-revision-received",this,this.onRemoteRevisionReceived),this.session.on("revision-undone",this,({commands:e})=>{this.dispatchFromCorePlugin("UNDO",{commands:e}),this.finalize()}),this.session.on("revision-redone",this,({commands:e})=>{this.dispatchFromCorePlugin("REDO",{commands:e}),this.finalize()}),this.session.on("unexpected-revision-id",this,()=>this.trigger("unexpected-revision-id")),this.session.on("collaborative-event-received",this,()=>{this.trigger("update")})}setupConfig(e){const t=e.client||{id:this.uuidGenerator.smallUuid(),name:fs("Anonymous").toString()},s=e.transportService||new nE,o="readonly"===e.mode||"dashboard"===e.mode;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:o?new rE(s):s,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),raiseBlockingErrorUI:e=>this.trigger("raise-error-ui",{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){const t=e.loadLocales||(()=>Promise.resolve(_c));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,custom:this.config.custom,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){const t=vr(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>"Success"!==e)?new br(t.flat()):br.Success}checkDispatchAllowedCoreCommand(e){const t=this.corePlugins.map(t=>t.allowDispatch(e));return t.push(this.range.allowDispatch(e)),t}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0,this.trigger("command-finalized")}canDispatch=(e,t)=>this.checkDispatchAllowed(BO(e,t));dispatch=(e,t)=>{const s=BO(e,t),o=this.status;if(this.getters.isReadonly()&&(i=s,!mr.has(i.type)))return new br("Readonly");var i;if(!this.session.canApplyOptimisticUpdate())return new br("WaitingSessionConfirmation");switch(o){case 0:const t=this.checkDispatchAllowed(s);if(!t.isSuccessful)return this.trigger("update"),t;this.status=1;const{changes:o,commands:i}=this.state.recordChanges(()=>{const t=performance.now();vr(s)&&this.state.addCommand(s),this.dispatchToHandlers(this.handlers,s),this.finalize();const o=performance.now()-t;o>5&&console.debug(e,o,"ms")});this.session.save(s,i,o),this.status=0,this.trigger("update");break;case 1:if(vr(s)){const e=this.checkDispatchAllowed(s);if(!e.isSuccessful)return e;this.state.addCommand(s)}this.dispatchToHandlers(this.handlers,s);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(vr(s))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,s)}return br.Success};dispatchFromCorePlugin=(e,t)=>{const s=BO(e,t),o=this.status;this.status=2;const i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,s),this.status=o,br.Success};dispatchToHandlers(e,t){const s=vr(t);for(const o of e)!s&&o instanceof XT||o.beforeHandle(t);for(const o of e)!s&&o instanceof XT||o.handle(t);this.trigger("command-dispatched",t)}drawLayer(e,t){const s=this.renderers[t];if(s)for(const o of s)e.ctx.save(),o.drawLayer(e,t),e.ctx.restore()}exportData(){let e=ZT();for(const t of this.handlers)t instanceof XT&&t.export(e);return e.revisionId=this.session.getRevisionId()||H,e=ae(e),e}updateMode(e){this.config.mode=e,this.trigger("update")}async exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={...ZT(),sheets:[jT(HT,"Sheet1")]};for(const t of this.handlers)t instanceof yr&&await t.exportForExcel(e);return e=ae(e),UO(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.PivotRuntimeDefinition=VD,e.Registry=Og,e.Revision=HE,e.SPREADSHEET_DIMENSIONS=ZB,e.Spreadsheet=kB,e.SpreadsheetPivotTable=yA,e.UIPlugin=Ir,e.__info__=qB,e.addFunction=function e(t,s){return uf.add(t,s),{addFunction:(t,s)=>e(t,s)}},e.addRenderingLayer=function(e,t){if(av[e])throw new Error(`Layer ${e} already exists`);av[e]=t},e.astToFormula=_D,e.categories=gf,e.chartHelpers=tG,e.compile=sE,e.compileTokens=oE,e.components=KB,e.constants=eG,e.convertAstNodes=Of,e.coreTypes=fr,e.createAutocompleteArgumentsProvider=Vz,e.findCellInNewZone=qt,e.functionCache=tE,e.getCaretDownSvg=oR,e.getCaretUpSvg=iR,e.helpers=YB,e.hooks=JB,e.invalidateCFEvaluationCommands=ur,e.invalidateChartEvaluationCommands=hr,e.invalidateDependenciesCommands=dr,e.invalidateEvaluationCommands=cr,e.iterateAstNodes=Ff,e.links=XB,e.load=zT,e.parse=Df,e.parseTokens=_f,e.readonlyAllowedCommands=mr,e.registries=jB,e.setDefaultSheetViewSize=function(e){j=e},e.setTranslationMethod=function(e,t=()=>!0){gs=e,ps=t},e.stores=QB,e.tokenColors=ie,e.tokenize=Mc,qB.version="19.1.0-alpha.6",qB.date="2025-10-16T14:35:52.911Z",qB.hash="8ab685e"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|
|
843
|
+
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){const{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{y:e}=this.env.model.getters.getMainViewportRect();return{top:`${this.props.topOffset+e}px`,right:"0px",width:"15px",bottom:By()?"15px":"0"}}onScroll(e){const{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:t,offsetY:e})}}class RU extends t.Component{static template="o-spreadsheet-Selection";static props={};static components={Highlight:CU};get highlightProps(){const 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:l}}}function xU({refName:e}){const s=t.useRef(e);t.useEffect(e=>{e?.focus()},()=>[s.el])}class TU extends t.Component{static template="o-spreadsheet-TextInput";static props={value:String,onChange:Function,class:{type:String,optional:!0},id:{type:String,optional:!0},placeholder:{type:String,optional:!0},autofocus:{type:Boolean,optional:!0},alwaysShowBorder:{type:Boolean,optional:!0}};inputRef=t.useRef("input");setup(){t.useExternalListener(window,"click",e=>{e.target!==this.inputRef.el&&this.inputRef.el?.value!==this.props.value&&this.save()},{capture:!0}),this.props.autofocus&&xU({refName:"input"})}onKeyDown(e){switch(e.key){case"Enter":this.save(),e.preventDefault(),e.stopPropagation();break;case"Escape":this.inputRef.el&&(this.inputRef.el.value=this.props.value,this.inputRef.el.blur()),e.preventDefault(),e.stopPropagation()}}save(){const e=(this.inputRef.el?.value||"").trim();e!==this.props.value&&this.props.onChange(e),this.inputRef.el?.blur()}onMouseDown(e){e.target!==document.activeElement&&(e.preventDefault(),e.stopPropagation())}onMouseUp(e){const t=e.target;t!==document.activeElement&&(t.focus(),t.select(),e.preventDefault(),e.stopPropagation())}get inputClass(){return[this.props.class,this.props.alwaysShowBorder?"o-input-border":void 0].filter(Te).join(" ")}}class AU extends t.Component{static template="o-spreadsheet-ActionButton";static props={action:Object,hasTriangleDownIcon:{type:Boolean,optional:!0},selectedColor:{type:String,optional:!0},class:{type:String,optional:!0},onClick:{type:Function,optional:!0}};actionButton=jf(this.props.action);setup(){t.onWillUpdateProps(e=>{e.action!==this.props.action&&(this.actionButton=jf(e.action))})}get isVisible(){return this.actionButton.isVisible(this.env)}get isEnabled(){return this.actionButton.isEnabled(this.env)}get isActive(){return this.actionButton.isActive?.(this.env)}get title(){const e=this.actionButton.name(this.env),t=this.actionButton.description(this.env);return e+(t?` (${t})`:"")}get iconTitle(){return this.actionButton.icon(this.env)}onClick(e){this.isEnabled&&(this.props.onClick?.(e),this.actionButton.execute?.(this.env))}get buttonStyle(){return this.props.selectedColor?Ey({"border-bottom":`4px solid ${this.props.selectedColor}`,height:"16px","margin-top":"2px"}):""}}class DU extends t.Component{static template="o-spreadsheet-ColorPickerWidget";static props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={ColorPicker:rM};colorPickerButtonRef=t.useRef("colorPickerButton");get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:"border-bottom-style: hidden"}get colorPickerAnchorRect(){const e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}}class _U extends t.Component{static template="o-spreadsheet-FontSizeEditor";static props={currentFontSize:Number,onFontSizeChanged:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String};static defaultProps={onFocusInput:()=>{}};static components={Popover:DF};fontSizes=K;dropdown=t.useState({isOpen:!1});inputRef=t.useRef("inputFontSize");rootEditorRef=t.useRef("FontSizeEditor");fontSizeListRef=t.useRef("fontSizeList");setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}get popoverProps(){const{x:e,y:t,width:s,height:o}=this.rootEditorRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:s,height:o},positioning:"bottom-left",verticalOffset:0}}onExternalClick(e){Dy(this.fontSizeListRef.el,e)||Dy(this.rootEditorRef.el,e)||this.closeFontList()}toggleFontList(){this.dropdown.isOpen?this.closeFontList():(this.props.onToggle?.(),this.inputRef.el.focus())}closeFontList(){this.dropdown.isOpen=!1}setSize(e){const t=ue(Math.floor(parseFloat(e)),1,400);this.props.onFontSizeChanged(t),this.closeFontList()}setSizeFromInput(e){this.setSize(e.target.value)}setSizeFromList(e){this.setSize(e)}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if("Enter"===e.key||"Escape"===e.key){this.closeFontList();const t=e.target;"Escape"===e.key&&(t.value=`${this.props.currentFontSize}`),this.props.onToggle?.()}}}class OU extends t.Component{static template="o-spreadsheet.TextStyler";static components={ColorPickerWidget:DU,ActionButton:AU,FontSizeEditor:_U};static props={style:Object,updateStyle:{type:Function,optional:!0},defaultStyle:{type:Object,optional:!0},hasVerticalAlign:{type:Boolean,optional:!0},hasHorizontalAlign:{type:Boolean,optional:!0},hasBackgroundColor:{type:Boolean,optional:!0},class:{type:String,optional:!0}};openedEl=null;setup(){t.useExternalListener(window,"click",this.onExternalClick)}state=t.useState({activeTool:""});updateFontSize(e){this.props.updateStyle?.({...this.props.style,fontSize:e})}toggleDropdownTool(e,t){const s=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=s?"":e,this.openedEl=s?null:t.target}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onTextColorChange(e){this.props.updateStyle?.({...this.props.style,color:e}),this.closeMenus()}onFillColorChange(e){this.props.updateStyle?.({...this.props.style,fillColor:e}),this.closeMenus()}updateAlignment(e){this.props.updateStyle?.({...this.props.style,align:e}),this.closeMenus()}updateVerticalAlignment(e){this.props.updateStyle?.({...this.props.style,verticalAlign:e}),this.closeMenus()}toggleBold(){this.props.updateStyle?.({...this.props.style,bold:!this.bold})}toggleItalic(){this.props.updateStyle?.({...this.props.style,italic:!this.italic})}closeMenus(){this.state.activeTool="",this.openedEl=null}get align(){return this.props.style.align??this.props.defaultStyle?.align}get verticalAlign(){return this.props.style.verticalAlign||this.props.defaultStyle?.verticalAlign}get bold(){return this.props.style.bold??this.props.defaultStyle?.bold}get italic(){return this.props.style.italic??this.props.defaultStyle?.italic}get currentFontSize(){return this.props.style.fontSize??this.props.defaultStyle?.fontSize??P.fontSize}get boldButtonAction(){return{name:fs("Bold"),execute:()=>this.toggleBold(),isActive:()=>this.bold||!1,icon:"o-spreadsheet-Icon.BOLD"}}get italicButtonAction(){return{name:fs("Italic"),execute:()=>this.toggleItalic(),isActive:()=>this.italic||!1,icon:"o-spreadsheet-Icon.ITALIC"}}get horizontalAlignButtonAction(){let e="o-spreadsheet-Icon.ALIGN_LEFT";return"center"===this.align?e="o-spreadsheet-Icon.ALIGN_CENTER":"right"===this.align&&(e="o-spreadsheet-Icon.ALIGN_RIGHT"),{name:fs("Horizontal alignment"),icon:e}}get horizontalAlignActions(){return[{name:fs("Left"),execute:()=>this.updateAlignment("left"),isActive:()=>"left"===this.align,icon:"o-spreadsheet-Icon.ALIGN_LEFT"},{name:fs("Center"),execute:()=>this.updateAlignment("center"),isActive:()=>"center"===this.align,icon:"o-spreadsheet-Icon.ALIGN_CENTER"},{name:fs("Right"),execute:()=>this.updateAlignment("right"),isActive:()=>"right"===this.align,icon:"o-spreadsheet-Icon.ALIGN_RIGHT"}]}get verticalAlignButtonAction(){let e="o-spreadsheet-Icon.ALIGN_MIDDLE";return"top"===this.verticalAlign?e="o-spreadsheet-Icon.ALIGN_TOP":"bottom"===this.verticalAlign&&(e="o-spreadsheet-Icon.ALIGN_BOTTOM"),{name:fs("Vertical alignment"),icon:e}}get verticalAlignActions(){return[{name:fs("Top"),execute:()=>this.updateVerticalAlignment("top"),isActive:()=>"top"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_TOP"},{name:fs("Middle"),execute:()=>this.updateVerticalAlignment("middle"),isActive:()=>"middle"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},{name:fs("Bottom"),execute:()=>this.updateVerticalAlignment("bottom"),isActive:()=>"bottom"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"}]}}class FU extends t.Component{static template="o-spreadsheet-CogWheelMenu";static components={MenuPopover:PF};static props={items:Array};buttonRef=t.useRef("button");menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});menuId=this.env.model.uuidGenerator.uuidv4();toggleMenu(e){e.closedMenuId!==this.menuId&&(this.menuState.isOpen=!this.menuState.isOpen,this.menuState.anchorRect=Fy(this.buttonRef.el),this.menuState.menuItems=qf(this.props.items))}}class PU extends t.Component{static template="o-spreadsheet-CarouselPanel";static props={onCloseSidePanel:Function,figureId:String};static components={Section:aM,TextInput:TU,TextStyler:OU,CogWheelMenu:FU};DEFAULT_CAROUSEL_TITLE_STYLE=te;dragAndDrop=cM();previewListRef=t.useRef("previewList");setup(){let e=[...this.carouselItems];t.onWillUpdateProps(()=>{Me(this.carouselItems,e)||this.dragAndDrop.cancel(),e=[...this.carouselItems]})}get carouselItems(){return this.env.model.getters.getCarousel(this.props.figureId).items}get title(){return this.env.model.getters.getCarousel(this.props.figureId).title}get carousel(){return this.env.model.getters.getCarousel(this.props.figureId)}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[this.getItemId(e)]||""}getItemId(e){return"chart"===e.type?e.chartId:"transparent-carousel"}addNewChartToCarousel(){this.env.model.dispatch("ADD_NEW_CHART_TO_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId})}get hasDataView(){return this.carouselItems.some(e=>"carouselDataView"===e.type)}isCarouselItemActive(e){return Me(this.env.model.getters.getSelectedCarouselItem(this.props.figureId),e)}addDataViewToCarousel(){const e=this.env.model.getters.getCarousel(this.props.figureId);this.updateItems([...e.items,{type:"carouselDataView"}])}activateCarouselItem(e){this.env.model.dispatch("UPDATE_CAROUSEL_ACTIVE_ITEM",{figureId:this.props.figureId,sheetId:this.carouselSheetId,item:e})}editCarouselItem(e){"chart"===e.type&&(this.activateCarouselItem(e),this.env.model.dispatch("SELECT_FIGURE",{figureId:this.props.figureId}),this.env.openSidePanel("ChartPanel",{chartId:e.chartId}))}renameCarouselItem(e,t){const s=t.trim();if(!s||s===this.getItemTitle(e).toString())return;const o=[...this.carouselItems],i=this.carouselItems.findIndex(t=>Me(t,e));-1!==i&&(o[i]={...e,title:s},this.updateItems(o))}deleteCarouselItem(e){const t=this.env.model.getters.getCarousel(this.props.figureId).items.filter(t=>!Me(t,e));this.updateItems(t)}popOutCarouselItem(e){"chart"===e.type&&this.env.model.dispatch("POPOUT_CHART_FROM_CAROUSEL",{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId})}onDragHandleMouseDown(e,t){if(0!==t.button)return;const s=Array.from(this.previewListRef.el.children).map(e=>Fy(e)),o=this.carouselItems.map((e,t)=>({id:this.getItemId(e),size:s[t].height,position:s[t].y}));this.dragAndDrop.start("vertical",{draggedItemId:this.getItemId(e),initialMousePosition:t.clientY,items:o,scrollableContainerEl:this.previewListRef.el,onDragEnd:(t,s)=>this.onDragEnd(e,s)})}onDragEnd(e,t){const s=this.carouselItems.findIndex(t=>Me(t,e));if(-1===s||s===t)return;const o=[...this.env.model.getters.getCarousel(this.props.figureId).items];o.splice(s,1),o.splice(t,0,e),this.updateItems(o)}getItemTitle(e){return b_(this.env.model.getters,e)}getItemPreview(e){return function(e,t){if("carouselDataView"===t.type)return"o-spreadsheet-Icon.DATA";const s=e.getChartDefinition(t.chartId);return(f_.getAll().find(e=>e.matcher?.(s))||f_.get(s.type)).preview}(this.env.model.getters,e)}updateItems(e){this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...this.carousel,items:e}})}updateTitleText(e){const t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,text:e}}})}updateTitleStyle(e){const t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,...e}}})}get carouselAddChartInfoMessage(){return fs("Add a chart to the carousel. You can also add a chart by dragging and dropping it over the carousel figure.")}getCogWheelMenuItems(e){const t=[];return"chart"===e.type&&(t.push({name:fs("Edit chart"),execute:()=>this.editCarouselItem(e),icon:"o-spreadsheet-Icon.EDIT"}),t.push({name:fs("Pop out chart"),execute:()=>this.popOutCarouselItem(e),icon:"o-spreadsheet-Icon.EXTERNAL"})),t.push({name:fs("Delete item"),execute:()=>this.deleteCarouselItem(e),icon:"o-spreadsheet-Icon.TRASH"}),t}get carouselSheetId(){const e=this.env.model.getters.getFigureSheetId(this.props.figureId);if(!e)throw new Error("Could not find the sheetId of the carousel figure");return e}get carouselDataViewMessage(){return fs("The data view makes the carousel transparent, revealing the data underneath.")}}class MU extends t.Component{static template="o-spreadsheet.ChartDataSeries";static components={SelectionInput:fM,Section:aM};static props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},onSelectionChanged:Function,onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},onSelectionConfirmed:Function,title:{type:String,optional:!0},maxNumberOfUsedRanges:{type:Number,optional:!0},datasetOrientation:{type:String,optional:!0},canChangeDatasetOrientation:{type:Boolean,optional:!0},onFlipAxis:{type:Function,optional:!0}};get ranges(){return this.props.ranges.map(e=>e.dataRange)}get disabledRanges(){return this.props.ranges.map((e,t)=>!!this.props.maxNumberOfUsedRanges&&t>=this.props.maxNumberOfUsedRanges)}get colors(){return this.props.ranges.map(e=>e.backgroundColor)}get title(){return this.props.title?this.props.title:this.props.hasSingleRange?fs("Data range"):fs("Data series")}}class NU extends t.Component{static template="o-spreadsheet.ChartErrorSection";static components={Section:aM,ValidationMessages:JV};static props={messages:{type:Array,element:String}}}class LU extends t.Component{static template="o-spreadsheet.ChartLabelRange";static components={SelectionInput:fM,Checkbox:IM,Section:aM};static props={title:{type:String,optional:!0},range:String,isInvalid:Boolean,onSelectionChanged:Function,onSelectionConfirmed:Function,options:{type:Array,optional:!0}};static defaultProps={title:fs("Categories / Labels"),options:[]}}class kU extends t.Component{static template="o-spreadsheet-GenericChartConfigPanel";static components={ChartDataSeries:MU,ChartLabelRange:LU,Section:aM,Checkbox:IM,ChartErrorSection:NU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};state=t.useState({datasetDispatchResult:void 0,labelsDispatchResult:void 0});dataSets=[];labelRange;datasetOrientation=void 0;chartTerms=Ig;setup(){this.dataSets=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange,this.datasetOrientation=this.computeDatasetOrientation()}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[]].filter(e=>"NoChanges"!==e).map(e=>Ig.Errors[e]||Ig.Errors.Unexpected)}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause("InvalidDataSet")}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause("InvalidLabelRange")}get dataSetsHaveTitleLabel(){return"rows"===this.datasetOrientation?fs("Use col %(column_name)s as headers",{column_name:it(this.calculateHeaderPosition()||0)}):fs("Use row %(row_position)s as headers",{row_position:this.calculateHeaderPosition()||""})}getLabelRangeOptions(){const e=this.props.definition;return[{name:"aggregated",label:this.chartTerms.AggregatedChart,value:("aggregated"in e&&e.aggregated)??!1,onChange:this.onUpdateAggregated.bind(this)},{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.chartId,{dataSetsHaveTitle:e})}get canChangeDatasetOrientation(){const e=new Set,t=[],s=this.env.model.getters.getActiveSheetName(),o=this.dataSets.map(e=>e.dataRange);this.labelRange&&o.push(this.labelRange);for(const i of o){if(!Et(i))return!1;const o=tr(i),n=It(o.xc);if(void 0===n.bottom||void 0===n.right)return!1;if(t.push(n),e.add(o.sheetName||s),e.size>1)return!1}const i=es(t);if(1!==i.length)return!1;const{left:n,right:r,top:a,bottom:l}=i[0];return!t.some(e=>!(e.top===a&&e.bottom===l||e.left===n&&e.right===r))}computeDatasetOrientation(){let e=!1,t=!1;for(const s of this.dataSets){if(!Et(s.dataRange))return;const o=It(s.dataRange);if(void 0===o.bottom||void 0===o.right)return;o.top===o.bottom&&(e=!0),o.left===o.right&&(t=!0)}return e&&!t?"rows":!e&&t?"columns":void 0}setDatasetOrientation(e){const t=this.props.definition.dataSets.map(e=>e.dataRange),s=this.transposeDataSet([this.props.definition.labelRange,...t],e);if(0===s.length)return;const o=s.length>1?s.shift().dataRange:"";this.props.updateChart(this.props.chartId,{labelRange:o,dataSets:s}),this.dataSets=s,this.labelRange=o,this.datasetOrientation=e}onDataSeriesRangesChanged(e){this.dataSets=e.map((e,t)=>({...this.dataSets?.[t],dataRange:e})),this.state.datasetDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesReordered(e){const t=KC({dataSets:this.dataSets},this.dataSets.length);this.datasetOrientation=void 0;const s=this.dataSets.map(e=>t.next());this.dataSets=e.map(e=>({backgroundColor:s[e],...this.dataSets[e]})),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesRemoved(e){const t=KC({dataSets:this.dataSets},this.dataSets.length),s=this.dataSets.map(e=>t.next());this.dataSets=this.dataSets.map((e,t)=>({backgroundColor:s[t],...e})).filter((t,s)=>s!==e),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesConfirmed(){this.dataSets=this.splitRanges,this.datasetOrientation=this.computeDatasetOrientation(),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets}),this.state.datasetDispatchResult.isSuccessful&&(this.dataSets=this.env.model.getters.getChartDefinition(this.props.chartId).dataSets)}get splitRanges(){const e=[];for(const t of this.dataSets){const s=t.dataRange;if(!this.env.model.getters.isRangeValid(s)){e.push(t);continue}const{sheetName:o}=tr(s),i=o?`${o}!`:"",n=It(s);if(n.bottom!==n.top&&n.left!==n.right){if("rows"!==this.datasetOrientation){if(void 0!==n.right)for(let s=n.left;s<=n.right;++s){const o=s===n.left?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Tt({left:s,right:s,top:n.top,bottom:n.bottom})}`})}else if(void 0!==n.bottom)for(let s=n.top;s<=n.bottom;++s){const o=s===n.top?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Tt({left:n.left,right:n.right,top:s,bottom:s})}`})}}else if(void 0!==n.bottom)for(let s=n.top;s<=n.bottom;++s){const o=s===n.top?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Tt({left:n.left,right:n.right,top:s,bottom:s})}`})}else if(void 0!==n.right)for(let s=n.left;s<=n.right;++s){const o=s===n.left?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Tt({left:s,right:s,top:n.top,bottom:n.bottom})}`})}}else e.push(t)}return e}getDataSeriesRanges(){return this.dataSets}onLabelRangeChanged(e){this.labelRange=e[0],this.state.labelsDispatchResult=this.props.canUpdateChart(this.props.chartId,{labelRange:this.labelRange})}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.chartId,{labelRange:this.labelRange})}getLabelRange(){return this.labelRange||""}onUpdateAggregated(e){this.props.updateChart(this.props.chartId,{aggregated:e})}calculateHeaderPosition(){if(this.isDatasetInvalid||this.isLabelInvalid)return;const e=this.env.model.getters,t=e.getActiveSheetId(),s=Rb(e,t,this.labelRange),o=eC(e,this.dataSets,t,this.props.definition.dataSetsHaveTitle);return o.length?"rows"===this.datasetOrientation?o[0].dataRange.zone.left:o[0].dataRange.zone.top+1:s?s.zone.top+1:void 0}get maxNumberOfUsedRanges(){return $y.get(this.props.definition.type).dataSeriesLimit}transposeDataSet(e,t){const s=this.env.model.getters;if(void 0===t)return e.filter(Te).map(e=>({dataRange:e}));const o={},i=[],n=s.getFigureIdFromChartId(this.props.chartId),r=s.getFigureSheetId(n);let a=s.getActiveSheet().name;r&&(a=s.getSheet(r).name);for(const t of e){if(!t)continue;if(!Et(t))return e.filter(Te).map(e=>({dataRange:e}));let{sheetName:s,xc:i}=tr(t);s=s??a,o[s]||(o[s]=[]),o[s].push(wt(i))}for(const e in o){const s=es(o[e]);if("columns"===t)for(const t of s)for(let s=t.left;s<=t.right;s++){const o=`${e===a?"":e+"!"}${Tt({...t,left:s,right:s})}`;i.push({dataRange:o})}else for(const t of s)for(let s=t.top;s<=t.bottom;s++){const o=`${e===a?"":e+"!"}${Tt({...t,top:s,bottom:s})}`;i.push({dataRange:o})}}return i}}class VU extends kU{static template="o-spreadsheet-BarConfigPanel";get stackedLabel(){return this.props.definition.horizontal?this.chartTerms.StackedBarChart:this.chartTerms.StackedColumnChart}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}}class UU extends t.Component{static template="o-spreadsheet.BadgeSelection";static props={choices:Array,onChange:Function,selectedValue:String}}class HU extends t.Component{static template="o-spreadsheet.ChartTitle";static components={Section:aM,TextStyler:OU};static props={title:{type:String,optional:!0},placeholder:{type:String,optional:!0},updateTitle:Function,name:{type:String},style:Object,defaultStyle:{type:Object,optional:!0},updateStyle:Function};static defaultProps={title:"",placeholder:""};updateTitle(e){this.props.updateTitle(e.target.value)}}class zU extends t.Component{static template="o-spreadsheet-AxisDesignEditor";static components={Section:aM,ChartTitle:HU,BadgeSelection:UU};static props={chartId:String,definition:Object,updateChart:Function,axesList:Array};state=t.useState({currentAxis:"x"});defaultFontSize=12;get axisTitleStyle(){return this.props.definition.axesDesign?.[this.state.currentAxis]?.title??{}}get badgeAxes(){return this.props.axesList.map(e=>({value:e.id,label:e.name}))}updateAxisEditor(e){this.state.currentAxis=e.target.value}getAxisTitle(){const e=this.props.definition.axesDesign??{};return e[this.state.currentAxis]?.title.text||""}updateAxisTitle(e){const t=ae(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:{...t?.[this.state.currentAxis]?.title,text:e}},this.props.updateChart(this.props.chartId,{axesDesign:t})}updateAxisTitleStyle(e){const t=ae(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:e},this.props.updateChart(this.props.chartId,{axesDesign:t})}}class BU extends t.Component{static template="o-spreadsheet.RadioSelection";static props={choices:Array,onChange:Function,selectedValue:{optional:!1},name:String,direction:{type:String,optional:!0}};static defaultProps={direction:"horizontal"}}class GU extends t.Component{static template="o-spreadsheet-GeneralDesignEditor";static components={RoundColorPicker:lM,ChartTitle:HU,Section:aM,SidePanelCollapsible:DP,RadioSelection:BU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function,defaultChartTitleFontSize:{type:Number,optional:!0},slots:{type:Object,optional:!0}};static defaultProps={defaultChartTitleFontSize:R};state;setup(){this.state=t.useState({activeTool:""})}get title(){return this.props.definition.title}toggleDropdownTool(e,t){const s=this.state.activeTool===e;this.state.activeTool=s?"":e}updateBackgroundColor(e){this.props.updateChart(this.props.chartId,{background:e})}updateTitle(e){const t={...this.title,text:e};this.props.updateChart(this.props.chartId,{title:t})}updateChartTitleStyle(e){const t={...this.title,...e};this.props.updateChart(this.props.chartId,{title:t}),this.state.activeTool=""}}class WU extends t.Component{static template="o-spreadsheet-ChartHumanizeNumbers";static components={Checkbox:IM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function}}class $U extends t.Component{static template="o-spreadsheet-ChartLegend";static components={Section:aM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e.target.value})}}class qU extends t.Component{static template="o-spreadsheet-SeriesDesignEditor";static components={SidePanelCollapsible:DP,Section:aM,RoundColorPicker:lM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function,slots:{type:Object,optional:!0}};state=t.useState({index:0});getDataSeries(){const e=this.env.model.getters.getChartRuntime(this.props.chartId);return e&&"chartJsConfig"in e?e.chartJsConfig.data.datasets.filter(e=>!fC(e.xAxisID??"")).map(e=>e.label):[]}updateEditedSeries(e){this.state.index=e.target.selectedIndex}updateDataSeriesColor(e){const t=this.props.definition.dataSets;t?.[this.state.index]&&(t[this.state.index]={...t[this.state.index],backgroundColor:e},this.props.updateChart(this.props.chartId,{dataSets:t}))}getDataSeriesColor(){const e=this.props.definition.dataSets;if(!e?.[this.state.index])return"";const t=e[this.state.index].backgroundColor;return t?bv(t):zv(this.state.index,Bv(this.props.definition.dataSets.length))}updateDataSeriesLabel(e){const t=e.target.value,s=this.props.definition.dataSets;s?.[this.state.index]&&(s[this.state.index]={...s[this.state.index],label:t},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSeriesLabel(){const e=this.props.definition.dataSets;return e[this.state.index]?.label||this.getDataSeries()[this.state.index]}}class ZU extends t.Component{static template="o-spreadsheet-SeriesWithAxisDesignEditor";static components={SeriesDesignEditor:qU,Checkbox:IM,RadioSelection:BU,Section:aM,RoundColorPicker:lM};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function,slots:{type:Object,optional:!0}};axisChoices=gC;updateDataSeriesAxis(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],yAxisId:"left"===t?"y":"y1"},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSerieAxis(e){const t=this.props.definition.dataSets;return t?.[e]&&"y1"===t[e].yAxisId?"right":"left"}get canHaveTwoVerticalAxis(){return!("horizontal"in this.props.definition&&this.props.definition.horizontal)}toggleDataTrend(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],trend:{type:"polynomial",order:1,...s[e].trend,display:t}},this.props.updateChart(this.props.chartId,{dataSets:s}))}getTrendLineConfiguration(e){const t=this.props.definition.dataSets;return t?.[e]?.trend}getTrendType(e){return e?"polynomial"===e.type&&1===e.order?"linear":e.type:""}onChangeTrendType(e,t){const s=t.target.value;let o;switch(s){case"linear":case"polynomial":o={type:"polynomial",order:"linear"===s?1:this.getMaxPolynomialDegree(e)};break;case"exponential":case"logarithmic":case"trailingMovingAverage":o={type:s};break;default:return}this.updateTrendLineValue(e,o)}getPolynomialDegrees(e){return ge(1,this.getMaxPolynomialDegree(e)+1)}onChangePolynomialDegree(e,t){const s=t.target;this.updateTrendLineValue(e,{order:parseInt(s.value)})}getMaxPolynomialDegree(e){const t=this.env.model.getters.getChartRuntime(this.props.chartId);return Math.min(10,t.chartJsConfig.data.datasets[e].data.length-1)}get defaultWindowSize(){return 2}onChangeMovingAverageWindow(e,t){const s=t.target;let o=parseInt(s.value)||2;o<=1&&(o=2),this.updateTrendLineValue(e,{window:o})}getDataSeriesColor(e){const t=this.props.definition.dataSets;if(!t?.[e])return"";const s=t[e].backgroundColor;return s?bv(s):zv(e,Bv(this.props.definition.dataSets.length))}getTrendLineColor(e){return this.getTrendLineConfiguration(e)?.color??_v(this.getDataSeriesColor(e),.5)}updateTrendLineColor(e,t){this.updateTrendLineValue(e,{color:t})}updateTrendLineValue(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],trend:{...s[e].trend,...t}},this.props.updateChart(this.props.chartId,{dataSets:s}))}}class jU extends t.Component{static template="o-spreadsheet-ChartShowValues";static components={Checkbox:IM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function,defaultValue:{type:Boolean,optional:!0}}}class YU extends t.Component{static template="o-spreadsheet-ChartWithAxisDesignPanel";static components={GeneralDesignEditor:GU,SidePanelCollapsible:DP,Section:aM,AxisDesignEditor:zU,SeriesWithAxisDesignEditor:ZU,ChartLegend:$U,ChartShowValues:jU,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function};get axesList(){const{useLeftAxis:e,useRightAxis:t}=hC(this.props.definition),s=[{id:"x",name:fs("Horizontal axis")}];return e&&s.push({id:"y",name:fs(t?"Left axis":"Vertical axis")}),t&&s.push({id:"y1",name:fs(e?"Right axis":"Vertical axis")}),s}}class XU extends t.Component{static template="o-spreadsheet-ChartShowDataMarkers";static components={Checkbox:IM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function}}class KU extends YU{static template="o-spreadsheet-GenericZoomableChartDesignPanel";static components={...YU.components,Checkbox:IM};onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}}class JU extends KU{static template="o-spreadsheet-ComboChartDesignPanel";static components={...KU.components,ChartShowDataMarkers:XU,RadioSelection:BU};seriesTypeChoices=[{value:"bar",label:fs("Bar")},{value:"line",label:fs("Line")}];updateDataSeriesType(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],type:t},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSeriesType(e){const t=this.props.definition.dataSets;return t?.[e]?t[e].type??"line":"bar"}}class QU extends t.Component{static template="o-spreadsheet-FunnelChartDesignPanel";static components={ChartShowValues:jU,GeneralDesignEditor:GU,SidePanelCollapsible:DP,RoundColorPicker:lM,Section:aM,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};getFunnelColorItems(){const e=this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig.data.labels||[],t=BC(e,this.props.definition.funnelColors);return e.map((e,s)=>({label:e||fs("Value %s",s+1),color:t[s]}))}updateFunnelItemColor(e,t){const s=je(this.props.definition.funnelColors||[],t,e);this.props.updateChart(this.props.chartId,{funnelColors:s})}}class eH extends t.Component{static template="o-spreadsheet-GaugeChartConfigPanel";static components={ChartErrorSection:NU,ChartDataSeries:MU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};state=t.useState({dataRangeDispatchResult:void 0});dataRange=this.props.definition.dataRange;get configurationErrorMessages(){return[...this.state.dataRangeDispatchResult?.reasons||[]].map(e=>Ig.Errors[e]||Ig.Errors.Unexpected)}get isDataRangeInvalid(){return!!this.state.dataRangeDispatchResult?.isCancelledBecause("InvalidGaugeDataRange")}onDataRangeChanged(e){this.dataRange=e[0],this.state.dataRangeDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataRange:this.dataRange})}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.chartId,{dataRange:this.dataRange})}getDataRange(){return{dataRange:this.dataRange||""}}}class tH extends t.Component{static template="o-spreadsheet-GaugeChartDesignPanel";static components={SidePanelCollapsible:DP,Section:aM,RoundColorPicker:lM,GeneralDesignEditor:GU,ChartErrorSection:NU,StandaloneComposer:JP,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};state;setup(){this.state=t.useState({sectionRuleCancelledReasons:this.checkSectionRuleFormulasAreValid(this.props.definition.sectionRule),sectionRule:ae(this.props.definition.sectionRule)})}get designErrorMessages(){return[...this.state.sectionRuleCancelledReasons||[]].map(e=>Ig.Errors[e]||Ig.Errors.Unexpected)}get isRangeMinInvalid(){return!(!this.state.sectionRuleCancelledReasons?.includes("EmptyGaugeRangeMin")&&!this.state.sectionRuleCancelledReasons?.includes("GaugeRangeMinNaN"))}get isRangeMaxInvalid(){return!(!this.state.sectionRuleCancelledReasons?.includes("EmptyGaugeRangeMax")&&!this.state.sectionRuleCancelledReasons?.includes("GaugeRangeMaxNaN"))}get isLowerInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.includes("GaugeLowerInflectionPointNaN")}get isUpperInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.includes("GaugeUpperInflectionPointNaN")}updateSectionColor(e,t){const s=ae(this.state.sectionRule);s.colors[e]=t,this.updateSectionRule(s)}updateSectionRule(e){this.state.sectionRuleCancelledReasons=[],this.state.sectionRuleCancelledReasons.push(...this.checkSectionRuleFormulasAreValid(this.state.sectionRule));const t=this.props.updateChart(this.props.chartId,{sectionRule:e});t.isSuccessful?this.state.sectionRule=ae(e):this.state.sectionRuleCancelledReasons.push(...t.reasons)}onConfirmGaugeRange(e,t){this.state.sectionRule={...this.state.sectionRule,[e]:t},this.updateSectionRule(this.state.sectionRule)}getGaugeInflectionComposerProps(e){const t="lowerColor"===e?"lowerInflectionPoint":"upperInflectionPoint",s=this.state.sectionRule[t];return{onConfirm:e=>{this.state.sectionRule={...this.state.sectionRule,[t]:{...s,value:e}},this.updateSectionRule(this.state.sectionRule)},composerContent:s.value,invalid:"lowerColor"===e?this.isLowerInflectionPointInvalid:this.isUpperInflectionPointInvalid,defaultRangeSheetId:this.sheetId,class:t,placeholder:fs("Value"),title:fs("Value or formula")}}checkSectionRuleFormulasAreValid(e){const t=[];return this.valueIsValidNumber(e.rangeMin)||t.push("GaugeRangeMinNaN"),this.valueIsValidNumber(e.rangeMax)||t.push("GaugeRangeMaxNaN"),this.valueIsValidNumber(e.lowerInflectionPoint.value)||t.push("GaugeLowerInflectionPointNaN"),this.valueIsValidNumber(e.upperInflectionPoint.value)||t.push("GaugeUpperInflectionPointNaN"),t}valueIsValidNumber(e){const t=this.env.model.getters.getLocale();if(!e.startsWith("="))return void 0!==So(e,t);const s=this.env.model.getters.evaluateFormula(this.sheetId,e);return!bi(s)&&void 0!==So(fi(s),t)}get sheetId(){const e=this.env.model.getters.getChart(this.props.chartId);if(!e)throw new Error("Chart not found with id "+this.props.chartId);return e.sheetId}}class sH extends t.Component{static template="o-spreadsheet-GeoChartRegionSelectSection";static components={Section:aM};static props={chartId:String,definition:Object,updateChart:Function};updateSelectedRegion(e){const t=e.target.value;this.props.updateChart(this.props.chartId,{region:t})}get availableRegions(){return this.env.model.getters.getGeoChartAvailableRegions()}get selectedRegion(){return this.props.definition.region||this.availableRegions[0]?.id}}class oH extends kU{static template="o-spreadsheet-GeoChartConfigPanel";static components={...kU.components,GeoChartRegionSelectSection:sH};get dataRanges(){return this.getDataSeriesRanges()}get disabledRanges(){return this.props.definition.dataSets.map((e,t)=>t>0)}getLabelRangeOptions(){return[{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}}const iH={minColor:"#FFF5EB",midColor:"#FD8D3C",maxColor:"#7F2704"};class nH extends YU{static template="o-spreadsheet-GeoChartDesignPanel";static components={...YU.components,RoundColorPicker:lM};colorScalesChoices=Ig.GeoChart.ColorScales;updateColorScaleType(e){const t=e.target.value;"custom"===t?this.updateColorScale(iH):this.updateColorScale(t)}updateColorScale(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}updateLegendPosition(e){const t=e.target.value;this.props.updateChart(this.props.chartId,{legendPosition:t})}get selectedColorScale(){return"object"==typeof this.props.definition.colorScale?"custom":this.props.definition.colorScale||"oranges"}get selectedMissingValueColor(){return this.props.definition.missingValueColor||"#ffffff"}get customColorScale(){if("object"==typeof this.props.definition.colorScale)return this.props.definition.colorScale}getCustomColorScaleColor(e){return this.customColorScale?.[e]??""}setCustomColorScaleColor(e,t){t||"midColor"===e||(t="#fff");const s=this.customColorScale;s&&this.updateColorScale({...s,[e]:t})}}class rH extends kU{static template="o-spreadsheet-HierarchicalChartConfigPanel";static components={...kU.components};getLabelRangeOptions(){return[{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}}class aH extends kU{static template="o-spreadsheet-LineConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.chartId);return!!(e&&e instanceof JO)&&HI(e.getDefinition(),e.dataSets,e.labelRange,this.env.model.getters)}get stackedLabel(){return this.props.definition.fillArea?this.chartTerms.StackedAreaChart:this.chartTerms.StackedLineChart}getLabelRangeOptions(){const e=super.getLabelRangeOptions();return this.canTreatLabelsAsText&&e.push({name:"labelsAsText",value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}onUpdateLabelsAsText(e){this.props.updateChart(this.props.chartId,{labelsAsText:e})}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}}class lH extends KU{static template="o-spreadsheet-LineChartDesignPanel";static components={...KU.components,ChartShowDataMarkers:XU}}class cH extends t.Component{static template="o-spreadsheet.PieHoleSize";static components={Section:aM};static props={onValueChange:Function,value:Number};debouncedOnChange=De(this.onChange.bind(this),100);onChange(e){isNaN(Number(e))||this.props.onValueChange(ue(Number(e),0,95))}}class hH extends t.Component{static template="o-spreadsheet-PieChartDesignPanel";static components={GeneralDesignEditor:GU,Section:aM,ChartLegend:$U,ChartShowValues:jU,PieHoleSize:cH,Checkbox:IM,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}get defaultHoleSize(){return 50}}class dH extends t.Component{static template="o-spreadsheet-RadarChartDesignPanel";static components={GeneralDesignEditor:GU,SeriesDesignEditor:qU,Section:aM,ChartLegend:$U,ChartShowValues:jU,ChartShowDataMarkers:XU,Checkbox:IM,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function}}class uH extends ny{dataSets;labelRange;background;legendPosition;labelsAsText;aggregated;type="scatter";dataSetsHaveTitle;dataSetDesign;axesDesign;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=eC(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.zoomable=e.zoomable}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static transformDefinition(e,t,s){return iC(e,t,s)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"scatter",labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues,zoomable:e.zoomable,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"scatter",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,zoomable:this.zoomable,humanize:this.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new uH(i,this.sheetId,this.getters)}getDefinitionForExcel(){const e=this.dataSets.map(e=>sC(this.getters,e)).filter(e=>""!==e.range),t=oC(this.getters,this.labelRange,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:e,labelRange:t,verticalAxis:hC(s)}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new uH(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new uH(t,e,this.getters)}}class gH extends t.Component{static template="o-spreadsheet-ScorecardChartConfigPanel";static components={SelectionInput:fM,ChartErrorSection:NU,Section:aM};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};state=t.useState({keyValueDispatchResult:void 0,baselineDispatchResult:void 0});keyValue=this.props.definition.keyValue;baseline=this.props.definition.baseline;get errorMessages(){return[...this.state.keyValueDispatchResult?.reasons||[],...this.state.baselineDispatchResult?.reasons||[]].map(e=>Ig.Errors[e]||Ig.Errors.Unexpected)}get isKeyValueInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause("InvalidScorecardKeyValue")}get isBaselineInvalid(){return!!this.state.keyValueDispatchResult?.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.target.value})}}class pH extends t.Component{static template="o-spreadsheet-ScorecardChartDesignPanel";static components={GeneralDesignEditor:GU,RoundColorPicker:lM,SidePanelCollapsible:DP,Section:aM,Checkbox:IM,ChartTitle:HU,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};get colorsSectionTitle(){return"progress"===this.props.definition.baselineMode?fs("Progress bar colors"):fs("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})}}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){const 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){const t={...this.baselineStyle,...e};this.props.updateChart(this.props.chartId,{baselineDescr:t})}}class mH extends t.Component{static template="o-spreadsheet-SunburstChartDesignPanel";static components={GeneralDesignEditor:GU,Section:aM,SidePanelCollapsible:DP,ChartShowValues:jU,Checkbox:IM,TextStyler:OU,RoundColorPicker:lM,ChartLegend:$U,PieHoleSize:cH};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};defaults=Ew;get showValues(){return this.props.definition.showValues??Ew.showValues}get showLabels(){return this.props.definition.showLabels??Ew.showLabels}get groupColors(){const e=this.props.chartId,t=this.env.model.getters.getChartRuntime(e).chartJsConfig.data.datasets[0];return t?.groupColors||[]}onGroupColorChanged(e,t){const s=ae(this.props.definition.groupColors)??[];s[e]=t,this.props.updateChart(this.props.chartId,{groupColors:s})}onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}}class fH extends t.Component{static template="o-spreadsheet-TreeMapCategoryColors";static components={Checkbox:IM,RoundColorPicker:lM};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){const e=this.props.definition.coloringOptions??CC.coloringOptions;if("categoryColor"!==e.type)throw new Error("Coloring options is not solid color");return e}getTreeGroupAndColors(){const e=this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig;return e.data.datasets[0]?.groupColors||[]}onGroupColorChanged(e,t){const s=ae(this.coloringOptions);s.colors[e]=t||void 0,this.props.onColorChanged(s)}useValueBasedGradient(e){if("categoryColor"!==this.coloringOptions.type)throw new Error("Coloring options is not solid color");this.props.onColorChanged({...this.coloringOptions,useValueBasedGradient:e})}}class vH extends t.Component{static template="o-spreadsheet-TreeMapColorScale";static components={RoundColorPicker:lM};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){const e=this.props.definition.coloringOptions??CC.coloringOptions;if("colorScale"!==e.type)throw new Error("Coloring options is not a color scale");return e}setColorScaleColor(e,t){this.props.onColorChanged({...this.coloringOptions,[e]:t})}}const bH={type:"colorScale",minColor:"#FFF5EB",midColor:"#FD8D3C",maxColor:"#7F2704"},SH={type:"categoryColor",colors:[],useValueBasedGradient:!0};class CH extends t.Component{static template="o-spreadsheet-TreeMapChartDesignPanel";static components={GeneralDesignEditor:GU,Section:aM,SidePanelCollapsible:DP,ChartShowValues:jU,Checkbox:IM,TextStyler:OU,RoundColorPicker:lM,BadgeSelection:UU,TreeMapCategoryColors:fH,TreeMapColorScale:vH};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};savedColors={categoryColors:SH,colorScale:bH};defaults=CC;get showHeaders(){return this.props.definition.showHeaders??CC.showHeaders}get showValues(){return this.props.definition.showValues??CC.showValues}get showLabels(){return this.props.definition.showLabels??CC.showLabels}get coloringOptions(){return this.props.definition.coloringOptions??CC.coloringOptions}changeColoringOption(e){const t="categoryColor"===e?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:fs("Category color"),value:"categoryColor"},{label:fs("Color scale"),value:"colorScale"}]}}class yH extends t.Component{static template="o-spreadsheet-WaterfallChartDesignPanel";static components={GeneralDesignEditor:GU,ChartShowValues:jU,Checkbox:IM,SidePanelCollapsible:DP,Section:aM,RoundColorPicker:lM,AxisDesignEditor:zU,RadioSelection:BU,ChartLegend:$U,ChartHumanizeNumbers:WU};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};axisChoices=gC;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:fs("Horizontal axis")},{id:"y",name:fs("Vertical axis")}]}get positiveValuesColor(){return this.props.definition.positiveValuesColor||m}get negativeValuesColor(){return this.props.definition.negativeValuesColor||f}get subTotalValuesColor(){return this.props.definition.subTotalValuesColor||v}updateVerticalAxisPosition(e){this.props.updateChart(this.props.chartId,{verticalAxisPosition:e})}onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}}const IH=new Og;IH.add("line",{configuration:aH,design:lH}).add("scatter",{configuration:class extends kU{static template="o-spreadsheet-ScatterConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.chartId);return!!(e&&e instanceof uH)&&HI(e.getDefinition(),e.dataSets,e.labelRange,this.env.model.getters)}onUpdateLabelsAsText(e){this.props.updateChart(this.props.chartId,{labelsAsText:e})}getLabelRangeOptions(){const e=super.getLabelRangeOptions();return this.canTreatLabelsAsText&&e.push({name:"labelsAsText",value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}},design:KU}).add("bar",{configuration:VU,design:KU}).add("combo",{configuration:kU,design:JU}).add("pie",{configuration:kU,design:hH}).add("gauge",{configuration:eH,design:tH}).add("scorecard",{configuration:gH,design:pH}).add("waterfall",{configuration:kU,design:yH}).add("pyramid",{configuration:kU,design:YU}).add("radar",{configuration:kU,design:dH}).add("sunburst",{configuration:rH,design:mH}).add("geo",{configuration:oH,design:nH}).add("funnel",{configuration:class extends kU{getLabelRangeOptions(){const e=this.props.definition;return[{name:"aggregated",label:this.chartTerms.AggregatedChart,value:e.aggregated??!1,onChange:this.onUpdateAggregated.bind(this)},{name:"cumulative",label:this.chartTerms.CumulativeData,value:e.cumulative??!1,onChange:this.onUpdateCumulative.bind(this)},{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}},design:QU}).add("treemap",{configuration:rH,design:CH});const wH={line:fs("Line"),column:fs("Column"),bar:fs("Bar"),area:fs("Area"),pie:fs("Pie"),hierarchical:fs("Hierarchical"),misc:fs("Miscellaneous")};class EH extends t.Component{static template="o-spreadsheet-ChartTypePicker";static components={Section:aM,Popover:DF};static props={chartId:String,chartPanelStore:Object};categories=wH;chartTypeByCategories={};popoverRef=t.useRef("popoverRef");selectRef=t.useRef("selectRef");state=t.useState({popoverProps:void 0,popoverStyle:""});setup(){t.useExternalListener(window,"pointerdown",this.onExternalClick,{capture:!0});for(const e of f_.getAll())this.chartTypeByCategories[e.category]?this.chartTypeByCategories[e.category].push(e):this.chartTypeByCategories[e.category]=[e]}onExternalClick(e){Dy(this.popoverRef.el?.parentElement,e)||Dy(this.selectRef.el,e)||this.closePopover()}onTypeChange(e){this.props.chartPanelStore.changeChartType(this.props.chartId,e),this.closePopover()}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}getSelectedChartSubtypeProperties(){const e=this.getChartDefinition(this.props.chartId);return f_.getAll().find(t=>t.matcher?.(e)||!1)||f_.get(e.type)}onPointerDown(e){if(this.state.popoverProps)return void this.closePopover();const t=e.currentTarget,{bottom:s,right:o,width:i}=t.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:o,y:s,width:0,height:0},positioning:"top-right",verticalOffset:0},this.state.popoverStyle=Ey({width:`${i}px`})}closePopover(){this.state.popoverProps=void 0}}class RH extends hv{mutators=["activatePanel","changeChartType"];panel="configuration";creationContexts={};activatePanel(e){this.panel=e}changeChartType(e,t){const s=this.getters.getContextCreationChart(e),o=this.creationContexts[e]||{};let i=s?.range;i?.every((e,t)=>Me(e,o.range?.[t]))&&(i=Object.assign([],o.range,s?.range)),this.creationContexts[e]={...o,...s,range:i};const n=this.getters.getFigureIdFromChartId(e),r=this.getters.getFigureSheetId(n);if(!r)return;const a=this.getChartDefinitionFromContextCreation(e,t);this.model.dispatch("UPDATE_CHART",{definition:a,chartId:e,figureId:n,sheetId:r})}getChartDefinitionFromContextCreation(e,t){const s=f_.get(t);return{...$y.get(s.chartType).getChartDefinitionFromContextCreation(this.creationContexts[e]),...s.subtypeDefinition}}}class xH extends t.Component{static template="o-spreadsheet-ChartPanel";static components={Section:aM,ChartTypePicker:EH};static props={onCloseSidePanel:Function,chartId:String};panelContentRef;scrollPositions={configuration:0,design:0};store;get chartId(){return this.props.chartId}setup(){this.store=tv(RH),this.panelContentRef=t.useRef("panelContent"),t.useEffect(()=>{const e=this.panelContentRef.el,t=this.store.panel;e&&(e.scrollTop=this.scrollPositions[t])},()=>[this.store.panel])}switchPanel(e){const t=this.panelContentRef.el;t&&(this.scrollPositions[this.store.panel]=t.scrollTop),this.store.activatePanel(e)}updateChart(e,t){const s=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId)return;const o={...this.getChartDefinition(this.chartId),...t};return this.env.model.dispatch("UPDATE_CHART",{definition:o,chartId:e,figureId:s,sheetId:this.env.model.getters.getFigureSheetId(s)})}canUpdateChart(e,t){const s=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId||!this.env.model.getters.isChartDefined(e))return;const o={...this.getChartDefinition(this.chartId),...t};return this.env.model.canDispatch("UPDATE_CHART",{definition:o,chartId:e,figureId:s,sheetId:this.env.model.getters.getFigureSheetId(s)})}onTypeChange(e){this.chartId&&this.store.changeChartType(this.chartId,e)}get chartPanel(){if(!this.chartId)throw new Error("Chart not defined.");const e=this.env.model.getters.getChartType(this.chartId);if(!e)throw new Error("Chart not defined.");const t=IH.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}}class TH extends t.Component{static template="o-spreadsheet-IconPicker";static props={onIconPicked:Function};icons=gR;iconSets=pR;onIconClick(e){e&&this.props.onIconPicked(e)}}function AH(e,s){const o=function(e){const s=t.useState({hovered:!1});return eU(e,"mouseenter",()=>s.hovered=!0),eU(e,"mouseleave",()=>s.hovered=!1),s}(e);DH({get highlights(){return o.hovered?s.highlights:[]}})}function DH(e){const s=Qf(),o=tv(ZP);t.onMounted(()=>{o.register(e)});let i=e.highlights;t.useEffect(e=>{Me(e,i)||(i=e,s.trigger("store-updated"))},()=>[e.highlights])}class _H extends t.Component{static template="o-spreadsheet-ConditionalFormatPreview";icons=gR;ref=t.useRef("cfPreview");setup(){AH(this.ref,this)}getPreviewImageStyle(){const e=this.props.conditionalFormat.rule;if("CellIsRule"===e.type)return Ey(Iy(e.style));if("ColorScaleRule"===e.type){const t=fv(e.minimum.color),s=e.midpoint?fv(e.midpoint.color):null,o=fv(e.maximum.color),i="background-image: linear-gradient(to right, ";return s?i+t+", "+s+", "+o+")":i+t+", "+o+")"}if("DataBarRule"===e.type){return`background-image: linear-gradient(to right, ${fv(e.color)} 50%, white 50%)`}return""}getDescription(){const e=this.props.conditionalFormat;switch(e.rule.type){case"CellIsRule":return QT.get(e.rule.operator).getPreview({...e.rule,type:e.rule.operator},this.env.model.getters);case"ColorScaleRule":return yg.ColorScale;case"IconSetRule":return yg.IconSet;case"DataBarRule":return yg.DataBar}}deleteConditionalFormat(){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:this.props.conditionalFormat.id,sheetId:this.env.model.getters.getActiveSheetId()})}onMouseDown(e){this.props.onMouseDown(e)}get highlights(){const e=this.env.model.getters.getActiveSheetId();return this.props.conditionalFormat.ranges.map(t=>({range:this.env.model.getters.getRangeFromSheetXC(e,t),color:o,fillAlpha:.06}))}}_H.props={conditionalFormat:Object,onPreviewClick:Function,onMouseDown:Function,class:String};class OH extends t.Component{static template="o-spreadsheet-ConditionalFormatPreviewList";static props={conditionalFormats:Array,onPreviewClick:Function,onAddConditionalFormat:Function};static components={ConditionalFormatPreview:_H};icons=gR;dragAndDrop=cM();cfListRef=t.useRef("cfList");setup(){t.onWillUpdateProps(e=>{Me(this.props.conditionalFormats,e.conditionalFormats)||this.dragAndDrop.cancel()})}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[e.id]||""}onPreviewMouseDown(e,t){if(0!==t.button)return;const s=Array.from(this.cfListRef.el.children).map(e=>Fy(e)),o=this.props.conditionalFormats.map((e,t)=>({id:e.id,size:s[t].height,position:s[t].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.id,initialMousePosition:t.clientY,items:o,scrollableContainerEl:this.cfListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const s=this.props.conditionalFormats.findIndex(t=>t.id===e)-t;0!==s&&this.env.model.dispatch("CHANGE_CONDITIONAL_FORMAT_PRIORITY",{cfId:e,delta:s,sheetId:this.env.model.getters.getActiveSheetId()})}}class FH extends t.Component{static template="o-spreadsheet-ConditionalFormattingEditor";static props={editedCf:Object,onCancel:Function,onExit:Function,isNewCf:Boolean};static components={SelectionInput:fM,IconPicker:TH,ColorPickerWidget:DU,ConditionalFormatPreviewList:OH,Section:aM,RoundColorPicker:lM,StandaloneComposer:JP,BadgeSelection:UU,ValidationMessages:JV,SelectMenu:CM};icons=gR;iconSets=pR;getTextDecoration=yy;colorNumberToHex=fv;state;setup(){switch(this.state=t.useState({errors:[],currentCFType:this.props.editedCf.rule.type,ranges:this.props.editedCf.ranges,rules:this.getDefaultRules(),hasEditedCf:this.props.isNewCf}),this.props.editedCf.rule.type){case"CellIsRule":this.state.rules.cellIs=this.props.editedCf.rule;break;case"ColorScaleRule":this.state.rules.colorScale=this.props.editedCf.rule;break;case"IconSetRule":this.state.rules.iconSet=this.props.editedCf.rule;break;case"DataBarRule":this.state.rules.dataBar=this.props.editedCf.rule}t.useExternalListener(window,"click",this.closeMenus)}get isRangeValid(){return this.state.errors.includes("EmptyRange")}get errorMessages(){return this.state.errors.map(e=>yg.Errors[e]||yg.Errors.Unexpected)}get cfTypesValues(){return[{value:"CellIsRule",label:fs("Single color")},{value:"ColorScaleRule",label:fs("Color scale")},{value:"IconSetRule",label:fs("Icon set")},{value:"DataBarRule",label:fs("Data bar")}]}updateConditionalFormat(e){const t=e.ranges||this.state.ranges;if(this.state.ranges.some(e=>!e.match(Xn)))return e.suppressErrors||(this.state.errors=["InvalidRange"]),["InvalidRange"];const s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getLocale(),i=e.rule||this.getEditedRule(this.state.currentCFType),n=this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:nh(i,o),id:this.props.editedCf.id},ranges:t.map(e=>this.env.model.getters.getRangeDataFromXc(s,e)),sheetId:s});n.isSuccessful&&(this.state.hasEditedCf=!0);const r=n.reasons.filter(e=>"NoChanges"!==e);return e.suppressErrors||(this.state.errors=r),r}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}}onSave(){0===this.updateConditionalFormat({}).length&&this.props.onExit()}onCancel(){this.state.hasEditedCf?this.props.onCancel():this.props.onExit()}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"isNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:KR("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}}}changeRuleType(e){this.state.currentCFType!==e&&(this.state.errors=[],this.state.currentCFType=e,this.updateConditionalFormat({rule:this.getEditedRule(e),suppressErrors:!0}))}onRangeUpdate(e){this.state.ranges=e}onRangeConfirmed(){this.updateConditionalFormat({ranges:this.state.ranges})}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){return this.state.errors.includes("FirstArgMissing")||this.state.errors.includes("ValueCellIsInvalidFormula")}get isValue2Invalid(){return this.state.errors.includes("SecondArgMissing")}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}onKeydown(e){if("F4"===e.key){const t=e.target,s=WP({start:t.selectionStart??0,end:t.selectionEnd??0},t.value,this.env.model.getters.getLocale());if(!s)return;t.value=s.content,t.setSelectionRange(s.selection.start,s.selection.end),t.dispatchEvent(new Event("input"))}}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,this.updateConditionalFormat({rule:this.state.rules.cellIs,suppressErrors:!0}),this.closeMenus()}get cfCriterionMenuItems(){return SM(e=>this.editOperator(e),pI)}get selectedCriterionName(){return QT.get(this.state.rules.cellIs.operator).name}get criterionComponent(){return bM.get(this.state.rules.cellIs.operator).component}get genericCriterion(){return{type:this.state.rules.cellIs.operator,values:this.state.rules.cellIs.values}}onRuleValuesChanged(e){this.state.rules.cellIs.values=e.values,this.updateConditionalFormat({rule:{...this.state.rules.cellIs,values:e.values}})}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes("MinInvalidFormula")||this.state.errors.includes("MinBiggerThanMid")||this.state.errors.includes("MinBiggerThanMax")||this.state.errors.includes("MinNaN");case"midpoint":return this.state.errors.includes("MidInvalidFormula")||this.state.errors.includes("MidNaN")||this.state.errors.includes("MidBiggerThanMax");case"maximum":return this.state.errors.includes("MaxInvalidFormula")||this.state.errors.includes("MaxNaN");default:return!1}}setColorScaleColor(e,t){if(!Sv(t))return;const s=this.state.rules.colorScale[e];s&&(s.color=vv(t)),this.updateConditionalFormat({rule:this.state.rules.colorScale}),this.closeMenus()}getPreviewGradient(){const e=this.state.rules.colorScale,t=fv(e.minimum.color),s=fv(e.midpoint?.color||h),o=fv(e.maximum.color),i="background-image: linear-gradient(to right, ";return void 0===e.midpoint?i+t+", "+o+")":i+t+", "+s+", "+o+")"}getThresholdColor(e){return fv(e?e.color:h)}onMidpointChange(e){const t=e.target.value,s=this.state.rules.colorScale;s.midpoint="none"===t?void 0:{color:h,value:"",...s.midpoint,type:t},this.updateConditionalFormat({rule:s,suppressErrors:!0})}updateThresholdType(e,t){this.state.rules.colorScale[e].type=t,this.updateConditionalFormat({rule:this.state.rules.colorScale,suppressErrors:!0})}updateThresholdValue(e,t){this.state.rules.colorScale[e].value=t,this.updateConditionalFormat({rule:this.state.rules.colorScale})}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes("ValueLowerInflectionNaN")||this.state.errors.includes("ValueLowerInvalidFormula")||this.state.errors.includes("LowerBiggerThanUpper");case"upperInflectionPoint":return this.state.errors.includes("ValueUpperInflectionNaN")||this.state.errors.includes("ValueUpperInvalidFormula")||this.state.errors.includes("LowerBiggerThanUpper");default:return!0}}reverseIcons(){const 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){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIcon(e,t){this.state.rules.iconSet.icons[e]=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionOperator(e,t){this.state.rules.iconSet[e].operator=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionValue(e,t){this.state.rules.iconSet[e].value=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionType(e,t,s){this.state.rules.iconSet[e].type=t,this.updateConditionalFormat({rule:this.state.rules.iconSet,suppressErrors:!0})}getColorScaleComposerProps(e){const t=this.state.rules.colorScale[e];if(!t)throw new Error("Threshold not found");const s=this.isValueInvalid(e);return{onConfirm:e=>{t.value=e,this.updateConditionalFormat({rule:this.state.rules.colorScale})},composerContent:t.value||"",placeholder:fs("Formula"),defaultStatic:!0,invalid:s,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getColorIconSetComposerProps(e){const t=this.state.rules.iconSet[e],s=this.isInflectionPointInvalid(e);return{onConfirm:e=>{t.value=e,this.updateConditionalFormat({rule:this.state.rules.iconSet})},composerContent:t.value||"",placeholder:fs("Formula"),defaultStatic:!0,invalid:s,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getRangeValues(){return[this.state.rules.dataBar.rangeValues||""]}updateDataBarColor(e){Sv(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})}}class PH extends t.Component{static template="o-spreadsheet-ConditionalFormattingPanel";static props={selection:{type:Object,optional:!0},onCloseSidePanel:Function};static components={ConditionalFormatPreviewList:OH,ConditionalFormattingEditor:FH,Section:aM};activeSheetId;originalEditedCf=void 0;state=t.useState({mode:"list"});setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId();const e=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===s.length){const e=this.conditionalFormats.find(e=>e.id===s[0]);e&&this.editConditionalFormat(e)}t.onWillUpdateProps(e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===s.length){const e=this.conditionalFormats.find(e=>e.id===s[0]);e&&this.editConditionalFormat(e)}else this.switchToList()}else this.editedCF||this.switchToList()})}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId()).map(e=>({...e,rule:rh(e.rule,this.env.model.getters.getLocale())}))}switchToList(){this.state.mode="list",this.state.editedCfId=void 0,this.originalEditedCf=void 0}addConditionalFormat(){const e=this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,ranges:this.env.model.getters.getSelectedZones().map(e=>this.env.model.getters.getRangeDataFromZone(this.activeSheetId,e)),cf:{id:e,rule:{type:"CellIsRule",operator:"isNotEmpty",style:{fillColor:"#b6d7a8"},values:[]}}}),this.state.editedCfId=e,this.state.mode="edit",this.originalEditedCf=void 0}editConditionalFormat(e){this.state.mode="edit",this.state.editedCfId=e.id,this.originalEditedCf=e}cancelEdition(){this.originalEditedCf?this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,ranges:this.originalEditedCf.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.activeSheetId,e)),cf:this.originalEditedCf}):this.state.editedCfId&&this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,id:this.state.editedCfId}),this.switchToList()}get editedCF(){return this.conditionalFormats.find(e=>e.id===this.state.editedCfId)}}const MH=new Og;class NH extends t.Component{static template="o-spreadsheet-CustomCurrencyPanel";static components={Section:aM,Checkbox:IM};static props={onCloseSidePanel:Function};availableCurrencies;state;setup(){this.availableCurrencies=[],this.state=t.useState({selectedCurrencyIndex:0,currencyCode:"",currencySymbol:"",selectedFormatIndex:0,isAccountingFormat:!1}),t.onWillStart(()=>this.updateAvailableCurrencies())}get formatProposals(){const e=this.availableCurrencies[this.state.selectedCurrencyIndex],t=e.position,s="before"===e.position?"after":"before",o=this.state.currencySymbol.trim()?this.state.currencySymbol:"",i=this.state.currencyCode.trim()?this.state.currencyCode:"",n=e.decimalPlaces;if(!o&&!i)return[];const r=[{symbol:o,position:t,decimalPlaces:0},{symbol:o,position:t,decimalPlaces:n},{symbol:o,position:t,decimalPlaces:0,code:i},{symbol:o,position:t,decimalPlaces:n,code:i},{symbol:o,position:s,decimalPlaces:0},{symbol:o,position:s,decimalPlaces:n},{symbol:o,position:s,decimalPlaces:0,code:i},{symbol:o,position:s,decimalPlaces:n,code:i}],a=new Set,l=this.env.model.getters.getLocale();return r.map(e=>{const t=Dn(e);if((e.symbol||e.code)&&!a.has(t))return a.add(t),{format:t,accountingFormat:_n(e),example:pn(1e3,{format:t,locale:l})}}).filter(Te)}get isSameFormat(){return!!this.selectedFormat&&this.selectedFormat===this.getCommonFormat()}async updateAvailableCurrencies(){if(0===MH.getAll().length){(await(this.env.loadCurrencies?.())||[]).forEach((e,t)=>{MH.add(t.toString(),e)})}const e={name:wg.Custom,code:"",symbol:"",decimalPlaces:2,position:"after"};this.availableCurrencies=[e,...MH.getAll()]}updateSelectCurrency(e){const t=e.target;this.state.selectedCurrencyIndex=parseInt(t.value,10);const s=this.availableCurrencies[this.state.selectedCurrencyIndex];this.state.currencyCode=s.code,this.state.currencySymbol=s.symbol}updateCode(e){const t=e.target;this.state.currencyCode=t.value,this.initAvailableCurrencies()}updateSymbol(e){const t=e.target;this.state.currencySymbol=t.value,this.initAvailableCurrencies()}updateSelectFormat(e){const t=e.target;this.state.selectedFormatIndex=parseInt(t.value,10)}apply(){this.env.model.dispatch("SET_FORMATTING_WITH_PIVOT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),format:this.selectedFormat})}initAvailableCurrencies(){this.state.selectedCurrencyIndex=0}getCommonFormat(){const e=this.env.model.getters.getSelectedZones(),t=this.env.model.getters.getActiveSheetId(),s=e.map(e=>this.env.model.getters.getEvaluatedCellsInZone(t,e)).flat(),o=s[0].format;return s.every(e=>e.format===o)?o:void 0}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:"")}toggleAccountingFormat(){this.state.isAccountingFormat=!this.state.isAccountingFormat}getFormatExamples(){const e=this.selectedFormat,t=this.env.model.getters.getLocale();return[{label:fs("positive")+":",value:pn(1234.56,{format:e,locale:t})},{label:fs("negative")+":",value:pn(-1234.56,{format:e,locale:t})},{label:fs("zero")+":",value:pn(0,{format:e,locale:t})}]}get selectedFormat(){const e=this.formatProposals[this.state.selectedFormatIndex];return this.state.isAccountingFormat?e?.accountingFormat:e?.format}}class LH extends t.Component{static template="o-spreadsheet-DataValidationEditor";static components={SelectionInput:fM,SelectMenu:CM,Section:aM,ValidationMessages:JV};static props={rule:{type:Object,optional:!0},onExit:Function,onCloseSidePanel:{type:Function,optional:!0}};state=t.useState({rule:this.defaultDataValidationRule,errors:[]});editingSheetId;setup(){this.editingSheetId=this.env.model.getters.getActiveSheetId(),this.props.rule&&(this.state.rule={...this.props.rule,ranges:this.props.rule.ranges.map(e=>this.env.model.getters.getRangeString(e,this.editingSheetId))},this.state.rule.criterion.type=this.props.rule.criterion.type)}onCriterionTypeChanged(e){this.state.rule.criterion.type=e}onRangesChanged(e){this.state.rule.ranges=e}onCriterionChanged(e){this.state.rule.criterion=e}changeRuleIsBlocking(e){const t=e.target.value;this.state.rule.isBlocking="true"===t}onSave(){if(this.state.rule){const e=this.env.model.dispatch("ADD_DATA_VALIDATION_RULE",this.dispatchPayload);e.isSuccessful?this.props.onExit():this.state.errors=e.reasons}}get dispatchPayload(){const e={...this.state.rule,ranges:void 0},t=this.env.model.getters.getLocale(),s=e.criterion,o=QT.get(s.type),i=s.values.slice(0,o.numberOfValues(s)).map(e=>e?.trim()).filter(e=>""!==e&&void 0!==e).map(e=>Jc(e,t));return e.criterion={...s,values:i},{sheetId:this.editingSheetId,ranges:this.state.rule.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.editingSheetId,e)),rule:e}}get dvCriterionMenuItems(){return SM(e=>this.onCriterionTypeChanged(e),mI)}get selectedCriterionName(){const e=this.state.rule.criterion.type;return QT.get(e).name}get defaultDataValidationRule(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones().map(t=>Tt(this.env.model.getters.getUnboundedZone(e,t)));return{id:this.env.model.uuidGenerator.smallUuid(),criterion:{type:"containsText",values:[""]},ranges:t}}get criterionComponent(){return bM.get(this.state.rule.criterion.type).component}get errorMessages(){return this.state.errors.map(e=>Ag.Errors[e]||Ag.Errors.Unexpected)}}class kH extends t.Component{static template="o-spreadsheet-DataValidationPreview";static props={onClick:Function,rule:Object};ref=t.useRef("dvPreview");setup(){AH(this.ref,this)}deleteDataValidation(){const 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:o,fillAlpha:.06}))}get rangesString(){const e=this.env.model.getters.getActiveSheetId();return this.props.rule.ranges.map(t=>this.env.model.getters.getRangeString(t,e)).join(", ")}get descriptionString(){return QT.get(this.props.rule.criterion.type).getPreview(this.props.rule.criterion,this.env.model.getters)}}class VH extends t.Component{static template="o-spreadsheet-DataValidationPanel";static props={onCloseSidePanel:Function};static components={DataValidationPreview:kH,DataValidationEditor:LH};state=t.useState({mode:"list",activeRule:void 0});onPreviewClick(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getDataValidationRule(t,e);s&&(this.state.mode="edit",this.state.activeRule=s)}addDataValidationRule(){this.state.mode="edit",this.state.activeRule=void 0}onExitEditMode(){this.state.mode="list",this.state.activeRule=void 0}localizeDVRule(e){if(!e)return e;return ah(e,this.env.model.getters.getLocale())}get validationRules(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getDataValidationRules(e)}}const UH="#8B008B";var HH;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(HH||(HH={}));class zH extends hv{mutators=["updateSearchOptions","updateSearchContent","searchFormulas","selectPreviousMatch","selectNextMatch","replace"];allSheetsMatches=[];activeSheetMatches=[];specificRangeMatches=[];currentSearchRegex=null;initialShowFormulaState;preserveSelectedMatchIndex=!1;irreplaceableMatchCount=0;isSearchDirty=!1;shouldFinalizeUpdateSelection=!1;notificationStore=this.get(jP);selectedMatchIndex=null;toSearch="";toReplace="";searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1,searchScope:"activeSheet",specificRange:void 0};constructor(e){super(e),this.initialShowFormulaState=this.model.getters.shouldShowFormulas(),this.searchOptions.searchFormulas=this.initialShowFormulaState;const t=e(ZP);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(HH.previous,{jumpToMatchSheet:!0,updateSelection:!0})}selectNextMatch(){this.selectNextCell(HH.next,{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;break;case"REPLACE_SEARCH":for(const 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}}finalize(){this.isSearchDirty&&(this.refreshSearch({jumpToMatchSheet:!1,updateSelection:this.shouldFinalizeUpdateSelection}),this.shouldFinalizeUpdateSelection=!1,this.isSearchDirty=!1)}get allSheetMatchesCount(){return this.allSheetsMatches.length}get activeSheetMatchesCount(){return this.activeSheetMatches.length}get specificRangeMatchesCount(){return this.specificRangeMatches.length}_updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null),this.toSearch=e,this.currentSearchRegex=Xe(this.toSearch,this.searchOptions),this.refreshSearch({jumpToMatchSheet:!0,updateSelection:!0})}refreshSearch(e){this.preserveSelectedMatchIndex||(this.selectedMatchIndex=null),this.findMatches(),this.selectNextCell(HH.current,e)}getSheetsInSearchOrder(){switch(this.searchOptions.searchScope){case"allSheets":const 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":const s=this.searchOptions.specificRange;return s&&s?[s.sheetId]:[]}}findMatches(){const e=[];if(this.toSearch)for(const t of this.getters.getSheetIds())e.push(...this.findMatchesInSheet(t));if(this.allSheetsMatches=e,this.activeSheetMatches=e.filter(e=>e.sheetId===this.getters.getActiveSheetId()),this.searchOptions.specificRange){const{sheetId:t,zone:s}=this.searchOptions.specificRange;this.specificRangeMatches=e.filter(e=>e.sheetId===t&&kt(e.col,e.row,s))}else this.specificRangeMatches=[]}findMatchesInSheet(e){const t=[],{left:s,right:o,top:i,bottom:n}=this.getters.getSheetZone(e);for(let r=i;r<=n;r++)for(let i=s;i<=o;i++){const s=this.getters.isColHidden(e,i),o=this.getters.isRowHidden(e,r);if(s||o)continue;const n={sheetId:e,col:i,row:r};if(this.currentSearchRegex?.test(this.getSearchableString(n))){const s={sheetId:e,col:i,row:r};t.push(s)}}return t}selectNextCell(e,t){const s=this.searchMatches;if(!s.length)return void(this.selectedMatchIndex=null);let o;if(null===this.selectedMatchIndex){let e=-1;for(const t of this.getSheetsInSearchOrder())if(e=s.findIndex(e=>e.sheetId===t),-1!==e)break;o=e}else o=this.selectedMatchIndex+e;o=(o+s.length)%s.length,this.selectedMatchIndex=o;const i=s[o];t.jumpToMatchSheet&&this.getters.getActiveSheetId()!==i.sheetId&&(this.preserveSelectedMatchIndex=!0,this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:i.sheetId}),this.preserveSelectedMatchIndex=!1,this.isSearchDirty=!1),this.model.selection.getBackToDefault(),t.updateSelection&&this.model.selection.selectCell(i.col,i.row)}replace(){null!==this.selectedMatchIndex&&(this.preserveSelectedMatchIndex=!0,this.shouldFinalizeUpdateSelection=!0,this.model.dispatch("REPLACE_SEARCH",{searchString:this.toSearch,replaceWith:this.toReplace,matches:[this.searchMatches[this.selectedMatchIndex]],searchOptions:this.searchOptions}),this.preserveSelectedMatchIndex=!1)}replaceAll(){this.model.dispatch("REPLACE_SEARCH",{searchString:this.toSearch,replaceWith:this.toReplace,matches:this.searchMatches,searchOptions:this.searchOptions})}showReplaceWarningMessage(e,t){const s=e-t;0===s?this.notificationStore.notifyUser({type:"warning",sticky:!1,text:fs("Match(es) cannot be replaced as they are part of a formula.")}):this.notificationStore.notifyUser({type:"warning",sticky:!1,text:fs("%(replaceable_count)s match(es) replaced. %(irreplaceable_count)s match(es) cannot be replaced as they are part of a formula.",{replaceable_count:s,irreplaceable_count:t})})}replaceMatch(e,t,s,o){const i=this.getters.getCell(e);if(!i?.content)return;if(i?.isFormula&&!o.searchFormulas)return void this.irreplaceableMatchCount++;const n=Xe(t,o),r=new RegExp(n.source,n.flags+"g"),a=Kc(this.getters.getCellText(e,{showFormula:o.searchFormulas}).replace(r,s),this.getters.getLocale());this.model.dispatch("UPDATE_CELL",{...e,content:a})}getSearchableString(e){return this.getters.getCellText(e,{showFormula:this.searchOptions.searchFormulas})}get highlights(){const e=[],t=this.getters.getActiveSheetId();for(const[s,o]of this.searchMatches.entries()){if(o.sheetId!==t)continue;const i=Zt(o),n=this.getters.expandZone(t,i),{width:r,height:a}=this.getters.getVisibleRect(n);r>0&&a>0&&e.push({range:this.model.getters.getRangeFromZone(t,n),color:UH,noBorder:s!==this.selectedMatchIndex,thinLine:!0,fillAlpha:.2})}if("specificRange"===this.searchOptions.searchScope){const s=this.searchOptions.specificRange;s&&s.sheetId===t&&e.push({range:s,color:UH,noFill:!0,thinLine:!0})}return e}}class BH extends t.Component{static template="o-spreadsheet-FindAndReplacePanel";static components={SelectionInput:fM,Section:aM,Checkbox:IM,ValidationMessages:JV};static props={onCloseSidePanel:Function};searchInput=t.useRef("searchInput");store;state;updateSearchContent;get hasSearchResult(){return null!==this.store.selectedMatchIndex}get searchOptions(){return this.store.searchOptions}get allSheetsMatchesCount(){return fs("%s matches in all sheets",this.store.allSheetMatchesCount)}get currentSheetMatchesCount(){return fs("%(matches)s matches in %(sheetName)s",{matches:this.store.activeSheetMatchesCount,sheetName:this.env.model.getters.getSheetName(this.env.model.getters.getActiveSheetId())})}get specificRangeMatchesCount(){const e=this.searchOptions.specificRange;if(!e)return"";const{sheetId:t,zone:s}=e;return fs("%(matches)s matches in range %(range)s of %(sheetName)s",{matches:this.store.specificRangeMatchesCount,range:Tt(s),sheetName:this.env.model.getters.getSheetName(t)})}get searchInfo(){return this.store.toSearch?[this.specificRangeMatchesCount,this.currentSheetMatchesCount,this.allSheetsMatchesCount]:[]}setup(){this.store=tv(zH),this.state=t.useState({dataRange:""}),t.onMounted(()=>this.searchInput.el?.focus()),t.onWillUnmount(()=>this.updateSearchContent.stopDebounce()),this.updateSearchContent=De(this.store.updateSearchContent,200),t.useExternalListener(window,"keydown",e=>{const t=ky(e);"Ctrl+F"!==t&&"Ctrl+H"!==t||(this.searchInput.el?.focus(),e.preventDefault(),e.stopPropagation())},{capture:!0})}onFocusSearch(){this.updateDataRange()}onSearchInput(e){this.updateSearchContent(e.target.value)}onKeydownSearch(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),e.shiftKey?this.store.selectPreviousMatch():this.store.selectNextMatch())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),this.store.replace())}searchFormulas(e){this.store.searchFormulas(e)}searchExactMatch(e){this.store.updateSearchOptions({exactMatch:e})}searchMatchCase(e){this.store.updateSearchOptions({matchCase:e})}changeSearchScope(e){const t=e.target.value;this.store.updateSearchOptions({searchScope:t})}onSearchRangeChanged(e){this.state.dataRange=e[0]}updateDataRange(){if(!this.state.dataRange||"specificRange"!==this.searchOptions.searchScope)return;const e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.dataRange);this.store.updateSearchOptions({specificRange:e})}get pendingSearch(){return this.updateSearchContent.isDebouncePending()}}const GH=qf([Zk,jk,Yk,Xk,Kk,Jk,Qk,eV,tV,Hk,zk,Bk,Gk,Wk,$k]);class WH extends t.Component{static template="o-spreadsheet-MoreFormatsPanel";static props={onCloseSidePanel:Function};get dateFormatsActions(){return GH}}class $H extends hv{pivotId;initialMeasure;mutators=["cancelMeasureDisplayEdition","updateMeasureDisplayType","updateMeasureDisplayField","updateMeasureDisplayValue"];measureDisplay;constructor(e,t,s){super(e),this.pivotId=t,this.initialMeasure=s,this.measureDisplay=s.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){const t=ae(this.model.getters.getPivotCoreDefinition(this.pivotId)),s=this.getMeasureIndex(this.initialMeasure.id,t),o={...t.measures[s],display:e};t.measures[s]=o;this.model.dispatch("UPDATE_PIVOT",{pivot:t,pivotId:this.pivotId}).isSuccessful&&(this.measureDisplay=e)}getMeasureDisplay(e,t,s){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||(t=this.fields[0]?.nameWithGranularity),{type:e,fieldNameWithGranularity:t};case"%_of":case"difference_from":case"%_difference_from":t||(t=this.fields[0]?.nameWithGranularity);const o=this.getPossibleValues(t);return void 0!==s&&o.find(e=>e.value===s)||(s=fI),{type:e,fieldNameWithGranularity:t,value:s??fI}}}getMeasureIndex(e,t){const s=t.measures.findIndex(t=>t.id===e);if(-1===s)throw new Error(`Measure with id ${e} not found in pivot.`);return s}get doesDisplayNeedsField(){return["%_of_parent_total","running_total","%_running_total","rank_asc","rank_desc"].includes(this.measureDisplay.type)||this.doesDisplayNeedsValue}get fields(){const e=this.getters.getPivot(this.pivotId).definition;return[...e.columns,...e.rows].map(e=>({...e,displayName:dp(e)}))}get doesDisplayNeedsValue(){return this.isDisplayValueDependant(this.measureDisplay)}isDisplayValueDependant(e){return["%_of","difference_from","%_difference_from"].includes(e.type)}get values(){const e=this.measureDisplay;return this.isDisplayValueDependant(e)?this.getPossibleValues(e.fieldNameWithGranularity):[]}getPossibleValues(e){const t=[{value:fI,label:fs("(previous)")},{value:vI,label:fs("(next)")}],s=this.fields.find(t=>t.nameWithGranularity===e);if(!s)return[];return[...t,...this.getters.getPivot(this.pivotId).getPossibleFieldValues(s)]}cancelMeasureDisplayEdition(){const e=ae(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})}}class qH extends t.Component{static template="o-spreadsheet-PivotMeasureDisplayPanel";static props={onCloseSidePanel:Function,pivotId:String,measure:Object};static components={Section:aM,Checkbox:IM,RadioSelection:BU};measureDisplayTypeLabels=_g.labels;measureDisplayDescription=_g.documentation;store;setup(){this.store=tv($H,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}))}}function ZH(e,t){const s=e.getActiveSheetId(),i=function(e,t){const s=[],o=e.getActiveSheetId();for(const i of e.getSheetViewVisibleCols())for(const n of e.getSheetViewVisibleRows()){const r={sheetId:o,col:i,row:n};t===e.getPivotIdFromPosition(r)&&s.push(r)}return s}(e,t);return es(i.map(Zt)).map(t=>({range:e.getRangeFromZone(s,t),noFill:!0,color:o}))}class jH extends t.Component{static template="o-spreadsheet-PivotDeferUpdate";static props={deferUpdate:Boolean,isDirty:Boolean,toggleDeferUpdate:Function,discard:Function,apply:Function};static components={Section:aM,Checkbox:IM};get deferUpdatesLabel(){return fs("Defer updates")}get deferUpdatesTooltip(){return fs("Changing the pivot definition requires to reload the data. It may take some time.")}}class YH extends t.Component{static template="o-spreadsheet-PivotCustomGroupsCollapsible";static props={pivotId:String,customField:Object,onCustomFieldUpdated:Function};static components={SidePanelCollapsible:DP,TextInput:TU,Checkbox:IM};get groups(){return this.props.customField.groups.sort((e,t)=>e.isOtherGroup||t.isOtherGroup?e.isOtherGroup?1:-1:0)}get hasOthersGroup(){return this.props.customField.groups.some(e=>e.isOtherGroup)}addOthersGroup(){if(this.hasOthersGroup)return;const e={name:pp(fs("Others"),this.props.customField),values:[],isOtherGroup:!0},t=[...this.props.customField.groups,e];this.updateCustomField({...this.props.customField,groups:t})}onDeleteGroup(e){const t=[...this.props.customField.groups];t.splice(e,1),this.updateCustomField({...this.props.customField,groups:t})}onRenameGroup(e,t){const s=ae(this.props.customField.groups),o=s[e];o&&(o.name=pp(t,this.props.customField),this.updateCustomField({...this.props.customField,groups:s}))}updateCustomField(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.props.onCustomFieldUpdated({customFields:{...t.customFields,[e.name]:e}})}}function XH(e,t,s,o){const i=[];e=e.toLowerCase();for(const n of e){const e=t.toLocaleLowerCase().indexOf(n);-1!==e&&(i.push({value:t.slice(0,e),color:""},{value:t[e],color:s,classes:[o]}),t=t.slice(e+1))}return i.push({value:t}),i.filter(e=>e.value)}class KH extends t.Component{static template="o-spreadsheet-AddDimensionButton";static components={Popover:DF,TextValueProvider:MP};static props={onFieldPicked:Function,fields:Array,slots:{type:Object,optional:!0}};buttonRef=t.useRef("button");popover=t.useState({isOpen:!1});search=t.useState({input:""});autoComplete;setup(){this.autoComplete=tv(YP),this.autoComplete.useProvider(this.getProvider()),t.useExternalListener(window,"click",e=>{e.target!==this.buttonRef.el&&(this.popover.isOpen=!1)}),xU({refName:"autofocus"})}getProvider(){return{proposals:this.proposals,autoSelectFirstProposal:!1,selectProposal:e=>{const t=this.props.fields.find(t=>t.string===e);t&&this.pickField(t)}}}get proposals(){let e;return e=this.search.input?tS(this.search.input,this.props.fields,e=>e.string):this.props.fields,e.map(e=>{const t=e.string;return{text:t,fuzzySearchKey:t,htmlContent:XH(this.search.input,t,g,"o-semi-bold")}})}get popoverProps(){const{x:e,y:t,width:s,height:o}=this.buttonRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:s,height:o},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":const t=this.autoComplete.provider?.proposals;1===t?.length&&this.autoComplete.provider?.selectProposal(t[0].text||"");const s=this.autoComplete.selectedProposal;this.autoComplete.provider?.selectProposal(s?.text||"");break;case"ArrowUp":case"ArrowDown":this.autoComplete.moveSelection("ArrowDown"===e.key?"next":"previous");break;case"Escape":this.popover.isOpen=!1}}}class JH extends t.Component{static template="o-spreadsheet-PivotDimension";static props={dimension:Object,onRemoved:{type:Function,optional:!0},onNameUpdated:{type:Function,optional:!0},slots:{type:Object,optional:!0}};static components={CogWheelMenu:FU,TextInput:TU};updateName(e){this.props.onNameUpdated?.(this.props.dimension,""===e||e.startsWith("=")?void 0:e)}}class QH extends t.Component{static template="o-spreadsheet-PivotDimensionGranularity";static props={dimension:Object,onUpdated:Function,availableGranularities:Set,allGranularities:Array};periods=Jg}class ez extends t.Component{static template="o-spreadsheet-PivotDimensionOrder";static props={dimension:Object,onUpdated:Function}}class tz extends t.Component{static template="o-spreadsheet-PivotMeasureEditor";static components={PivotDimension:JH,StandaloneComposer:JP};static props={definition:Object,measure:Object,onMeasureUpdated:Function,onRemoved:Function,generateMeasureId:Function,aggregators:Object,pivotId:String};getMeasureAutocomplete(){return e=this.props.definition,t=this.props.measure,{sequence:0,autoSelectFirstProposal:!0,getProposals(s){const o=e.measures.filter(e=>e!==t).map(e=>{const t=he(e.id);return{text:t,description:e.displayName,htmlContent:[{value:t,color:x}],fuzzySearchKey:e.displayName+t+e.fieldName}}),i=e.rows.concat(e.columns).map(e=>{const t=he(e.nameWithGranularity);return{text:t,description:e.displayName,htmlContent:[{value:t,color:x}],fuzzySearchKey:e.displayName+t+e.fieldName}});return o.concat(i)},selectProposal(e,t){let s=e.end;"SYMBOL"===e.type&&(s=e.start);const o=e.end;this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}};var e,t}updateMeasureFormula(e){this.props.onMeasureUpdated({...this.props.measure,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:"="===e[0]?e:"="+e}})}updateAggregator(e){this.props.onMeasureUpdated({...this.props.measure,aggregator:e,id:this.props.generateMeasureId(this.props.measure.fieldName,e)})}updateName(e,t){this.props.measure.computedBy&&t?this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t,id:this.props.generateMeasureId(t,this.props.measure.aggregator),fieldName:t}):this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t})}toggleMeasureVisibility(){this.props.onMeasureUpdated({...this.props.measure,isHidden:!this.props.measure.isHidden})}openShowValuesAs(){this.env.replaceSidePanel("PivotMeasureDisplayPanel",`pivot_key_${this.props.pivotId}`,{pivotId:this.props.pivotId,measure:this.props.measure})}getColoredSymbolToken(e){if("SYMBOL"!==e.type)return;const t=ce(e.value,"'");return this.props.definition.columns.some(e=>e.nameWithGranularity===t)||this.props.definition.rows.some(e=>e.nameWithGranularity===t)||this.props.definition.measures.some(e=>e.id===t&&e.id!==this.props.measure.id)?x:void 0}get isCalculatedMeasureInvalid(){return sE(this.props.measure.computedBy?.formula??"").isBadExpression}}class sz extends t.Component{static template="o-spreadsheet-PivotSortSection";static components={Section:aM};static props={definition:Object,pivotId:String};get hasValidSort(){const e=this.env.model.getters.getPivot(this.props.pivotId);return!!this.props.definition.sortedColumn&&gp(this.props.definition.sortedColumn,e)}get sortDescription(){const e="asc"===this.props.definition.sortedColumn?.order?fs("ascending"):fs("descending");return fs("Sorted on column (%(ascOrDesc)s):",{ascOrDesc:e})}get sortValuesAndFields(){const e=this.props.definition.sortedColumn;if(!e)return[];const t=this.env.model.getters.getPivot(this.props.pivotId),s=this.env.model.getters.getLocale(),o=[],i=[];for(const n of e.domain){o.push(n);const{value:e,format:r}=t.getPivotHeaderValueAndFormat(o),a=pn(e,{format:r,locale:s}),l=t.definition.getDimension(n.field);i.push({field:dp(l),value:a})}0===e.domain.length&&i.push({value:fs("Total")});const n=t.getMeasure(e.measure).displayName;return i.push({value:n,field:fs("Measure")}),i}}class oz extends t.Component{static template="o-spreadsheet-PivotLayoutConfigurator";static components={AddDimensionButton:KH,PivotDimension:JH,PivotDimensionOrder:ez,PivotDimensionGranularity:QH,PivotMeasureEditor:tz,PivotSortSection:sz,PivotCustomGroupsCollapsible:YH};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=t.useRef("pivot-dimensions");dragAndDrop=cM();AGGREGATORS=Yg;composerFocus;isDateOrDatetimeField=tp;setup(){this.composerFocus=ev(uv)}startDragAndDrop(e,t){if(0!==t.button||"SELECT"===t.target.tagName)return;const s=this.getDimensionElementsRects(),o=this.props.definition,{columns:i,rows:n}=o,r=[...i.map(e=>e.nameWithGranularity),"__rows_title__",...n.map(e=>e.nameWithGranularity)],a=i.concat(n),l=r.map((e,t)=>({id:e,size:s[t+1].height,position:s[t+1].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:l,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{const s=r.findIndex(t=>t===e);if(s===t)return;const o=[...r];o.splice(s,1),o.splice(t,0,e);const i=o.slice(0,o.indexOf("__rows_title__")),n=o.slice(o.indexOf("__rows_title__")+1);this.props.onDimensionsUpdated({columns:i.map(e=>a.find(t=>t.nameWithGranularity===e)).filter(Te),rows:n.map(e=>a.find(t=>t.nameWithGranularity===e)).filter(Te)})}})}getGranularitiesFor(e){return tp(e)?"date"===e.type?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(0!==t.button||"SELECT"===t.target.tagName||"INPUT"===t.target.tagName||"inactive"!==this.composerFocus.focusMode)return;const s=this.getDimensionElementsRects(),o=this.props.definition,{measures:i,columns:n,rows:r}=o,a=i.map(e=>e.id),l=3+n.length+r.length,c=a.map((e,t)=>({id:e,size:s[t+l].height,position:s[t+l].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{const s=a.findIndex(t=>t===e);if(s===t)return;const o=[...a];o.splice(s,1),o.splice(t,0,e),this.props.onDimensionsUpdated({measures:o.map(e=>i.find(t=>t.id===e)).filter(Te)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{const t=getComputedStyle(e),s=e.getBoundingClientRect();return{x:s.x,y:s.y,width:s.width+parseInt(t.marginLeft||"0")+parseInt(t.marginRight||"0"),height:s.height+parseInt(t.marginTop||"0")+parseInt(t.marginBottom||"0")}})}removeDimension(e){const{columns:t,rows:s}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:s.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){const{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){const{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:"asc"}])})}addRowDimension(e){const{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:"asc"}])})}addMeasureDimension(e){const{measures:t}=this.props.definition,s=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,s),fieldName:e,aggregator:s}])})}updateMeasure(e,t){const{measures:s}=this.props.definition,o={measures:s.map(s=>s.id===e.id?t:s)};this.props.definition.sortedColumn?.measure===e.id&&(o.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(o)}getMeasureId(e,t){const s=e.replaceAll("'","")+(t?`:${t}`:"");let o=s,i=2;for(;this.props.definition.measures.some(e=>e.id===o);)o=`${s}:${i}`,i++;return o}getDefaultMeasureAggregator(e){const t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:"count"}addCalculatedMeasure(){const{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,"sum"),fieldName:t,aggregator:"sum",computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:"=0"}}])})}getCustomField(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);return t.customFields?.[e.nameWithGranularity]}updateOrder(e,t){const{rows:s,columns:o}=this.props.definition;this.props.onDimensionsUpdated({rows:s.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,order:t||void 0}:s),columns:o.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,order:t||void 0}:s)})}updateGranularity(e,t){const{rows:s,columns:o}=this.props.definition;this.props.onDimensionsUpdated({rows:s.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,granularity:t}:s),columns:o.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,granularity:t}:s)})}getMeasureDescription(e){const t=e.display;if(!t||"no_calculations"===t.type)return"";const s=this.env.model.getters.getPivot(this.props.pivotId),o=[...s.definition.columns,...s.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=o?dp(o):"";return _g.descriptions[t.type](i)}getHugeDimensionErrorMessage(e){const t=this.env.model.getters.getPivot(this.props.pivotId).getPossibleFieldValues(e);return t.length>100?fs("This dimension contains a lot of values (%s), and might slow down the pivot table.",t.length):void 0}}class iz extends t.Component{static template="o-spreadsheet-PivotTitleSection";static components={CogWheelMenu:FU,Section:aM,TextInput:TU};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:fs("Flip axes"),icon:"o-spreadsheet-Icon.EXCHANGE",execute:this.props.flipAxis},{name:fs("Duplicate"),icon:"o-spreadsheet-Icon.COPY",execute:()=>this.duplicatePivot()},{name:fs("Delete"),icon:"o-spreadsheet-Icon.TRASH",execute:()=>this.delete()}]}get name(){return this.env.model.getters.getPivotName(this.props.pivotId)}get displayName(){return this.env.model.getters.getPivotDisplayName(this.props.pivotId)}duplicatePivot(){const e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),s=this.env.model.dispatch("DUPLICATE_PIVOT_IN_NEW_SHEET",{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t});let o;o=s.isSuccessful?fs("Pivot duplicated."):s.isCancelledBecause("PivotInError")?fs("Cannot duplicate a pivot in error."):fs("Pivot duplication failed.");const i=s.isSuccessful?"success":"danger";this.env.notifyUser({text:o,sticky:!1,type:i}),s.isSuccessful&&this.env.openSidePanel("PivotSidePanel",{pivotId:e})}delete(){this.env.askConfirmation(fs("Are you sure you want to delete this pivot?"),()=>{this.env.model.dispatch("REMOVE_PIVOT",{pivotId:this.props.pivotId})})}onNameChanged(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch("UPDATE_PIVOT",{pivotId:this.props.pivotId,pivot:{...t,name:e}})}}class nz extends hv{pivotId;mutators=["reset","deferUpdates","applyUpdate","discardPendingUpdate","update"];updatesAreDeferred;draft=null;notification=this.get(jP);alreadyNotified=!1;alreadyNotifiedForPivotSize=!1;constructor(e,t){super(e),this.pivotId=t,this.updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){if("UPDATE_PIVOT"===e.type)e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){const e=XD.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){const e=[{name:"__count",string:fs("Count"),type:"integer",aggregator:"sum"}],t=this.fields;for(const s in t){const o=t[s];o&&(XD.get(this.pivot.type).isMeasureCandidate(o)&&e.push(o))}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){const e=[],t=this.fields;for(const s in t){const o=t[s];o&&(XD.get(this.pivot.type).isGroupable(o)&&e.push(o))}const{columns:s,rows:o,measures:i}=this.definition,n=i.concat(o).concat(s).map(e=>e.fieldName),r=this.unusedGranularities;return e.filter(e=>tp(e)?!n.includes(e.name)||r[e.name].size>0:!n.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return XD.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return XD.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this.updatesAreDeferred=!0,this.draft=null}deferUpdates(e){!1===e&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this.updatesAreDeferred=e}applyUpdate(){if(this.draft){if(this.model.dispatch("UPDATE_PIVOT",{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot()){const e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:"info",text:fs("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})}const e=this.getters.getPivot(this.pivotId),t=e.isValid()?e.getExpandedTableStructure().numberOfCells:0;!this.alreadyNotifiedForPivotSize&&t>Q&&(this.alreadyNotifiedForPivotSize=!0,this.notification.notifyUser({type:"warning",text:yP(t,this.getters.getLocale()),sticky:!0}))}}discardPendingUpdate(){this.draft=null}update(e){const t=this.getters.getPivotCoreDefinition(this.pivotId),s={...t,...this.draft,...e},o={...s,columns:s.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:s.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:s.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display})),sortedColumn:this.shouldKeepSortedColumn(s)?s.sortedColumn:void 0};if(o.collapsedDomains){const{COL:e,ROW:t}=o.collapsedDomains;o.collapsedDomains={COL:e.filter(e=>this.areDomainFieldsValid(e,o.columns)),ROW:t.filter(e=>this.areDomainFieldsValid(e,o.rows))}}if(!this.draft&&Me(t,o))return;const i=this.addDefaultDateTimeGranularity(this.fields,o);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0;const t=this.getters.getPivotFormulaId(this.pivotId);for(const s of this.getters.getVisibleCellPositions()){const o=this.getters.getCell(s);if(o?.isFormula){const s=MD(o.compiledFormula.tokens),i=s?.args[0]?.value;if(s&&t===i.toString()){if("PIVOT"===s.functionName)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){const{columns:s,rows:o}=t,i=ae(s),n=ae(o),r=this.getUnusedGranularities(e,t);for(const t of i.concat(n)){const s=e[t.fieldName]?.type;if(("date"===s||"datetime"===s)&&!t.granularity){const e=r[t.fieldName]?.values().next().value||"year";r[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:n}}getUnusedGranularities(e,t){const{columns:s,rows:o,measures:i}=t,n=s.concat(o).concat(i).filter(t=>{const s=e[t.fieldName]?.type;return"date"===s||"datetime"===s}),r={};for(const t of n)r[t.fieldName]=new Set("date"===e[t.fieldName]?.type?this.dateGranularities:this.datetimeGranularities);for(const e of n)r[e.fieldName].delete(e.granularity||"month");return r}shouldKeepSortedColumn(e){const{sortedColumn:t}=e;if(!t)return!0;const s=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find(e=>e.id===t.measure)&&Me(s.columns,e.columns)}areDomainFieldsValid(e,t){const s=t.map(({fieldName:e,granularity:t})=>e+(t?`:${t}`:""));for(let t=0;t<e.length;t++)if(e[t].field!==s[t])return!1;return!0}}class rz extends t.Component{static template="o-spreadsheet-PivotSpreadsheetSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:oz,Section:aM,SelectionInput:fM,Checkbox:IM,PivotDeferUpdate:jH,PivotTitleSection:iz};store;state;pivotSidePanelRef=t.useRef("pivotSidePanel");setup(){this.store=tv(nz,this.props.pivotId),this.state=t.useState({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return(!this.store.isDirty||!this.state.rangeHasChanged)&&this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,"forceSheetReference")]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){const e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;const t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){const{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}}const az=new Og;az.add("SPREADSHEET",{editor:rz});class lz extends t.Component{static template="o-spreadsheet-PivotSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:oz,Section:aM};setup(){DH(this)}get sidePanelEditor(){const e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw new Error("pivotId does not correspond to a pivot.");return az.get(e.type).editor}get highlights(){return ZH(this.env.model.getters,this.props.pivotId)}}class cz extends t.Component{static template="o-spreadsheet-RemoveDuplicatesPanel";static components={ValidationMessages:JV,Section:aM,Checkbox:IM};static props={onCloseSidePanel:Function};state=t.useState({hasHeader:!1,columns:{}});setup(){this.updateColumns(),t.onWillUpdateProps(()=>this.updateColumns())}toggleHasHeader(){this.state.hasHeader=!this.state.hasHeader}toggleAllColumns(){const e=!this.isEveryColumnSelected;for(const t in this.state.columns)this.state.columns[t]=e}toggleColumn(e){this.state.columns[e]=!this.state.columns[e]}onRemoveDuplicates(){this.env.model.dispatch("REMOVE_DUPLICATES",{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()})}getColLabel(e){const t=parseInt(e);let s=fs("Column %s",it(t));if(this.state.hasHeader){const e=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSelectedZone().top,i=this.env.model.getters.getEvaluatedCell({sheetId:e,col:t,row:o});"empty"!==i.type&&(s+=` - ${i.value}`)}return s}get isEveryColumnSelected(){return Object.values(this.state.columns).every(e=>e)}get errorMessages(){const e=this.env.model.canDispatch("REMOVE_DUPLICATES",{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()}).reasons,t=new Set;for(const s of e)t.add(Tg.Errors[s]||Tg.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){const e=Ut(this.env.model.getters.getSelectedZone());return fs("%(row_count)s rows and %(column_count)s columns selected",{row_count:e.numberOfRows,column_count:e.numberOfCols})}get canConfirm(){return 0===this.errorMessages.length}updateColumns(){const e=this.env.model.getters.getSelectedZone(),t=this.state.columns,s={};for(let o=e.left;o<=e.right;o++)s[o]=!(o in t)||t[o];this.state.columns=s}getColsToAnalyze(){return Object.keys(this.state.columns).filter(e=>this.state.columns[e]).map(e=>parseInt(e))}}class hz extends t.Component{static template="o-spreadsheet-SettingsPanel";static components={Section:aM,ValidationMessages:JV,BadgeSelection:UU};static props={onCloseSidePanel:Function};loadedLocales=[];setup(){t.onWillStart(()=>this.loadLocales())}onLocaleChange(e){const t=this.loadedLocales.find(t=>t.code===e);t&&this.env.model.dispatch("UPDATE_LOCALE",{locale:t})}async loadLocales(){this.loadedLocales=(await this.env.loadLocales()).filter(e=>{const t=Xc(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t}).sort((e,t)=>e.name.localeCompare(t.name))}get numberFormatPreview(){return pn(1234567.89,{format:"#,##0.00",locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){const e=this.env.model.getters.getLocale();return pn(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){const e=this.env.model.getters.getLocale();return pn(1.6,{format:hh(e),locale:e})}get firstDayOfWeek(){const e=this.env.model.getters.getLocale().weekStart;return un[e%7]}get currentLocale(){return this.env.model.getters.getLocale()}get supportedLocales(){const e=this.currentLocale,t=this.loadedLocales.find(t=>t.code===e.code);if(!t)return[...this.loadedLocales,e].sort((e,t)=>e.name.localeCompare(t.name));if(!Me(e,t)){const s=this.loadedLocales.indexOf(t),o=[...this.loadedLocales];return o[s]=e,o.sort((e,t)=>e.name.localeCompare(t.name)),o}return this.loadedLocales}}const dz={SplitIsDestructive:fs("This will overwrite data in the subsequent columns. Split anyway?")};const uz=[{name:fs("Detect automatically"),value:"auto"},{name:fs("Custom separator"),value:"custom"},{name:fs("Space"),value:" "},{name:fs("Comma"),value:","},{name:fs("Semicolon"),value:";"},{name:fs("Line Break"),value:X}];class gz extends t.Component{static template="o-spreadsheet-SplitIntoColumnsPanel";static components={ValidationMessages:JV,Section:aM,Checkbox:IM};static props={onCloseSidePanel:Function};state=t.useState({separatorValue:"auto",addNewColumns:!1,customSeparator:""});setup(){const e=ev(uv);t.useEffect(e=>{"inactive"!==e&&this.props.onCloseSidePanel()},()=>[e.focusMode]),t.onMounted(()=>{e.activeComposer.stopEdition()})}onSeparatorChange(e){this.state.separatorValue=e}updateCustomSeparator(e){e.target&&(this.state.customSeparator=e.target.value)}updateAddNewColumnsCheckbox(e){this.state.addNewColumns=e}confirm(){(function(e,t,s){let o=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:s});return o.isCancelledBecause("SplitWillOverwriteContent")&&e.askConfirmation(dz.SplitIsDestructive,()=>{o=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:s,force:!0})}),o})(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){const e=this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(const s of e)switch(s){case"SplitWillOverwriteContent":case"EmptySplitSeparator":break;default:t.add(xg.Errors[s]||xg.Errors.Unexpected)}return Array.from(t)}get warningMessages(){const e=[];return this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes("SplitWillOverwriteContent")&&e.push(xg.Errors.SplitWillOverwriteContent),e}get separatorValue(){return"custom"===this.state.separatorValue?this.state.customSeparator:"auto"===this.state.separatorValue?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return uz}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}}function pz(e,t,s,o){e.resetTransform(),function(e,t,s,o){e.save();for(let i=0;i<5;i++)for(let n=0;n<5;n++)e.fillStyle=t.styles[i][n].fillColor||"#fff",e.fillRect(i*s,n*o,s,o);e.restore()}(e,t,s,o),function(e,t,s,o){e.save(),e.translate(0,.5),e.lineWidth=1;for(let i=0;i<5;i++)for(let n=0;n<5;n++){const r=t.borders[i][n];r.top&&(e.strokeStyle=r.top.color,e.beginPath(),e.moveTo(i*s,n*o),e.lineTo(i*s+s,n*o),e.stroke()),r.bottom&&(e.strokeStyle=r.bottom.color,e.beginPath(),e.moveTo(i*s,n*o+o),e.lineTo(i*s+s,n*o+o),e.stroke())}e.resetTransform(),e.translate(.5,0);for(let i=0;i<5;i++)for(let n=0;n<5;n++){const r=t.borders[i][n];r.left&&(e.strokeStyle=r.left.color,e.beginPath(),e.moveTo(i*s,n*o),e.lineTo(i*s,n*o+o),e.stroke()),r.right&&(e.strokeStyle=r.right.color,e.beginPath(),e.moveTo(i*s+s,n*o),e.lineTo(i*s+s,n*o+o+1),e.stroke())}e.restore()}(e,t,s,o),function(e,t,s,o){e.save(),e.translate(0,.5),e.lineWidth=1;const i=Math.floor(s/4),n=Math.floor(o/2);for(let r=0;r<5;r++)for(let a=0;a<5;a++)e.strokeStyle=t.styles[r][a].textColor||"#000",e.beginPath(),e.moveTo(r*s+i+1,a*o+n),e.lineTo(r*s+s-i,a*o+n),e.stroke();e.restore()}(e,t,s,o)}class mz extends t.Component{static template="o-spreadsheet-TableStylePreview";static components={MenuPopover:PF};static props={tableConfig:Object,tableStyle:Object,class:String,styleId:{type:String,optional:!0},selected:{type:Boolean,optional:!0},onClick:{type:Function,optional:!0}};canvasRef=t.useRef("canvas");menu=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});setup(){t.onWillUpdateProps(e=>{Me(this.props.tableConfig,e.tableConfig)&&Me(this.props.tableStyle,e.tableStyle)||this.drawTable(e)}),t.onMounted(()=>this.drawTable(this.props))}drawTable(e){const t=this.canvasRef.el.getContext("2d"),{width:s,height:o}=this.canvasRef.el.getBoundingClientRect();this.canvasRef.el.width=s,this.canvasRef.el.height=o;pz(t,AA(e.tableConfig,e.tableStyle,5,5),(s-1)/5,(o-1)/5)}onContextMenu(e){var t,s;this.props.styleId&&(this.menu.menuItems=(t=this.env,s=this.props.styleId,t.model.getters.isTableStyleEditable(s)?qf([{id:"editTableStyle",name:fs("Edit table style"),execute:e=>e.openSidePanel("TableStyleEditorPanel",{styleId:s}),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.EDIT"},{id:"deleteTableStyle",name:fs("Delete table style"),execute:e=>e.model.dispatch("REMOVE_TABLE_STYLE",{tableStyleId:s}),icon:"o-spreadsheet-Icon.TRASH"}]):[]),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.env.model.getters.getTableStyle(this.props.styleId).displayName:""}get isStyleEditable(){return!!this.props.styleId&&this.env.model.getters.isTableStyleEditable(this.props.styleId)}editTableStyle(){this.env.openSidePanel("TableStyleEditorPanel",{styleId:this.props.styleId})}}class fz extends t.Component{static template="o-spreadsheet-TableStylesPopover";static components={Popover:DF,TableStylePreview:mz};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0}};categories=cE;tableStyleListRef=t.useRef("tableStyleList");state=t.useState({selectedCategory:this.initialSelectedCategory});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!Dy(this.tableStyleListRef.el,e)&&(this.props.closePopover(),e.hasClosedTableStylesPopover=!0)}get displayedStyles(){const e=this.env.model.getters.getTableStyles();return Object.keys(e).filter(t=>e[t].category===this.state.selectedCategory)}get initialSelectedCategory(){return this.props.selectedStyleId?this.env.model.getters.getTableStyle(this.props.selectedStyleId).category:"medium"}newTableStyle(){this.props.closePopover(),this.env.openSidePanel("TableStyleEditorPanel",{onStylePicked:this.props.onStylePicked})}}class vz extends t.Component{static template="o-spreadsheet-TableStylePicker";static components={TableStylesPopover:fz,TableStylePreview:mz};static props={table:Object};state=t.useState({popoverProps:void 0});getDisplayedTableStyles(){const e=this.env.model.getters.getTableStyles(),t=e[this.props.table.config.styleId].category,s=Object.keys(e).filter(s=>e[s].category===t),o=s.indexOf(this.props.table.config.styleId);if(-1===o)return o;const i=4*Math.floor(o/4);return s.slice(i)}onStylePicked(e){const t=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("UPDATE_TABLE",{sheetId:t,zone:this.props.table.range.zone,config:{styleId:e}}),this.closePopover()}onArrowButtonClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps)return void this.closePopover();const t=e.currentTarget,{bottom:s,right:o}=t.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:o,y:s,width:0,height:0},positioning:"top-right",verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}}class bz extends t.Component{static template="o-spreadsheet-TablePanel";static components={TableStylePicker:vz,SelectionInput:fM,ValidationMessages:JV,Checkbox:IM,Section:aM};static props={onCloseSidePanel:Function,table:Object};state;setup(){const e=this.env.model.getters.getActiveSheetId();this.state=t.useState({tableZoneErrors:[],tableXc:this.env.model.getters.getRangeString(this.props.table.range,e),filtersEnabledIfPossible:this.props.table.config.hasFilters})}updateHasFilters(e){this.state.filtersEnabledIfPossible=e,this.updateTableConfig("hasFilters",e)}updateTableConfig(e,t){const s=this.env.model.getters.getActiveSheetId();return this.env.model.dispatch("UPDATE_TABLE",{sheetId:s,zone:this.props.table.range.zone,config:{[e]:t}})}updateHasHeaders(e){const t=e?1:0;this.updateNumberOfHeaders(t)}updateTableIsDynamic(e){const t=e?"dynamic":"forceStatic";if(t===this.props.table.type)return;const s=this.env.model.getters.getTable(RA(this.props.table));if(!s)return;const o=this.env.model.getters.getActiveSheetId(),i=this.env.model.dispatch("UPDATE_TABLE",{sheetId:o,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(s.range),tableType:t}),n=this.env.model.getters.getCoreTable(RA(this.props.table));if(i.isSuccessful&&n){const e=n.range;this.state.tableXc=this.env.model.getters.getRangeString(e,o),this.state.tableZoneErrors=[]}}onChangeNumberOfHeaders(e){const t=e.target,s=parseInt(t.value);this.updateNumberOfHeaders(s).isSuccessful||(t.value=this.props.table.config.numberOfHeaders.toString())}updateNumberOfHeaders(e){const t=e>0&&(this.tableConfig.hasFilters||this.state.filtersEnabledIfPossible);return this.env.model.dispatch("UPDATE_TABLE",{sheetId:this.env.model.getters.getActiveSheetId(),zone:this.props.table.range.zone,config:{numberOfHeaders:e,hasFilters:t}})}onRangeChanged(e){const t=this.env.model.getters.getActiveSheetId();this.state.tableXc=e[0];const s=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(s.zone)}).reasons}onRangeConfirmed(){const e=this.env.model.getters.getActiveSheetId();let t=this.env.model.getters.getRangeFromSheetXC(e,this.state.tableXc);if(1===Kt(t.zone)){const s=this.env.model.getters.getContiguousZone(e,t.zone);t=this.env.model.getters.getRangeFromZone(e,s)}const s=t.zone,o=this.props.table.range.zone,i=s.top===o.top&&s.left===o.left?"RESIZE_TABLE":"UPDATE_TABLE",n=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)}),r={sheetId:e,col:t.zone.left,row:t.zone.top},a=this.env.model.getters.getCoreTable(r);if(n.isSuccessful&&a){const t=RA(a);this.env.model.selection.selectZone({zone:Zt(t),cell:t});const s=a.range;this.state.tableXc=this.env.model.getters.getRangeString(s,e)}}deleteTable(){const e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("REMOVE_TABLE",{sheetId:e,target:[this.props.table.range.zone]})}getNewTableType(e){if("forceStatic"===this.props.table.type)return"forceStatic";const t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.canCreateDynamicTableOnZones(t,[e])?"dynamic":"static"}get tableConfig(){return this.props.table.config}get errorMessages(){return(this.state.tableZoneErrors||[]).map(e=>Dg.Errors[e]||Dg.Errors.Unexpected)}getCheckboxLabel(e){return Dg.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:Dg.Tooltips.filterWithoutHeader}get canBeDynamic(){const e=this.env.model.getters.getActiveSheetId();return"dynamic"===this.props.table.type||this.env.model.getters.canCreateDynamicTableOnZones(e,[this.props.table.range.zone])}get dynamicTableTooltip(){return Dg.Tooltips.isDynamic}}const Sz="#3C78D8";class Cz extends t.Component{static template="o-spreadsheet-TableStyleEditorPanel";static components={Section:aM,RoundColorPicker:lM,TableStylePreview:mz};static props={onCloseSidePanel:Function,onStylePicked:{type:Function,optional:!0},styleId:{type:String,optional:!0}};state=t.useState(this.getInitialState());setup(){t.useExternalListener(window,"click",()=>this.state.pickerOpened=!1)}getInitialState(){const e=this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId):null;return{pickerOpened:!1,primaryColor:e?.primaryColor||Sz,selectedTemplateName:e?.templateName||"lightColoredText",styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=Sv(e)?e:Sz,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){const e=this.props.styleId||this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch("CREATE_TABLE_STYLE",{tableStyleId:e,tableStyleName:this.state.styleName,templateName:this.state.selectedTemplateName,primaryColor:this.state.primaryColor}),this.props.onStylePicked?.(e),this.props.onCloseSidePanel()}onCancel(){this.props.onCloseSidePanel()}onDelete(){this.props.styleId&&(this.env.model.dispatch("REMOVE_TABLE_STYLE",{tableStyleId:this.props.styleId}),this.props.onCloseSidePanel())}get colorPreviewStyle(){return Ey({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(TE).filter(e=>"none"!==e)}get previewTableConfig(){return{bandedColumns:!1,bandedRows:!0,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,totalRow:!0,hasFilters:!0,styleId:""}}get selectedStyle(){return this.computeTableStyle(this.state.selectedTemplateName)}computeTableStyle(e){return AE(this.state.styleName,e,this.state.primaryColor)}}const yz=new Og;yz.add("ConditionalFormatting",{title:fs("Conditional formatting"),Body:PH}),yz.add("ChartPanel",{title:fs("Chart"),Body:xH,computeState:(e,t)=>{const s=e.getSelectedFigureId(),o=s?e.getChartIdFromFigureId(s):t.chartId;return o&&e.isChartDefined(o)?{isOpen:!0,props:{chartId:o}}:{isOpen:!1}}}),yz.add("FindAndReplace",{title:fs("Find and Replace"),Body:BH}),yz.add("CustomCurrency",{title:fs("Custom currency format"),Body:NH}),yz.add("SplitToColumns",{title:fs("Split text into columns"),Body:gz}),yz.add("Settings",{title:fs("Spreadsheet settings"),Body:hz}),yz.add("RemoveDuplicates",{title:fs("Remove duplicates"),Body:cz}),yz.add("DataValidation",{title:fs("Data validation"),Body:VH}),yz.add("DataValidationEditor",{title:fs("Data validation"),Body:LH}),yz.add("MoreFormats",{title:fs("More date formats"),Body:WH}),yz.add("TableSidePanel",{title:fs("Edit table"),Body:bz,computeState:e=>{const t=e.getFirstTableInSelection();if(!t)return{isOpen:!1};return{isOpen:!0,props:{table:e.getCoreTable(RA(t))},key:t.id}}}),yz.add("TableStyleEditorPanel",{title:fs("Create custom table style"),Body:Cz,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??"new"})}),yz.add("PivotSidePanel",{title:(e,t)=>fs("Pivot #%s",e.model.getters.getPivotFormulaId(t.pivotId)),Body:lz,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),yz.add("PivotMeasureDisplayPanel",{title:(e,t)=>{const s=e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id);return fs('Measure "%s" options',s.displayName)},Body:qH,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(e){return{isOpen:!1}}}}),yz.add("CarouselPanel",{title:fs("Carousel"),Body:PU,computeState:(e,t)=>{const s=t.figureId||e.getSelectedFigureId();return s&&e.doesCarouselExist(s)?{isOpen:!0,props:{figureId:s}}:{isOpen:!1}}});class Iz{mutators=["setSmallThreshhold"];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}}const wz=350,Ez=150;class Rz extends hv{mutators=["open","replace","toggle","close","changePanelSize","resetPanelSize","togglePinPanel","closeMainPanel","changeSpreadsheetWidth","toggleCollapsePanel"];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(Iz);get isMainPanelOpen(){return!(!this.mainPanel||!this.mainPanel.componentTag)&&this.computeState(this.mainPanel).isOpen}get isSecondaryPanelOpen(){return!(!this.secondaryPanel||!this.secondaryPanel.componentTag)&&this.computeState(this.secondaryPanel).isOpen}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){const t=this.computeState(e);return t.isOpen?t.props??{}:{}}getPanelKey(e){const t=this.computeState(e);if(t.isOpen)return t.key}open(e,t={}){if(this.screenWidthStore.isSmall)return;const s={initialPanelProps:t,componentTag:e,size:wz},o=this.computeState(s);if(!o.isOpen)return;if(!this.mainPanel||!this.mainPanel.isPinned||this.mainPanelKey===o.key)return void this._openPanel("mainPanel",s,o);const i=this.mainPanel.isCollapsed?wz:this.mainPanel.size;!this.secondaryPanel&&i+wz>this.availableWidth?this.get(jP).notifyUser({sticky:!1,type:"warning",text:fs("The window is too small to display multiple side panels.")}):this._openPanel("secondaryPanel",s,o)}replace(e,t,s={}){const o={initialPanelProps:s,componentTag:e,size:wz},i=this.computeState(o);if(!i.isOpen)return;const n=()=>{this.mainPanel?.isCollapsed&&this.toggleCollapsePanel("mainPanel")},r=this.mainPanelKey===i.key,a=this.secondaryPanelKey===i.key;if(r&&this.secondaryPanel)return this.close(),void n();if(a)return this.closeMainPanel(),this.togglePinPanel(),void n();const l=this.mainPanelKey===t?"mainPanel":"secondaryPanel";this._openPanel(l,o,i)}_openPanel(e,t,s){const o=this[e];o&&t.componentTag!==o.componentTag&&o.initialPanelProps?.onCloseSidePanel?.(),this[e]={initialPanelProps:s.props??{},componentTag:t.componentTag,size:o?.size||wz,isCollapsed:o?.isCollapsed||!1,isPinned:!(!o||!("isPinned"in o))&&o.isPinned},this[e].isCollapsed&&this.toggleCollapsePanel(e)}toggle(e,t){const s=this.mainPanel?.isPinned?this.secondaryPanel:this.mainPanel;s&&e===s.componentTag?this.close():this.open(e,t)}close(){this.mainPanel?.isPinned?this.secondaryPanel&&(this.secondaryPanel.initialPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0):(this.mainPanel?.initialPanelProps.onCloseSidePanel?.(),this.mainPanel=void 0)}closeMainPanel(){this.mainPanel?.initialPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel||void 0,this.secondaryPanel=void 0}changePanelSize(e,t){const s=this[e];if(!s||"isCollapsed"in s&&s.isCollapsed)return;t=Math.max(t,wz);let o="mainPanel"===e?this.secondaryPanel?.size||0:this.mainPanel?.size||0;t>this.availableWidth-o&&("mainPanel"===e&&this.secondaryPanel&&(this.secondaryPanel.size=Math.max(this.availableWidth-t,wz),o=this.secondaryPanel.size),t=Math.max(this.availableWidth-o,wz)),s.size=t}resetPanelSize(e){this[e]&&(this[e].size=wz)}togglePinPanel(){this.mainPanel&&(this.mainPanel.isPinned=!this.mainPanel.isPinned,!this.mainPanel.isPinned&&this.secondaryPanel&&(this.secondaryPanel?.initialPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel,this.secondaryPanel=void 0))}toggleCollapsePanel(e){const t=this[e];t&&(t.isCollapsed?(t.isCollapsed=!1,this.changePanelSize(e,wz)):(t.isCollapsed=!0,t.size=45))}computeState({componentTag:e,initialPanelProps:t}){const s=yz.get(e).computeState,o=s?s(this.getters,t):{isOpen:!0,props:t};return o.isOpen?{...o,key:o.key||e}:o}changeSpreadsheetWidth(e){this.availableWidth=e-Ez,this.secondaryPanel&&e-this.totalPanelSize<Ez&&(this.secondaryPanel?.initialPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0),this.mainPanel&&e-this.totalPanelSize<Ez&&(this.mainPanel.size=Math.max(e-Ez,wz))}}class xz extends t.Component{static template="o-spreadsheet-TableResizer";static props={table:Object};state=t.useState({highlightZone:void 0});dragNDropGrid=VV(this.env);setup(){DH(this)}get containerStyle(){const e=this.props.table.range.zone,t={...e,left:e.right,top:e.bottom},s=this.env.model.getters.getVisibleRect(t);return 0===s.height||0===s.width?Ey({display:"none"}):Ey({top:s.y+s.height-6+"px",left:s.x+s.width-6+"px"})}onMouseDown(e){const t=this.props.table.range.zone,s={col:t.left,row:t.top};document.body.style.cursor="nwse-resize";this.dragNDropGrid.start(e,(e,t,o)=>{this.state.highlightZone={left:s.col,top:s.row,right:Math.max(e,s.col),bottom:Math.max(t,s.row)}},()=>{document.body.style.cursor="";const e=this.state.highlightZone;if(!e)return;const t=this.props.table.range.sheetId;this.env.model.dispatch("RESIZE_TABLE",{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0})}get highlights(){return this.state.highlightZone?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:"#777",noFill:!0}]:[]}}const Tz={ROW:NV,COL:DV,CELL:vk,GROUP_HEADERS:PV,UNGROUP_HEADERS:MV};class Az extends t.Component{static template="o-spreadsheet-Grid";static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:qV,GridOverlay:rU,GridPopover:aU,HeadersOverlay:gU,MenuPopover:PF,Autofill:HV,ClientTag:BV,Highlight:CU,Popover:DF,VerticalScrollBar:EU,HorizontalScrollBar:wU,TableResizer:xz,Selection:RU};HEADER_HEIGHT=A;HEADER_WIDTH=D;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=VV(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=ev(ZP),this.menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.hoveredCell=ev(HF),this.composerFocusStore=ev(uv),this.DOMFocusableElementStore=ev(OP),this.sidePanel=ev(Rz),this.paintFormatStore=ev(sU),this.clientFocusStore=ev(kV),ev(LV),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),t.useExternalListener(document.body,"cut",this.copy.bind(this,!0)),t.useExternalListener(document.body,"copy",this.copy.bind(this,!1)),t.useExternalListener(document.body,"paste",this.paste),t.onMounted(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),mU("canvas",this.env.model,()=>this.env.model.getters.getSheetViewDimensionWithHeaders()),this.onMouseWheel=vU((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=ev(wP),t.useEffect((e,t)=>{e||t||this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),fU(this.gridRef,this.moveCanvas.bind(this),()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){return Ey({top:"26px",left:"48px",height:"calc(100% - 41px)",width:"calc(100% - 63px)"})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>{this.env.model.getters.getActiveCell().type===_d.empty?this.onComposerCellFocused():this.onComposerContentFocused()},Tab:()=>this.env.model.selection.moveAnchorCell("right",1),"Shift+Tab":()=>this.env.model.selection.moveAnchorCell("left",1),F2:()=>{this.env.model.getters.getActiveCell().type===_d.empty?this.onComposerCellFocused():this.onComposerContentFocused()},Delete:()=>{this.env.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch("CLEAN_CLIPBOARD_HIGHLIGHT")},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch("REQUEST_UNDO"),"Ctrl+Y":()=>this.env.model.dispatch("REQUEST_REDO"),F4:()=>this.env.model.dispatch("REQUEST_REDO"),"Ctrl+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>uN(this.env),"Alt+=":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:s}=this.env.model.getters.getSelection(),o=this.env.model.getters.getAutomaticSums(e,t,s.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&o.length<=1){const t=o[0]?.zone,s=t?this.env.model.getters.zoneToXC(e,o[0].zone):"",i=`=SUM(${s})`;this.onComposerCellFocused(i,{start:5,end:5+s.length})}else this.env.model.dispatch("SUM_SELECTION")},"Alt+Enter":()=>{const e=this.env.model.getters.getActiveCell();e.link&&Wf(e.link,this.env)},"Ctrl+Home":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:s}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,s)},"Ctrl+End":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),s=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,s)},"Shift+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},s=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:s,zone:t})},"Ctrl+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},s=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:s,zone:t})},"Ctrl+D":async()=>this.env.model.dispatch("COPY_PASTE_CELLS_ABOVE"),"Ctrl+R":async()=>this.env.model.dispatch("COPY_PASTE_CELLS_ON_LEFT"),"Ctrl+H":()=>this.sidePanel.open("FindAndReplace",{}),"Ctrl+F":()=>this.sidePanel.open("FindAndReplace",{}),"Ctrl+Shift+E":()=>this.setHorizontalAlign("center"),"Ctrl+Shift+L":()=>this.setHorizontalAlign("left"),"Ctrl+Shift+R":()=>this.setHorizontalAlign("right"),"Ctrl+Shift+V":()=>rN(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{const e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),s=1===this.env.model.getters.getSelectedZones().length,o=e.size>0&&s,i=t.size>0&&s;o&&!i?hN(this.env):i&&!o&&cN(this.env)},"Ctrl+Alt+-":()=>{const e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&0===t.length?this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:"COL",elements:e}):t.length>0&&0===e.length&&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")},PageDown:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PageUp:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"Ctrl+K":()=>gN(this.env),"Alt+Shift+ArrowRight":()=>this.processHeaderGroupingKey("right"),"Alt+Shift+ArrowLeft":()=>this.processHeaderGroupingKey("left"),"Alt+Shift+ArrowUp":()=>this.processHeaderGroupingKey("up"),"Alt+Shift+ArrowDown":()=>this.processHeaderGroupingKey("down")};focusDefaultElement(){this.env.model.getters.getSelectedFigureId()||"inactive"!==this.composerFocusStore.activeComposer.editionMode||this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw new Error("Grid el is not defined.");return this.gridRef.el}getAutofillPosition(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-4,top:t.y+t.height-4}}get isAutofillVisible(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(0===t.width||0===t.height)}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t-D,height:e-A,gridOffsetX:D,gridOffsetY:A})}moveCanvas(e,t){const{scrollX:s,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s+e,offsetY:o+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(){return{...Oy(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,s,o){if(o.preventDefault(),"editing"===this.composerFocusStore.activeComposer.editionMode&&this.composerFocusStore.activeComposer.stopEdition(),s.expandZone?this.env.model.selection.setAnchorCorner(e,t):s.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t),this.env.isMobile())return;let i=e,n=t;this.dragNDropGrid.start(o,(e,t,s)=>{s.preventDefault(),(e!==i&&-1!==e||t!==n&&-1!==t)&&(i=-1===e?i:e,n=-1===t?n:t,this.env.model.selection.setAnchorCorner(i,n))},()=>{this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){const s=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:s,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:s,col:e,row:t}).type===_d.empty?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),PP(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){const t=ky(e),s=this.keyDownMapping[t];if(s)return e.preventDefault(),e.stopPropagation(),void s();" "!==t?e.key.startsWith("Arrow")&&this.processArrows(e):this.processSpaceKey(e)}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:s,top:o}=t;let i="CELL";this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(s)?i="COL":this.env.model.getters.getActiveRows().has(o)&&(i="ROW");const{x:n,y:r,width:a}=this.env.model.getters.getVisibleRect(t),l=this.getGridRect();this.toggleContextMenu(i,l.x+n+a,l.y+r)}onCellRightClicked(e,t,{x:s,y:o}){const i=this.env.model.getters.getSelectedZones();let n="CELL";kt(e,t,i[i.length-1])?this.env.model.getters.getActiveCols().has(e)?n="COL":this.env.model.getters.getActiveRows().has(t)&&(n="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(n,s,o)}toggleContextMenu(e,t,s){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.anchorRect={x:t,y:s,width:0,height:0},this.menuState.menuItems=Tz[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement))return;if("inactive"!==this.composerFocusStore.activeComposer.editionMode)return;e?YN(this.env):this.env.model.dispatch("COPY");const s=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(s),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();const t=e.clipboardData;if(!t)return;const s=[...t.files]?.find(e=>S_.includes(e.type)),o={content:{[gI.PlainText]:t?.getData(gI.PlainText),[gI.Html]:t?.getData(gI.Html)}};s&&(o.content[s.type]=s);const i=this.env.model.getters.getSelectedZones(),n=this.env.model.getters.isCutOperation(),r=this.env.model.getters.getClipboardId(),a=w_(o.content),l=a.data?.clipboardId;r===l?tN(this.env,i):await sN(this.env,i,a),n&&await this.env.clipboard.write({[gI.PlainText]:""})}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(1!==this.env.model.getters.getSelectedZones().length)return;const t=this.env.model.getters.getActiveRows().size>0,s=this.env.model.getters.getActiveCols().size>0;s&&t?this.processHeaderGroupingEventOnWholeSheet(e):s?this.processHeaderGroupingEventOnHeaders(e,"COL"):t?this.processHeaderGroupingEventOnHeaders(e,"ROW"):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){const s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSelectedZone(),i="COL"===t?o.left:o.top,n="COL"===t?o.right:o.bottom;switch(e){case"right":this.env.model.dispatch("GROUP_HEADERS",{sheetId:s,dimension:t,start:i,end:n});break;case"left":this.env.model.dispatch("UNGROUP_HEADERS",{sheetId:s,dimension:t,start:i,end:n});break;case"down":this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:s,dimension:t,zone:o});break;case"up":this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:s,dimension:t,zone:o})}}processHeaderGroupingEventOnWholeSheet(e){const t=this.env.model.getters.getActiveSheetId();"up"===e?(this.env.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"ROW"}),this.env.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"COL"})):"down"===e&&(this.env.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"ROW"}),this.env.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"COL"}))}processHeaderGroupingEventOnGrid(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getSelectedZone();switch(e){case"down":this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"ROW",zone:s}),this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"COL",zone:s});break;case"up":this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"ROW",zone:s}),this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"COL",zone:s});break;case"right":{const{x:e,y:t,width:o}=this.env.model.getters.getVisibleRect(s),i=this.getGridRect();this.toggleContextMenu("GROUP_HEADERS",e+o+i.x,t+i.y);break}case"left":{if(!jN(this.env,"COL")&&!jN(this.env,"ROW"))return;const{x:e,y:t,width:o}=this.env.model.getters.getVisibleRect(s),i=this.getGridRect();this.toggleContextMenu("UNGROUP_HEADERS",e+o+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:"cellFocus"})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:"contentFocus"})}get staticTables(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(TA)}get displaySelectionHandler(){return this.env.isMobile()&&"inactive"===this.composerFocusStore.activeComposer.editionMode}}function Dz(e,t){const s=`"${t?`${e.name}:${t}`:e.name}"`,o=e.string!==e.name?e.string+s:s;return{text:s,description:e.string+(e.help?` (${e.help})`:""),htmlContent:[{value:s,color:ie.STRING}],fuzzySearchKey:o}}function _z(e){const t=e.functionContext?.args[0];if(t&&["STRING","NUMBER"].includes(t.type))return t.value}const Oz=new Og;Oz.add("SPREADSHEET",!1);class Fz extends t.Component{static template="o-spreadsheet-ClickableCellSortIcon";static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=ev(oU)}get style(){const e=this.env.model.getters.getCellComputedStyle(this.props.position);return Ey({color:e.textColor||I,"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){const t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?function(e,t){const s=Ev(t),o=Ev(e),i=s.a+o.a*(1-s.a);return wv({r:Math.round((s.r*s.a+o.r*o.a*(1-s.a))/i),g:Math.round((s.g*s.a+o.g*o.a*(1-s.a))/i),b:Math.round((s.b*s.a+o.b*o.a*(1-s.a))/i),a:i})}(e.fillColor||"#FFFFFF",t):e.fillColor||"#FFFFFF"}}class Pz extends t.Component{static template="o-spreadsheet-FullScreenFigure";static props={};static components={ChartFigure:LF};fullScreenFigureStore;ref=t.useRef("fullScreenFigure");spreadsheetRect=AF();figureRegistry=VF;setup(){this.fullScreenFigureStore=ev(EF);const e=ev(iS);let s;t.onWillUpdateProps(()=>{s!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+"-fullscreen"),s=this.figureUI?.id}),t.useEffect(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){"Escape"===e.key&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return VF.get(this.figureUI.tag).Component}}class Mz extends t.Component{static template="o_spreadsheet.PivotHTMLRenderer";static components={Checkbox:IM};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=t.useState({showMissingValuesOnly:!1});setup(){const e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;const e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){const t=this.pivot.getExpandedTableStructure().rows,s=[...t[e].values];if(s.length<=1)return[e];s.pop();const o=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(s));return[e].concat(this.addRecursiveRow(o))}buildColumnsMissing(e){const t=[];for(const e of this.data.columns){const s=[];for(const t in e)for(let o=0;o<e[t].span;o++)s.push(parseInt(t,10));t.push(s)}for(let s=t[t.length-1].length;s>=0;s--)if(!e.includes(s))for(const e of t)e.splice(s,1);const s=[];for(const e in t){const o=[];let i,n=1;for(let s=0;s<t[e].length;s++)i!==t[e][s]?(void 0!==i&&o.push(Object.assign({},this.data.columns[e][i],{span:n})),i=t[e][s],n=1):n++;void 0!==i&&o.push(Object.assign({},this.data.columns[e][i],{span:n})),s.push(o)}return s}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){const s=e.map(()=>[]);for(const o of t)for(const t in e)s[t].push(this.data.values[e[t]][o]);return s}getColumnsIndexes(){const e=new Set;for(let t=0;t<this.data.columns.length;t++){const s=[];for(let e=0;e<this.data.columns[t].length;e++)for(let o=0;o<this.data.columns[t][e].span;o++)s.push(this.data.columns[t][e]);for(let t=0;t<s.length;t++)s[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++){this.data.values[t].find(e=>e.isMissing)&&e.add(t)}return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){const e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(const s of this.data.values)s[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){const s=[];for(const o of t.columns){const t=[];for(const s of o){const o=[];for(let e=0;e<s.fields.length;e++)o.push({value:s.fields[e]},{value:s.values[e]});const i=this.pivot.parseArgsToPivotDomain(o),n=this.env.model.getters.getLocale();if("measure"===i.at(-1)?.field){const{value:o,format:r}=this.pivot.getPivotMeasureValue(Eo(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${sp(e,i).join(",")})`,value:pn(o,{format:r,locale:n}),span:s.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{const{value:o,format:r}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${sp(e,i).join(",")})`,value:pn(o,{format:r,locale:n}),span:s.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}s.push(t)}const o=s[s.length-1];return s[s.length-1]=o.map(e=>(e.isMissing||(e.style="color: #756f6f;"),e)),s}_buildRowHeaders(e,t){const s=[];for(const o of t.rows){const t=[];for(let e=0;e<o.fields.length;e++)t.push({value:o.fields[e]},{value:o.values[e]});const i=this.pivot.parseArgsToPivotDomain(t),{value:n,format:r}=this.pivot.getPivotHeaderValueAndFormat(i),a=this.env.model.getters.getLocale(),l={formula:`=PIVOT.HEADER(${sp(e,i).join(",")})`,value:pn(n,{format:r,locale:a}),isMissing:!this.tracker?.isHeaderPresent(i)};o.indent>1&&(l.style=`padding-left: ${o.indent-10}px`),s.push(l)}return s}_buildValues(e,t){const s=[];for(const o of t.columns.at(-1)||[]){const i=[],n=Eo(o.values[o.values.length-1]);for(const s of t.rows){const t=[];for(let e=0;e<s.fields.length;e++)t.push({value:s.fields[e]},{value:s.values[e]});for(let e=0;e<o.fields.length-1;e++)t.push({value:o.fields[e]},{value:o.values[e]});const r=this.pivot.parseArgsToPivotDomain(t),{value:a,format:l}=this.pivot.getPivotCellValueAndFormat(n,r),c=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${sp(e,r,n).join(",")})`,value:pn(a,{format:l,locale:c}),isMissing:!this.tracker?.isValuePresent(n,r)})}s.push(i)}return s}}class Nz{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,s="copyPaste"){}paste(e,t,s){}isPasteAllowed(e,t,s,o){return"Success"}isCutAllowed(e){return"Success"}getPasteTarget(e,t,s,o){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}}class Lz extends Nz{copy(e,t,s="copyPaste"){}pasteFromCopy(e,t,s,o){if(1===t.length)for(const i of I_(t,s))this.pasteZone(e,i.left,i.top,s,o);else for(const i of ft(t))for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++)this.pasteZone(e,t,n,s,o)}pasteZone(e,t,s,o,i){}}class kz extends Lz{isCutAllowed(e){return 1!==e.zones.length?"WrongCutSelection":"Success"}copy(e,t,s="copyPaste"){const o=e.sheetId,{clippedZones:i,rowsIndexes:n,columnsIndexes:r}=e,a=[],l=1===n.length&&1===r.length;for(const t of n){const i=[];for(const a of r){const c={col:a,row:t,sheetId:o};let h=this.getters.getCell(c);const d=this.getters.getEvaluatedCell(c),u=this.getters.getPivotIdFromPosition(c),g=this.getters.getArrayFormulaSpreadingOn(c);if("shiftCells"!==s&&u&&g){const t=this.getters.getSpreadZone(g);if((!Me(g,c)||!l)&&t&&!e.zones.some(e=>Vt(t,e))){const e=this.getters.getPivotCellFromPosition(c),t=ip(this.getters.getPivotFormulaId(u),e);h={id:h?.id||"",style:h?.style,format:h?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if("shiftCells"!==s&&g&&!Me(g,c)){const e=n.includes(g.row)&&r.includes(g.col)?"":pn(d.value,{locale:this.getters.getLocale()});h={id:h?.id||"",style:h?.style,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:h?.content??"",style:h?.style,format:h?.format,tokens:h?.isFormula?h.compiledFormula.tokens.map(({value:e,type:t})=>({value:e,type:t})):[],border:this.getters.getCellBorder(c)||void 0,evaluatedCell:d,position:c})}a.push(i)}return{cells:a,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,s,o){if(!s.cells)return"Success";if(o?.isCutOperation&&void 0!==o?.pasteOption)return"WrongPasteOption";if(t.length>1&&(s.cells.length>1||s.cells[0].length>1))return"WrongPasteSelection";const i=s.cells.length,n=s.cells[0].length;for(const o of I_(t,s.cells))if(this.getters.doesIntersectMerge(e,o)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*n!==1))return"WillRemoveExistingMerge";return"Success"}paste(e,t,s){const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t,s):this.pasteFromCopy(i,o,t.cells,s)}getPasteTarget(e,t,s,o){const i=s.cells[0].length,n=s.cells.length;return o?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+n-1}]}:1===i&&1===n?{zones:[],sheetId:e}:{sheetId:e,zones:I_(t,s.cells)}}pasteFromCut(e,t,s,o){this.clearClippedZones(s);const i=t[0];this.pasteZone(e,i.left,i.top,s.cells,o)}clearClippedZones(e){this.dispatch("CLEAR_CELLS",{sheetId:e.sheetId,target:e.zones}),this.dispatch("CLEAR_FORMATTING",{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){if(!a)continue;const r={col:t+o,row:s+n,sheetId:e};this.pasteCell(a,r,i)}}pasteCell(e,t,s){const{sheetId:o,col:i,row:n}=t,r=this.getters.getEvaluatedCell(t),a=e?.format||e.evaluatedCell.format;if("asValue"===s?.pasteOption)return void this.dispatch("UPDATE_CELL",{...t,content:e.evaluatedCell.value?.toString()||"",format:a});if("onlyFormat"===s?.pasteOption)return void this.dispatch("UPDATE_CELL",{...t,style:e?.style??null,format:a??r.format});let l=e?.content;e?.tokens&&e.tokens.length>0&&!s?.isCutOperation?l=this.getters.getTranslatedCellFormula(o,i-e.position.col,n-e.position.row,e.tokens):e?.tokens&&e.tokens.length>0&&(l=this.getters.getFormulaMovedInSheet(e.position.sheetId,o,e.tokens)),""!==l||e?.format||e?.style?this.dispatch("UPDATE_CELL",{...t,content:l,style:e?.style||null,format:e?.format}):r&&this.dispatch("CLEAR_CELL",t)}convertTextToClipboardData(e){const t=this.getters.getLocale(),s={cells:[]},o=[];let i=0;for(const[t,s]of e.replace(/\r/g,"").split("\n").entries())o.push(s.split("\t")),o[t].length>i&&(i=o[t].length);for(const e of o){const o=[];for(let s=0;s<i;s++){const i=eh(e[s]||"",t);o.push({content:i,evaluatedCell:{formattedValue:i}})}s.cells.push(o)}return s}}function Vz(e,t){for(let s=0;s<t.length;s++){const o=t[s].proposalValues;if(void 0===o||0===o.length)continue;const i=t=>{const i=t.functionContext;if(!i||i.parent.toUpperCase()!==e.toUpperCase()||i.argPosition!==s)return;const n=[];let r="";for(const{value:e,label:t}of o){switch(typeof e){case"string":r=`"${e}"`;break;case"number":r=e.toString();break;case"boolean":r=e?"TRUE":"FALSE"}n.push({text:r,description:t,htmlContent:[{value:r,color:"string"==typeof e?ie.STRING:ie.NUMBER}],fuzzySearchKey:r,alwaysExpanded:!0})}return n};$P.add(`${e}_function_${t[s].name}_argument_proposals`,{sequence:50,autoSelectFirstProposal:!0,selectProposal:Uz,getProposals:i})}}function Uz(e,t){let s=e.end;const o=e.end;["LEFT_PAREN","ARG_SEPARATOR"].includes(e.type)||(s=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}F_.add("data_cleanup",class extends Ir{allowDispatch(e){return"REMOVE_DUPLICATES"===e.type?this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique)):"Success"}handle(e){switch(e.type){case"REMOVE_DUPLICATES":this.removeDuplicates(e.columns,e.hasHeader);break;case"TRIM_WHITESPACE":this.trimWhitespace()}}removeDuplicates(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.getSelectedZone();t&&(o.top+=1);const i=this.getUniqueRowsIndexes(s,o.top,o.bottom,e),n=i.length;if(n===Ut(o).numberOfRows)return void this.notifyRowsRemovedAndRemaining(0,n);const r=i.map(e=>({left:o.left,top:e,right:o.right,bottom:e})),a=new kz(this.getters,this.dispatch),l=a.copy(C_(s,r),!1);if(!l)return;this.dispatch("CLEAR_CELLS",{target:[o],sheetId:s});const c={left:o.left,top:o.top,right:o.left,bottom:o.top};a.paste({zones:[c],sheetId:s},l,{isCutOperation:!1});const h={left:o.left,top:o.top-(t?1:0),right:o.right,bottom:o.top+n-1};this.selection.selectZone({cell:{col:h.left,row:h.top},zone:h});const d=o.bottom-o.top+1-n;this.notifyRowsRemovedAndRemaining(d,n)}getUniqueRowsIndexes(e,t,s,o){const i=new Map;for(const n of wC(t,s+1)){const t=o.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).value);!Object.values(i).some(e=>xC(e,t))&&(i[n]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:"info",text:fs("%s duplicate rows found and removed.\n%s unique rows remain.",e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return 1!==this.getters.getSelectedZones().length?"MoreThanOneRangeSelected":"Success"}checkNoMergeInZone(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?"WillRemoveExistingMerge":"Success"}checkRangeContainsValues(e){const t=this.getters.getActiveSheetId(),s=this.getters.getSelectedZone();e.hasHeader&&(s.top+=1);return this.getters.getEvaluatedCellsInZone(t,s).every(e=>"empty"===e.type)?"EmptyTarget":"Success"}checkNoColumnProvided(e){return 0===e.columns.length?"NoColumnsProvided":"Success"}checkColumnsIncludedInZone(e){const t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?"ColumnsNotIncludedInZone":"Success"}checkColumnsAreUnique(e){return e.columns.length!==new Set(e.columns).size?"DuplicatesColumnsSelected":"Success"}trimWhitespace(){const e=ft(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId();let s=0;for(const{col:o,row:i}of e.map(Bt).flat()){const e=this.getters.getCell({col:o,row:i,sheetId:t});if(!e)continue;const n=_C(e.content);n!==e.content&&(s+=1,this.dispatch("UPDATE_CELL",{sheetId:t,col:o,row:i,content:n}))}const o=s?fs("Trimmed whitespace from %s cells.",s):fs("No selected cells had whitespace trimmed.");this.ui.notifyUI({type:"info",text:o,sticky:!1})}}),$P.add("dataValidation",{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(ot(t))return[];if(!this.composer.currentEditedCell)return[];const s=this.composer.currentEditedCell,o=this.getters.getValidationRuleForCell(s);if(!o||"isValueInList"!==o.criterion.type&&"isValueInRange"!==o.criterion.type)return[];const i=this.composer.currentEditedCell.sheetId,n="isValueInRange"===o.criterion.type?this.getters.getDataValidationRangeValues(i,o.criterion):o.criterion.values.map(e=>({label:e,value:e}));if(!("chip"===o.criterion.displayStyle))return n.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));const r=o.criterion.colors;return n.map(e=>{const t=r?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:t?Pv(t):void 0,backgroundColor:t||C,classes:["badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start"]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t),this.composer.stopEdition()}}),$P.add("functions",{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if("SYMBOL"!==e.type)return[];const t=e.value;if(!ot(this.composer.currentContent))return[];const s=Object.entries(uf.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:s}])=>({text:e,description:s,htmlContent:XH(t,e,g,"o-semi-bold")})).sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text));return s},selectProposal(e,t){let s=e.end,o=e.end;["SYMBOL","FUNCTION"].includes(e.type)&&(s=e.start);const i=this.composer.currentTokens;t+="(";const n=i.map(e=>e.start).indexOf(e.start);if(n+1<i.length){const e=i[n+1];"LEFT_PAREN"===e?.type&&o++}this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}}),uf.getAll().forEach(e=>Vz(e.name,e.args)),$P.add("pivot_ids",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!["PIVOT.VALUE","PIVOT.HEADER","PIVOT"].includes(t.parent.toUpperCase())||0!==t.argPosition)return;const s=this.getters.getPivotIds();return s.includes(e.value)?void 0:s.map(e=>{const t=this.getters.getPivotCoreDefinition(e),s=`${this.getters.getPivotFormulaId(e)}`;return{text:s,description:t.name,htmlContent:[{value:s,color:ie.NUMBER}],fuzzySearchKey:s+t.name,alwaysExpanded:!0}}).filter(Te)},selectProposal:Uz}),$P.add("pivot_measures",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if("PIVOT.VALUE"!==t?.parent.toUpperCase()||1!==t.argPosition)return[];const s=_z(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return[];const i=this.getters.getPivot(o);return i.init(),i.isValid()?i.definition.measures.map(e=>{if("__count"===e.fieldName){const e='"__count"';return{text:e,description:fs("Count"),htmlContent:[{value:e,color:ie.STRING}],fuzzySearchKey:fs("Count")+e}}return function(e){const t=`"${e.id}"`,s=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:ie.STRING}],fuzzySearchKey:s}}(e)}).filter(Te):[]},selectProposal:Uz}),$P.add("pivot_group_fields",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!function(e){const t=e.functionContext;return"PIVOT.VALUE"===t?.parent.toUpperCase()&&t.argPosition>=2&&t.argPosition%2==0}(e)&&!function(e){const t=e.functionContext;return"PIVOT.HEADER"===t?.parent.toUpperCase()&&t.argPosition>=1&&t.argPosition%2==1}(e))return;const s=_z(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return;const i=this.getters.getPivot(o);i.init();const n=i.getFields(),{columns:r,rows:a}=i.definition;let l=t.args;"PIVOT.VALUE"===t?.parent.toUpperCase()?(l=l.filter((e,t)=>t%2==0),l=l.slice(1,t.argPosition)):l=l.filter((e,t)=>t%2==1);const c=l.map(e=>e?.value).filter(Te),h=r.map(e=>e.nameWithGranularity),d=a.map(e=>e.nameWithGranularity),u=[];let g=["ARG_SEPARATOR","SPACE"].includes(e.type)?c.at(-1):c.at(-2);const p=Oz.get(i.type);if(p&&g?.startsWith("#")&&(g=g.slice(1)),void 0===g&&(u.push(h[0]),u.push(d[0])),d.includes(g)){const e=d[d.indexOf(g)+1];u.push(e),u.push(h[0])}if(h.includes(g)){const e=h[h.indexOf(g)+1];u.push(e)}const m=u.filter(Te);return m.map(e=>{const[t,s]=e.split(":"),o=n[t];return o?Dz(o,s):void 0}).concat(m.map(e=>{if(!p)return;const t=e.split(":")[0],s=n[t];if(!s)return;const o=`"#${e}"`;return{text:o,description:fs("%s (positional)",s.string)+(s.help?` (${s.help})`:""),htmlContent:[{value:o,color:ie.STRING}],fuzzySearchKey:s.string+o}})).filter(Te)},selectProposal:Uz}),$P.add("pivot_group_values",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!e||!function(e){const t=e.functionContext;return"PIVOT.VALUE"===t?.parent.toUpperCase()&&t.argPosition>=2&&t.argPosition%2==1}(e)&&!function(e){const t=e.functionContext;return"PIVOT.HEADER"===t?.parent.toUpperCase()&&t.argPosition>=1&&t.argPosition%2==0}(e))return;const s=_z(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return;const i=this.getters.getPivot(o);if(!i.isValid())return;const n=t.argPosition,r=e.functionContext?.args[n-1]?.value;if(!r)return;let a;try{a=i.definition.getDimension(r)}catch(e){return}return"month_number"===a.granularity?Object.values(dn).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:ie.NUMBER}]})):"quarter_number"===a.granularity?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:fs("Quarter %s",e),htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"day_of_month"===a.granularity?ge(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"iso_week_number"===a.granularity?ge(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"day_of_week"===a.granularity?ge(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"hour_number"===a.granularity?ge(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"minute_number"===a.granularity?ge(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):"second_number"===a.granularity?ge(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ie.NUMBER}]})):i.getPossibleFieldValues(a).map(({value:e,label:t})=>{const s="string"==typeof e,o=s?`"${e}"`:e.toString(),i=t===e?"":t;return{text:o,description:i,htmlContent:[{value:o,color:s?ie.STRING:ie.NUMBER}],fuzzySearchKey:o+i}})},selectProposal:Uz}),$P.add("sheet_names",{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return"SYMBOL"===e.type||"UNKNOWN"===e.type&&e.value.startsWith("'")?this.getters.getSheetIds().map(e=>{const t=he(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith("'")?t:"'"+t}}):[]},selectProposal(e,t){const s=e.start,o=e.end;this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t+"!")}});const Hz=new Og;Hz.add("link",{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,s)=>Wf(t.model.getters.getEvaluatedCell(e).link,t,s),title:(e,t)=>{const s=t.getEvaluatedCell(e).link;return s?s.isExternal?fs("Go to url: %(url)s",{url:s.url}):fs("Go to %(label)s",{label:s.label}):""},sequence:5}),Hz.add("dashboard_pivot_sorting",{condition:(e,t)=>{if(!t.isDashboard())return!1;const s=t.getPivotCellFromPosition(e);return gk(t,e)&&"MEASURE_HEADER"===s.type},execute:(e,t)=>{pk(t,e,function(e,t){return zz[e.getPivotCellSortDirection(t)??"none"]}(t.model.getters,e))},component:Fz,componentProps:(e,t)=>({position:e,sortDirection:t.getPivotCellSortDirection(e)}),sequence:2});const zz={none:"asc",asc:"desc",desc:"none"};vD.add("filter_icon",(e,t)=>{if(e.isFilterHeader(t)){const s=e.isFilterActive(t),o=Iv(e.getCellComputedStyle(t).fillColor||"#fff")<.45;return{type:"filter_icon",svg:uR(s,o,!1),hoverSvg:uR(s,o,!0),priority:3,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const s=t.getStore(wP),o=s.persistentCellPopover;o.isOpen&&o.col===e.col&&o.row===e.row&&"FilterMenu"===o.type?s.close():s.open(e,"FilterMenu")}}}});const Bz=new Og;Bz.add("format_number_automatic",{..._k,id:"format_number_automatic",sequence:10}).add("format_number_plain_text",{...Ok,id:"format_number_plain_text",sequence:15,separator:!0}).add("format_number_number",{...Fk,id:"format_number_number",sequence:20}).add("format_number_percent",{...Mk,id:"format_number_percent",sequence:30,separator:!0}).add("format_number_currency",{...Nk,id:"format_number_currency",sequence:40}).add("format_number_accounting",{...kk,id:"format_number_accounting",sequence:45}).add("format_number_currency_rounded",{...Lk,id:"format_number_currency_rounded",sequence:50}).add("format_custom_currency",{...Uk,id:"format_custom_currency",sequence:60,separator:!0}).add("format_number_date",{...Hk,id:"format_number_date",sequence:70}).add("format_number_time",{...zk,id:"format_number_time",sequence:80}).add("format_number_date_time",{...Bk,id:"format_number_date_time",sequence:90}).add("format_number_duration",{...Gk,id:"format_number_duration",sequence:100,separator:!0}).add("more_formats",{...qk,id:"more_formats",sequence:120});const Gz=$e(e=>wn(e)?"date":e.includes("[$")?"currency":"number"),Wz={name:fs("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[e=>{const t=function(e){const t=new Set(Bz.getAll().map(t=>"function"==typeof t.format?t.format(e):t.format)),s=new Map;for(const o of e.model.getters.getSheetIds()){const i=e.model.getters.getEvaluatedCells(o);for(const e in i){const o=i[e];if(o.format&&!s.has(o.format)&&!t.has(o.format)){const e=Gz(o.format);"date"!==e&&"currency"!==e||s.set(o.format,Dk({descriptionValue:"currency"===e?1e3:Vk,format:o.format,name:o.format}))}}}return[...s.values()]}(e).map(e=>({...e,sequence:110}));return t.length>0&&(t[t.length-1].separator=!0),qf([...Bz.getAll(),...t])}]};const $z=new kM;$z.add("file",{name:fs("File"),sequence:10}).addChild("settings",["file"],{name:fs("Settings"),sequence:200,execute:e=>e.openSidePanel("Settings"),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.COG"}).add("edit",{name:fs("Edit"),sequence:20}).addChild("undo",["edit"],{...KN,sequence:10}).addChild("redo",["edit"],{...JN,sequence:20,separator:!0}).addChild("copy",["edit"],{...QN,sequence:30}).addChild("cut",["edit"],{...eL,sequence:40}).addChild("paste",["edit"],{...tL,sequence:50}).addChild("paste_special",["edit"],{...sL,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...oL,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{...iL,sequence:20}).addChild("edit_table",["edit"],{...vL,isVisible:mN,sequence:60}).addChild("find_and_replace",["edit"],{...nL,sequence:65,separator:!0}).addChild("delete",["edit"],{name:fs("Delete"),icon:"o-spreadsheet-Icon.TRASH",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...rL,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...aL,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...hL,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{...pL,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...mL,sequence:50}).addChild("edit_unhide_columns",["edit"],{...RN,sequence:80}).addChild("edit_unhide_rows",["edit"],{...AN,sequence:80}).add("view",{name:fs("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...DN,sequence:4}).addChild("freeze_panes",["view"],{..._N,sequence:5}).addChild("unfreeze_rows",["view","freeze_panes"],{...ON,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...FN,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...PN,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...MN,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...NN,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...LN,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...kN,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...VN,sequence:40}).addChild("group_headers",["view"],{name:fs("Group"),sequence:15,separator:!0,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",isVisible:vN}).addChild("group_columns",["view","group_headers"],{...BN,sequence:5}).addChild("ungroup_columns",["view","group_headers"],{...WN,isVisible:e=>jN(e,"COL"),sequence:10}).addChild("group_rows",["view","group_headers"],{...GN,sequence:15}).addChild("ungroup_rows",["view","group_headers"],{...$N,isVisible:e=>jN(e,"ROW"),sequence:20}).addChild("show",["view"],{name:fs("Show"),sequence:1,icon:"o-spreadsheet-Icon.SHOW"}).addChild("view_gridlines",["view","show"],{...UN,sequence:5}).addChild("view_formulas",["view","show"],{...zN,sequence:10}).addChild("view_irregularity_map",["view"],{...HN,sequence:40,separator:!0}).add("insert",{name:fs("Insert"),sequence:40}).addChild("insert_row",["insert"],{...yL,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...wL,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...xL,sequence:20}).addChild("insert_column",["insert"],{...TL,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...DL,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...FL,sequence:20}).addChild("insert_cell",["insert"],{...PL,sequence:30}).addChild("insert_cell_down",["insert","insert_cell"],{...ML,name:fs("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...NL,name:fs("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...KL,sequence:40,separator:!0}).addChild("insert_chart",["insert"],{...LL,sequence:50}).addChild("insert_carousel",["insert"],{...kL,sequence:51}).addChild("insert_pivot",["insert"],{...VL,sequence:52}).addChild("insert_image",["insert"],{...UL,sequence:55}).addChild("insert_table",["insert"],{...HL,sequence:57}).addChild("insert_function",["insert"],{...zL,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...BL,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...GL,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{...WL,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...$L,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...qL,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...ZL,sequence:50}).addChild("categories_function_list",["insert","insert_function"],()=>{const e=uf.content;return[...new Set(uf.getAll().filter(e=>!e.hidden).map(e=>e.category))].filter(Te).sort().map((t,s)=>{const o=Object.keys(e).filter(s=>e[s].category===t&&!e[s].hidden);return{name:t,children:JL(o)}})}).addChild("insert_link",["insert"],{...jL,separator:!0,sequence:70}).addChild("insert_checkbox",["insert"],{...YL,sequence:80}).addChild("insert_dropdown",["insert"],{...XL,separator:!0,sequence:90}).add("format",{name:fs("Format"),sequence:50}).addChild("format_number",["format"],{...Wz,name:fs("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{...iV,sequence:20}).addChild("format_italic",["format"],{...nV,sequence:30}).addChild("format_underline",["format"],{...rV,sequence:40}).addChild("format_strikethrough",["format"],{...aV,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...lV,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...cV,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...dV,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...uV,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...gV,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{...mV,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...fV,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{...vV,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...bV,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...CV,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...yV,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...IV,sequence:30}).addChild("format_cf",["format"],{...wV,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...EV,sequence:100,separator:!0}).add("data",{name:fs("Data"),sequence:60}).addChild("sort_range",["data"],{...bk,sequence:10,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...Sk,sequence:10}).addChild("sort_descending",["data","sort_range"],{...wk,sequence:20}).addChild("data_cleanup",["data"],{...Ck,sequence:15}).addChild("remove_duplicates",["data","data_cleanup"],{...yk,sequence:10}).addChild("trim_whitespace",["data","data_cleanup"],{...Ik,sequence:20}).addChild("split_to_columns",["data"],{...xk,sequence:20}).addChild("data_validation",["data"],{name:fs("Data Validation"),execute:e=>{e.openSidePanel("DataValidation")},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.DATA_VALIDATION",sequence:30,separator:!0}).addChild("add_remove_data_filter",["data"],{...Ek,sequence:40,separator:!0}).addChild("pivot_data_sources",["data"],e=>{const t=e.model.getters.getPivotIds().length;return e.model.getters.getPivotIds().map((s,o)=>{const i={get highlights(){return ZH(e.model.getters,s)}};return{id:`item_pivot_${e.model.getters.getPivotFormulaId(s)}`,name:e.model.getters.getPivotDisplayName(s),sequence:50+o/t,isReadonlyAllowed:!0,execute:e=>e.openSidePanel("PivotSidePanel",{pivotId:s}),isEnabled:e=>!e.isSmall,onStartHover:e=>e.getStore(ZP).register(i),onStopHover:e=>e.getStore(ZP).unRegister(i),icon:"o-spreadsheet-Icon.PIVOT",separator:o===e.model.getters.getPivotIds().length-1,secondaryIcon:e=>e.model.getters.isPivotUnused(s)?"o-spreadsheet-Icon.UNUSED_PIVOT_WARNING":void 0}})}).addChild("reinsert_dynamic_pivot",["data"],Tk).addChild("reinsert_static_pivot",["data"],Ak);const qz=[Zz,function(e,t){return"target"in t&&Array.isArray(t.target)?{...ae(t),target:e.getSelectedZones()}:t},Yz,function(e,t){return"ranges"in t?{...ae(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}];function Zz(e,t){return"sheetId"in t?{...ae(t),sheetId:e.getActiveSheetId()}:t}function jz(e,t){return"zone"in t?{...ae(t),zone:e.getSelectedZone()}:t}function Yz(e,t){if(!("row"in t)||!("col"in t))return t;const{col:s,row:o}=e.getActivePosition();return{...ae(t),col:s,row:o}}const Xz=new lr;function Kz(e,t){const s=e.getSelectedZone();return{...Zz(e,t),elements:"COL"===t.dimension?ge(s.left,s.right+1):ge(s.top,s.bottom+1)}}function Jz(e,t){const s=e.getSelectedZone();return{...ae(t),zone:s}}function Qz(e,t){const s=ae(t),o=e.getSelectedZone(),{top:i,bottom:n,left:r,right:a}=o;return"cols"in s?s.cols=ge(r,a+1):"rows"in s&&(s.rows=ge(i,n+1)),s}function eB(e,t){const s=e.getSelectedZone();return{...Zz(e,t),start:"COL"===t.dimension?s.left:s.top,end:"COL"===t.dimension?s.right:s.bottom}}function tB(e,t){let s=IC(t);for(const t of qz)s=t(e,s);return s}u_.add("UPDATE_CELL",tB),u_.add("CLEAR_CELL",tB),u_.add("CLEAR_CELLS",tB),u_.add("DELETE_CONTENT",tB),u_.add("ADD_MERGE",tB),u_.add("REMOVE_MERGE",tB),u_.add("SET_FORMATTING",tB),u_.add("CLEAR_FORMATTING",tB),u_.add("SET_BORDER",tB),u_.add("CREATE_TABLE",tB),u_.add("REMOVE_TABLE",tB),u_.add("HIDE_SHEET",tB),u_.add("ADD_COLUMNS_ROWS",function(e,t){const s=e.getActivePosition();return{...Zz(e,t),base:"COL"===t.dimension?s.col:s.row}}),u_.add("REMOVE_COLUMNS_ROWS",Kz),u_.add("HIDE_COLUMNS_ROWS",Kz),u_.add("RESIZE_COLUMNS_ROWS",Kz),u_.add("CREATE_SHEET",function(e,t){const s=ae(t);s.sheetId=Xz.smallUuid();const o=t.name||e.getSheet(e.getActiveSheetId()).name,i=o.match(/(.+?)\d*$/)?.[1]||o;return s.name=e.getNextSheetName(i),s}),u_.add("CREATE_FIGURE",function(e,t){const s=Yz(e,Zz(e,t));return s.figureId=Xz.smallUuid(),s}),u_.add("CREATE_CHART",function(e,t){const s=Xz.smallUuid();return{...Zz(e,t),figureId:s,chartId:s}}),u_.add("CREATE_IMAGE",function(e,t){return{...Zz(e,t),figureId:Xz.smallUuid()}}),u_.add("GROUP_HEADERS",eB),u_.add("UNGROUP_HEADERS",eB),u_.add("UNFOLD_HEADER_GROUPS_IN_ZONE",jz),u_.add("FOLD_HEADER_GROUPS_IN_ZONE",jz),g_.add("PASTE",function(e,t){return{type:"REPEAT_PASTE",pasteOption:ae(t.pasteOption),target:e.getSelectedZones()}}),g_.add("INSERT_CELL",Jz),g_.add("DELETE_CELL",Jz),g_.add("AUTORESIZE_COLUMNS",Qz),g_.add("AUTORESIZE_ROWS",Qz),g_.add("SORT_CELLS",function(e,t){const s=e.getSelectedZone();return{...Zz(e,t),col:s.left,row:s.top,zone:s}}),g_.add("SUM_SELECTION",tB),g_.add("SET_DECIMAL",tB),g_.add("DELETE_UNFILTERED_CONTENT",tB);const sB=new class extends Og{mapping={};uuidGenerator=new lr;replace(e,t){const s={...t,id:this.uuidGenerator.uuidv4()};return super.replace(e,s)}getAllOrdered(){return this.getAll().sort((e,t)=>e.sequence-t.sequence)}};class oB{fileStore;constructor(e){this.fileStore=e}async requestImage(){const e=await this.userImageUpload(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}async uploadFile(e){const t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}userImageUpload(){return new Promise((e,t)=>{const s=document.createElement("input");s.setAttribute("type","file"),s.setAttribute("accept","image/*"),s.addEventListener("change",async()=>{null===s.files||1!==s.files.length?t():e(s.files[0])}),s.click()})}getImageOriginalSize(e){return new Promise((t,s)=>{const o=new Image;o.addEventListener("load",()=>{const e={width:o.width,height:o.height};t(e)}),o.addEventListener("error",s),o.src=e})}}const iB=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];class nB extends t.Component{static template="o-spreadsheet-RippleEffect";static props={x:String,y:String,color:String,opacity:Number,duration:Number,width:Number,height:Number,offsetY:Number,offsetX:Number,allowOverflow:Boolean,onAnimationEnd:Function,style:String};rippleRef=t.useRef("ripple");setup(){let e;t.onMounted(()=>{const t=this.rippleRef.el;t&&t.animate&&(e=t.animate(iB,{duration:this.props.duration,easing:"ease-out"}),e.addEventListener("finish",this.props.onAnimationEnd))}),t.onWillUnmount(()=>{e?.removeEventListener("finish",this.props.onAnimationEnd)})}get rippleStyle(){const{x:e,y:t,width:s,height:o}=this.props;return Ey({transform:"scale(0)",left:e,top:t,"margin-left":`${-s/2+(this.props.offsetX||0)}px`,"margin-top":`${-o/2+(this.props.offsetY||0)}px`,width:`${s}px`,height:`${o}px`,background:this.props.color,"border-radius":"100%",opacity:`${this.props.opacity}`})}}class rB extends t.Component{static template="o-spreadsheet-Ripple";static props={color:{type:String,optional:!0},opacity:{type:Number,optional:!0},duration:{type:Number,optional:!0},ignoreClickPosition:{type:Boolean,optional:!0},width:{type:Number,optional:!0},height:{type:Number,optional:!0},offsetY:{type:Number,optional:!0},offsetX:{type:Number,optional:!0},allowOverflow:{type:Boolean,optional:!0},enabled:{type:Boolean,optional:!0},onAnimationEnd:{type:Function,optional:!0},slots:Object,class:{type:String,optional:!0}};static components={RippleEffect:nB};static defaultProps={color:"#aaaaaa",opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:""};childContainer=t.useRef("childContainer");state=t.useState({ripples:[]});currentId=1;onClick(e){if(!this.props.enabled)return;if(!this.childContainer.el)return;const t=this.getRippleChildRectInfo(),{x:s,y:o,width:i,height:n}=t,r=Math.max(i,n),a={x:e.clientX-s,y:e.clientY-o,width:this.props.width||2.85*r,height:this.props.height||2.85*r};this.state.ripples.push({rippleRect:a,id:this.currentId++})}getRippleStyle(){const e=this.childContainer.el;if(!e||1!==e.childElementCount||!e.firstElementChild)return"";const t=this.getRippleChildRectInfo();return Ey({top:t.marginTop+"px",left:t.marginLeft+"px",width:t.width+"px",height:t.height+"px"})}getRippleChildRectInfo(){const e=this.childContainer.el;if(!e)throw new Error("No child container element found");if(1!==e.childElementCount||!e.firstElementChild){return{...Fy(e),marginLeft:0,marginTop:0}}const t=e.firstElementChild,s=function(e){const t=window.getComputedStyle(e);return{top:parseInt(t.marginTop,10)||0,bottom:parseInt(t.marginBottom,10)||0,left:parseInt(t.marginLeft,10)||0,right:parseInt(t.marginRight,10)||0}}(t);return{...Fy(t),marginLeft:s.left,marginTop:s.top}}removeRipple(e){const t=this.state.ripples.findIndex(t=>t.id===e);-1!==t&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){const t=this.state.ripples.find(t=>t.id===e)?.rippleRect;if(!t)throw new Error("Cannot find a ripple with the id "+e);return{color:this.props.color,opacity:this.props.opacity,duration:this.props.duration,x:this.props.ignoreClickPosition?"50%":t.x+"px",y:this.props.ignoreClickPosition?"50%":t.y+"px",width:t.width,height:t.height,offsetX:this.props.offsetX||0,offsetY:this.props.offsetY||0,allowOverflow:this.props.allowOverflow||!1,style:this.getRippleStyle(),onAnimationEnd:()=>this.removeRipple(e)}}}class aB extends t.Component{static template="o-spreadsheet-BottomBarSheet";static props={sheetId:String,openContextMenu:Function,style:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0}};static components={Ripple:rB,ColorPicker:rM};static defaultProps={onMouseDown:()=>{},style:""};state=t.useState({isEditing:!1,pickerOpened:!1});sheetDivRef=t.useRef("sheetDiv");sheetNameRef=t.useRef("sheetNameSpan");editionState="initializing";DOMFocusableElementStore;setup(){t.onPatched(()=>{this.sheetNameRef.el&&this.state.isEditing&&"initializing"===this.editionState&&(this.editionState="editing",this.focusInputAndSelectContent())}),this.DOMFocusableElementStore=ev(OP),t.useExternalListener(window,"click",()=>this.state.pickerOpened=!1),t.useEffect(e=>{this.props.sheetId===e&&this.scrollToSheet()},()=>[this.env.model.getters.getActiveSheetId()])}focusInputAndSelectContent(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.sheetNameRef.el.focus();const e=window.getSelection();e&&this.sheetNameRef.el.firstChild&&e.setBaseAndExtent(this.sheetNameRef.el.firstChild,0,this.sheetNameRef.el.firstChild,this.sheetNameRef.el.textContent?.length||0)}scrollToSheet(){this.sheetDivRef.el?.scrollIntoView?.({behavior:"smooth",inline:"nearest"})}onFocusOut(){this.state.isEditing&&"initializing"!==this.editionState&&this.stopEdition()}onClick(){this.env.isMobile()&&this.activateSheet()}onMouseDown(e){this.env.isMobile()||(this.activateSheet(),this.props.onMouseDown(e))}activateSheet(){this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:this.props.sheetId}),this.scrollToSheet()}onDblClick(){this.env.model.getters.isReadonly()||this.startEdition()}onKeyDown(e){this.state.isEditing&&("Enter"===e.key&&(e.preventDefault(),this.stopEdition(),this.DOMFocusableElementStore.focus()),"Escape"===e.key&&(this.cancelEdition(),this.DOMFocusableElementStore.focus()))}onMouseEventSheetName(e){this.state.isEditing&&e.stopPropagation()}startEdition(){this.state.isEditing=!0,this.editionState="initializing"}stopEdition(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el.blur();const e=this.getInputContent()||"";!function(e,t,s,o){const i=e.model.dispatch("RENAME_SHEET",{sheetId:t,newName:s,oldName:e.model.getters.getSheetName(t)});i.reasons.includes("MissingSheetName")?e.raiseError(fs("The sheet name cannot be empty."),o):i.reasons.includes("DuplicatedSheetName")?e.raiseError(fs("A sheet with the name %s already exists. Please select another name.",s),o):i.reasons.includes("ForbiddenCharactersInSheetName")&&e.raiseError(fs("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",$.join(" ")),o)}(this.env,this.props.sheetId,e,()=>this.startEdition())}cancelEdition(){this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el?.blur(),this.setInputContent(this.sheetName)}onIconClick(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}onContextMenu(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}getInputContent(){return this.sheetNameRef.el?.textContent}setInputContent(e){this.sheetNameRef.el&&(this.sheetNameRef.el.textContent=e)}onColorPicked(e){this.state.pickerOpened=!1,this.env.model.dispatch("COLOR_SHEET",{sheetId:this.props.sheetId,color:e})}get colorPickerAnchorRect(){return Fy(this.sheetDivRef.el)}get contextMenuRegistry(){return function(e){const t=new kM;return t.add("delete",{..._M,sequence:10}).add("hide_sheet",{...LM,sequence:20}).add("duplicate",{...OM,sequence:30,separator:!0}).add("rename",{...FM(e),sequence:40}).add("change_color",{...PM(e),sequence:50,separator:!0}).add("move_right",{...MM,sequence:60}).add("move_left",{...NM,sequence:70}),t}({renameSheetCallback:()=>{this.scrollToSheet(),this.startEdition()},openSheetColorPickerCallback:()=>{this.state.pickerOpened=!0}})}get isSheetActive(){return this.env.model.getters.getActiveSheetId()===this.props.sheetId}get sheetName(){return this.env.model.getters.getSheetName(this.props.sheetId)}get sheetColorStyle(){return Ey({background:this.env.model.getters.getSheet(this.props.sheetId).color||""})}}const lB=[{name:fs("Sum"),types:[_d.number],compute:(e,t)=>Er([[e]],t)},{name:fs("Avg"),types:[_d.number],compute:(e,t)=>Ga([[e]],t)},{name:fs("Min"),types:[_d.number],compute:(e,t)=>Za([[e]],t).value},{name:fs("Max"),types:[_d.number],compute:(e,t)=>qa([[e]],t).value},{name:fs("Count"),types:[_d.number,_d.text,_d.boolean,_d.error],compute:e=>$a([[e]])},{name:fs("Count Numbers"),types:[_d.number,_d.text,_d.boolean,_d.error],compute:(e,t)=>Wa([[e]],t)}];class cB extends hv{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)})}handle(e){switch((cr.has(e.type)||"UPDATE_CELL"===e.type&&("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.statisticFnResults=this._computeStatisticFnResults())}handleEvent(){this.getters.isGridSelectionActive()&&(this.statisticFnResults=this._computeStatisticFnResults())}_computeStatisticFnResults(){const e=this.getters,t=e.getActiveSheetId(),s=[],o=ft(e.getSelectedZones(),[]),i=this.getters.getSheetSize(t).numberOfRows-1,n=this.getters.getSheetSize(t).numberOfCols-1;for(const r of o)for(let o=r.left;o<=(r.right??n);o++)for(let n=r.top;n<=(r.bottom??i);n++){if(e.isRowHidden(t,n)||e.isColHidden(t,o))continue;const i=e.getEvaluatedCell({sheetId:t,col:o,row:n});i.type!==_d.empty&&s.push(i)}const r=e.getLocale(),a={},l=$e(e=>{const t=e.split(",");return s.filter(e=>t.includes(e.type))});for(const e of lB){let t;const s=l(e.types.sort().join(","));s.length&&(t=Oe(()=>e.compute(s,r))),a[e.name]=t}return a}}class hB extends t.Component{static template="o-spreadsheet-BottomBarStatistic";static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:rB};selectedStatisticFn="";store;setup(){this.store=ev(cB),t.onWillUpdateProps(()=>{Object.values(this.store.statisticFnResults).every(e=>void 0===e)&&this.props.closeContextMenu()})}getSelectedStatistic(){if(!Object.values(this.store.statisticFnResults).every(e=>void 0===e))return""===this.selectedStatisticFn&&(this.selectedStatisticFn=Object.keys(this.store.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn)}listSelectionStatistics(e){const t=new kM;let s=0;for(const[e]of Object.entries(this.store.statisticFnResults))t.add(e,{name:()=>this.getComposedFnName(e),sequence:s,isReadonlyAllowed:!0,execute:()=>{this.selectedStatisticFn=e}}),s++;const o=e.currentTarget,{top:i,left:n,width:r}=o.getBoundingClientRect();this.props.openContextMenu(n+r,i,t)}getComposedFnName(e){const t=this.env.model.getters.getLocale(),s=this.store.statisticFnResults[e];return e+": "+(void 0!==s?pn(s(),{locale:t}):"__")}}class dB extends t.Component{static template="o-spreadsheet-BottomBar";static props={onClick:Function};static components={MenuPopover:PF,Ripple:rB,BottomBarSheet:aB,BottomBarStatistic:hB};bottomBarRef=t.useRef("bottomBar");sheetListRef=t.useRef("sheetList");dragAndDrop=cM();targetScroll=void 0;state=t.useState({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=t.useState({isOpen:!1,menuId:void 0,anchorRect:null,menuItems:[]});sheetList=this.getVisibleSheets();setup(){t.onWillUpdateProps(()=>{this.updateScrollState();const e=this.getVisibleSheets();Me(this.sheetList,e)||this.dragAndDrop.cancel(),this.sheetList=e})}clickAddSheet(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getSheetIds().findIndex(e=>e===t)+1,o=this.env.model.uuidGenerator.smallUuid(),i=this.env.model.getters.getNextSheetName(fs("Sheet"));this.env.model.dispatch("CREATE_SHEET",{sheetId:o,position:s,name:i}),this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map(e=>{const t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}})}clickListSheets(e){const t=new kM,s=this.env.model.getters.getActiveSheetId();let o=0;for(const e of this.env.model.getters.getSheetIds()){const i=this.env.model.getters.getSheet(e);t.add(e,{name:i.name,sequence:o,isReadonlyAllowed:!0,textColor:i.isVisible?void 0:"#808080",execute:t=>{this.env.model.getters.isSheetVisible(e)||this.env.model.dispatch("SHOW_SHEET",{sheetId:e}),t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:s,sheetIdTo:e})},isEnabled:e=>!e.model.getters.isReadonly()||i.isVisible,icon:i.color?"o-spreadsheet-Icon.SMALL_DOT_RIGHT_ALIGN":void 0,iconColor:i.color}),o++}const i=e.currentTarget,{left:n}=i.getBoundingClientRect(),r=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(n,r,"listSheets",t)}openContextMenu(e,t,s,o){this.menuState.isOpen=!0,this.menuState.menuId=s,this.menuState.menuItems=o.getMenuItems(),this.menuState.anchorRect={x:e,y:t,width:0,height:0}}onSheetContextMenu(e,t,s){const o=s.currentTarget,{top:i,left:n}=o.getBoundingClientRect();s.closedMenuId!==e?this.openContextMenu(n,i,e,t):this.closeMenu()}closeMenu(){this.menuState.isOpen=!1,this.menuState.menuId=void 0,this.menuState.menuItems=[],this.menuState.anchorRect=null}closeContextMenuWithId(e){this.menuState.menuId===e&&this.closeMenu()}onWheel(e){this.targetScroll=void 0;e.currentTarget.scrollLeft+=.5*e.deltaY}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll+this.sheetListWidth;this.scrollSheetListTo(Math.min(this.sheetListMaxScroll,t))}updateScrollState(){this.state.isSheetListScrollableLeft=this.sheetListCurrentScroll>0,this.state.isSheetListScrollableRight=this.sheetListCurrentScroll<this.sheetListMaxScroll}scrollSheetListTo(e){this.sheetListRef.el&&(this.targetScroll=e,this.sheetListRef.el.scrollTo({top:0,left:e,behavior:"smooth"}))}onSheetMouseDown(e,t){if(0!==t.button||this.env.model.getters.isReadonly())return;if(this.closeMenu(),this.env.isMobile())return;const s=this.getVisibleSheets(),o=this.getSheetItemRects(),i=s.map((e,t)=>({id:e.id,size:o[t].width,position:o[t].x}));this.dragAndDrop.start("horizontal",{draggedItemId:e,initialMousePosition:t.clientX,items:i,scrollableContainerEl:this.sheetListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const s=t-this.getVisibleSheets().findIndex(t=>t.id===e);e&&0!==s&&this.env.model.dispatch("MOVE_SHEET",{sheetId:e,delta:s})}getSheetStyle(e){return this.dragAndDrop.itemsStyle[e]||""}getSheetItemRects(){return Array.from(this.bottomBarRef.el.querySelectorAll(".o-sheet")).map(e=>e.getBoundingClientRect()).map(e=>({x:e.x,width:e.width-1,y:e.y,height:e.height}))}get sheetListCurrentScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollLeft:0}get sheetListWidth(){return this.sheetListRef.el?this.sheetListRef.el.clientWidth:0}get sheetListMaxScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollWidth-this.sheetListRef.el.clientWidth:0}}class uB extends hv{_clickableCells=t.markRaw({});_registryItems=t.markRaw(Hz.getAll().sort((e,t)=>e.sequence-t.sequence));handle(e){(cr.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this._clickableCells=t.markRaw({}),this._registryItems=t.markRaw(Hz.getAll().sort((e,t)=>e.sequence-t.sequence)))}getClickableItem(e){const{sheetId:t,col:s,row:o}=e,i=this._clickableCells,n=mt(s,o);if(i[t]||(i[t]={}),!(n in i[t])){const s=this.findClickableItem(e);i[t][n]=s}return i[t][n]}findClickableItem(e){const t=this.getters;for(const s of this._registryItems)if(s.condition(e,t))return s}get clickableCells(){const e=[],t=this.getters,s=t.getActiveSheetId();for(const o of this.getters.getVisibleCellPositions()){const i=this.getClickableItem(o);if(!i)continue;const n="function"==typeof i.title?i.title(o,t):i.title,r=t.expandZone(s,Zt(o));e.push({coordinates:t.getVisibleRect(r),position:o,action:i.execute,title:n||"",component:i.component,componentProps:i.componentProps?.(o,t)??{}})}return e}}class gB extends t.Component{static template="o-spreadsheet-SpreadsheetDashboard";static props={getGridSize:Function};static components={GridOverlay:rU,GridPopover:aU,Popover:DF,VerticalScrollBar:EU,HorizontalScrollBar:wU};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;gridRef;setup(){this.gridRef=t.useRef("grid"),this.hoveredCell=ev(HF),this.clickableCellsStore=ev(uB),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),mU("canvas",this.env.model,()=>this.env.model.getters.getSheetViewDimension()),this.onMouseWheel=vU((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=ev(wP),fU(this.gridRef,this.moveCanvas.bind(this),()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0})}get gridContainer(){const e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e),{end:s}=this.env.model.getters.getColDimensions(e,t);return Ey({"max-width":`${s}px`})}get gridOverlayDimensions(){return Ey({height:"100%",width:"100%"})}getCellClickableStyle(e){return Ey({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){return t.toRaw(this.clickableCellsStore.clickableCells)}selectClickableCell(e,t){const{position:s,action:o}=t;o(s,this.env,Hy(e))}onClosePopover(){this.cellPopovers.close()}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:0,gridOffsetY:0})}moveCanvas(e,t){const{scrollX:s,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s+e,offsetY:o+t})}getGridRect(){return{...Oy(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}}class pB extends t.Component{static template="o-spreadsheet-HeaderGroup";static props={group:Object,layerOffset:Number,openContextMenu:Function};toggleGroup(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group;OV(this.env,e,this.dimension,t,s)}get groupBoxStyle(){const e=this.groupBox;return Ey({top:`${e.groupRect.y}px`,left:`${e.groupRect.x}px`,width:`${e.groupRect.width}px`,height:`${e.groupRect.height}px`})}get groupButtonStyle(){return Ey({"background-color":this.isGroupFolded?"#333":"#fff",color:this.isGroupFolded?"#fff":"#333"})}get groupButtonIcon(){return this.isGroupFolded?"o-spreadsheet-Icon.PLUS":"o-spreadsheet-Icon.MINUS"}get isGroupFolded(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.group;return this.env.model.getters.isGroupFolded(e,this.dimension,t.start,t.end)}onContextMenu(e){const t=this.env.model.getters.getActiveSheetId(),s={x:e.clientX,y:e.clientY},o=this.props.group,i=function(e,t,s,o){const i=qf([{id:"toggle_group",name:e=>{const i=e.model.getters.getActiveSheetId(),n=e.model.getters.isGroupFolded(i,t,s,o);return fs(n?"ROW"===t?"Expand row group":"Expand column group":"ROW"===t?"Collapse row group":"Collapse column group")},execute:e=>{const i=e.model.getters.getActiveSheetId();OV(e,i,t,s,o)},icon:e=>{const i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,s,o)?"o-spreadsheet-Icon.EXPAND":"o-spreadsheet-Icon.COLLAPSE"}},{id:"remove_group",name:fs("ROW"===t?"Remove row group":"Remove column group"),execute:e=>{const i=e.model.getters.getActiveSheetId();e.model.dispatch("UNGROUP_HEADERS",{sheetId:i,dimension:t,start:s,end:o})},icon:"o-spreadsheet-Icon.TRASH",separator:!0}]);return[...i,...FV(e,t)]}(t,this.dimension,o.start,o.end);this.props.openContextMenu(s,i)}}class mB extends pB{dimension="ROW";get groupBorderStyle(){const e=this.groupBox;return 0===this.groupBox.groupRect.height?"":Ey({top:e.headerRect.height/2+"px",left:"calc(50% - 1px)",width:"30%",height:`calc(100% - ${e.headerRect.height/2}px)`,"border-left":"1px solid","border-bottom":e.isEndHidden?"":"1px solid"})}get groupHeaderStyle(){return Ey({width:"100%",height:`${this.groupBox.headerRect.height}px`})}get groupBox(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group,o=this.env.model.getters.getRowDimensions(e,t).start,i=this.env.model.getters.getRowDimensions(e,s).end;let n=0,r=A;if(0!==t){const s=this.env.model.getters.getRowDimensions(e,t-1);n=A+s.start,r=s.end-s.start}const a={x:this.props.layerOffset,y:n,width:F,height:r};return{headerRect:a,groupRect:{x:this.props.layerOffset,y:a.y,width:F,height:a.height+(i-o)},isEndHidden:this.env.model.getters.isRowHidden(e,s)}}}class fB extends pB{dimension="COL";get groupBorderStyle(){const e=this.groupBox;return 0===e.groupRect.width?"":Ey({top:"calc(50% - 1px)",left:e.headerRect.width/2+"px",width:`calc(100% - ${e.headerRect.width/2}px)`,height:"30%","border-top":"1px solid","border-right":e.isEndHidden?"":"1px solid"})}get groupHeaderStyle(){return Ey({width:`${this.groupBox.headerRect.width}px`,height:"100%"})}get groupBox(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group,o=this.env.model.getters.getColDimensions(e,t).start,i=this.env.model.getters.getColDimensions(e,s).end;let n=0,r=D;if(0!==t){const s=this.env.model.getters.getColDimensions(e,t-1);n=D+s.start,r=s.end-s.start}const a={x:n,y:this.props.layerOffset,width:r,height:F};return{headerRect:a,groupRect:{x:a.x,y:this.props.layerOffset,width:a.width+(i-o),height:F},isEndHidden:this.env.model.getters.isColHidden(e,s)}}}class vB extends t.Component{static template="o-spreadsheet-HeaderGroupContainer";static props={dimension:String,layers:Array};static components={RowGroup:mB,ColGroup:fB,MenuPopover:PF};menu=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});getLayerOffset(e){return e*F}onContextMenu(e){const t=this.env.model.getters.getActiveSheetId(),s={x:e.clientX,y:e.clientY},o=FV(t,this.props.dimension);this.openContextMenu(s,o)}openContextMenu(e,t){this.menu.isOpen=!0,this.menu.anchorRect={...e,width:0,height:0},this.menu.menuItems=t}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get groupComponent(){return"ROW"===this.props.dimension?mB:fB}get hasFrozenPane(){const e=this.env.model.getters.getMainViewportCoordinates();return"COL"===this.props.dimension?e.x>0:e.y>0}get scrollContainerStyle(){const{scrollX:e,scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo(),s={};return"COL"===this.props.dimension?s.left=-e-this.frozenPaneContainerSize+"px":s.top=-t-this.frozenPaneContainerSize+"px",Ey(s)}get frozenPaneContainerStyle(){const e={};return"COL"===this.props.dimension?e.width=`${this.frozenPaneContainerSize}px`:e.height=`${this.frozenPaneContainerSize}px`,Ey(e)}get frozenPaneContainerSize(){if(!this.hasFrozenPane)return 0;const e=this.env.model.getters.getMainViewportCoordinates();return"COL"===this.props.dimension?D+e.x:A+e.y}}class bB extends t.Component{static template="o-spreadsheet-SidePanel";static props={panelContent:Object,panelProps:Object,onCloseSidePanel:Function,onStartHandleDrag:Function,onResetPanelSize:Function,isPinned:{type:Boolean,optional:!0},onTogglePinPanel:{type:Function,optional:!0},onToggleCollapsePanel:{type:Function,optional:!0},isCollapsed:{type:Boolean,optional:!0}};spreadsheetRect=AF();getTitle(){const e=this.props.panelContent;return"function"==typeof e.title?e.title(this.env,this.props.panelProps):e.title}get pinInfoMessage(){return fs("Pin this panel to allow to open another side panel beside it.")}}class SB extends t.Component{static template="o-spreadsheet-SidePanels";static props={};static components={SidePanel:bB};sidePanelStore;spreadsheetRect=AF();setup(){this.sidePanelStore=ev(Rz),t.useEffect(()=>{this.sidePanelStore.mainPanel&&!this.sidePanelStore.isMainPanelOpen&&this.sidePanelStore.closeMainPanel(),this.sidePanelStore.secondaryPanel&&!this.sidePanelStore.isSecondaryPanelOpen&&this.sidePanelStore.close()},()=>[this.sidePanelStore.isMainPanelOpen,this.sidePanelStore.isSecondaryPanelOpen])}startHandleDrag(e,t){const s=document.body.style.cursor,o="mainPanel"===e?this.sidePanelStore.mainPanel:this.sidePanelStore.secondaryPanel;if(!o)return;const i=o.size,n=t.clientX;iM(t=>{document.body.style.cursor="col-resize";const s=i+n-t.clientX;this.sidePanelStore.changePanelSize(e,s)},()=>{document.body.style.cursor=s})}get mainPanelProps(){const e=this.sidePanelStore.mainPanelProps;if(this.sidePanelStore.mainPanel&&e)return{panelContent:yz.get(this.sidePanelStore.mainPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.closeMainPanel(),onTogglePinPanel:()=>this.sidePanelStore.togglePinPanel(),onStartHandleDrag:e=>this.startHandleDrag("mainPanel",e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize("mainPanel"),isPinned:this.sidePanelStore.mainPanel?.isPinned,onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel("mainPanel"),isCollapsed:this.sidePanelStore.mainPanel?.isCollapsed}}get secondaryPanelProps(){const e=this.sidePanelStore.secondaryPanelProps;if(this.sidePanelStore.secondaryPanel&&e)return{panelContent:yz.get(this.sidePanelStore.secondaryPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.close(),onStartHandleDrag:e=>this.startHandleDrag("secondaryPanel",e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize("secondaryPanel"),onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel("secondaryPanel"),isCollapsed:this.sidePanelStore.secondaryPanel?.isCollapsed}}get panelList(){return[{key:this.sidePanelStore.secondaryPanelKey,props:this.secondaryPanelProps,style:this.sidePanelStore.secondaryPanel?Ey({width:`${this.sidePanelStore.secondaryPanel.size}px`}):""},{key:this.sidePanelStore.mainPanelKey,props:this.mainPanelProps,style:this.sidePanelStore.mainPanel?Ey({width:`${this.sidePanelStore.mainPanel.size}px`}):""}].filter(e=>e.key&&e.props)}}class CB extends t.Component{static template="o-spreadsheet-RibbonMenu";static props={onClose:Function};static components={Menu:RF};rootItems=$z.getMenuItems();menuRef=t.useRef("menu");containerRef=t.useRef("container");state=t.useState({menuItems:this.rootItems,title:fs("Menu Bar"),parentState:void 0});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.onMounted(this.updateShadows)}onExternalClick(e){this.menuRef.el?.contains(e.target)||this.props.onClose()}onClickMenu(e){const t=e.children(this.env);t.length?(this.state.parentState={...this.state},this.state.menuItems=t,this.state.title=e.name(this.env),this.containerRef.el?.scrollTo({top:0})):(this.state.menuItems=this.rootItems,this.state.title=void 0,this.state.parentState=void 0,e.execute?.(this.env),this.props.onClose())}get menuProps(){return{menuItems:this.state.menuItems,onClose:this.props.onClose,onClickMenu:this.onClickMenu.bind(this)}}get style(){return Ey({height:`${this.props.height}px`})}updateShadows(){if(!this.containerRef.el)return;this.containerRef.el.classList.remove("scroll-top","scroll-bottom");const e=this.containerRef.el.scrollHeight-this.containerRef.el.clientHeight||0;this.containerRef.el.scrollTop<e-1&&this.containerRef.el.classList.add("scroll-bottom"),this.containerRef.el.scrollTop>0&&this.containerRef.el.classList.add("scroll-top")}onClickBack(){this.state.parentState?(this.state.menuItems=this.state.parentState.menuItems,this.state.title=this.state.parentState.title,this.state.parentState=this.state.parentState.parentState,this.containerRef.el?.scrollTo({top:0})):this.props.onClose()}get backTitle(){return this.state.parentState?fs("Go to previous menu"):fs("Close menu bar")}}class yB extends t.Component{static components={Composer:zP,BottomBar:dB,Ripple:rB,RibbonMenu:CB};static template="o-spreadsheet-SmallBottomBar";static props={onClick:Function};composerFocusStore;composerStore;composerInterface;composerRef=t.useRef("bottombarComposer");menuState=t.useState({isOpen:!1});setup(){this.composerFocusStore=ev(uv);const e=ev(WV);this.composerStore=e,this.composerInterface={id:"bottombarComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},t.useEffect(()=>{this.env.isMobile()&&!this.menuState.isOpen&&"inactive"!==this.composerStore.editionMode&&this.composerFocusStore.activeComposer!==this.composerInterface&&this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"})})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get showFxIcon(){return"inactive"===this.focus&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get rect(){return this.composerRef.el?Fy(this.composerRef.el):{x:0,y:0,width:0,height:0}}get composerProps(){const{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,composerStore:this.composerStore,onComposerContentFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus",selection:e}),isDefaultFocus:!1,inputStyle:Ey({height:"inactive"===this.focus?"26px":"fit-content","max-height":"130px"}),showAssistant:!Gy(),placeholder:this.composerStore.placeholder}}get symbols(){return["=","(",")",":","-","/","*",",","+","$","."]}insertSymbol(e){this.composerStore.replaceComposerCursorSelection(e),this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"})}toggleRibbon(){this.composerStore.cancelEdition(),this.menuState.isOpen=!this.menuState.isOpen}}class IB extends t.Component{static template="o-spreadsheet-TopBarComposer";static props={};static components={Composer:zP};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=ev(uv);const e=ev(WV);this.composerStore=e,this.composerInterface={id:"topbarComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition}}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get showFxIcon(){return"inactive"===this.focus&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get composerStyle(){const e={padding:"5px 0px 5px 8px","max-height":"300px","line-height":"24px"};return e.height="inactive"===this.focus?"34px":"fit-content",Ey(e)}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}}class wB{mutators=["closeDropdowns","openDropdown"];_currentDropdown=null;closeDropdowns(){this._currentDropdown=null}openDropdown(e){this._currentDropdown=e}get currentDropdown(){return this._currentDropdown}}function EB(){const e=t.useComponent(),s=ev(wB);return t.onWillUnmount(()=>{e===s.currentDropdown&&s.closeDropdowns()}),{closeDropdowns:()=>s.closeDropdowns(),openDropdown:()=>{s.openDropdown(e)},get isActive(){return s.currentDropdown===e}}}const RB=[[["all","o-spreadsheet-Icon.BORDERS"],["hv","o-spreadsheet-Icon.BORDER_HV"],["h","o-spreadsheet-Icon.BORDER_H"],["v","o-spreadsheet-Icon.BORDER_V"],["external","o-spreadsheet-Icon.BORDER_EXTERNAL"]],[["left","o-spreadsheet-Icon.BORDER_LEFT"],["top","o-spreadsheet-Icon.BORDER_TOP"],["right","o-spreadsheet-Icon.BORDER_RIGHT"],["bottom","o-spreadsheet-Icon.BORDER_BOTTOM"],["clear","o-spreadsheet-Icon.BORDER_CLEAR"]]];class xB extends t.Component{static template="o-spreadsheet-BorderEditor";static props={class:{type:String,optional:!0},currentBorderColor:{type:String,optional:!1},currentBorderStyle:{type:String,optional:!1},currentBorderPosition:{type:String,optional:!0},onBorderColorPicked:Function,onBorderStylePicked:Function,onBorderPositionPicked:Function,maxHeight:{type:Number,optional:!0},anchorRect:Object};static components={ColorPickerWidget:DU,Popover:DF};BORDER_POSITIONS=RB;lineStyleButtonRef=t.useRef("lineStyleButton");borderStyles=As;state=t.useState({activeTool:void 0});toggleDropdownTool(e){const t=this.state.activeTool===e;this.state.activeTool=t?void 0:e}closeDropdown(){this.state.activeTool=void 0}setBorderPosition(e){this.props.onBorderPositionPicked(e),this.closeDropdown()}setBorderColor(e){this.props.onBorderColorPicked(e),this.closeDropdown()}setBorderStyle(e){this.props.onBorderStylePicked(e),this.closeDropdown()}get lineStylePickerPopoverProps(){return{anchorRect:this.lineStylePickerAnchorRect,positioning:"bottom-left",verticalOffset:0}}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"bottom-left",verticalOffset:0}}get lineStylePickerAnchorRect(){const e=this.lineStyleButtonRef.el;if(null===e)return{x:0,y:0,width:0,height:0};const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}}class TB extends t.Component{static template="o-spreadsheet-BorderEditorWidget";static props={disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={BorderEditor:xB};topBarToolStore;borderEditorButtonRef=t.useRef("borderEditorButton");state=t.useState({currentColor:U,currentStyle:V,currentPosition:void 0});setup(){this.topBarToolStore=EB(),t.onWillUpdateProps(()=>{this.isActive||(this.state.currentPosition=void 0)})}get dropdownMaxHeight(){return this.env.model.getters.getSheetViewDimension().height}get borderEditorAnchorRect(){const e=this.borderEditorButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}onBorderPositionPicked(e){this.state.currentPosition=e,this.updateBorder()}onBorderColorPicked(e){this.state.currentColor=e,this.updateBorder()}onBorderStylePicked(e){this.state.currentStyle=e,this.updateBorder()}get isActive(){return this.topBarToolStore.isActive}toggleBorderEditor(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}updateBorder(){void 0!==this.state.currentPosition&&this.env.model.dispatch("SET_ZONE_BORDERS",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),border:{position:this.state.currentPosition,color:this.state.currentColor,style:this.state.currentStyle}})}}class AB extends t.Component{static template="o-spreadsheet-PaintFormatButton";static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=ev(sU)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}}class DB extends t.Component{static template="o-spreadsheet-TableDropdownButton";static components={TableStylesPopover:fz,ActionButton:AU};static props={class:{type:String,optional:!0}};topBarToolStore;state=t.useState({popoverProps:void 0});setup(){this.topBarToolStore=EB()}onStylePicked(e){const t=this.env.model.getters.getActiveSheetId(),s={...this.tableConfig,styleId:e};oN(this.env,t,s).isSuccessful&&this.env.openSidePanel("TableSidePanel",{}),this.closePopover()}onClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps)return void this.closePopover();if(this.env.model.getters.getFirstTableInSelection())return this.topBarToolStore.closeDropdowns(),void this.env.toggleSidePanel("TableSidePanel",{});const t=e.currentTarget,{left:s,bottom:o}=t.getBoundingClientRect();this.topBarToolStore.openDropdown(),this.state.popoverProps={anchorRect:{x:s,y:o,width:0,height:0},positioning:"bottom-left",verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}get action(){return{name:e=>e.model.getters.getFirstTableInSelection()?fs("Edit table"):fs("Insert table"),icon:e=>e.model.getters.getFirstTableInSelection()?"o-spreadsheet-Icon.EDIT_TABLE":"o-spreadsheet-Icon.PAINT_TABLE"}}get tableConfig(){return{...hE,numberOfHeaders:1,bandedRows:!0}}}class _B extends t.Component{static components={ColorPickerWidget:DU};static props={class:String,style:String,icon:String,title:String};static template="o-spreadsheet-ColorEditor";topBarToolStore;state=t.useState({isOpen:!1});setup(){this.topBarToolStore=EB()}get currentColor(){return this.env.model.getters.getCurrentStyle()[this.props.style]||("textColor"===this.props.style?"#000000":"#ffffff")}setColor(e){nN(this.env,{[this.props.style]:e}),this.state.isOpen=!1}get isMenuOpen(){return this.topBarToolStore.isActive}onClick(){this.isMenuOpen?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}}class OB extends t.Component{static template="o-spreadsheet-DropdownAction";static components={ActionButton:AU,Popover:DF};static props={parentAction:Object,childActions:Array,class:String,childClass:String};topBarToolStore;actionRef=t.useRef("actionRef");setup(){this.topBarToolStore=EB()}toggleDropdown(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}get popoverProps(){return{anchorRect:this.actionRef.el?this.actionRef.el.getBoundingClientRect():{x:0,y:0,width:0,height:0},positioning:"bottom-left",verticalOffset:0,class:"rounded"}}}class FB extends t.Component{static components={FontSizeEditor:_U};static props={class:String};static template="o-spreadsheet-TopBarFontSizeEditor";topBarToolStore;setup(){this.topBarToolStore=EB()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||L}setFontSize(e){nN(this.env,{fontSize:e})}onToggle(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}}class PB extends t.Component{static template="o-spreadsheet-NumberFormatsTool";static components={MenuPopover:PF,ActionButton:AU};static props={class:String};formatNumberMenuItemSpec=Wz;topBarToolStore;buttonRef=t.useRef("buttonRef");state=t.useState({anchorRect:{x:0,y:0,width:0,height:0},menuItems:[]});setup(){this.topBarToolStore=EB()}toggleMenu(){if(this.isActive)this.topBarToolStore.closeDropdowns();else{const e=jf(this.formatNumberMenuItemSpec);this.state.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.anchorRect=Fy(this.buttonRef.el),this.topBarToolStore.openDropdown()}}get isActive(){return this.topBarToolStore.isActive}}const MB=new class{content={};add(e){if(e in this.content)throw new Error(`${e} is already present in this registry!`);return this.content[e]=[],this}addChild(e,t){return this.content[e].push(t),this}getEntries(e){return this.content[e].sort((e,t)=>e.sequence-t.sequence)}getCategories(){return Object.keys(this.content)}};MB.add("edit").addChild("edit",{component:AU,props:{action:KN,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("edit",{component:AU,props:{action:JN,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("edit",{component:AB,props:{class:"o-hoverable-button o-toolbar-button o-mobile-disabled"},sequence:3}).addChild("edit",{component:AU,props:{action:EV,class:"o-hoverable-button o-toolbar-button"},sequence:4}).add("numberFormat").addChild("numberFormat",{component:AU,props:{action:Pk,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("numberFormat",{component:AU,props:{action:oV,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("numberFormat",{component:AU,props:{action:sV,class:"o-hoverable-button o-toolbar-button"},sequence:3}).addChild("numberFormat",{component:PB,props:{class:"o-menu-item-button o-hoverable-button o-toolbar-button"},sequence:4}).add("fontSize").addChild("fontSize",{component:FB,props:{class:"o-hoverable-button o-toolbar-button"},sequence:3}).add("textStyle").addChild("textStyle",{component:AU,props:{action:iV,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("textStyle",{component:AU,props:{action:nV,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("textStyle",{component:AU,props:{action:aV,class:"o-hoverable-button o-toolbar-button"},sequence:3}).addChild("textStyle",{component:_B,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button",style:"textColor",icon:"o-spreadsheet-Icon.TEXT_COLOR",title:fs("Text Color")},sequence:4}).add("cellStyle").addChild("cellStyle",{component:_B,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button",style:"fillColor",icon:"o-spreadsheet-Icon.FILL_COLOR",title:fs("Fill Color")},sequence:1}).addChild("cellStyle",{component:TB,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:2}).addChild("cellStyle",{component:AU,props:{action:fL,class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:3}).add("alignment").addChild("alignment",{component:OB,props:{parentAction:hV,childActions:[dV,uV,gV],class:"o-hoverable-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:1}).addChild("alignment",{component:OB,props:{parentAction:pV,childActions:[mV,fV,vV],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:2}).addChild("alignment",{component:OB,props:{parentAction:SV,childActions:[CV,yV,IV],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:3}).add("misc").addChild("misc",{component:DB,props:{class:"o-toolbar-button o-hoverable-button o-menu-item-button o-mobile-disabled"},sequence:1}).addChild("misc",{component:AU,props:{action:Rk,class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:2});class NB extends t.Component{static template="o-spreadsheet-TopBar";static props={onClick:Function,dropdownMaxHeight:Number};static components={MenuPopover:PF,TopBarComposer:IB,Popover:DF};toolsCategories=MB.getCategories();state=t.useState({menuState:{isOpen:!1,anchorRect:null,menuItems:[]},invisibleToolsCategories:[],toolsPopoverState:{isOpen:!1}});isSelectingMenu=!1;openedEl=null;menus=[];toolbarMenuRegistry=MB;formatNumberMenuItemSpec=Wz;isntToolbarMenu=!1;composerFocusStore;fingerprints;topBarToolStore;toolBarContainerRef=t.useRef("toolBarContainer");toolbarRef=t.useRef("toolBar");moreToolsContainerRef=t.useRef("moreToolsContainer");moreToolsButtonRef=t.useRef("moreToolsButton");spreadsheetRect=AF();setup(){this.composerFocusStore=ev(uv),this.fingerprints=ev(yN),this.topBarToolStore=ev(wB),t.useExternalListener(window,"click",this.onExternalClick),t.onWillStart(()=>this.updateCellState()),t.onWillUpdateProps(()=>this.updateCellState()),t.useEffect(()=>{this.state.toolsPopoverState.isOpen=!1,this.setVisibilityToolsGroups()},()=>[this.spreadsheetRect.width])}setVisibilityToolsGroups(){if(this.env.model.getters.isReadonly())return;const e=[],{x:t}=this.toolbarRef.el.getBoundingClientRect(),{x:s}=this.toolBarContainerRef.el.getBoundingClientRect();this.moreToolsContainerRef.el?.classList.remove("d-none");const o=this.moreToolsButtonRef.el?.getBoundingClientRect().width||0,i=Math.round(this.spreadsheetRect.width)-o-(t-s)-16,n=document.querySelectorAll(".tool-container");let r=0;for(let t=0;t<n.length;t++){const s=n[t];s.classList.remove("d-none");const{width:o}=s.getBoundingClientRect();r+=o,r>i&&(s.classList.add("d-none"),e.push(this.toolsCategories[t]))}this.state.invisibleToolsCategories=e,e.length||this.moreToolsContainerRef.el?.classList.add("d-none")}get topbarComponents(){return sB.getAllOrdered().filter(e=>!e.isVisible||e.isVisible(this.env))}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||L}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.isntToolbarMenu&&this.openMenu(e,t)}toggleContextMenu(e,t){this.state.menuState.isOpen&&this.isntToolbarMenu?this.closeMenus():(this.openMenu(e,t),this.isntToolbarMenu=!0)}openMenu(e,t){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!0,this.state.menuState.anchorRect=Fy(t.currentTarget),this.state.menuState.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.composerFocusStore.activeComposer.stopEdition()}closeMenus(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){this.menus=$z.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){nN(this.env,{[e]:t}),this.onClick()}setFontSize(e){nN(this.env,{fontSize:e})}toggleMoreTools(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!this.state.toolsPopoverState.isOpen}get toolsPopoverProps(){return{anchorRect:this.moreToolsButtonRef.el?Fy(this.moreToolsButtonRef.el):{x:0,y:0,width:0,height:0},positioning:"bottom-left",verticalOffset:0,class:"rounded",maxWidth:300}}showDivider(e){return e<this.toolsCategories.length-1||this.state.invisibleToolsCategories.length>0}}class LB{clipboard;constructor(e){this.clipboard=e}async write(e){if(this.clipboard?.write)try{await(this.clipboard?.write(this.getClipboardItems(e)))}catch(t){console.log("Failed to write on the clipboard, falling back to plain/html text. Error %s",t);try{await(this.clipboard?.write([new ClipboardItem({[gI.PlainText]:this.getBlob(e,gI.PlainText),[gI.Html]:this.getBlob(e,gI.Html)})]))}catch(e){}}else await this.writeText(e[gI.PlainText]??"")}async writeText(e){try{this.clipboard?.writeText(e)}catch(e){}}async read(){let e;try{e=await navigator.permissions.query({name:"clipboard-read"})}catch(e){}if(!this.clipboard?.read)return{status:"ok",content:{[gI.PlainText]:await(this.clipboard?.readText())}};try{const e=await this.clipboard.read(),t={};for(const s of e)for(const e of s.types){const o=await s.getType(e);if(S_.includes(e))t[e]=o;else{const s=await o.text();t[e]=s}}return{status:"ok",content:t}}catch(t){return{status:"denied"===e?.state?"permissionDenied":"notImplemented"}}}getClipboardItems(e){const t={};for(const s of Object.keys(e))t[s]=this.getBlob(e,s);return[new ClipboardItem(t)]}getBlob(e,t){const s=e[t];return s instanceof Blob||s instanceof File?s:new Blob([e[t]||""],{type:t})}}class kB extends t.Component{static template="o-spreadsheet-Spreadsheet";static props={model:Object,notifyUser:{type:Function,optional:!0},raiseError:{type:Function,optional:!0},askConfirmation:{type:Function,optional:!0}};static components={TopBar:NB,Grid:Az,BottomBar:dB,SmallBottomBar:yB,SidePanels:SB,SpreadsheetDashboard:gB,HeaderGroupContainer:vB,FullScreenFigure:Pz};sidePanel;spreadsheetRef=t.useRef("spreadsheet");spreadsheetRect=AF();_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){const e={};this.env.isDashboard()?e["grid-template-rows"]="auto":e["grid-template-rows"]="min-content auto min-content";const t=this.sidePanel.mainPanel?`${this.sidePanel.totalPanelSize||wz}px`:"auto";return e["grid-template-columns"]=`auto ${t}`,Ey(e)}setup(){if(!("isSmall"in this.env)){const e=function(){const e=AF();return{get isSmall(){return e.width<768}}}();t.useSubEnv({get isSmall(){return e.isSmall}})}const e=Qf();e.inject(nv,this.model);const s=this.env;e.get(Iz).setSmallThreshhold(()=>s.isSmall),this.notificationStore=ev(jP),this.composerFocusStore=ev(uv),this.sidePanel=ev(Rz);const o=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:o?new oB(o):void 0,loadCurrencies:this.model.config.external.loadCurrencies,loadLocales:this.model.config.external.loadLocales,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.sidePanel.open.bind(this.sidePanel),replaceSidePanel:this.sidePanel.replace.bind(this.sidePanel),toggleSidePanel:this.sidePanel.toggle.bind(this.sidePanel),clipboard:this.env.clipboard||new LB(navigator.clipboard),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,s)=>this.notificationStore.askConfirmation(e,t,s),raiseError:(e,t)=>this.notificationStore.raiseError(e,t),isMobile:Wy}),this.notificationStore.updateNotificationCallbacks({...this.props}),t.useEffect(()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()},()=>[this.env.model.getters.getActiveSheetId()]),t.useExternalListener(window,"resize",()=>this.render(!0)),t.useExternalListener(document.body,"wheel",()=>{}),this.bindModelEvents(),t.onWillUpdateProps(e=>{if(e.model!==this.props.model)throw new Error("Changing the props model is not supported at the moment.");e.notifyUser===this.props.notifyUser&&e.askConfirmation===this.props.askConfirmation&&e.raiseError===this.props.raiseError||this.notificationStore.updateNotificationCallbacks({...e})});const i=function(e){let t=!1;return async(...s)=>{t||(t=!0,await Promise.resolve(),t=!1,e(...s))}}(this.render.bind(this,!0));t.onMounted(()=>{this.checkViewportSize(),e.on("store-updated",this,i),n.observe(this.spreadsheetRef.el)}),t.onWillUnmount(()=>{this.unbindModelEvents(),e.off("store-updated",this),n.disconnect(),function(){if(window.Chart)for(const e of sS.getAll())e.unregister(window.Chart)}()}),t.onPatched(()=>{this.checkViewportSize()});const n=new ResizeObserver(()=>{this.sidePanel.changeSpreadsheetWidth(this.spreadsheetRect.width)})}bindModelEvents(){this.model.on("update",this,()=>this.render(!0)),this.model.on("notify-ui",this,e=>this.notificationStore.notifyUser(e)),this.model.on("raise-error-ui",this,({text:e})=>this.notificationStore.raiseError(e))}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this),this.model.off("raise-error-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(isFinite(e)&&isFinite(t))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.notificationStore.notifyUser({text:fs("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),type:"warning",sticky:!1}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}focusGrid(){this._focusGrid&&this._focusGrid()}get gridHeight(){return this.env.model.getters.getSheetViewDimension().height}get gridContainerStyle(){const e=F*this.rowLayers.length,t=F*this.colLayers.length;return Ey({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`})}get rowLayers(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,"ROW")}get colLayers(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,"COL")}getGridSize(){const e=this.spreadsheetRef.el?.querySelector(".o-spreadsheet-topbar-wrapper")?.getBoundingClientRect().height||0,t=this.spreadsheetRef.el?.querySelector(".o-spreadsheet-bottombar-wrapper")?.getBoundingClientRect().height||0,s=this.spreadsheetRef.el?.querySelector(".o-grid")?.getBoundingClientRect().width||0,o=(this.spreadsheetRef.el?.getBoundingClientRect().height||0)-(this.spreadsheetRef.el?.querySelector(".o-column-groups")?.getBoundingClientRect().height||0)-e-t;return{width:Math.max(s-O,0),height:Math.max(o-O,0)}}}class VB extends ny{dataSets;labelRange;background;legendPosition;aggregated;dataSetsHaveTitle;dataSetDesign;axesDesign;type="combo";showValues;hideDataMarkers;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers,this.zoomable=e.zoomable}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId),type:this.dataSetDesign?.[t]?.type??(t?"line":"bar")});return{type:"combo",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,zoomable:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:e,labelRange:t,verticalAxis:hC(s)}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new VB(i,this.sheetId,this.getters)}static getDefinitionFromContextCreation(e){const t=(e.range??[]).map((e,t)=>({...e,type:t?"line":"bar"}));return{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated,legendPosition:e.legendPosition??"top",title:e.title||{text:""},labelRange:e.auxiliaryRange||void 0,type:"combo",axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new VB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new VB(t,e,this.getters)}}class UB extends ny{dataSets;labelRange;background;legendPosition;aggregated;type="funnel";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;showValues;funnelColors;cumulative;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.horizontal=!0,this.funnelColors=e.funnelColors,this.cumulative=e.cumulative}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:"none",title:e.title||{text:""},type:"funnel",labelRange:e.auxiliaryRange||void 0,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new UB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new UB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"funnel",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,horizontal:this.horizontal,axesDesign:this.axesDesign,showValues:this.showValues,funnelColors:this.funnelColors,cumulative:this.cumulative,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new UB(i,this.sheetId,this.getters)}}class HB extends ny{dataSets;labelRange;background;legendPosition;type="geo";dataSetsHaveTitle;dataSetDesign;colorScale;missingValueColor;region;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.colorScale=e.colorScale,this.missingValueColor=e.missingValueColor,this.region=e.region}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"geo",labelRange:e.auxiliaryRange||void 0,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new HB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new HB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"geo",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,colorScale:this.colorScale,missingValueColor:this.missingValueColor,region:this.region,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new HB(i,this.sheetId,this.getters)}}class zB extends ny{dataSets;labelRange;background;legendPosition;aggregated;type="pyramid";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;stacked=!0;showValues;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"pyramid",labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new zB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new zB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"pyramid",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,horizontal:!0,stacked:!0,showValues:this.showValues,humanize:this.humanize}}getDefinitionForExcel(e){const{dataSets:t,labelRange:s}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),o=this.getDefinition(),i=_I(o,this.dataSets,this.labelRange,e),{dataSetsValues:n}=i,r=Math.max(...n.map(e=>Math.max(...e.data.map(Math.abs))));return{...o,horizontal:!0,backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:t,labelRange:s,verticalAxis:hC(o),maxValue:r}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new zB(i,this.sheetId,this.getters)}}class BB extends ny{dataSets;labelRange;background;legendPosition;stacked;aggregated;type="radar";dataSetsHaveTitle;dataSetDesign;fillArea;showValues;hideDataMarkers;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.fillArea=e.fillArea,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"radar",labelRange:e.auxiliaryRange||void 0,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new BB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new BB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"radar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated,fillArea:this.fillArea,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,humanize:this.humanize}}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,cC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:uI(this.background||c),fontColor:uI(nC(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new BB(i,this.sheetId,this.getters)}}class GB extends ny{dataSets;labelRange;background;legendPosition;type="sunburst";dataSetsHaveTitle;showValues;showLabels;valuesDesign;groupColors;pieHolePercentage;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.groupColors=e.groupColors,this.pieHolePercentage=e.pieHolePercentage}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static getDefinitionFromContextCreation(e){const t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"sunburst",labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){const e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}getDefinitionWithSpecificDataSets(e,t,s){return{type:"sunburst",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,showValues:this.showValues,showLabels:this.showLabels,valuesDesign:this.valuesDesign,groupColors:this.groupColors,pieHolePercentage:this.pieHolePercentage,humanize:this.humanize}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new GB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new GB(t,e,this.getters)}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new GB(i,this.sheetId,this.getters)}}class WB extends ny{static defaults={background:c,legendPosition:"top",dataSetsHaveTitle:!1,showHeaders:!0,headersColor:"#000000"};dataSets;labelRange;background;legendPosition;type="treemap";dataSetsHaveTitle;showHeaders;headerDesign;showValues;showLabels;valuesDesign;coloringOptions;constructor(e,t,s){super(e,t,s),this.dataSets=eC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Rb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showHeaders=e.showHeaders,this.headerDesign=e.headerDesign,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.coloringOptions=e.coloringOptions}static transformDefinition(e,t,s){return iC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,aC,lC)}static getDefinitionFromContextCreation(e){const t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"treemap",labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions,humanize:e.humanize}}getContextCreation(){const e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}duplicateInDuplicatedSheet(e){const t=KS(this.sheetId,e,this.dataSets),s=JS(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new WB(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new WB(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)}));return{type:"treemap",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,showValues:this.showValues,showHeaders:this.showHeaders,headerDesign:this.headerDesign,showLabels:this.showLabels,valuesDesign:this.valuesDesign,coloringOptions:this.coloringOptions,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=XS(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new WB(i,this.sheetId,this.getters)}}$y.add("bar",{match:e=>"bar"===e,createChart:(e,t,s)=>new qw(e,t,s),getChartRuntime:Zw,validateChartDefinition:qw.validateChartDefinition,transformDefinition:qw.transformDefinition,getChartDefinitionFromContextCreation:qw.getDefinitionFromContextCreation,sequence:10}),$y.add("combo",{match:e=>"combo"===e,createChart:(e,t,s)=>new VB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=DI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:VC(s,o)},options:{...nI,layout:QI(0,o),scales:dw(s,o),plugins:{title:Dw(s,t),legend:nw(s),tooltip:Pw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}},validateChartDefinition:VB.validateChartDefinition,transformDefinition:VB.transformDefinition,getChartDefinitionFromContextCreation:VB.getDefinitionFromContextCreation,sequence:15}),$y.add("line",{match:e=>"line"===e,createChart:(e,t,s)=>new JO(e,t,s),getChartRuntime:QO,validateChartDefinition:JO.validateChartDefinition,transformDefinition:JO.transformDefinition,getChartDefinitionFromContextCreation:JO.getDefinitionFromContextCreation,sequence:20}),$y.add("pie",{match:e=>"pie"===e,createChart:(e,t,s)=>new eF(e,t,s),getChartRuntime:tF,validateChartDefinition:eF.validateChartDefinition,transformDefinition:eF.transformDefinition,getChartDefinitionFromContextCreation:eF.getDefinitionFromContextCreation,sequence:30}),$y.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,s)=>new gy(e,t,s),getChartRuntime:my,validateChartDefinition:gy.validateChartDefinition,transformDefinition:gy.transformDefinition,getChartDefinitionFromContextCreation:gy.getDefinitionFromContextCreation,sequence:40}),$y.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,s)=>new ZO(e,t,s),getChartRuntime:jO,validateChartDefinition:ZO.validateChartDefinition,transformDefinition:ZO.transformDefinition,getChartDefinitionFromContextCreation:ZO.getDefinitionFromContextCreation,sequence:50}),$y.add("scatter",{match:e=>"scatter"===e,createChart:(e,t,s)=>new uH(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=OI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"line",data:{labels:o.labels,datasets:LC(s,o)},options:{...nI,layout:QI(0,o),scales:gw(s,o),plugins:{title:Dw(s,t),legend:iw(s),tooltip:Mw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}},validateChartDefinition:uH.validateChartDefinition,transformDefinition:uH.transformDefinition,getChartDefinitionFromContextCreation:uH.getDefinitionFromContextCreation,sequence:60}),$y.add("waterfall",{match:e=>"waterfall"===e,createChart:(e,t,s)=>new sF(e,t,s),getChartRuntime:oF,validateChartDefinition:sF.validateChartDefinition,transformDefinition:sF.transformDefinition,getChartDefinitionFromContextCreation:sF.getDefinitionFromContextCreation,sequence:70}),$y.add("pyramid",{match:e=>"pyramid"===e,createChart:(e,t,s)=>new zB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=_I(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:PC(s,o)},options:{...nI,indexAxis:"y",layout:QI(0,o),scales:mw(s,o),plugins:{title:Dw(s,t),legend:tw(s),tooltip:kw(s,o),chartShowValuesPlugin:Tw(s,o)}}},background:e.background||c}},validateChartDefinition:zB.validateChartDefinition,transformDefinition:zB.transformDefinition,getChartDefinitionFromContextCreation:zB.getDefinitionFromContextCreation,sequence:80,dataSeriesLimit:2}),$y.add("radar",{match:e=>"radar"===e,createChart:(e,t,s)=>new BB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=PI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"radar",data:{labels:o.labels,datasets:UC(s,o)},options:{...nI,layout:QI(0,o),scales:fw(s,o),plugins:{title:Dw(s,t),legend:aw(s),tooltip:Vw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}},validateChartDefinition:BB.validateChartDefinition,transformDefinition:BB.transformDefinition,getChartDefinitionFromContextCreation:BB.getDefinitionFromContextCreation,sequence:80}),$y.add("geo",{match:e=>"geo"===e,createChart:(e,t,s)=>new HB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=MI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"choropleth",data:{datasets:HC(s,o)},options:{...nI,layout:QI(0,o),scales:vw(s,o),plugins:{title:Dw(s,t),tooltip:Uw(s,o),legend:{display:!1}}}},background:e.background||c}},validateChartDefinition:HB.validateChartDefinition,transformDefinition:HB.transformDefinition,getChartDefinitionFromContextCreation:HB.getDefinitionFromContextCreation,sequence:90,dataSeriesLimit:1}),$y.add("funnel",{match:e=>"funnel"===e,createChart:(e,t,s)=>new UB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=NI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"funnel",data:{labels:o.labels,datasets:zC(s,o)},options:{...nI,indexAxis:"y",layout:QI(0,o),scales:bw(0,o),plugins:{title:Dw(s,t),legend:{display:!1},tooltip:Hw(s,o),chartShowValuesPlugin:Rw(s,o)}}},background:e.background||c}},validateChartDefinition:UB.validateChartDefinition,transformDefinition:UB.transformDefinition,getChartDefinitionFromContextCreation:UB.getDefinitionFromContextCreation,sequence:100,dataSeriesLimit:1}),$y.add("sunburst",{match:e=>"sunburst"===e,createChart:(e,t,s)=>new GB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=LI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"doughnut",data:{datasets:GC(s,o)},options:{cutout:void 0===e.pieHolePercentage?"25%":`${e.pieHolePercentage}%`,...nI,layout:QI(0,o),plugins:{title:Dw(s,t),legend:lw(s),tooltip:zw(s,o),sunburstLabelsPlugin:xw(s,o),sunburstHoverPlugin:{enabled:!0}}}},background:e.background||c}},validateChartDefinition:GB.validateChartDefinition,transformDefinition:GB.transformDefinition,getChartDefinitionFromContextCreation:GB.getDefinitionFromContextCreation,sequence:30}),$y.add("treemap",{match:e=>"treemap"===e,createChart:(e,t,s)=>new WB(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=LI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"treemap",data:{labels:o.labels,datasets:ZC(s,o)},options:{...nI,layout:QI(0,o),plugins:{title:Dw(s,t),legend:{display:!1},tooltip:Bw(s,o)}}},background:e.background||c}},validateChartDefinition:WB.validateChartDefinition,transformDefinition:WB.transformDefinition,getChartDefinitionFromContextCreation:WB.getDefinitionFromContextCreation,sequence:100}),f_.add("line",{matcher:e=>"line"===e.type&&!e.stacked&&!e.fillArea,displayName:fs("Line"),chartType:"line",chartSubtype:"line",subtypeDefinition:{stacked:!1,fillArea:!1},category:"line",preview:"o-spreadsheet-ChartPreview.LINE_CHART"}).add("stacked_line",{matcher:e=>"line"===e.type&&!e.fillArea&&!!e.stacked,displayName:fs("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=>"line"===e.type&&!e.stacked&&!!e.fillArea,displayName:fs("Area"),chartType:"line",chartSubtype:"area",subtypeDefinition:{stacked:!1,fillArea:!0},category:"area",preview:"o-spreadsheet-ChartPreview.AREA_CHART"}).add("stacked_area",{matcher:e=>"line"===e.type&&e.stacked&&!!e.fillArea,displayName:fs("Stacked Area"),chartType:"line",chartSubtype:"stacked_area",subtypeDefinition:{stacked:!0,fillArea:!0},category:"area",preview:"o-spreadsheet-ChartPreview.STACKED_AREA_CHART"}).add("scatter",{displayName:fs("Scatter"),chartType:"scatter",chartSubtype:"scatter",category:"misc",preview:"o-spreadsheet-ChartPreview.SCATTER_CHART"}).add("column",{matcher:e=>"bar"===e.type&&!e.stacked&&!e.horizontal,displayName:fs("Column"),chartType:"bar",chartSubtype:"column",subtypeDefinition:{stacked:!1,horizontal:!1},category:"column",preview:"o-spreadsheet-ChartPreview.COLUMN_CHART"}).add("stacked_column",{matcher:e=>"bar"===e.type&&e.stacked&&!e.horizontal,displayName:fs("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=>"bar"===e.type&&!e.stacked&&!!e.horizontal,displayName:fs("Bar"),chartType:"bar",chartSubtype:"bar",subtypeDefinition:{horizontal:!0,stacked:!1},category:"bar",preview:"o-spreadsheet-ChartPreview.BAR_CHART"}).add("stacked_bar",{matcher:e=>"bar"===e.type&&e.stacked&&!!e.horizontal,displayName:fs("Stacked Bar"),chartType:"bar",chartSubtype:"stacked_bar",subtypeDefinition:{horizontal:!0,stacked:!0},category:"bar",preview:"o-spreadsheet-ChartPreview.STACKED_BAR_CHART"}).add("combo",{displayName:fs("Combo"),chartSubtype:"combo",chartType:"combo",category:"line",preview:"o-spreadsheet-ChartPreview.COMBO_CHART"}).add("pie",{matcher:e=>"pie"===e.type&&!e.isDoughnut,displayName:fs("Pie"),chartSubtype:"pie",chartType:"pie",subtypeDefinition:{isDoughnut:!1},category:"pie",preview:"o-spreadsheet-ChartPreview.PIE_CHART"}).add("doughnut",{matcher:e=>"pie"===e.type&&!!e.isDoughnut,displayName:fs("Doughnut"),chartSubtype:"doughnut",chartType:"pie",subtypeDefinition:{isDoughnut:!0},category:"pie",preview:"o-spreadsheet-ChartPreview.DOUGHNUT_CHART"}).add("gauge",{displayName:fs("Gauge"),chartSubtype:"gauge",chartType:"gauge",category:"misc",preview:"o-spreadsheet-ChartPreview.GAUGE_CHART"}).add("scorecard",{displayName:fs("Scorecard"),chartSubtype:"scorecard",chartType:"scorecard",category:"misc",preview:"o-spreadsheet-ChartPreview.SCORECARD_CHART"}).add("waterfall",{displayName:fs("Waterfall"),chartSubtype:"waterfall",chartType:"waterfall",category:"misc",preview:"o-spreadsheet-ChartPreview.WATERFALL_CHART"}).add("pyramid",{displayName:fs("Population Pyramid"),chartSubtype:"pyramid",chartType:"pyramid",category:"misc",preview:"o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART"}).add("radar",{matcher:e=>"radar"===e.type&&!e.fillArea,displayName:fs("Radar"),chartSubtype:"radar",chartType:"radar",subtypeDefinition:{fillArea:!1},category:"misc",preview:"o-spreadsheet-ChartPreview.RADAR_CHART"}).add("filled_radar",{matcher:e=>"radar"===e.type&&!!e.fillArea,displayName:fs("Filled Radar"),chartType:"radar",chartSubtype:"filled_radar",subtypeDefinition:{fillArea:!0},category:"misc",preview:"o-spreadsheet-ChartPreview.FILLED_RADAR_CHART"}).add("geo",{displayName:fs("Geo Chart"),chartSubtype:"geo",chartType:"geo",category:"misc",preview:"o-spreadsheet-ChartPreview.GEO_CHART"}).add("funnel",{displayName:fs("Funnel"),chartSubtype:"funnel",chartType:"funnel",category:"misc",preview:"o-spreadsheet-ChartPreview.FUNNEL_CHART"}).add("sunburst",{matcher:e=>"sunburst"===e.type,displayName:fs("Sunburst"),chartSubtype:"sunburst",chartType:"sunburst",category:"hierarchical",preview:"o-spreadsheet-ChartPreview.SUNBURST_CHART"}).add("treemap",{matcher:e=>"treemap"===e.type,displayName:fs("Tree Map"),chartType:"treemap",chartSubtype:"treemap",category:"hierarchical",preview:"o-spreadsheet-ChartPreview.TREE_MAP_CHART"});class $B extends Nz{copy(e){}}T_.figureHandlers.add("chart",class extends $B{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);if("chart"!==s.tag)return;const o={...s},i=this.getters.getChartFromFigureId(e.figureId);if(!i)throw new Error(`No chart for the given id: ${e.figureId}`);const n=i.copyInSheetId(t);return{figureId:e.figureId,copiedFigure:o,copiedChart:n}}getPasteTarget(e,t,s,o){return{zones:[],figureId:(new lr).smallUuid(),sheetId:e}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=e.sheetId,{width:r,height:a}=t.copiedFigure,l=t.copiedChart.copyInSheetId(n),c=this.getters.getMaxAnchorOffset(n,a,r);let{left:h,top:d}=o[0];const u={x:0,y:0};h>c.col&&(h=c.col,u.x=c.offset.x),d>c.row&&(d=c.row,u.y=c.offset.y),this.dispatch("CREATE_CHART",{figureId:i,chartId:(new lr).smallUuid(),sheetId:n,definition:l.getDefinition(),col:h,row:d,offset:u,size:{height:a,width:r}}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}).add("image",class extends $B{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);const o={...s};if("image"!==s.tag)return;const i=ae(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:o,copiedImage:i,sheetId:t}}getPasteTarget(e,t,s,o){return{sheetId:e,zones:[],figureId:(new lr).smallUuid()}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=this.getters.getActiveSheetId(),{width:r,height:a}=t.copiedFigure,l=ae(t.copiedImage),c=this.getters.getMaxAnchorOffset(n,a,r);let{left:h,top:d}=o[0];const u={x:0,y:0};h>c.col&&(h=c.col,u.x=c.offset.x),d>c.row&&(d=c.row,u.y=c.offset.y),this.dispatch("CREATE_IMAGE",{figureId:i,sheetId:n,col:h,row:d,offset:u,size:{height:a,width:r},definition:l}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}).add("carousel",class extends $B{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);if("carousel"!==s.tag)return;const o={...s},i=this.getters.getCarousel(e.figureId),n={};for(const e of i.items)if("chart"===e.type){const s=this.getters.getChart(e.chartId);if(!s)throw new Error(`No chart for the given id: ${e.chartId}`);n[e.chartId]=s.copyInSheetId(t)}return{figureId:e.figureId,copiedFigure:o,copiedCarousel:i,copiedCharts:n,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:(new lr).smallUuid(),sheetId:e}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=e.sheetId,{width:r,height:a}=t.copiedFigure,l=this.getters.getMaxAnchorOffset(n,a,r);let{left:c,top:h}=o[0];const d={x:0,y:0};c>l.col&&(c=l.col,d.x=l.offset.x),h>l.row&&(h=l.row,d.y=l.offset.y),this.dispatch("CREATE_CAROUSEL",{figureId:i,sheetId:n,definition:{items:[]},col:c,row:h,offset:d,size:{height:a,width:r}});const u=new lr,g=ae(t.copiedCarousel.items);for(const e of g){if("chart"!==e.type)continue;const s=t.copiedCharts[e.chartId],o=u.smallUuid(),r=s.copyInSheetId(n).getDefinition();this.dispatch("CREATE_CHART",{figureId:i,chartId:o,sheetId:n,definition:r}),e.chartId=o}this.dispatch("UPDATE_CAROUSEL",{sheetId:n,figureId:i,definition:{...t.copiedCarousel,items:g}}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}),T_.cellHandlers.add("dataValidation",class extends Lz{uuidGenerator=new lr;queuedChanges={};copy(e){const{rowsIndexes:t,columnsIndexes:s}=e,o=e.sheetId,i=[];for(const e of t){const t=[];for(const i of s){const s={sheetId:o,col:i,row:e},n=this.getters.getValidationRuleForCell(s);t.push({position:s,rule:n})}i.push(t)}return{dvRules:i}}paste(e,t,s){if(this.queuedChanges={},s.pasteOption)return;const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t):this.pasteFromCopy(i,o,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,s){const o=t[0];this.pasteZone(e,o.left,o.top,s.dvRules,{isCutOperation:!0})}pasteZone(e,t,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){const r={col:t+o,row:s+n,sheetId:e};this.pasteDataValidation(a,r,i?.isCutOperation)}}pasteDataValidation(e,t,s){if(e){const o=Zt(t),i=Zt(e.position),n=e.rule;if(!n){const e=this.getters.getValidationRuleForCell(t);return void(e&&this.adaptDataValidationRule(t.sheetId,e,[],[o]))}const r=[];if(s&&r.push(i),e.position.sheetId===t.sheetId){const s=this.getDataValidationRuleToCopyTo(t.sheetId,n,!1);this.adaptDataValidationRule(e.position.sheetId,s,[o],r)}else{const s=this.getters.getValidationRuleForCell(e.position);s&&this.adaptDataValidationRule(e.position.sheetId,s,[],r);const i=this.getDataValidationRuleToCopyTo(t.sheetId,n);this.adaptDataValidationRule(t.sheetId,i,[o],[])}}}getDataValidationRuleToCopyTo(e,t,s=!0){let o=this.getters.getDataValidationRules(e).find(e=>Me(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking);const i=this.queuedChanges[e];return!o&&i&&(o=i.find(e=>Me(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),o||{...t,id:s?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,s,o){this.queuedChanges[e]||(this.queuedChanges[e]=[]);const i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...s),i.toRemove.push(...o)):this.queuedChanges[e].push({toAdd:s,toRemove:o,rule:t})}executeQueuedChanges(){for(const e in this.queuedChanges)for(const{toAdd:t,toRemove:s,rule:o}of this.queuedChanges[e]){const i=o.ranges.map(e=>e.zone),n=ft(i,s),r=ft([...n,...t],[]);0!==r.length?this.dispatch("ADD_DATA_VALIDATION_RULE",{rule:{id:o.id,criterion:o.criterion,isBlocking:o.isBlocking},ranges:r.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e}):this.dispatch("REMOVE_DATA_VALIDATION_RULE",{sheetId:e,id:o.id})}}}).add("cell",kz).add("sheet",class extends Lz{isPasteAllowed(e,t,s,o){if(!("cells"in s))return"Success";const{xSplit:i,ySplit:n}=this.getters.getPaneDivisions(e);return Jt(I_(t,s.cells),i,n)?"FrozenPaneOverlap":"Success"}}).add("merge",class extends Lz{copy(e){const t=this.getters.getActiveSheetId(),{rowsIndexes:s,columnsIndexes:o}=e,i=[];for(const e of s){const s=[];for(const i of o){const o={col:i,row:e,sheetId:t};s.push(this.getters.getMerge(o))}i.push(s)}return{merges:i,sheetId:t}}paste(e,t,s){if(s.isCutOperation){const e=t.merges.flat().filter(Te);this.dispatch("REMOVE_MERGE",{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,s)}pasteZone(e,t,s,o){for(const[i,n]of o.entries())for(const[o,r]of n.entries()){const n={col:t+o,row:s+i,sheetId:e};this.pasteMerge(r,n)}}pasteMerge(e,t){if(!e)return;if(this.getters.isInMerge(t))return;const{sheetId:s,col:o,row:i}=t;this.dispatch("ADD_MERGE",{sheetId:s,force:!0,target:[{left:o,top:i,right:o+e.right-e.left,bottom:i+e.bottom-e.top}]})}}).add("table",class extends Lz{copy(e,t,s="copyPaste"){const o=e.sheetId,{rowsIndexes:i,columnsIndexes:n,zones:r}=e,a=new Set,l=[];for(const e of i){const c=[];l.push(c);for(const l of n){const n={col:l,row:e,sheetId:o},h=this.getters.getTable(n);if(!h){c.push({});continue}const d=this.getters.getCoreTable(n),u=d?.range.zone;let g;if(!a.has(h.id)&&d&&u&&r.some(e=>Vt(u,e))){a.add(h.id);let{numberOfRows:e}=Ut(u);for(let s=u.top;s<=u.bottom;s++)t||i.includes(s)||e--;const s=d.range,o=this.getters.extendRange(d.range,"ROW",s.zone.top+e-1-s.zone.bottom);g={range:this.getters.getRangeData(o),config:d.config,type:d.type}}"shiftCells"!==s&&c.push({table:g,style:this.getTableStyleToCopy(n),isWholeTableCopied:a.has(h.id)})}}return{tableCells:l,sheetId:e.sheetId}}getTableStyleToCopy(e){const t=this.getters.getCellTableStyle(e),s=this.getters.getCellStyle(e),o=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Ve(s)},border:{...o,...Ve(i)}}}paste(e,t,s){const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t,s):this.pasteFromCopy(i,o,t.tableCells,s)}pasteFromCut(e,t,s,o){for(const e of s.tableCells)for(const t of e)t.table&&this.dispatch("REMOVE_TABLE",{sheetId:s.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});const i=t[0];this.pasteZone(e,i.left,i.top,s.tableCells,o)}pasteZone(e,t,s,o,i){for(let n=0;n<o.length;n++){const r=o[n];for(let o=0;o<r.length;o++){const a=r[o];if(!a)continue;const l={col:t+o,row:s+n,sheetId:e};this.pasteTableCell(e,a,l,i)}}if(1===o.length)for(let i=0;i<o[0].length;i++)this.dispatch("AUTOFILL_TABLE_COLUMN",{col:t+i,row:s,sheetId:e})}pasteTableCell(e,t,s,o){if(t.table&&!o?.pasteOption){const{range:o}=t.table,i=Ut(this.getters.getRangeFromRangeData(o).zone),n={left:s.col,top:s.row,right:s.col+i.numberOfCols-1,bottom:s.row+i.numberOfRows-1};this.dispatch("CREATE_TABLE",{sheetId:s.sheetId,ranges:[this.getters.getRangeDataFromZone(e,n)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(s)||"asValue"===o?.pasteOption||(o?.pasteOption||t.isWholeTableCopied)&&"onlyFormat"!==o?.pasteOption||(t.style?.style&&this.dispatch("UPDATE_CELL",{...s,style:t.style.style}),t.style?.border&&this.dispatch("SET_BORDER",{...s,border:t.style.border}))}}).add("conditionalFormat",class extends Lz{uuidGenerator=new lr;queuedChanges={};copy(e){if(!e.zones.length)return;const{rowsIndexes:t,columnsIndexes:s}=e,o=e.sheetId,i=[];for(const e of t){const t=[];for(const i of s){const s=Array.from(this.getters.getRulesByCell(o,i,e));t.push({position:{col:i,row:e,sheetId:o},rules:s})}i.push(t)}return{cfRules:i}}paste(e,t,s){if(this.queuedChanges={},"asValue"===s.pasteOption)return;const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t):this.pasteFromCopy(i,o,t.cfRules,s),this.executeQueuedChanges()}pasteFromCut(e,t,s){const o=t[0];this.pasteZone(e,o.left,o.top,s.cfRules,{isCutOperation:!0})}pasteZone(e,t,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){const r={col:t+o,row:s+n,sheetId:e};this.pasteCf(a,r,i?.isCutOperation)}}pasteCf(e,t,s){if(e?.rules&&e.rules.length>0){const o=Zt(e.position),i=Zt(t);for(const n of e.rules){const r=[];if(s&&r.push(o),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,n,[i],r);else{this.adaptCFRules(e.position.sheetId,n,[],r);const s=this.getCFToCopyTo(t.sheetId,n);this.adaptCFRules(t.sheetId,s,[i],[])}}}}adaptCFRules(e,t,s,o){this.queuedChanges[e]||(this.queuedChanges[e]=[]);const i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...s),i.toRemove.push(...o)):this.queuedChanges[e].push({toAdd:s,toRemove:o,cf:t})}executeQueuedChanges(){for(const e in this.queuedChanges)for(const{toAdd:t,toRemove:s,cf:o}of this.queuedChanges[e]){const i=this.getters.getAdaptedCfRanges(e,o,t,s);i&&(0!==i.length?this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:o.id,rule:o.rule,stopIfTrue:o.stopIfTrue},ranges:i,sheetId:e}):this.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:o.id,sheetId:e}))}}getCFToCopyTo(e,t){let s=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&Me(e.rule,t.rule));const o=this.queuedChanges[e];return!s&&o&&(s=o.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&Me(e.cf.rule,t.rule))?.cf),s||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}}).add("references",class extends Lz{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,s){if(s.isCutOperation){const s=e.zones[0];this.dispatch("MOVE_RANGES",{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:s.left,row:s.top})}}}).add("border",class extends Lz{copy(e){const t=e.sheetId;if(0===e.zones.length)return;const s=[];let o=0;for(const i of EC(e.columnsIndexes)){let n=0;for(const r of EC(e.rowsIndexes)){const e={left:i[0],right:i[i.length-1],top:r[0],bottom:r[r.length-1]};s.push(...this.getters.getBorders(t,e).map(({zone:t,style:s})=>({zone:{left:t.left-e.left+o,right:t.right&&t.right-e.left+o,top:t.top-e.top+n,bottom:t.bottom&&t.bottom-e.top+n},style:s}))),n+=r.length}o+=i.length}return{borders:s,width:e.columnsIndexes.length,height:e.rowsIndexes.length}}paste(e,t,s){const o=e.sheetId;if("asValue"===s.pasteOption)return;const i=e.zones;if(s.isCutOperation){const{left:e,top:s}=i[0];this.pasteBorderZone(o,e,s,t.borders)}else for(const e of i)for(const s of y_(e,t.width,t.height))this.pasteBorderZone(o,s.left,s.top,t.borders)}pasteBorderZone(e,t,s,o){for(const i of o){const o={left:i.zone.left+t,right:i.zone.right&&i.zone.right+t||i.zone.left+t,top:i.zone.top+s,bottom:i.zone.bottom&&i.zone.bottom+s||i.zone.top+s};for(const[t,s]of this.getOptimalBorderCommands(i.style))s&&this.dispatch("SET_ZONE_BORDERS",{sheetId:e,target:[o],border:{position:t,...s}})}}getOptimalBorderCommands(e){const t=xC(e.horizontal,e.vertical),s=xC(e.left,e.right,e.top,e.bottom);return t&&s&&xC(e.horizontal,e.left)?[["all",e.top]]:t&&s?[["hv",e.horizontal],["external",e.top]]:s?[["h",e.horizontal],["v",e.vertical],["external",e.top]]:t?[["hv",e.horizontal],["top",e.top],["bottom",e.bottom],["left",e.left],["right",e.right]]:[["h",e.horizontal],["v",e.vertical],["top",e.top],["bottom",e.bottom],["left",e.left],["right",e.right]]}});const qB={},ZB={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:A,HEADER_WIDTH:D,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:_,SCROLLBAR_WIDTH:O},jB={autoCompleteProviders:$P,autofillModifiersRegistry:e_,autofillRulesRegistry:t_,cellMenuRegistry:vk,colMenuRegistry:DV,errorTypes:Ss,linkMenuRegistry:VM,functionRegistry:uf,featurePluginRegistry:F_,iconsOnCellRegistry:vD,statefulUIPluginRegistry:P_,coreViewsPluginRegistry:M_,corePluginRegistry:O_,rowMenuRegistry:NV,sidePanelRegistry:yz,figureRegistry:VF,chartSidePanelComponentRegistry:IH,chartComponentRegistry:wF,chartRegistry:$y,chartSubtypeRegistry:f_,topbarMenuRegistry:$z,topbarComponentRegistry:sB,clickableCellRegistry:Hz,otRegistry:aE,inverseCommandRegistry:GE,urlRegistry:Uf,cellPopoverRegistry:IP,numberFormatMenuRegistry:Bz,repeatLocalCommandTransformRegistry:g_,repeatCommandTransformRegistry:u_,clipboardHandlersRegistries:T_,pivotRegistry:XD,pivotTimeAdapterRegistry:Fg,pivotSidePanelRegistry:az,pivotNormalizationValueRegistry:cp,supportedPivotPositionalFormulaRegistry:Oz,pivotToFunctionValueRegistry:hp,migrationStepRegistry:LT,chartJsExtensionRegistry:sS},YB={arg:as,isEvaluationError:mo,toBoolean:To,toJsDate:Ao,toNumber:bo,toString:Eo,toNormalizedPivotValue:np,toFunctionPivotValue:ap,toXC:mt,toZone:wt,toUnboundedZone:It,toCartesian:pt,numberToLetters:it,lettersToNumber:nt,UuidGenerator:lr,formatValue:pn,createCurrencyFormat:Dn,ColorGenerator:Gv,computeTextWidth:zb,createEmptyWorkbookData:ZT,createEmptySheet:qT,createEmptyExcelSheet:jT,rgbaToHex:wv,colorToRGBA:Ev,positionToZone:Zt,isDefined:Te,isMatrix:Ds,lazy:Oe,genericRepeat:tB,createAction:jf,createActions:qf,transformRangeData:os,deepEquals:Me,overlap:Lt,union:Ft,isInside:kt,deepCopy:ae,expandZoneOnInsertion:At,reduceZoneOnDeletion:Ot,unquote:ce,getMaxObjectId:Kg,getFunctionsFromTokens:kf,getFirstPivotFunction:MD,getNumberOfPivotFunctions:ND,parseDimension:ep,isDateOrDatetimeField:tp,makeFieldProposal:Dz,insertTokenAfterArgSeparator:function(e,t){let s=e.end;const o=e.end;"ARG_SEPARATOR"!==e.type&&(s=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)},insertTokenAfterLeftParenthesis:function(e,t){let s=e.end;const o=e.end;"LEFT_PAREN"!==e.type&&(s=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)},mergeContiguousZones:es,getPivotHighlights:ZH,pivotTimeAdapter:Pg,UNDO_REDO_PIVOT_COMMANDS:JD,createPivotFormula:ip,areDomainArgsFieldsValid:op,splitReference:tr,sanitizeSheetName:de,getUniqueText:st,isNumber:lo,isDateTime:$s,createCustomFields:fp},XB={isMarkdownLink:Se,parseMarkdownLink:Ie,markdownLink:ye,openLink:Wf,urlRepresentation:Gf},KB={Checkbox:IM,Section:aM,RoundColorPicker:lM,ChartDataSeries:MU,ChartErrorSection:NU,ChartLabelRange:LU,ChartTitle:HU,ChartPanel:xH,ChartFigure:LF,ChartJsComponent:iy,ClickableCellSortIcon:Fz,ZoomableChartJsComponent:mF,Grid:Az,GridOverlay:rU,ScorecardChart:Cy,GaugeChartComponent:yF,LineConfigPanel:aH,BarConfigPanel:VU,PieChartDesignPanel:hH,GenericChartConfigPanel:kU,ChartWithAxisDesignPanel:YU,GenericZoomableChartDesignPanel:KU,LineChartDesignPanel:lH,GaugeChartConfigPanel:eH,GaugeChartDesignPanel:tH,ScorecardChartConfigPanel:gH,ScorecardChartDesignPanel:pH,GeoChartDesignPanel:nH,RadarChartDesignPanel:dH,WaterfallChartDesignPanel:yH,ComboChartDesignPanel:JU,FunnelChartDesignPanel:QU,SunburstChartDesignPanel:mH,TreeMapChartDesignPanel:CH,ChartTypePicker:EH,FigureComponent:UF,MenuPopover:PF,Popover:DF,SelectionInput:fM,ValidationMessages:JV,AddDimensionButton:KH,PivotDimensionGranularity:QH,PivotDimensionOrder:ez,PivotDimension:JH,PivotLayoutConfigurator:oz,PivotHTMLRenderer:Mz,PivotDeferUpdate:jH,PivotTitleSection:iz,CogWheelMenu:FU,TextInput:TU,SidePanelCollapsible:DP,RadioSelection:BU,GeoChartRegionSelectSection:sH,ChartDashboardMenu:MF,FullScreenFigure:Pz},JB={useDragAndDropListItems:cM,useHighlights:DH,useHighlightsOnHover:AH},QB={useStoreProvider:Qf,DependencyContainer:Xf,CellPopoverStore:wP,ComposerFocusStore:uv,CellComposerStore:WV,FindAndReplaceStore:zH,HighlightStore:ZP,DelayedHoveredCellStore:HF,HoveredTableStore:oU,ModelStore:nv,NotificationStore:jP,RendererStore:cv,SelectionInputStore:mM,SpreadsheetStore:hv,useStore:ev,useLocalStore:tv,SidePanelStore:Rz,PivotSidePanelStore:nz,PivotMeasureDisplayPanelStore:$H,ClientFocusStore:kV,GridRenderer:pU};const eG={DEFAULT_LOCALE:Oc,HIGHLIGHT_COLOR:o,PIVOT_TABLE_CONFIG:J,ChartTerms:Ig,FIGURE_ID_SPLITTER:z,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2},tG={...iF,...$w};e.AbstractCellClipboardHandler=Lz,e.AbstractChart=ny,e.AbstractFigureClipboardHandler=$B,e.CellErrorType=bs,e.ClientDisconnectedError=zE,e.CorePlugin=XT,e.CoreViewPlugin=MA,e.DEFAULT_LOCALE=Oc,e.DEFAULT_LOCALES=_c,e.DispatchResult=br,e.EvaluationError=Cs,e.LocalTransportService=nE,e.Model=class extends Yf{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},s=[],o=new lr,i=!1){const n=performance.now();console.debug("##### Model creation #####"),super(),gs===ds&&ps===us&&(ps=()=>!0),s=WT(e,s);const r=zT(e,i);this.state=new V_,this.uuidGenerator=o,this.config=this.setupConfig(t),this.session=this.setupSession(r.revisionId),this.coreGetters={},this.range=new N_(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.adaptFormulaStringDependencies=this.range.adaptFormulaStringDependencies.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.getters={isReadonly:()=>"readonly"===this.config.mode||"dashboard"===this.config.mode,isDashboard:()=>"dashboard"===this.config.mode},this.selection=new k_(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(const e of O_.getAll())this.setupCorePlugin(e,r);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(s);for(const e of M_.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(const e of P_.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(const e of F_.getAll()){const t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.joinSession(),t.snapshotRequested||e["[Content_Types].xml"]&&!this.getters.isReadonly()){const e=performance.now();console.debug("Snapshot requested"),this.session.snapshot(this.exportData()),this.garbageCollectExternalResources(),console.debug("Snapshot taken in",performance.now()-e,"ms")}console.debug("Model created in",performance.now()-n,"ms"),console.debug("######")}joinSession(){this.session.join(this.config.client)}async leaveSession(){const e=this.getters.isReadonly()?void 0:Oe(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(const s of e.getters){if(!(s in t))throw new Error(`Invalid getter name: ${s} for plugin ${t.constructor}`);if(s in this.getters)throw new Error(`Getter "${s}" is already defined.`);this.getters[s]=t[s].bind(t)}for(const s of e.layers)this.renderers[s]||(this.renderers[s]=[]),this.renderers[s].push(t);return t}setupCoreViewPlugin(e){const t=new e(this.coreViewPluginConfig);for(const s of e.getters){if(!(s in t))throw new Error(`Invalid getter name: ${s} for plugin ${t.constructor}`);if(s in this.getters)throw new Error(`Getter "${s}" is already defined.`);this.getters[s]=t[s].bind(t)}return t}setupCorePlugin(e,t){const s=new e(this.corePluginConfig);for(const t of e.getters){if(!(t in s))throw new Error(`Invalid getter name: ${t} for plugin ${s.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=s[t].bind(s)}s.import(t),this.corePlugins.push(s),this.coreHandlers.push(s),this.handlers.push(s)}onRemoteRevisionReceived({commands:e}){for(const t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new BE(JE({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{this.checkDispatchAllowed(e).isSuccessful?(this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1):this.dispatchToHandlers(this.coreHandlers,{type:"UNDO",commands:[e]})}}),this.config.transportService,e)}setupSessionEvents(){this.session.on("remote-revision-received",this,this.onRemoteRevisionReceived),this.session.on("revision-undone",this,({commands:e})=>{this.dispatchFromCorePlugin("UNDO",{commands:e}),this.finalize()}),this.session.on("revision-redone",this,({commands:e})=>{this.dispatchFromCorePlugin("REDO",{commands:e}),this.finalize()}),this.session.on("unexpected-revision-id",this,()=>this.trigger("unexpected-revision-id")),this.session.on("collaborative-event-received",this,()=>{this.trigger("update")})}setupConfig(e){const t=e.client||{id:this.uuidGenerator.smallUuid(),name:fs("Anonymous").toString()},s=e.transportService||new nE,o="readonly"===e.mode||"dashboard"===e.mode;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:o?new rE(s):s,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),raiseBlockingErrorUI:e=>this.trigger("raise-error-ui",{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){const t=e.loadLocales||(()=>Promise.resolve(_c));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,custom:this.config.custom,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){const t=vr(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>"Success"!==e)?new br(t.flat()):br.Success}checkDispatchAllowedCoreCommand(e){const t=this.corePlugins.map(t=>t.allowDispatch(e));return t.push(this.range.allowDispatch(e)),t}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0,this.trigger("command-finalized")}canDispatch=(e,t)=>this.checkDispatchAllowed(BO(e,t));dispatch=(e,t)=>{const s=BO(e,t),o=this.status;if(this.getters.isReadonly()&&(i=s,!mr.has(i.type)))return new br("Readonly");var i;if(!this.session.canApplyOptimisticUpdate())return new br("WaitingSessionConfirmation");switch(o){case 0:const t=this.checkDispatchAllowed(s);if(!t.isSuccessful)return this.trigger("update"),t;this.status=1;const{changes:o,commands:i}=this.state.recordChanges(()=>{const t=performance.now();vr(s)&&this.state.addCommand(s),this.dispatchToHandlers(this.handlers,s),this.finalize();const o=performance.now()-t;o>5&&console.debug(e,o,"ms")});this.session.save(s,i,o),this.status=0,this.trigger("update");break;case 1:if(vr(s)){const e=this.checkDispatchAllowed(s);if(!e.isSuccessful)return e;this.state.addCommand(s)}this.dispatchToHandlers(this.handlers,s);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(vr(s))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,s)}return br.Success};dispatchFromCorePlugin=(e,t)=>{const s=BO(e,t),o=this.status;this.status=2;const i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,s),this.status=o,br.Success};dispatchToHandlers(e,t){const s=vr(t);for(const o of e)!s&&o instanceof XT||o.beforeHandle(t);for(const o of e)!s&&o instanceof XT||o.handle(t);this.trigger("command-dispatched",t)}drawLayer(e,t){const s=this.renderers[t];if(s)for(const o of s)e.ctx.save(),o.drawLayer(e,t),e.ctx.restore()}exportData(){let e=ZT();for(const t of this.handlers)t instanceof XT&&t.export(e);return e.revisionId=this.session.getRevisionId()||H,e=ae(e),e}updateMode(e){this.config.mode=e,this.trigger("update")}async exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={...ZT(),sheets:[jT(HT,"Sheet1")]};for(const t of this.handlers)t instanceof yr&&await t.exportForExcel(e);return e=ae(e),UO(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.PivotRuntimeDefinition=VD,e.Registry=Og,e.Revision=HE,e.SPREADSHEET_DIMENSIONS=ZB,e.Spreadsheet=kB,e.SpreadsheetPivotTable=yA,e.UIPlugin=Ir,e.__info__=qB,e.addFunction=function e(t,s){return uf.add(t,s),{addFunction:(t,s)=>e(t,s)}},e.addRenderingLayer=function(e,t){if(av[e])throw new Error(`Layer ${e} already exists`);av[e]=t},e.astToFormula=_D,e.categories=gf,e.chartHelpers=tG,e.compile=sE,e.compileTokens=oE,e.components=KB,e.constants=eG,e.convertAstNodes=Of,e.coreTypes=fr,e.createAutocompleteArgumentsProvider=Vz,e.findCellInNewZone=qt,e.functionCache=tE,e.getCaretDownSvg=oR,e.getCaretUpSvg=iR,e.helpers=YB,e.hooks=JB,e.invalidateCFEvaluationCommands=ur,e.invalidateChartEvaluationCommands=hr,e.invalidateDependenciesCommands=dr,e.invalidateEvaluationCommands=cr,e.iterateAstNodes=Ff,e.links=XB,e.load=zT,e.parse=Df,e.parseTokens=_f,e.readonlyAllowedCommands=mr,e.registries=jB,e.setDefaultSheetViewSize=function(e){j=e},e.setTranslationMethod=function(e,t=()=>!0){gs=e,ps=t},e.stores=QB,e.tokenColors=ie,e.tokenize=Mc,qB.version="19.1.0-alpha.7",qB.date="2025-10-17T11:09:35.690Z",qB.hash="a11279d"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|