@odoo/o-spreadsheet 19.1.0-alpha.4 → 19.1.0-alpha.6

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.
@@ -1,843 +0,0 @@
1
- !function(e,t){"use strict";function s(e){return e.map(i).sort(((e,t)=>e.sequence-t.sequence))}let o=1;function i(e){const t=e.name,s=e.children,n=e.description,r=e.icon,a=e.secondaryIcon,l=e.id||o++,c=e.isEnabled?e.isEnabled:()=>!0;return{id:l.toString(),name:"function"==typeof t?t:()=>t,isVisible:e.isVisible?e.isVisible:()=>!0,isEnabled:c,isActive:e.isActive,execute:e.execute?(t,s)=>{if(c(t))return e.execute(t,s)}:void 0,children:s?e=>s.map((t=>"function"==typeof t?t(e):t)).flat().map(i):()=>[],isReadonlyAllowed:e.isReadonlyAllowed||!1,separator:e.separator||!1,icon:"function"==typeof r?r:()=>r||"",iconColor:e.iconColor,secondaryIcon:"function"==typeof a?a:()=>a||"",description:"function"==typeof n?n:()=>n||"",textColor:e.textColor,sequence:e.sequence||0,onStartHover:e.onStartHover,onStopHover:e.onStopHover}}class n{content={};add(e,t){if(e in this.content)throw new Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){return this.content[e]=t,this}get(e){const t=this.content[e];if(!t&&!(e in this.content))throw new Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}}var r,a;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(r||(r={})),function(e){e.PlainText="text/plain",e.Html="text/html",e.Image="image"}(a||(a={}));const l=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","DUPLICATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","UNDO","REDO","ADD_MERGE","REMOVE_MERGE","DUPLICATE_SHEET","UPDATE_LOCALE","ADD_PIVOT","UPDATE_PIVOT","INSERT_PIVOT","RENAME_PIVOT","REMOVE_PIVOT","DUPLICATE_PIVOT"]),c=new Set(["EVALUATE_CELLS","EVALUATE_CHARTS","UPDATE_CELL","UNHIDE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","GROUP_HEADERS","UNGROUP_HEADERS","FOLD_ALL_HEADER_GROUPS","FOLD_HEADER_GROUP","FOLD_HEADER_GROUPS_IN_ZONE","UNFOLD_ALL_HEADER_GROUPS","UNFOLD_HEADER_GROUP","UNFOLD_HEADER_GROUPS_IN_ZONE","UPDATE_TABLE","UPDATE_FILTER","UNDO","REDO"]),h=new Set(["MOVE_RANGES"]),d=new Set(["EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","CHANGE_CONDITIONAL_FORMAT_PRIORITY"]),u=new Set(["AUTOFILL_CELL","SET_BORDER","SET_ZONE_BORDERS","SET_BORDERS_ON_TARGET"]),g=new Set(["UNHIDE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","GROUP_HEADERS","UNGROUP_HEADERS","FOLD_ALL_HEADER_GROUPS","FOLD_HEADER_GROUP","FOLD_HEADER_GROUPS_IN_ZONE","UNFOLD_ALL_HEADER_GROUPS","UNFOLD_HEADER_GROUP","UNFOLD_HEADER_GROUPS_IN_ZONE","UPDATE_TABLE","UPDATE_FILTER"]),p=new Set(["START","ACTIVATE_SHEET","COPY","RESIZE_SHEETVIEW","SET_VIEWPORT_OFFSET","EVALUATE_CELLS","EVALUATE_CHARTS","SET_FORMULA_VISIBILITY","UPDATE_FILTER","UPDATE_CHART","UPDATE_CAROUSEL_ACTIVE_ITEM","UPDATE_PIVOT"]),m=new Set(["UPDATE_CELL","UPDATE_CELL_POSITION","CLEAR_CELL","CLEAR_CELLS","DELETE_CONTENT","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","RESIZE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","UNHIDE_COLUMNS_ROWS","SET_GRID_LINES_VISIBILITY","UNFREEZE_COLUMNS","UNFREEZE_ROWS","FREEZE_COLUMNS","FREEZE_ROWS","UNFREEZE_COLUMNS_ROWS","ADD_MERGE","REMOVE_MERGE","CREATE_SHEET","DELETE_SHEET","DUPLICATE_SHEET","MOVE_SHEET","RENAME_SHEET","COLOR_SHEET","HIDE_SHEET","SHOW_SHEET","MOVE_RANGES","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","CHANGE_CONDITIONAL_FORMAT_PRIORITY","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","CREATE_CAROUSEL","UPDATE_CAROUSEL","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","SET_ZONE_BORDERS","SET_BORDERS_ON_TARGET","CREATE_CHART","UPDATE_CHART","DELETE_CHART","CREATE_TABLE","REMOVE_TABLE","UPDATE_TABLE","CREATE_TABLE_STYLE","REMOVE_TABLE_STYLE","CREATE_IMAGE","GROUP_HEADERS","UNGROUP_HEADERS","UNFOLD_HEADER_GROUP","FOLD_HEADER_GROUP","FOLD_ALL_HEADER_GROUPS","UNFOLD_ALL_HEADER_GROUPS","UNFOLD_HEADER_GROUPS_IN_ZONE","FOLD_HEADER_GROUPS_IN_ZONE","ADD_DATA_VALIDATION_RULE","REMOVE_DATA_VALIDATION_RULE","UPDATE_LOCALE","ADD_PIVOT","UPDATE_PIVOT","INSERT_PIVOT","RENAME_PIVOT","REMOVE_PIVOT","DUPLICATE_PIVOT"]);function f(e){return m.has(e.type)}class v{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>"Success"!==e))}static get Success(){return b}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}const b=new v;var S;e.CommandResult=void 0,(S=e.CommandResult||(e.CommandResult={})).Success="Success",S.CancelledForUnknownReason="CancelledForUnknownReason",S.WillRemoveExistingMerge="WillRemoveExistingMerge",S.CannotMoveTableHeader="CannotMoveTableHeader",S.MergeIsDestructive="MergeIsDestructive",S.CellIsMerged="CellIsMerged",S.InvalidTarget="InvalidTarget",S.EmptyUndoStack="EmptyUndoStack",S.EmptyRedoStack="EmptyRedoStack",S.NotEnoughElements="NotEnoughElements",S.NotEnoughSheets="NotEnoughSheets",S.MissingSheetName="MissingSheetName",S.UnchangedSheetName="UnchangedSheetName",S.DuplicatedSheetName="DuplicatedSheetName",S.DuplicatedSheetId="DuplicatedSheetId",S.ForbiddenCharactersInSheetName="ForbiddenCharactersInSheetName",S.WrongSheetMove="WrongSheetMove",S.WrongSheetPosition="WrongSheetPosition",S.InvalidAnchorZone="InvalidAnchorZone",S.SelectionOutOfBound="SelectionOutOfBound",S.TargetOutOfSheet="TargetOutOfSheet",S.WrongCutSelection="WrongCutSelection",S.WrongPasteSelection="WrongPasteSelection",S.WrongPasteOption="WrongPasteOption",S.WrongFigurePasteOption="WrongFigurePasteOption",S.EmptyClipboard="EmptyClipboard",S.EmptyRange="EmptyRange",S.InvalidRange="InvalidRange",S.InvalidZones="InvalidZones",S.InvalidSheetId="InvalidSheetId",S.InvalidCellId="InvalidCellId",S.InvalidFigureId="InvalidFigureId",S.InputAlreadyFocused="InputAlreadyFocused",S.MaximumRangesReached="MaximumRangesReached",S.MinimumRangesReached="MinimumRangesReached",S.InvalidChartDefinition="InvalidChartDefinition",S.InvalidDataSet="InvalidDataSet",S.InvalidLabelRange="InvalidLabelRange",S.InvalidScorecardKeyValue="InvalidScorecardKeyValue",S.InvalidScorecardBaseline="InvalidScorecardBaseline",S.InvalidGaugeDataRange="InvalidGaugeDataRange",S.EmptyGaugeRangeMin="EmptyGaugeRangeMin",S.GaugeRangeMinNaN="GaugeRangeMinNaN",S.EmptyGaugeRangeMax="EmptyGaugeRangeMax",S.GaugeRangeMaxNaN="GaugeRangeMaxNaN",S.GaugeLowerInflectionPointNaN="GaugeLowerInflectionPointNaN",S.GaugeUpperInflectionPointNaN="GaugeUpperInflectionPointNaN",S.InvalidAutofillSelection="InvalidAutofillSelection",S.MinBiggerThanMax="MinBiggerThanMax",S.LowerBiggerThanUpper="LowerBiggerThanUpper",S.MidBiggerThanMax="MidBiggerThanMax",S.MinBiggerThanMid="MinBiggerThanMid",S.FirstArgMissing="FirstArgMissing",S.SecondArgMissing="SecondArgMissing",S.MinNaN="MinNaN",S.MidNaN="MidNaN",S.MaxNaN="MaxNaN",S.ValueUpperInflectionNaN="ValueUpperInflectionNaN",S.ValueLowerInflectionNaN="ValueLowerInflectionNaN",S.MinInvalidFormula="MinInvalidFormula",S.MidInvalidFormula="MidInvalidFormula",S.MaxInvalidFormula="MaxInvalidFormula",S.ValueUpperInvalidFormula="ValueUpperInvalidFormula",S.ValueLowerInvalidFormula="ValueLowerInvalidFormula",S.InvalidSortAnchor="InvalidSortAnchor",S.InvalidSortZone="InvalidSortZone",S.SortZoneWithArrayFormulas="SortZoneWithArrayFormulas",S.WaitingSessionConfirmation="WaitingSessionConfirmation",S.MergeOverlap="MergeOverlap",S.TooManyHiddenElements="TooManyHiddenElements",S.Readonly="Readonly",S.InvalidViewportSize="InvalidViewportSize",S.InvalidScrollingDirection="InvalidScrollingDirection",S.ViewportScrollLimitsReached="ViewportScrollLimitsReached",S.FigureDoesNotExist="FigureDoesNotExist",S.InvalidConditionalFormatId="InvalidConditionalFormatId",S.InvalidCellPopover="InvalidCellPopover",S.EmptyTarget="EmptyTarget",S.InvalidFreezeQuantity="InvalidFreezeQuantity",S.FrozenPaneOverlap="FrozenPaneOverlap",S.ValuesNotChanged="ValuesNotChanged",S.InvalidFilterZone="InvalidFilterZone",S.TableNotFound="TableNotFound",S.TableOverlap="TableOverlap",S.InvalidTableConfig="InvalidTableConfig",S.InvalidTableStyle="InvalidTableStyle",S.FilterNotFound="FilterNotFound",S.MergeInTable="MergeInTable",S.NonContinuousTargets="NonContinuousTargets",S.DuplicatedFigureId="DuplicatedFigureId",S.InvalidSelectionStep="InvalidSelectionStep",S.DuplicatedChartId="DuplicatedChartId",S.ChartDoesNotExist="ChartDoesNotExist",S.InvalidHeaderIndex="InvalidHeaderIndex",S.InvalidQuantity="InvalidQuantity",S.MoreThanOneColumnSelected="MoreThanOneColumnSelected",S.EmptySplitSeparator="EmptySplitSeparator",S.SplitWillOverwriteContent="SplitWillOverwriteContent",S.NoSplitSeparatorInSelection="NoSplitSeparatorInSelection",S.NoActiveSheet="NoActiveSheet",S.InvalidLocale="InvalidLocale",S.MoreThanOneRangeSelected="MoreThanOneRangeSelected",S.NoColumnsProvided="NoColumnsProvided",S.ColumnsNotIncludedInZone="ColumnsNotIncludedInZone",S.DuplicatesColumnsSelected="DuplicatesColumnsSelected",S.InvalidHeaderGroupStartEnd="InvalidHeaderGroupStartEnd",S.HeaderGroupAlreadyExists="HeaderGroupAlreadyExists",S.UnknownHeaderGroup="UnknownHeaderGroup",S.UnknownDataValidationRule="UnknownDataValidationRule",S.UnknownDataValidationCriterionType="UnknownDataValidationCriterionType",S.InvalidDataValidationCriterionValue="InvalidDataValidationCriterionValue",S.InvalidNumberOfCriterionValues="InvalidNumberOfCriterionValues",S.InvalidCopyPasteSelection="InvalidCopyPasteSelection",S.NoChanges="NoChanges",S.InvalidInputId="InvalidInputId",S.SheetIsHidden="SheetIsHidden",S.InvalidTableResize="InvalidTableResize",S.PivotIdNotFound="PivotIdNotFound",S.PivotInError="PivotInError",S.EmptyName="EmptyName",S.ValueCellIsInvalidFormula="ValueCellIsInvalidFormula",S.InvalidDefinition="InvalidDefinition",S.InvalidColor="InvalidColor",S.InvalidPivotDataSet="InvalidPivotDataSet",S.InvalidPivotCustomField="InvalidPivotCustomField",S.MissingFigureArguments="MissingFigureArguments",S.InvalidCarouselItem="InvalidCarouselItem";const C=new Set(["containsText","notContainsText","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","beginsWithText","endsWithText","isNotEmpty","isEmpty","isNotEqual","isEqual","customFormula"]),y=new Set(["containsText","notContainsText","isEqualText","isEmail","isLink","dateIs","dateIsBefore","dateIsOnOrBefore","dateIsAfter","dateIsOnOrAfter","dateIsBetween","dateIsNotBetween","dateIsValid","isEqual","isNotEqual","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","isBoolean","isValueInList","isValueInRange","customFormula"]),I=[{name:"English (US)",code:"en_US",thousandsSeparator:",",decimalSeparator:".",weekStart:7,dateFormat:"m/d/yyyy",timeFormat:"hh:mm:ss a",formulaArgSeparator:","},{name:"French",code:"fr_FR",thousandsSeparator:" ",decimalSeparator:",",weekStart:1,dateFormat:"dd/mm/yyyy",timeFormat:"hh:mm:ss",formulaArgSeparator:";"}],w=I[0],E=["thin","medium","thick","dashed","dotted"];function R(e){return Array.isArray(e)&&Array.isArray(e[0])}var x;!function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(x||(x={}));const T=.5,A="#017E84",D="#F8F9FA",_="#E8EAED",F="#595959",O="#666666",P="#3266ca",M="#FFFFFF",N=11982760,L=A,k="#188038",V="#9B359B",U="#00000000",H="#4EA7F2",z="#EA6175",B="#AAAAAA",G="#111827",W="#D8DADD",$="#E7E9ED",q="#374151",Z=q+"C2",j=A,Y=20,X=10,K=15,J=16,Q=12,ee="#F28C28",te=["#000000","#434343","#666666","#999999","#B7B7B7","#CCCCCC","#D9D9D9","#EFEFEF","#F3F3F3","#FFFFFF","#980000","#FF0000","#FF9900","#FFFF00","#00FF00","#00FFFF","#4A86E8","#0000FF","#9900FF","#FF00FF","#E6B8AF","#F4CCCC","#FCE5CD","#FFF2CC","#D9EAD3","#D0E0E3","#C9DAF8","#CFE2F3","#D9D2E9","#EAD1DC","#DD7E6B","#EA9999","#F9CB9C","#FFE599","#B6D7A8","#A2C4C9","#A4C2F4","#9FC5E8","#B4A7D6","#D5A6BD","#CC4125","#E06666","#F6B26B","#FFD966","#93C47D","#76A5AF","#6D9EEB","#6FA8DC","#8E7CC3","#C27BA0","#A61C00","#CC0000","#E69138","#F1C232","#6AA84F","#45818E","#3C78D8","#3D85C6","#674EA7","#A64D79","#85200C","#990000","#B45F06","#BF9000","#38761D","#134F5C","#1155CC","#0B5394","#351C75","#741B47","#5B0F00","#660000","#783F04","#7F6000","#274E13","#0C343D","#1C4587","#073763","#20124D","#4C1130"],se=26,oe=48,ie=96,ne=23,re=15,ae=4,le=3,ce=ae,he=21,de=2*ne,ue={align:"left",verticalAlign:"bottom",wrapping:"overflow",bold:!1,italic:!1,strikethrough:!1,underline:!1,fontSize:10,fillColor:"",textColor:""},ge=ue.verticalAlign,pe=ue.wrapping,me="400",fe=ue.fontSize,ve="'Roboto', arial",be="thin",Se="#000000",Ce="START_REVISION",ye=1,Ie=20,we="??",Ee="difference",Re="#43C5B1",xe="#EA6175",Te=.4,Ae=3,De=2,_e=["'","*","?","/","\\","[","]"],Fe=/'|\*|\?|\/|\\|\[|\]/,Oe="|";let Pe=0;function Me(){return Pe}const Ne="\n",Le=[6,7,8,9,10,11,12,14,18,24,36],ke={hasFilters:!1,totalRow:!1,firstColumn:!0,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,styleId:"TableStyleMedium5",automaticAutofill:!1},Ve=1e5,Ue={symbol:"$",position:"before",decimalPlaces:2,code:"",name:"Dollar"},He={fontSize:J,color:q},ze="#000000",Be="#3da4ab",Ge={OPERATOR:Be,NUMBER:"#02c39a",STRING:"#00a82d",FUNCTION:ze,DEBUGGER:Be,LEFT_PAREN:ze,RIGHT_PAREN:ze,ARG_SEPARATOR:ze,ORPHAN_RIGHT_PAREN:"#ff0000"},We=new RegExp(Fe,"g");function $e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qe(e){switch(typeof e){case"object":{if(null===e)return e;if(function(e){return"clone"in e&&e.clone instanceof Function}(e))return e.clone();if(!(function(e){return"object"==typeof e&&null!==e&&(e?.constructor===Object||void 0===e?.constructor)}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");const t=Array.isArray(e)?new Array(e.length):{};if(Array.isArray(e))for(let s=0,o=e.length;s<o;s++)s in e&&(t[s]=qe(e[s]));else for(const s in e)t[s]=qe(e[s]);return t}case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function Ze(e){return je(e,"'")}function je(e,t='"'){return e.startsWith(t)&&(e=e.slice(1)),e.endsWith(t)&&(e=e.slice(0,-1)),e}function Ye(e){return e.match(/\w/g)?.length!==e.length&&(e=`'${e}'`),e}function Xe(e,t=" "){return e.replace(We,t)}function Ke(e,t,s){return e<t?t:e>s?s:e}function Je(e,t,s=1){if(t<=e&&s>0)return[];if(0===s)throw new Error("range() step must not be zero");const o=Math.ceil(Math.abs((t-e)/s)),i=Array(o);for(let t=0;t<o;t++)i[t]=e+t*s;return i}function Qe(e){return e.reduce(((e,t,s,o)=>{if(1===Math.abs(t-o[s-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*et(e,t){t.next();for(const s of e){const e=t.next();yield{...s,next:e.done?void 0:e.value}}}function tt(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}const st=/^\[(.+)\]\((.+)\)$/,ot=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function it(e){return st.test(e)}function nt(e){return ot.test(e)}function rt(e,t){return`[${e}](${t})`}function at(e){const t=e.match(st)||[],s=t[1],o=t[2];if(!s||!o)throw new Error(`Could not parse markdown link ${e}.`);return{label:s,url:o}}const lt="o-spreadsheet://";function ct(e){return e.startsWith(lt)}function ht(e){return`${lt}${e}`}function dt(e){if(e.startsWith(lt))return e.slice(lt.length);throw new Error(`${e} is not a valid sheet link`)}function ut(e){return void 0!==e}function gt(e){return void 0===e||Object.values(e).every((e=>"object"==typeof e?gt(e):!e))}function pt(e,t,s){let o;const i=function(){const i=this,n=Array.from(arguments);const r=s&&!o;clearTimeout(o),o=setTimeout((function(){o=void 0,s||e.apply(i,n)}),t),r&&e.apply(i,n)};return i.isDebouncePending=()=>void 0!==o,i.stopDebounce=()=>{clearTimeout(o)},i}function mt(e){let t="";for(let s=0,o=e.length;s<o;s++)t+=e[s];return t}function ft(e){let t,s=!1;const o=()=>(s||(t=e instanceof Function?e():e,s=!0),t);return o.map=e=>ft((()=>e(o()))),o}function vt(e,t){let s=e.slice(t).find((e=>e));return s||(s=e.slice(0,t).reverse().find((e=>e))),s||""}function bt(e,t){return"after"===e?t+1:t}function St(...e){if(e.length<=1)return!0;for(let t=1;t<e.length;t++)if(!Ct(e[0],e[t]))return!1;return!0}function Ct(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;if(typeof e!=typeof t)return!1;if("object"!=typeof e)return!1;for(const s in t)if(!(s in e)&&void 0!==t[s])return!1;for(const s in e){if(typeof e[s]!=typeof t[s])return!1;if("object"==typeof e[s]){if(!Ct(e[s],t[s]))return!1}else if(e[s]!==t[s])return!1}return!0}function yt(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!St(e[s],t[s]))return!1;return!0}function It(e,t){if(e.length<t.length)return!1;const s=new Set(e);return t.every((e=>s.has(e)))}function wt(e){if(!e)return e;const t={...e};return Object.keys(t).forEach((e=>!t[e]&&delete t[e])),t}const Et=["\t","\f","\v",String.fromCharCode(parseInt("00a0",16)),String.fromCharCode(parseInt("1680",16)),String.fromCharCode(parseInt("2000",16)),String.fromCharCode(parseInt("200a",16)),String.fromCharCode(parseInt("2028",16)),String.fromCharCode(parseInt("2029",16)),String.fromCharCode(parseInt("202f",16)),String.fromCharCode(parseInt("205f",16)),String.fromCharCode(parseInt("3000",16)),String.fromCharCode(parseInt("feff",16))],Rt=new RegExp(Et.join("|"),"g"),xt=/(\r\n|\r)/g,Tt=Et.concat([" "]);function At(e){return e?e.replace(xt,Ne):""}function Dt(e){const t=Array.from(e).sort(((e,t)=>e-t));for(let e=1;e<t.length;e++)if(t[e]-t[e-1]!=1)return!1;return!0}function _t(e){const t=new Map,s=e.name?e.name+" (memoized)":"memoized";return{[s]:(...s)=>(t.has(s[0])||t.set(s[0],e(...s)),t.get(s[0]))}[s]}function Ft(e,t){const s=new Set(t),o=[];for(let t=0;t<e.length;t++)s.has(t)||o.push(e[t]);return o}function Ot(e,t,s){return e.slice(0,s).concat(t).concat(e.slice(s))}function Pt(e,t,s){const o=[...e];return o[s]=t,o}function Mt(e){return e.split("\n").map((e=>e.replace(/\s+/g," ").trim())).join("\n")}function Nt(e,t,s){return t>s?Nt(e,s,t):e>=t&&e<=s}function Lt(e,t){let s=$e(e);const o=t.matchCase?"":"i";return t.exactMatch&&(s=`^${s}$`),RegExp(s,o)}function kt(e){let t=e.length;if(t<1e5)return Math.max(...e);let s=-1/0;for(;t--;)s=e[t]>s?e[t]:s;return s}function Vt(e){let t=e.length;if(t<1e5)return Math.min(...e);let s=1/0;for(;t--;)s=e[t]<s?e[t]:s;return s}class Ut{text;currentIndex=0;current;constructor(e){this.text=e,this.current=e[0]}shift(){const e=this.current,t=this.text[++this.currentIndex];return this.current=t,e}advanceBy(e){this.currentIndex+=e,this.current=this.text[this.currentIndex]}isOver(){return this.currentIndex>=this.text.length}remaining(){return this.text.substring(this.currentIndex)}currentStartsWith(e){if(this.current!==e[0])return!1;for(let t=1;t<e.length;t++)if(this.text[this.currentIndex+t]!==e[t])return!1;return!0}}function Ht(e,t=(e=>e)){const s=new Set;return e.filter((e=>{const o=t(e);return!s.has(o)&&(s.add(o),!0)}))}function zt(e){const t={};for(const s in e)for(const o in e[s])t[o]||(t[o]={}),t[o][s]=e[s][o];return t}function Bt(e,t,s={}){const o=s.compute??((e,t)=>`${e} (${t})`),i=s.computeFirstOne??!1;let n=s.start??1,r=i?o(e,n):e;for(;t.includes(r);)r=o(e,n++);return r}function Gt(e){return e.startsWith("=")||e.startsWith("+")}const Wt={Background:0,Highlights:1,Clipboard:2,Chart:4,Autofill:5,Selection:6,Headers:100},$t=_t((()=>Object.keys(Wt).sort(((e,t)=>Wt[e]-Wt[t]))));new Set(["containsText","notContainsText","isEqualText","dateIs","dateIsBefore","dateIsOnOrBefore","dateIsAfter","dateIsOnOrAfter","dateIsBetween","dateIsNotBetween","isEqual","isNotEqual","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","customFormula","beginsWithText","endsWithText","isNotEmpty","isEmpty"]);const qt=["containsText","notContainsText","isEqualText","isEmpty","isNotEmpty","beginsWithText","endsWithText"],Zt=["isEqual","isNotEqual","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","isEmpty","isNotEmpty"],jt=["dateIs","dateIsBefore","dateIsOnOrBefore","dateIsAfter","dateIsOnOrAfter","dateIsBetween","dateIsNotBetween","isEmpty","isNotEmpty"],Yt=["image/avif","image/bmp","image/gif","image/vnd.microsoft.icon","image/jpeg","image/png","image/tiff","image/webp"];function Xt(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Xt(Math.floor(e/26)-1)+Xt(e%26)}function Kt(e){let t=0;const s=e.length;for(let o=0;o<s;o++){t=26*t+Jt(e[o])}return t-1}function Jt(e){const t=e.charCodeAt(0);return t>=65&&t<=90?t-64:t-96}function Qt(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function es(e){return e>="0"&&e<="9"}const ts=Kt("ZZZ"),ss=9999998;function os(e){for(;" "===e.current;)e.advanceBy(1)}function is(e){if("$"===e.current&&e.advanceBy(1),!e.current||!Qt(e.current))return-1;let t=0;for(;e.current&&Qt(e.current);)t=26*t+Jt(e.shift());return t}function ns(e){if("$"===e.current&&e.advanceBy(1),!e.current||!es(e.current))return-1;let t=0;for(;e.current&&es(e.current);)t=10*t+Number(e.shift());return t}function rs(e){const t=new Ut(e);os(t);const s=is(t);if(-1===s||!t.current)throw new Error(`Invalid cell description: ${e}`);const o=ns(t);os(t);const i=s-1,n=o-1;if(!t.isOver()||i>ts||n>ss)throw new Error(`Invalid cell description: ${e}`);return{col:i,row:n}}function as(e,t,s={colFixed:!1,rowFixed:!1}){return(s.colFixed?"$":"")+Xt(e)+(s.rowFixed?"$":"")+String(t+1)}function ls(e,t=[]){if(e.length<=1&&0===t.length)return e;const s=[0],o=new Map([[0,[]]]);return cs(s,o,e,!1),cs(s,o,t,!0),function(e,t){const s=[];let o=[];for(let i=0;i<e.length;i++){const n=e[i],r=t.get(n);if(!r||0===r.length){s.push(...o),o=[];continue}let a=e[i+1];void 0!==a&&a--;const l=[];for(let e=0;e<r.length;e+=2){const t=r[e];let s=r[e+1];void 0!==s&&s--;const i={top:t,left:n,bottom:s,right:a,hasHeader:void 0===s&&0!==t||void 0===a&&0!==n};let c=!1;for(let e=o.length-1;e>=0;e--){const t=o[e];if(t.top===i.top&&t.bottom===i.bottom){t.right=i.right,o.splice(e,1),l.push(t),c=!0;break}}c||l.push(i)}s.push(...o),o=l}return s.push(...o),s}(s,o)}function cs(e,t,s,o=!1){for(const i of s){const s=i.left,n=void 0===i.right?void 0:i.right+1,r=hs(e,t,s,!0,0),a=hs(e,t,n,!1,r);for(let s=r;s<=a;s++){ds(t.get(e[s]),i,o)}us(e,t,r,a)}}function hs(e,t,s,o,i){if(void 0===s)return e.length-1;const n=gs(e,s,i);return s!==e[n]?(e.splice(n+1,0,s),t.set(s,[...t.get(e[n])]),o?n+1:n):o?n:n-1}function ds(e,t,s=!1){const o=t.top,i=void 0===t.bottom?void 0:t.bottom+1,n=[],r=gs(e,o,0,!1);if((r%2!=0&&!s||r%2==0&&s)&&n.push(o),void 0===i)return e.splice(r+1),void e.push(...n);const a=function(e,t,s=0,o=!0){let i=e.length-1,n=e.length;for(;s<=i;){const r=Math.floor((s+i)/2);if(e[r]===t&&o)return r;e[r]>t?(n=r,i=r-1):s=r+1}return n}(e,i,0,!1);(a%2==0&&!s||a%2!=0&&s)&&n.push(i),e.splice(r+1,a-r-1,...n)}function us(e,t,s,o){const i=s-1==-1?0:s-1;for(let s=o===e.length-1?o:o+1;s>i;s--)yt(t.get(e[s]),t.get(e[s-1]))&&(t.delete(e[s]),e.splice(s,1))}function gs(e,t,s=0,o=!0){let i=e.length-1,n=-1;for(;s<=i;){const r=Math.floor((s+i)/2);if(e[r]===t&&o)return r;e[r]<t?(n=r,s=r+1):i=r-1}return n}function ps(e){const t=function(e){const t=new Ut(e);os(t);const s=e.indexOf("!");-1!==s&&t.advanceBy(s+1);const o=is(t),i=ns(t);let n,r,a,l,c=!1,h=!1,d=!1;if(-1===i?(a=l=o-1,n=r=0,c=!0):-1===o?(n=r=i-1,a=l=0,h=!0):(a=l=o-1,n=r=i-1,d=!0),os(t),":"===t.current){t.advanceBy(1),os(t);const e=is(t),s=ns(t);-1===s?(l=e-1,c=!0):-1===e?(r=s-1,h=!0):(l=e-1,r=s-1,n=c?r:n,a=h?l:a,d=!0)}const u={top:n,left:a,bottom:c?void 0:r,right:h?void 0:l};return d=d&&(h||c),d&&(u.hasHeader=d),u}(e),s=Ls(t),o=s.bottom,i=s.right;if(void 0!==o&&o>ss||void 0!==i&&i>ts)throw new Error(`Range string out of bounds: ${e}`);if(void 0===o&&void 0===i)throw new Error("Wrong zone xc. The zone cannot be at the same time a full column and a full row");return s}function ms(e){const t=ps(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function fs(e){try{return function(e){return vs(ps(e))}(e)}catch(e){return!1}}function vs(e){const{bottom:t,top:s,left:o,right:i}=e;return!(void 0!==t&&isNaN(t)||isNaN(s)||isNaN(o)||void 0!==i&&isNaN(i))&&(bs(e)&&e.top>=0&&e.left>=0)}function bs(e){return(void 0===e.bottom||e.bottom>=e.top&&e.bottom>=0)&&(void 0===e.right||e.right>=e.left&&e.right>=0)}function Ss(e){const{top:t,bottom:s,left:o,right:i}=e,n="hasHeader"in e&&e.hasHeader,r=t===s&&o===i;if(void 0===s&&void 0!==i)return 0!==t||n?`${as(o,t)}:${Xt(i)}`:`${Xt(o)}:${Xt(i)}`;if(void 0===i&&void 0!==s)return 0!==o||n?`${as(o,t)}:${s+1}`:`${t+1}:${s+1}`;if(void 0!==s&&void 0!==i)return r?as(o,t):`${as(o,t)}:${as(i,s)}`;throw new Error("Bad zone format")}function Cs(e,t,s,o,i){const n="left"===t?"columns":"rows",r="before"===o?s-1:s,a=e["left"===t?"right":"bottom"];return e[t]<=r&&a&&a>r?ks(e,n,"RESIZE",i):r<e[t]?ks(e,n,"MOVE",i):{...e}}function ys(e,t,s,o,i){const n="left"===t?"columns":"rows",r="before"===o?s-1:s,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?ks(e,n,"RESIZE",i):r<e[t]?ks(e,n,"MOVE",i):{...e}}function Is(e,t,s){const o="left"===t?"right":"bottom";let i=e[t],n=e[o];for(const r of s.sort(((e,t)=>t-e)))e[t]>r&&(i--,n--),e[t]<r&&e[o]>=r&&n--;return{...e,[t]:i,[o]:n}}function ws(e,t,s){const o="left"===t?"right":"bottom";let i=e[t],n=e[o];const r=e[o];for(const o of s.sort(((e,t)=>t-e)))e[t]>o&&(i--,void 0!==n&&n--),void 0!==r&&void 0!==n&&e[t]<=o&&r>=o&&n--;if(!(void 0!==n&&i>n))return{...e,[t]:i,[o]:n}}function Es(...e){return{top:Math.min(...e.map((e=>e.top))),left:Math.min(...e.map((e=>e.left))),bottom:Math.max(...e.map((e=>e.bottom))),right:Math.max(...e.map((e=>e.right)))}}function Rs(e,t){if(As(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:void 0!==e.bottom?Math.min(e.bottom,t.bottom):e.bottom??t.bottom,right:void 0!==e.right?Math.min(e.right,t.right):e.right??t.right}}function xs(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom&&e.hasHeader===t.hasHeader}function Ts(e,t){if(Rs(e,t))return;let s;return e.left===t.right+1&&(s={position:"left",start:Math.max(e.top,t.top),stop:void 0!==e.bottom?Math.min(e.bottom,t.bottom):t.bottom}),void 0!==e.right&&e.right+1===t.left&&(s={position:"right",start:Math.max(e.top,t.top),stop:void 0!==e.bottom?Math.min(e.bottom,t.bottom):t.bottom}),e.top===t.bottom+1&&(s={position:"top",start:Math.max(e.left,t.left),stop:void 0!==e.right?Math.min(e.right,t.right):t.right}),void 0!==e.bottom&&e.bottom+1===t.top&&(s={position:"bottom",start:Math.max(e.left,t.left),stop:void 0!==e.right?Math.min(e.right,t.right):t.right}),s&&s.start<=s.stop?s:void 0}function As(e,t){return!(void 0!==e.bottom&&e.bottom<t.top||void 0!==t.bottom&&t.bottom<e.top)&&!(void 0!==e.right&&e.right<t.left||void 0!==t.right&&t.right<e.left)}function Ds(e,t,s){const{left:o,right:i,top:n,bottom:r}=s;return e>=o&&e<=i&&t>=n&&t<=r}function _s(e,t){return xs(Es(t,e),t)}function Fs(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function Os(e){const{numberOfCols:t,numberOfRows:s}=Fs(e);return 1===t||1===s}function Ps(e){const t={};for(const s of e)t[s.sheetId]??=[],t[s.sheetId].push(Us(s));for(const e in t)t[e]=ls(t[e]);return t}function Ms(e){const t=[],{left:s,right:o,top:i,bottom:n}=Ls(e);for(const e of Je(s,o+1))for(const s of Je(i,n+1))t.push({col:e,row:s});return t}function Ns(e,t){const s=[],{left:o,right:i,top:n,bottom:r}=Ls(t);for(const t of Je(o,i+1))for(const o of Je(n,r+1))s.push({sheetId:e,col:t,row:o});return s}function Ls(e){return void 0!==e.right&&e.left>e.right&&(e={...e,left:e.right,right:e.left}),void 0!==e.bottom&&e.top>e.bottom&&(e={...e,top:e.bottom,bottom:e.top}),e}function ks(e,t,s,o){const i="both"===t?o[0]:"columns"===t?o:0,n="both"===t?o[1]:"rows"===t?o:0,r="hasHeader"in e&&e.hasHeader;let a;a=Bs(e)&&!r?"rows"!==t:!(zs(e)&&!r)||"columns"!==t;const l={...e};return a&&"MOVE"===s&&(l.left+=i,l.top+=n),void 0!==l.right&&(l.right+=i),void 0!==l.bottom&&(l.bottom+=n),l}function Vs(e,t){let s,o;const{left:i,right:n,top:r,bottom:a}=e,{left:l,right:c,top:h,bottom:d}=t;return s=l!==i?l:c!==n?c:l,o=h!==r?h:d!==a?d:h,{col:s,row:o}}function Us(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function Hs(e){return{...e,right:e.left,bottom:e.top}}function zs(e){return void 0===e.right}function Bs(e){return void 0===e.bottom}function Gs(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function Ws(e,t,s){return e.some((e=>function(e,t,s){return e.left<t&&t<=e.right||e.top<s&&s<=e.bottom}(e,t,s)))}function $s(e){return e.length<2||1===ls(e).length}function qs(e){const t=[...e];let s=!0;for(;s;){s=!1;for(let e=0;e<t.length;e++){const o=t[e],i=t.findIndex(((t,s)=>{return e!==s&&(n=o,((i=t).right+1===n.left||i.left===n.right+1?i.top<=n.bottom&&i.top>=n.top||n.top<=i.bottom&&n.top>=i.top:(i.bottom+1===n.top||i.top===n.bottom+1)&&(i.left<=n.right&&i.left>=n.left||n.left<=i.right&&n.left>=i.left))||As(t,o));var i,n}));if(-1!==i){t[e]=Es(t[i],o),t.splice(i,1),s=!0;break}}}return t}function Zs(e,t){const s=Ts(e,t);if(!s)return[e];const o=[];switch(s.position){case"bottom":case"top":return o.push({top:e.top,bottom:e.bottom,left:s.start,right:s.stop}),s.start>e.left&&o.push({top:e.top,bottom:e.bottom,left:e.left,right:s.start-1}),(void 0===e.right||s.stop<e.right)&&o.push({top:e.top,bottom:e.bottom,left:s.stop+1,right:e.right}),o;case"left":case"right":return o.push({top:s.start,bottom:s.stop,left:e.left,right:e.right}),s.start>e.top&&o.push({top:e.top,bottom:s.start-1,left:e.left,right:e.right}),(void 0===e.bottom||s.stop<e.bottom)&&o.push({top:s.stop+1,bottom:e.bottom,left:e.left,right:e.right}),o}}function js(e,t){const s=new Set(t.map((e=>e.left))),o=new Set(t.map((e=>e.right))),i=new Set(t.map((e=>e.top))),n=new Set(t.map((e=>e.bottom))),r=1===i.size&&1===n.size||1===s.size&&1===o.size?function(e){return e.reduce(((e,t)=>{const s=e.length;for(let o=0;o<s;o++)if(As(e[o],t))return e[o]=Es(e[o],t),e;return e[s]=t,e}),[])}(t):[t[t.length-1]],a=r.map((e=>Ms(e))).flat();return{sheetId:e,zones:t,clippedZones:r,columnsIndexes:[...new Set(a.map((e=>e.col)))].sort(((e,t)=>e-t)),rowsIndexes:[...new Set(a.map((e=>e.row)))].sort(((e,t)=>e-t))}}function Ys(e,t,s){const o=Math.max(e.right-t+1,e.left),i=Math.max(e.bottom-s+1,e.top),n=[];for(let r=e.left;r<=o;r+=t)for(let o=e.top;o<=i;o+=s)n.push({left:r,top:o,bottom:o+s-1,right:r+t-1});return n}function Xs(e,t){if(!t.length||!t[0].length)return e;const s=t[0].length,o=t.length;return e.map((e=>Ys(e,s,o))).flat()}function Ks(e){let t;if(e[a.Html]){t=function(e){const t=[...e.documentElement.attributes];if(t.some((e=>e.value.includes("microsoft"))))return;const s=e.querySelector("div")?.getAttribute("data-osheet-clipboard");return s&&JSON.parse(s)}((new DOMParser).parseFromString(e[a.Html],"text/html"))}const s=e[a.PlainText]||"";let o;if(!s.trim())for(const t of Yt)if(e[t]){o=e[t];break}return{text:s,data:t,imageBlob:o}}const Js=(e,t,s,o)=>{e.forEach((({handlerName:e,handler:i})=>{const n=t[e];n&&i.paste(s,n,o)}))};function Qs(e,t,s,o,i){let n;const r=[],a={sheetId:e,zones:t};for(const{handlerName:l,handler:c}of o){const o=s[l];if(!o)continue;const h=c.getPasteTarget(e,t,o,i);h.figureId&&(a.figureId=h.figureId);for(const e of h.zones)r.push(e),n=void 0!==n?Es(n,e):e}return{target:a,zone:n,selectedZones:r}}const eo=(e,t,s)=>{const o={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:o,zone:Es(...s)},{scrollIntoView:!1})},to=/rgba?\(|\s+|\)/gi,so=/^#([A-F\d]{2}){3,4}$/,oo=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function io(e,t=1){const s=1!==t?Math.round(255*t).toString(16).padStart(2,"0"):"";return ro(e.toString(16).padStart(6,"0"))+s}function no(e){return"number"==typeof e?e:Number.parseInt(ro(e).slice(1,7),16)}function ro(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(to,"").split(",");let s=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");if(isNaN(e))throw new Error("invalid alpha value");s=Math.round(255*e)}const o=t.map((e=>parseInt(e,10)));255!==s&&o.push(s);return"#"+mt(o.map((e=>e.toString(16).padStart(2,"0")))).toUpperCase()}(e):(t=e.replace("#","").toUpperCase(),3!==t.length&&4!==t.length||(t=t.split("").reduce(((e,t)=>e+t+t),"")),t=`#${t}`),!so.test(t))throw new Error(`invalid color input: ${e}`);return t}function ao(e){try{return ro(e),!0}catch(e){return!1}}const lo=e=>e>=0&&e<=255;function co(e,t,s,o=1){if(!lo(e)||!lo(t)||!lo(s)||o<0||o>1)throw new Error(`Invalid RGBA values ${[e,t,s,o]}`);return{a:o,b:s,g:t,r:e}}function ho(e){let{r:t,g:s,b:o}=go(e);t/=255,s/=255,o/=255;const i=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*i(t)+.7152*i(s)+.0722*i(o)}function uo(e){let t=e.r.toString(16),s=e.g.toString(16),o=e.b.toString(16),i=Math.round(255*e.a).toString(16);return 1===t.length&&(t="0"+t),1===s.length&&(s="0"+s),1===o.length&&(o="0"+o),1===i.length&&(i="0"+i),"ff"===i&&(i=""),("#"+t+s+o+i).toUpperCase()}function go(e){let t,s,o,i;if(7===(e=ro(e)).length)t=parseInt(e[1]+e[2],16),s=parseInt(e[3]+e[4],16),o=parseInt(e[5]+e[6],16),i=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),s=parseInt(e[3]+e[4],16),o=parseInt(e[5]+e[6],16),i=parseInt(e[7]+e[8],16)}return i=+(i/255).toFixed(3),{a:i,r:t,g:s,b:o}}function po(e){(e={...e}).s/=100,e.l/=100;const t=(1-Math.abs(2*e.l-1))*e.s,s=t*(1-Math.abs(e.h/60%2-1)),o=e.l-t/2;let i=0,n=0,r=0;return 0<=e.h&&e.h<60?(i=t,n=s,r=0):60<=e.h&&e.h<120?(i=s,n=t,r=0):120<=e.h&&e.h<180?(i=0,n=t,r=s):180<=e.h&&e.h<240?(i=0,n=s,r=t):240<=e.h&&e.h<300?(i=s,n=0,r=t):300<=e.h&&e.h<360&&(i=t,n=0,r=s),i=Math.round(255*(i+o)),n=Math.round(255*(n+o)),r=Math.round(255*(r+o)),{a:e.a,r:i,g:n,b:r}}function mo(e){const t=e.r/255,s=e.g/255,o=e.b/255,i=Math.min(t,s,o),n=Math.max(t,s,o),r=n-i;let a=0,l=0,c=0;return a=0===r?0:n===t?(s-o)/r%6:n===s?(o-t)/r+2:(t-s)/r+4,a=Math.round(60*a),a<0&&(a+=360),c=(n+i)/2,l=0===r?0:r/(1-Math.abs(2*c-1)),l=+(100*l).toFixed(1),c=+(100*c).toFixed(1),{a:e.a,h:a,s:l,l:c}}function fo(e){return uo(po(e))}function vo(e){return mo(go(e))}function bo(e){return go("number"==typeof e?io(e):e)}function So(e,t){return 1===t?ro(e).slice(0,7):uo({...go(e),a:t})}function Co(e,t){const s=vo(e);return 1===t?"#fff":(s.l=t*(100-s.l)+s.l,fo(s))}function yo(e,t){const s=vo(e);return 1===t?"#000":(s.s=Math.min(100,t*s.s+s.s),s.l=s.l-t*s.l,fo(s))}function Io(e){return ho(e)<.6?Co(e,.9):yo(e,.75)}const wo=["#4EA7F2","#EA6175","#43C5B1","#F4A261","#8481DD","#FFD86D"],Eo=["#4EA7F2","#3188E6","#43C5B1","#00A78D","#EA6175","#CE4257","#F4A261","#F48935","#8481DD","#5752D1","#FFD86D","#FFBC2C"],Ro=["#4EA7F2","#3188E6","#056BD9","#A76DBC","#7F4295","#6D2387","#EA6175","#CE4257","#982738","#43C5B1","#00A78D","#0E8270","#F4A261","#F48935","#BE5D10","#8481DD","#5752D1","#3A3580","#A4A8B6","#7E8290","#545B70","#FFD86D","#FFBC2C","#C08A16"],xo=["#4EA7F2","#3188E6","#056BD9","#155193","#A76DBC","#7F4295","#6D2387","#4F1565","#EA6175","#CE4257","#982738","#791B29","#43C5B1","#00A78D","#0E8270","#105F53","#F4A261","#F48935","#BE5D10","#7D380D","#8481DD","#5752D1","#3A3580","#26235F","#A4A8B6","#7E8290","#545B70","#3F4250","#FFD86D","#FFBC2C","#C08A16","#936A12"],To=["#4EA7F2","#43C5B1","#EA6175","#F4A261","#8481DD","#FFD86D","#3188E6","#00A78D","#CE4257","#F48935","#5752D1","#FFBC2C"],Ao=["#4EA7F2","#A76DBC","#EA6175","#43C5B1","#F4A261","#8481DD","#A4A8B6","#FFD86D","#3188E6","#7F4295","#CE4257","#00A78D","#F48935","#5752D1","#7E8290","#FFBC2C","#056BD9","#6D2387","#982738","#0E8270","#BE5D10","#3A3580","#545B70","#C08A16"],Do=["#4EA7F2","#A76DBC","#EA6175","#43C5B1","#F4A261","#8481DD","#A4A8B6","#FFD86D","#3188E6","#7F4295","#CE4257","#00A78D","#F48935","#5752D1","#7E8290","#FFBC2C","#056BD9","#6D2387","#982738","#0E8270","#BE5D10","#3A3580","#545B70","#C08A16","#155193","#4F1565","#791B29","#105F53","#7D380D","#26235F","#3F4250","#936A12"];function _o(e,t){return t[e%t.length]}function Fo(e){return e<=6?wo:e<=12?Eo:e<=24?Ro:xo}class Oo{preferredColors;currentColorIndex=0;palette;constructor(e,t=[]){this.preferredColors=t,this.palette=Fo(e).filter((e=>!t.includes(e)))}next(){return this.preferredColors?.[this.currentColorIndex]?this.preferredColors[this.currentColorIndex++]:_o(this.currentColorIndex++,this.palette)}}class Po extends Oo{constructor(e,t=[]){var s;super(e,t),this.palette=(s=e,s<=6?wo:s<=12?To:s<=24?Ao:Do).filter((e=>!t.includes(e)))}}class Mo{availableColors;colors={};constructor(e=12){this.availableColors=new Po(e)}get(e){return this.colors[e]||(this.colors[e]=this.availableColors.next()),this.colors[e]}}function No(e){if(e.length<2)throw new Error("Color scale must have at least 2 points");const t=[...e.sort(((e,t)=>e.value-t.value))],s=[];for(let e=1;e<t.length;e++){const o=bo(t[e-1].color).a,i=bo(t[e].color).a,n=no(t[e-1].color),r=no(t[e].color);s.push({min:t[e-1].value,max:t[e].value,minColor:n,maxColor:r,minColorAlpha:o,maxColorAlpha:i,colorDiff:Lo(t[e-1].value,t[e].value,n,r)})}return e=>{if(e<s[0].min)return io(s[0].minColor,s[0].minColorAlpha);for(const t of s)if(e>=t.min&&e<=t.max)return io(ko(e,t.min,t.minColor,t.colorDiff),t.maxColorAlpha);return io(s[s.length-1].maxColor,s[s.length-1].maxColorAlpha)}}function Lo(e,t,s,o){const i=t-e;return[((s>>16)%256-(o>>16)%256)/i,((s>>8)%256-(o>>8)%256)/i,(s%256-o%256)/i]}function ko(e,t,s,o){const[i,n,r]=o;return Math.round((s>>16)%256-i*(e-t))<<16|Math.round((s>>8)%256-n*(e-t))<<8|Math.round(s%256-r*(e-t))}const Vo=e=>e,Uo=()=>!1;let Ho=Vo,zo=Uo;function Bo(e,...t){if(1!==t.length||"object"!=typeof t[0]||t[0]instanceof String)t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));else{const s=t[0];e=e.replace(/\%\(([^\)]+)\)s/g,((e,t)=>s[t]))}return e}const Go=function(e,...t){return zo()?Bo(Ho(e),...t):new Wo(e,t)};class Wo extends String{values;constructor(e,t){super(e),this.values=t}valueOf(){const e=super.valueOf();return zo()?Bo(Ho(e),...this.values):Bo(e,...this.values)}toString(){return this.valueOf()}}function $o(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const qo=new n;function Zo(e,t){return{url:e=$o(e),label:t||e,isExternal:!0,isUrlEditable:!0}}qo.add("sheet_URL",{match:e=>ct(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){const s=dt(e);return t.tryGetSheetName(s)||Go("Invalid sheet")},open(e,t){const s=dt(e);t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:s}).isCancelledBecause("SheetIsHidden")&&t.notifyUser({type:"warning",sticky:!1,text:Go("Cannot open the link because the linked sheet is hidden.")})},sequence:0});const jo={createLink:Zo,match:e=>nt(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function Yo(e){return qo.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((t=>t.match(e)))||jo}function Xo(e,t){return Yo(e.url).urlRepresentation(e.url,t)}function Ko(e,t,s){Yo(e.url).open(e.url,t,s)}function Jo(e){if("string"==typeof e){if(it(e)){const{label:t,url:s}=at(e);return Yo(s).createLink(s,t)}return nt(e)?Zo(e):void 0}}class Qo{jsDate;constructor(e,t,s,o=0,i=0,n=0){this.jsDate=new Date(Date.UTC(e,t,s,o,i,n,0))}static fromTimestamp(e){const t=new Date(e);return new Qo(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())}static now(){const e=new Date;return new Qo(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds())}toString(){return this.jsDate.toString()}toLocaleDateString(){return this.jsDate.toLocaleDateString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}getQuarter(){return Math.floor(this.getMonth()/3)+1}getDate(){return this.jsDate.getUTCDate()}getDay(){return this.jsDate.getUTCDay()}getHours(){return this.jsDate.getUTCHours()}getMinutes(){return this.jsDate.getUTCMinutes()}getSeconds(){return this.jsDate.getUTCSeconds()}getIsoWeek(){const e=new Date(this.jsDate.getTime()),t=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-t);const s=new Date(Date.UTC(e.getUTCFullYear(),0,1));return Math.ceil(((e.getTime()-s.getTime())/864e5+1)/7)}setFullYear(e){return this.jsDate.setUTCFullYear(e)}setMonth(e){return this.jsDate.setUTCMonth(e)}setDate(e){return this.jsDate.setUTCDate(e)}setHours(e){return this.jsDate.setUTCHours(e)}setMinutes(e){return this.jsDate.setUTCMinutes(e)}setSeconds(e){return this.jsDate.setUTCSeconds(e)}}const ei=new Qo(1899,11,30),ti=864e5,si=2e3,oi=Qo.now().getFullYear(),ii=Qo.now().getMonth(),ni=Qo.fromTimestamp(0).getTime()-ei.getTime(),ri=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,ai=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,li=Tt.join(""),ci=new RegExp(`/|-|${Tt.join("|")}`),hi=new RegExp(`^(\\d{1,4})[/${li}-](\\d{1,4})([/${li}-](\\d{1,4}))?$`),di=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function ui(e,t){switch(typeof e){case"number":return e;case"string":return gi(e,t)?mi(e,t)?.value:!e||isNaN(Number(e))?void 0:Number(e);default:return}}function gi(e,t){return null!==mi(e,t)}const pi=new Map;function mi(e,t){return pi.has(t)||pi.set(t,new Map),pi.get(t).has(e)||pi.get(t).set(e,function(e,t){e=e.trim();let s=null;const o=e.match(di);if(o){if(s=function(e){if(e=e.trim(),di.test(e)){const t=/AM/i.test(e),s=/PM/i.test(e),o=(t||s?e.substring(0,e.length-2).trim():e).split(/:/),i=o.length>=2,n=3===o.length;let r=Number(o[0]),a=i?Number(o[1]):0,l=n?Number(o[2]):0,c=n?"hh:mm:ss":"hh:mm";if(t||s)c+=" a";else if(!i)return null;r>=12&&t?r-=12:r<12&&s&&(r+=12),a+=Math.floor(l/60),l%=60,r+=Math.floor(a/60),a%=60,r>=24&&(c="hhhh:mm:ss");return{value:r/24+a/1440+l/86400,format:c,jsDate:new Qo(1899,11,30,r,a,l)}}return null}(o[0]),null===s)return null;e=e.replace(o[0],"").trim()}let i=null;const n=function(e,t){const s=e.match(hi);if(!s)return null;const[,o,i,,n]=s;if(o.length>2&&n&&n.length>2)return null;if(o.length>2)return{year:o,month:i,day:n,dateString:e,type:"ymd"};const r=function(e){switch(e.dateFormat[0]){case"d":return"dmy";case"m":return"mdy";case"y":return"ymd"}throw new Error("Invalid date format in locale")}(t);if(!n)return i.length>2?{month:o,year:i,day:void 0,dateString:e,type:r}:"dmy"===r?{day:o,month:i,year:n,dateString:e,type:"dmy"}:{month:o,day:i,year:n,dateString:e,type:"mdy"};if(n.length>2)return"mdy"===r?{month:o,day:i,year:n,dateString:e,type:"mdy"}:{day:o,month:i,year:n,dateString:e,type:"dmy"};if("mdy"===r)return{month:o,day:i,year:n,dateString:e,type:"mdy"};if("ymd"===r)return{year:o,month:i,day:n,dateString:e,type:"ymd"};if("dmy"===r)return{day:o,month:i,year:n,dateString:e,type:"dmy"};return null}(e,t);if(n){const t=n.dateString.match(ci)[0];if(i=function(e,t){const{year:s,month:o,day:i}=e,n=function(e){if(!e)return ii;const t=Number(e);if(t>=1&&t<=12)return t-1;return null}(o),r=function(e){if(!e)return 1;const t=Number(e);if(t>=0&&t<=31)return t;return null}(i),a=function(e){if(!e)return oi;const t=Number(e);switch(e.length){case 1:return si+t;case 2:return si+(si+t>oi+10?-100:0)+t;case 3:case 4:return t}return null}(s);if(null===a||null===n||null===r)return null;const l=2===o?.length&&n+1<10||2===i?.length&&r<10,c=2!==s?.length,h=new Qo(a,n,r);if(h.getMonth()!==n||h.getDate()!==r)return null;const d=h.getTime()-ei.getTime(),u=function(e,t,s,o){const i=e.year?o?"yyyy":"yy":void 0,n=e.month?s?"mm":"m":void 0,r=e.day?s?"dd":"d":void 0;switch(e.type){case"mdy":return[n,r,i].filter(ut).join(t);case"ymd":return[i,n,r].filter(ut).join(t);case"dmy":return[r,n,i].filter(ut).join(t)}}(e,t,l,c);return{value:Math.round(d/ti),format:u,jsDate:h}}(n,t),null===i)return null;e=e.replace(n.dateString,"").trim()}if(""!==e||!i&&!s)return null;if(i&&i.jsDate&&s&&s.jsDate)return{value:i.value+s.value,format:i.format+" "+("hhhh:mm:ss"===s.format?"hh:mm:ss":s.format),jsDate:new Qo(i.jsDate.getFullYear()+s.jsDate.getFullYear()-1899,i.jsDate.getMonth()+s.jsDate.getMonth()-11,i.jsDate.getDate()+s.jsDate.getDate()-30,i.jsDate.getHours()+s.jsDate.getHours(),i.jsDate.getMinutes()+s.jsDate.getMinutes(),i.jsDate.getSeconds()+s.jsDate.getSeconds())};return i||s}(e,t)),pi.get(t).get(e)}function fi(e){const t=Math.trunc(e),s=Qo.fromTimestamp(t*ti-ni);let o=e-t;o=o<0?1+o:o;const i=Math.round(24*o),n=Math.round(24*(o-i/24)*60),r=Math.round(24*(o-i/24-n/24/60)*60*60);return s.setHours(i),s.setMinutes(n),s.setSeconds(r),s}function vi(e){return Math.round(bi(e))}function bi(e){return(e.getTime()-ei.getTime())/ti}function Si(e){return new Qo(e.getFullYear(),e.getMonth()+1,0).getDate()}function Ci(e){return Si(e)===e.getDate()}function yi(e,t,s){const o=e.getFullYear(),i=e.getMonth(),n=e.getDate(),r=new Qo(o,i+t,1);return s&&n===Si(e)||n>Si(r)?r.setDate(Si(r)):r.setDate(n),r}function Ii(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function wi(e,t,s){if(e===t)return 0;if(e>t){const s=t;t=e,e=s}const o=fi(e),i=fi(t);let n=o.getDate(),r=i.getDate();const a=o.getMonth(),l=i.getMonth(),c=o.getFullYear(),h=i.getFullYear();let d=0,u=0;switch(s){case 0:31===n&&(n=30),30===n&&31===r&&(r=30),1===a&&n===(Ii(c)?29:28)&&(n=30,1===l&&r===(Ii(h)?29:28)&&(r=30)),d=c+(30*a+n)/360,u=h+(30*l+r)/360;break;case 1:let s=365;const o=c===h;if(!o&&!(c+1===h)||!o&&a<l||!o&&a===l&&n<r){let e=0,t=0;for(let s=c;s<=h;s++)e++,t+=Ii(s)?366:365;s=t/e}else o?Ii(c)&&(s=366):(Ii(c)&&a<2&&(s=366),Ii(h)&&(l>1||1===l&&29===r)&&(s=366));d=e/s,u=t/s;break;case 2:d=e/360,u=t/360;break;case 3:d=e/365,u=t/365;break;case 4:31===n&&(n=30),31===r&&(r=30),d=c+(30*a+n)/360,u=h+(30*l+r)/360}return u-d}function Ei(e,t){const s=12*(t.getFullYear()-e.getFullYear())+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?s-1:s}function Ri(e,t){const s=e.getTime(),o=t.getTime();return Math.floor((o-s)/ti)}function xi(e,t){const s=t.getFullYear()-e.getFullYear(),o=e.getMonth(),i=t.getMonth(),n=e.getDate(),r=t.getDate();return i>o||i===o&&r>=n?s:s-1}function Ti(e,t,s){return t>s?Ti(e,s,t):(e=Math.trunc(e),t=Math.trunc(t),s=Math.trunc(s),e>=t&&e<=s)}const Ai=_t((function(e){return e=$e(e),new RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:e(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)})),Di=_t((function(e){const t=$e(e.decimalSeparator),s="(?:\\s*"+`(?:\\d+(?:${$e(e.thousandsSeparator||"")}\\d{3,})*(?:${t}\\d*)?)`+"|"+`(?:${t}\\d+)`+")(?:e(?:\\+|-)?\\d+)?(?:\\s*%)?",o="(?:\\s*-)?",i="(?:\\s*[\\$€])?",n="^(?:(?:"+[o+i+s,o+s+i,i+o+s].join(")|(?:")+"))$";return new RegExp(n,"i")}));function _i(e,t){return!!e&&Di(t).test(e.trim())}const Fi=_t((function(e){return new RegExp(`[$€${$e(e.thousandsSeparator||"")}]`,"g")}));function Oi(e,t){e=e.replace(Fi(t),""),"."!==t.decimalSeparator&&(e=e.replace(t.decimalSeparator,"."));let s=Number(e);return isNaN(s)&&e.includes("%")&&(s=Number(e.split("%")[0]),!isNaN(s))?s/100:s}function Pi(e,t,s){const o=[...e].sort(((e,t)=>e-t));let i=(o.length+(s?-1:1))*t;if(s||i--,Number.isInteger(i))return o[i];const n=Math.ceil(i),r=Math.floor(i);return o[n]*(i-r)+o[r]*(n-i)}const Mi={NotAvailable:"#N/A",InvalidReference:"#REF",BadExpression:"#BAD_EXPR",CircularDependency:"#CYCLE",UnknownFunction:"#NAME?",DivisionByZero:"#DIV/0!",SpilledBlocked:"#SPILL!",GenericError:"#ERROR",NullError:"#NULL!"},Ni=new Set(Object.values(Mi));class Li{message;value;constructor(e=Go("Error"),t=Mi.GenericError){this.message=e,this.value=t,this.message=e.toString()}}class ki extends Li{constructor(e=Go("Invalid expression")){super(e,Mi.BadExpression)}}class Vi extends Li{constructor(e=Go("Circular reference")){super(e,Mi.CircularDependency)}}class Ui extends Li{constructor(e=Go("Invalid reference")){super(e,Mi.InvalidReference)}}class Hi extends Li{constructor(e=Go("Data not available")){super(e,Mi.NotAvailable)}}class zi extends Li{constructor(e=Go("Unknown function")){super(e,Mi.UnknownFunction)}}class Bi extends Li{constructor(e=Go("Spill range is not empty")){super(e,Mi.SpilledBlocked)}}class Gi extends Li{constructor(e=Go("Division by zero")){super(e,Mi.DivisionByZero)}}const Wi=["number","string","boolean","undefined"];function $i(e){if(void 0!==e)return R(e)?e[0][0]?.format:e.format}function qi(e){return"string"==typeof e&&Ni.has(e)}function Zi(e){return{value:Mi.NotAvailable,message:Go("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",tn(e))}}const ji=e=>Go("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function Yi(e,t){const s=an(e);switch(typeof s){case"number":return s;case"boolean":return s?1:0;case"string":if(_i(s,t)||""===s)return Oi(s,t);const e=mi(s,t);if(e)return e.value;throw new Li(ji(s));default:return 0}}function Xi(e,t){try{return Yi(e,t)}catch(e){return}}function Ki(e,t){return An(e).map((e=>e.map((e=>{if("number"!=typeof e.value)throw new Li(Go("Function [[FUNCTION_NAME]] expects number values for %s, but got a %s.",t,typeof e.value));return e.value}))))}function Ji(e,t){const s=an(e);if(""===s)throw new Li(ji(s));return Yi(s,t)}function Qi(e,t){return Math.trunc(Yi(e,t))}function en(e,t){return Math.trunc(Ji(e,t))}function tn(e){const t=an(e);switch(typeof t){case"string":return t;case"number":return t.toString();case"boolean":return t?"TRUE":"FALSE";default:return""}}const sn=_t((function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")})),on=e=>Go("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a boolean.",e);function nn(e){const t=an(e);switch(typeof t){case"boolean":return t;case"string":if(t){const e=t.toUpperCase();if("TRUE"===e)return!0;if("FALSE"===e)return!1;throw new Li(on(t))}return!1;case"number":return!!t;default:return!1}}function rn(e,t){return fi(Yi(an(e),t))}function an(e){if("object"==typeof e&&null!==e&&"value"in e){if(qi(e.value))throw e;return e.value}if(qi(e))throw new Li("",e);return e}function ln(e,t,s){for(const o of e)if(R(o)){const e=o.length,s=o[0].length;for(let i=0;i<s;i++)for(let s=0;s<e;s++)t(o[s][i])}else s(o)}function cn(e,t){ln(e,(e=>{if(qi(e.value))throw e;t(e)}),(e=>{if(qi(e?.value))throw e;t(e)}))}function hn(e,t,s){ln(e,(e=>{if("number"==typeof e?.value&&t(e),qi(e?.value))throw e}),(e=>{t({value:Ji(e,s),format:e?.format})}))}function dn(e,t,s,o,i="rowFirst"){let n=o;for(const o of e)if(R(o)){const e=o.length,s=o[0].length;if("rowFirst"===i)for(let i=0;i<s;i++)for(let s=0;s<e;s++)n=t(n,o[s][i]);else for(let i=0;i<e;i++)for(let e=0;e<s;e++)n=t(n,o[i][e])}else n=s(n,o);return n}function un(e,t,s,o="rowFirst"){return dn(e,t,t,s,o)}function gn(e,t,s,o){return dn(e,((e,s)=>{const o=s?.value;if("number"==typeof o)return t(e,o);if(qi(o))throw s;return e}),((e,s)=>t(e,Ji(s,o))),s)}function pn(e,t,s,o){return dn(e,((e,s)=>{const i=s?.value;if(null!=i){if("number"==typeof i)return t(e,i);if("boolean"==typeof i)return t(e,Yi(i,o));if(qi(i))throw s;return t(e,0)}return e}),((e,s)=>t(e,Yi(s,o))),s)}function mn(e,t,s){const o=Array(e);for(let i=0;i<e;i++){o[i]=Array(t);for(let e=0;e<t;e++)o[i][e]=s(i,e)}return o}function fn(e,t){return 0===e.length?[]:mn(e.length,e[0].length,((s,o)=>t(e[s][o])))}function vn(e){return e.length?mn(e[0].length,e.length,((t,s)=>e[s][t])):[]}function bn(e,t,s=void 0){let o,i=1,n=1,r=1/0,a=1/0;for(let e=0;e<t.length;e++){const l=t[e];if(R(l)&&(void 0===s||s[e])){const s=l.length,c=l[0].length;1!==s||1!==c?(o??=new Array(t.length),1!==s&&1!==c?(o[e]="matrix",i=Math.max(i,s),n=Math.max(n,c),r=Math.min(r,s),a=Math.min(a,c)):1!==s?(o[e]="horizontal",i=Math.max(i,s),r=Math.min(r,s)):1!==c&&(o[e]="vertical",n=Math.max(n,c),a=Math.min(a,c))):t[e]=l[0][0]}}if(1===i&&1===n)return e(...t);return mn(i,n,((s,i)=>{if(s>r-1||i>a-1)return new Hi(Go("Array arguments to [[FUNCTION_NAME]] are of different size."));const n=e(...(l=s,c=i,t.map(((e,t)=>{switch(o?.[t]){case"matrix":return e[l][c];case"horizontal":return e[l][0];case"vertical":return e[0][c];case void 0:return e}}))));var l,c;return R(n)?n[0][0]:n}))}function Sn(e,t){return function(e,t,s){for(const o of e)if(R(o)){const e=o.length,s=o[0].length;for(let i=0;i<s;i++)for(let s=0;s<e;s++)if(!t(o[s][i]??void 0))return}else if(!s(o))return}(e,(e=>{const s=e?.value;if("boolean"==typeof s)return t(s);if("number"==typeof s)return t(!!s);if(qi(s))throw e;return!0}),(e=>void 0===e||null===e.value||t(function(e){const t=an(e);if(""===t)throw new Li(on(t));return nn(t)}(e))))}function Cn(e,t){let s,o,i=e.substring(0,2);return"<="===i||">="===i||"<>"===i?(s=i,o=e.substring(2)):(i=e.substring(0,1),"<"===i||">"===i||"="===i?(s=i,o=e.substring(1)):(s="=",o=e)),_i(o,t)||gi(o,t)?o=Yi(o,t):"TRUE"!==o&&"FALSE"!==o||(o=nn(o)),{operator:s,operand:o}}const yn=_t((function(e){if("*"===e)return/.+/;let t="",s="";for(const o of e)"?"===o&&"~"!==s?t+=".":"*"===o&&"~"!==s?t+=".*":("*"!==o&&"?"!==o||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(o)&&(t+="\\"),t+=o),s=o;return new RegExp("^"+t+"$","i")}));function In(e="",t,s){const{operator:o,operand:i}=t;if(void 0===i||null===e||null===i)return!1;if("number"==typeof i&&"="===o)return"string"==typeof e&&(_i(e,s)||gi(e,s))?Yi(e,s)===i:e===i;if("<>"===o||"="===o){let t;return t=typeof e==typeof i&&("string"==typeof e&&"string"==typeof i?yn(i).test(e):e===i),"="===o?t:!t}if(typeof e==typeof i)switch(o){case"<":return e<i;case">":return e>i;case"<=":return e<=i;case">=":return e>=i}return!1}function wn(e,t,s,o=!1){const i=e.length;if(i%2==1)throw new Li(Go("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const n=An(e[0]),r=n.length,a=n[0].length,l=[];for(let t=0;t<i-1;t+=2){const i=An(e[t]);if(i.length!==r||i[0].length!==a)throw new Li(Go("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const n=Cn(tn(e[t+1]),s);o&&"string"==typeof n.operand&&(n.operand+="*"),l.push(n)}for(let o=0;o<r;o++)for(let n=0;n<a;n++){let r=!0;for(let t=0;t<i-1;t+=2){if(r=In(An(e[t])[o][n].value??void 0,l[t/2],s),!r)break}r&&t(o,n)}}function En(e,t,s,o,i,n){if(void 0===t||null===t.value)return-1;if(qi(t.value))throw t;const r=xn(t.value),a=typeof r;let l,c,h,d,u,g,p=0,m=i-1;const f="desc"===o?t=>xn(n(e,i-t-1)):t=>xn(n(e,t));for(;m-p>=0;){for(h=Math.floor((p+m)/2),d=h,u=f(d),g=typeof u;p<d&&a!==g;)d--,u=f(d),g=typeof u;g===a&&null!=u?("strict"===s&&u===r?(l=u,c=d):"nextSmaller"===s&&u<=r?(null==l||l<u||l===u&&c<d)&&(l=u,c=d):"nextGreater"===s&&u>=r&&(void 0===l||l>u||l===u&&c<d)&&(l=u,c=d),u>r||"strict"===s&&u===r?m=d-1:p=h+1):p=h+1}return void 0===c?-1:"desc"===o?i-c-1:c}function Rn(e,t,s,o,i,n,r=!1){if(void 0===t||null===t.value)return-1;if(qi(t.value))throw t;const a=xn(t.value),l=r?(e,t)=>xn(i(e,o-t-1)):(e,t)=>xn(i(e,t)),c="wildcard"!==s||"string"!=typeof a||!(a.includes("*")||a.includes("?"));if(n&&c){const t=r?"reverseSearch":"forwardSearch";let i=n[t].get(e);if(void 0===i){i=new Map;for(let t=0;t<o;t++){const s=l(e,t)??null;i.has(s)||i.set(s,t)}n[t].set(e,i)}if(i.has(a)){const e=i.get(a);return r?o-e-1:e}if("strict"===s)return-1}const h=function(e,t,s,o,i){let n=s=>i(e,s)===t;if("wildcard"===s&&"string"==typeof t&&(t.includes("*")||t.includes("?"))){const s=yn(t);n=t=>{const o=i(e,t);return"string"==typeof o&&s.test(o)}}let r,a=-1;"nextSmaller"===s&&(n=s=>{const o=i(e,s);return(!r&&Tn(t,o)>=0||Tn(t,o)>=0&&Tn(o,r)>0)&&(r=o,a=s),o===t});"nextGreater"===s&&(n=s=>{const o=i(e,s);return(!r&&Tn(t,o)<=0||Tn(t,o)<=0&&Tn(o,r)<0)&&(r=o,a=s),o===t});for(let e=0;e<o;e++)if(n(e))return e;return a}(e,a,s,o,l);return r&&-1!==h?o-h-1:h}function xn(e){return"string"==typeof e?sn(e):e}function Tn(e,t){let s=Wi.indexOf(typeof e)-Wi.indexOf(typeof t);return 0===s&&("string"==typeof e&&"string"==typeof t?s=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?s=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(s=Number(e)-Number(t))),s}function An(e){return void 0===e?[[]]:R(e)?e:[[e]]}function Dn(e,t){return un(e,((e,s)=>(e.push(t(s)),e)),[],"rowFirst")}function _n(e){if(void 0===e)return!1;const{value:t}=e;return null!==t&&""!==t}const Fn=Go("[[FUNCTION_NAME]] has no valid input data.");function On(e){return Go("[[FUNCTION_NAME]] expects the provided values of %(argName)s to be a non-empty matrix.",{argName:e})}function Pn(e){let t;if('"'===e.current?(e.shift(),t='"'):e.currentStartsWith("[$")&&(e.advanceBy(2),t="]"),!t)return null;let s="";for(;e.current&&e.current!==t;)s+=e.shift();if(e.current!==t)throw new Error("Unterminated string in format");return e.shift(),{type:"STRING",value:s}}const Mn=new Set("$+-/():!^&~{}<>= ");function Nn(e){if("\\"===e.current){e.shift();const t=e.shift();if(!t)throw new Error("Unexpected end of format string");return{type:"CHAR",value:t}}return Mn.has(e.current)?{type:"CHAR",value:e.shift()}:null}function Ln(e){return","===e.current?(e.shift(),{type:"THOUSANDS_SEPARATOR",value:","}):null}function kn(e){return"@"===e.current?(e.shift(),{type:"TEXT_PLACEHOLDER",value:"@"}):null}function Vn(e){return"."===e.current?(e.shift(),{type:"DECIMAL_POINT",value:"."}):null}function Un(e){return"%"===e.current?(e.shift(),{type:"PERCENT",value:"%"}):null}function Hn(e){if("0"===e.current||"#"===e.current){const t=e.current;return e.shift(),{type:"DIGIT",value:t}}return null}const zn=new Set("dmqyhsa");function Bn(e){if(!zn.has(e.current))return null;const t=e.current;let s="";for(;e.current===t;)s+=e.shift();return{type:"DATE_PART",value:s}}function Gn(e){if("*"!==e.current)return null;e.shift();const t=e.shift();if(!t)throw new Error("Unexpected end of format string");return{type:"REPEATED_CHAR",value:t}}const Wn=20,$n={};function qn(e){let t=$n[e];return void 0===t&&(t=function(e){const t=function(e){const t=new Ut(e),s=[];let o=[];for(s.push(o);!t.isOver();){if(";"===t.current){o=[],s.push(o),t.shift();continue}const e=Hn(t)||Pn(t)||Nn(t)||Ln(t)||Vn(t)||Un(t)||Bn(t)||kn(t)||Gn(t);if(!e)throw new Error("Unknown token at "+t.remaining());o.push(e)}return s}(e);for(const e of t){const t=e.filter((e=>"REPEATED_CHAR"===e.type));for(const e of t.slice(1))e.type="CHAR"}const s=jn(t[0])||Zn(t[0])||Yn(t[0]);if(!s)throw new Error("Invalid first format part of: "+e);if(t.length>1&&"text"===s.type)throw new Error("The first format in a multi-part format must be a number format: "+e);const o=jn(t[1])||Zn(t[1]);if(t[1]?.length&&!o)throw new Error("Invalid second format part of: "+e);const i=jn(t[2])||Zn(t[2]);if(t[2]?.length&&!i)throw new Error("Invalid third format part of: "+e);const n=Yn(t[3]);if(t[3]?.length&&!n)throw new Error("Invalid fourth format part of: "+e);return{positive:s,negative:o,zero:i,text:n}}(e),$n[e]=t),t}function Zn(e){if(!e||!function(e){return e.every((e=>"DIGIT"===e.type||"DECIMAL_POINT"===e.type||"THOUSANDS_SEPARATOR"===e.type||"PERCENT"===e.type||"STRING"===e.type||"CHAR"===e.type||"REPEATED_CHAR"===e.type))}(e))return;const t=[];let s,o=t,i=0,n=0,r=e.findLastIndex((e=>"DIGIT"===e.type)),a=!1,l=0;for(let c=0;c<e.length;c++){const h=e[c];switch(h.type){case"DIGIT":o===t?o.push(h):l<Wn&&(o.push(h),l++);break;case"DECIMAL_POINT":if(o!==t)throw new Error("Multiple decimal points in a number format");s=[],o=s;break;case"REPEATED_CHAR":case"CHAR":case"STRING":o.push(h);break;case"PERCENT":i++,o.push(h);break;case"THOUSANDS_SEPARATOR":c-1===r?(n+=1,r++,o.push(h)):"DIGIT"===e[c+1]?.type&&"DIGIT"===e[c-1]?.type?(o===t&&(a=!0),o.push(h)):o.push({type:"CHAR",value:","})}}return{type:"number",integerPart:t,decimalPart:s,percentSymbols:i,thousandsSeparator:a,magnitude:n}}function jn(e){const t=e&&function(e){return e.every((e=>"DATE_PART"===e.type||"DECIMAL_POINT"===e.type||"THOUSANDS_SEPARATOR"===e.type||"STRING"===e.type||"CHAR"===e.type||"REPEATED_CHAR"===e.type))}(e)?{type:"date",tokens:e}:void 0;if(!t)return;if(t.tokens.length&&t.tokens.every((e=>"DATE_PART"===e.type&&"a"===e.value)))throw new Error("Invalid date format");const s=function(e){const t=e.filter((e=>"DATE_PART"===e.type));for(let e=0;e<t.length;e++)!t[e].value.startsWith("m")||t[e].value.length>2||(t[e-1]?.value.startsWith("h")||t[e+1]?.value.startsWith("s"))&&(t[e].value=t[e].value.replaceAll("m","M"));return e}(t.tokens.map((e=>"THOUSANDS_SEPARATOR"===e.type||"DECIMAL_POINT"===e.type?{type:"CHAR",value:e.value}:e)));return{type:"date",tokens:s}}function Yn(e){return e&&function(e){return e.every((e=>"STRING"===e.type||"TEXT_PLACEHOLDER"===e.type||"CHAR"===e.type||"REPEATED_CHAR"===e.type))}(e)?{type:"text",tokens:e}:void 0}function Xn(e){return[Kn(e.positive),Kn(e.negative),Kn(e.zero),Kn(e.text)].filter(ut).join(";")}function Kn(e){if(!e)return;let t="";const s="number"!==e.type?e.tokens:function(e){const t=[...e.integerPart];e.decimalPart&&(t.push({type:"DECIMAL_POINT",value:"."}),t.push(...e.decimalPart));return t}(e);for(const e of s)switch(e.type){case"STRING":t+=`[$${e.value}]`;break;case"CHAR":t+=(o=e.value,Mn.has(o)?e.value:`\\${e.value}`);break;case"REPEATED_CHAR":t+="*"+e.value;break;case"DATE_PART":t+="MM"===e.value?"mm":e.value;break;default:t+=e.value}var o;return t}const Jn=11,Qn="REPEATED_CHAR_PLACEHOLDER_",er={0:Go("January"),1:Go("February"),2:Go("March"),3:Go("April"),4:Go("May"),5:Go("June"),6:Go("July"),7:Go("August"),8:Go("September"),9:Go("October"),10:Go("November"),11:Go("December")},tr={0:Go("Sunday"),1:Go("Monday"),2:Go("Tuesday"),3:Go("Wednesday"),4:Go("Thursday"),5:Go("Friday"),6:Go("Saturday")};function sr(e,t,s,o=!1){return o?wr({value:e,format:t},s):or(e,{format:t,locale:s})}function or(e,{format:t,locale:s,formatWidth:o}){switch("boolean"==typeof e&&(e=e?"TRUE":"FALSE"),typeof e){case"string":{if(e.includes('\\"')&&(e=e.replaceAll(/\\"/g,'"')),!t)return e;const s=ir(e,qn(t)).format;return s&&"text"===s.type?nr(e,s,o):e}case"number":t||(t=mr(e));const i=qn(t),{format:n,isNegativeFormat:r}=ir(e,i);if(!n)return e.toString();if("text"===n.type)return nr(e.toString(),n,o);if(r&&(e=Math.abs(e)),"date"===n.type)return rr(function(e,t){const s=fi(e),o=t.tokens.some((e=>"DATE_PART"===e.type&&"a"===e.value));let i="";for(const e of t.tokens)switch(e.type){case"DATE_PART":i+=gr(s,e.value,o);break;case"REPEATED_CHAR":i+=Qn+e.value;break;default:i+=e.value}return i}(e,n),o);const a=e<0,l=rr(function(e,t,s){if(e===1/0)return"∞"+(t.percentSymbols?"%":"");const o=2*t.percentSymbols-3*t.magnitude;e*=10**o;let i=0;void 0!==t.decimalPart&&(i=t.decimalPart.filter((e=>"DIGIT"===e.type)).length);const{integerDigits:n,decimalDigits:r}=lr(Math.abs(e),i);let a=function(e,t,s){let o=t.integerPart;o.some((e=>"DIGIT"===e.type))||(o=[...o,{type:"DIGIT",value:"#"}]);"0"===e&&(e="");let i="";const n=o.findIndex((e=>"DIGIT"===e.type));let r=e.length-1;function a(t,o){if("0"===o&&(t=t||"0"),!t)return;const n=e.length-1-r;i=s&&n>0&&n%3==0?t+s+i:t+i}for(let t=o.length-1;t>=0;t--){const s=o[t];switch(s.type){case"DIGIT":if(a(e[r],s.value),r--,n===t)for(;r>=0;)a(e[r],"0"),r--;break;case"THOUSANDS_SEPARATOR":break;case"REPEATED_CHAR":i=Qn+s.value+i;break;default:i=s.value+i}}return i}(n,t,t.thousandsSeparator?s.thousandsSeparator:void 0);void 0!==t.decimalPart&&(a+=s.decimalSeparator+function(e,t){if(!t.decimalPart)return"";let s="",o=0;for(const i of t.decimalPart)switch(i.type){case"DIGIT":s+="#"===i.value?e[o]||"":e[o]||"0",o++;break;case"THOUSANDS_SEPARATOR":break;case"REPEATED_CHAR":s+=Qn+i.value;break;default:s+=i.value}return s}(r||"",t));return a}(Math.abs(e),n,s),o);return a?"-"+l:l;case"object":return""}}function ir(e,t){let s,o=!1;switch(typeof e){case"number":e<0&&t.negative?(s=t.negative,o=!0):s=0===e&&t.zero?t.zero:t.positive;break;case"string":const i=t.text||t.positive;"text"===i.type&&(s=i)}return{format:s,isNegativeFormat:o}}function nr(e,t,s){let o="";for(const s of t.tokens)switch(s.type){case"TEXT_PLACEHOLDER":o+=e;break;case"CHAR":case"STRING":o+=s.value;break;case"REPEATED_CHAR":o+=Qn+s.value}return rr(o,s)}function rr(e,t){const s=e.indexOf(Qn);if(-1===s)return e;const o=e.slice(0,s),i=e.slice(s+Qn.length+1),n=e[s+Qn.length];const{timesToRepeat:r,padding:a}=function(){if(!t)return{timesToRepeat:0,padding:""};const e=t.measureText(o+i),s=t.measureText(n),r=t.availableWidth-e;if(r<=0)return{timesToRepeat:0,padding:""};const a=Math.floor(r/s),l=r-a*s,c=t.measureText(" ");return{timesToRepeat:a,padding:" ".repeat(Math.floor(l/c))}}();return o+n.repeat(r)+a+i}const ar=[];function lr(e,t=Wn){const s=e.toString();if(s.includes("e"))return function(e,t=Wn){let s=ar[t];s||(s=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),ar[t]=s);const[o,i]=s.format(e).split(".");return{integerDigits:o,decimalDigits:i}}(e,t);if(Number.isInteger(e))return{integerDigits:s,decimalDigits:void 0};const o=s.indexOf(".");let i=s.substring(0,o),n=s.substring(o+1);if(0===t)return Number(n[0])>=5&&(i=(Number(i)+1).toString()),{integerDigits:i,decimalDigits:void 0};if(n.length>t){const{integerDigits:e,decimalDigits:s}=function(e,t){let s="0",o=e;const i=e.slice(0,t),n=t;if(Number(e[n])<5)return{integerDigits:s,decimalDigits:i};const r=i.match(hr)?.[0]||"",a=(Number(i)+1).toString(),l=i.slice(r.length),c=a.length>l.length;c&&!r?(s="1",o=void 0):o=c?r.slice(0,-1)+a:r+a;return{integerDigits:s,decimalDigits:o}}(n,t);n=s,"0"!==e&&(i=(Number(i)+Number(e)).toString())}return{integerDigits:i,decimalDigits:cr(n||"")}}function cr(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const hr=/^0+/;function dr(e,t){const{integerDigits:s,decimalDigits:o}=lr(e,20);return o?s+t+o:s}const ur=_t((function(e){if(!e)return!1;try{return"date"===qn(e).positive.type}catch(e){return!1}}));function gr(e,t,s){switch(t){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return tr[e.getDay()].slice(0,3);case"dddd":return tr[e.getDay()].toString();case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return er[e.getMonth()].slice(0,3);case"mmmm":return er[e.getMonth()].toString();case"mmmmm":return er[e.getMonth()].slice(0,1);case"qq":return Go("Q%(quarter)s",{quarter:e.getQuarter()}).toString();case"qqqq":return Go("Quarter %(quarter)s",{quarter:e.getQuarter()}).toString();case"yy":const o=String(e.getFullYear()).replace("-","").padStart(2,"0");return o.slice(o.length-2);case"yyyy":return e.getFullYear();case"hhhh":return Math.floor((e.getTime()-ei.getTime())/36e5).toString();case"hh":let i=e.getHours();return s&&(i=0===i?12:i>12?i-12:i),i.toString().padStart(2,"0");case"MM":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");case"a":return e.getHours()>=12?"PM":"AM";default:throw new Error(`invalid date format token: ${t}`)}}const pr=_t((function(e){return new RegExp(`[0-9]+${$e(e.decimalSeparator)}[0-9]`)}));function mr(e){let{integerDigits:t,decimalDigits:s}=lr(e);if(!s)return"0";const o=t.replace("-","").length;if(o+2>Jn)return"0";const i=Jn-o-1;return({decimalDigits:s}=lr(e,Math.min(i,s.length))),s?"0."+"0".repeat(s.length):"0"}function fr(e,t){if(!gi(e,t))return;return mi(e,t).format}function vr(e){const t=e.includes(".")?"0.00":"0",s=e.match(/[\$€]/);if(s){const o=e.match(/[\d]/),i="[$"+s.values().next().value+"]";return o.index<s.index?"#,##"+t+i:i+"#,##"+t}if(e.includes("%"))return t+"%"}function br(e){const t=e.decimalPlaces??2,s=e.position??"before",o=e.code??"",i=e.symbol??"",n="#,##0"+(t?"."+"0".repeat(t):"");let r=`${o} ${i}`.trim();return"after"===s&&o&&(r=" "+r),function(e,t,s){const o=`[$${e}]`;return"before"===t?o+s:s+o}(r,s,n)}function Sr(e){const t=e.decimalPlaces??2,s=e.position??"before",o=e.code??"",i=e.symbol??"",n="#,##0"+(t?"."+"0".repeat(t):"");let r=`${o} ${i}`.trim();"after"===s&&o&&(r=" "+r);return[Cr(r,s,` ${n} `),Cr(r,s,`(${n})`),Cr(r,s," - ")].join(";")}function Cr(e,t,s){const o=`[$${e}]`;return"before"===t?o+"* "+s:s+"* "+o}function yr(e){const t=qn(e);return Xn({positive:Ir(t.positive),negative:t.negative?Ir(t.negative):void 0,zero:t.zero?Ir(t.zero):void 0,text:t.text})}function Ir(e){if("number"!==e.type||!e.decimalPart)return e;const t=e.decimalPart.filter((e=>"DIGIT"!==e.type));return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...t]}}function wr({value:e,format:t},s){return or(e,{format:Er({value:e,format:t},void 0,s),locale:s})}function Er(e,t,s){let o=0;try{o=Math.abs(Yi(e?.value,s))}catch(e){return""}const i=e?.format;if(void 0!==t){const e=t?.value;switch(e){case"k":return Rr(i,1,"k");case"m":return Rr(i,2,"m");case"b":return Rr(i,3,"b");default:throw new Li(Go("The formatting unit should be 'k', 'm' or 'b'."))}}return o<1e5?Rr(i,0,""):o<1e8?Rr(i,1,"k"):o<1e11?Rr(i,2,"m"):Rr(i,3,"b")}function Rr(e,t,s,o){const i=qn(e||"#,##0");return Xn({positive:xr(i.positive,t,s),negative:i.negative?xr(i.negative,t,s):void 0,zero:i.zero?xr(i.zero,t,s):void 0,text:i.text})}function xr(e,t,s){if("number"!==e.type)return e;const o={type:"STRING",value:s};let i=[...e.integerPart];const n=i.findLastIndex((e=>"DIGIT"===e.type));if(-1===n)throw new Error("Cannot create a large number format from a format with no digit.");for(;"THOUSANDS_SEPARATOR"===i[n+1]?.type;)i=Ft(i,[n+1]);const r=i[n+1];i="STRING"===r?.type&&["m","k","b"].includes(r.value)?Pt(i,o,n+1):Ot(i,[o],n+1),t>0&&(i=Ot(i,Array(t).fill({type:"THOUSANDS_SEPARATOR",value:","}),n+1));const a=e.percentSymbols-i.filter((e=>"PERCENT"===e.type)).length;return i.push(...new Array(a).fill({type:"PERCENT",value:"%"})),{...e,integerPart:i,decimalPart:void 0,magnitude:t}}function Tr(e,t){const s=qn(e);return Xn(qn(Xn({positive:Ar(s.positive,t),negative:s.negative?Ar(s.negative,t):void 0,zero:s.zero?Ar(s.zero,t):void 0,text:s.text})))}function Ar(e,t){return"number"!==e.type?e:t>0?function(e,t){let s=e.integerPart,o=e.decimalPart;if(!o){const e=s.findLastIndex((e=>"DIGIT"===e.type));o=s.slice(e+1),s=s.slice(0,e+1)}const i=Je(0,t).map((()=>({type:"DIGIT",value:"0"}))),n=o.findLastIndex((e=>"DIGIT"===e.type));o=-1===n?[...i,...o]:Ot(o,i,n+1);return{...e,decimalPart:o,integerPart:s}}(e,t):function(e,t){let s=e.decimalPart;if(!s)return e;const o=[];let i=0;for(let e=s.length-1;e>=0&&!(i>=Math.abs(t));e--)"DIGIT"===s[e].type&&(i++,o.push(e));if(s=Ft(s,o),s.some((e=>"DIGIT"===e.type)))return{...e,decimalPart:s};return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...s]}}(e,Math.abs(t))}function Dr(e){const t=qn(e);for(const e of[t.positive,t.negative,t.zero])if(e&&"date"===e.type&&e.tokens.some((e=>"DATE_PART"===e.type&&e.value.includes("q"))))return!1;return!0}function _r(e){if(!e)return!1;try{return"text"===qn(e).positive.type}catch{return!1}}function Fr(e,t,s){return Pr({value:_r(t.format)&&null!==e.parsedValue?e.content:e.parsedValue,format:t.format,origin:s},t.locale)}function Or(e,t){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);if(""===e)return null;if(e.includes("\n"))return e;if(_i(e,w))return Oi(e,w);const s=mi(e,t);return s?s.value:tt(e)?"TRUE"===e.toUpperCase():e}function Pr(e,t=w,s,o){const i=Jo(e.value);if(!i){return kr(Mr(e,t,s),e.origin??o)}const n=Or(i.label,t);return kr({...Mr({value:n,format:e.format||("number"==typeof n?fr(i.label,t)||vr(i.label):void 0)},t,s),link:i},e.origin??o)}function Mr(e,t,s){let{value:o,format:i,message:n}=e;i=s?.format||i;const a=or(o,{format:i,locale:t});return qi(o)?function(e,t){return{value:e,formattedValue:e,message:t,type:r.error,isAutoSummable:!1,defaultAlign:"center"}}(o,n):null===o?Lr(i):_r(i)?Nr(tn(o),i,a):"number"==typeof o?ur(i||"")?function(e,t,s){return{value:e,format:t,formattedValue:s,type:r.number,isAutoSummable:!1,defaultAlign:"right"}}(o,i,a):function(e,t,s){return{value:e||0,format:t,formattedValue:s,type:r.number,isAutoSummable:!0,defaultAlign:"right"}}(o,i,a):"boolean"==typeof o?function(e,t,s){return{value:e,format:t,formattedValue:s,type:r.boolean,isAutoSummable:!1,defaultAlign:"center"}}(o,i,a):Nr(o,i,a)}function Nr(e,t,s){return{value:e,format:t,formattedValue:s,type:r.text,isAutoSummable:!0,defaultAlign:"left"}}const Lr=_t((function(e){return{value:null,format:e,formattedValue:"",type:r.empty,isAutoSummable:!0,defaultAlign:"left"}}));function kr(e,t){return null===e.value||"origin"in e||(e.origin=t),e}function Vr(e){const t=Qo.now();switch(e){case"today":return bi(t);case"yesterday":return bi(Qo.fromTimestamp(t.setDate(t.getDate()-1)));case"tomorrow":return bi(Qo.fromTimestamp(t.setDate(t.getDate()+1)));case"lastWeek":return bi(Qo.fromTimestamp(t.setDate(t.getDate()-7)));case"lastMonth":return bi(Qo.fromTimestamp(t.setMonth(t.getMonth()-1)));case"lastYear":return bi(Qo.fromTimestamp(t.setFullYear(t.getFullYear()-1)))}}function Ur(e,t){return"dateValue"in e&&"exactDate"!==e.dateValue?[Vr(e.dateValue)]:e.values.map((e=>ui(e,t)))}function Hr(e,t){return e.map((e=>{if(e.startsWith("="))return e;const s=Or(e,t);return"number"==typeof s?or(s,{format:t.dateFormat,locale:t}):""}))}const zr=new WeakMap,Br=new WeakMap;function Gr(e,t){zr.has(t)||(zr.set(t,new Map),Br.set(t,0));const s=zr.get(t),o=qr(e);if(s.has(o)){const i=s.get(o);return t[i]=e,i}const i=Br.get(t)+1;return s.set(o,i),Br.set(t,i),t[i]=e,i}function Wr(e){const t={};for(const s in e){const o=ls(e[s].map(Us));for(const e of o)t[Ss(e)]=Number(s)}return t}function*$r(e,t){for(const s in t){const o=ms(s),i=t[s];for(let t=o.top;t<=o.bottom;t++)for(let s=o.left;s<=o.right;s++){const o={sheetId:e,col:s,row:t};yield[o,i]}}}function qr(e){if(null===e)return"null";if(void 0===e)return"undefined";if("object"!=typeof e)return String(e);if(Array.isArray(e)){const t=e.length;let s="[";for(let o=0;o<t;o++)o>0&&(s+=","),s+=qr(e[o]);return s+"]"}const t=Object.keys(e).sort();let s="{";for(const o of t)void 0!==e[o]&&(s+=`"${o}":${qr(e[o])},`);return s+="}",s}function Zr(e){return 20+120*Math.exp(-.035*(e-1))}const jr=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),Yr=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),Xr=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),Kr=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),Jr=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),Qr=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),ea=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[jr.source,/(\$?[A-Z]{1,3})?\$?[0-9]{1,7}\s*:\s*(\$?[A-Z]{1,3})?\$?[0-9]{1,7}\s*/i.source,/\$?[A-Z]{1,3}(\$?[0-9]{1,7})?\s*:\s*\$?[A-Z]{1,3}(\$?[0-9]{1,7})?\s*/i.source].join("|")+")"+/$/.source,"i");function ta(e){return Qr.test(e)}function sa(e){return Xr.test(e)}function oa(e){return Kr.test(e)}function ia(e){return Yr.test(e)}function na(e){if(!e.includes("!"))return{xc:e};const t=e.split("!"),s=t.pop();return{sheetName:Ze(t.join("!"))||void 0,xc:s}}function ra(e,t){return void 0!==e?`${Ye(e)}!${t}`:t}function aa(e){const t=[];for(let s=0;s<e;s++){const e={cells:{}};t.push(e)}return t}function la(e,t,s){return s.map((s=>s>=e?s+t:s))}function ca(e,t){return e=[...e].sort(((e,t)=>t-e)),t.map((t=>{for(const s of e)if(t>s)t--;else if(t===s)return;return t})).filter(ut)}function ha(e,t="Sheet"){let s=1,o=`${t}${s}`;for(;e.includes(o);)o=`${t}${s}`,s++;return o}function da(e,t){let s=1;const o=Go("Copy of %s",e);let i=o.toString();for(;t.includes(i);)i=`${o} (${s})`,s++;return i}function ua(e,t){return void 0!==e&&void 0!==t&&Ze(e.trim().toUpperCase())===Ze(t.trim().toUpperCase())}function ga(e,t){const s=e.zone,o=function(e,t){const{left:s,top:o,bottom:i,right:n}=e;if(void 0!==n&&void 0!==i)return e;if(void 0===i&&void 0!==n)return{right:n,top:o,left:s,bottom:t.numberOfRows-1};if(void 0===n&&void 0!==i)return{bottom:i,left:s,top:o,right:t.numberOfCols-1};throw new Error("Bad zone format")}(s,t(e.sheetId));let i=e.parts;return 1===e.parts.length&&Gs(o)>1?i=[e.parts[0],e.parts[0]]:2===e.parts.length&&1===Gs(o)&&(i=[e.parts[0]]),{unboundedZone:s,zone:o,parts:i,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function pa(e,t){const s=e.xc,{xc:o,sheetName:i}=na(s),n=ps(o),r=function(e,t){const s=e.split(":").map((e=>{const t=ta(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}})),o=void 0===t.bottom,i=void 0===t.right;o&&(s[0].rowFixed=s[0].rowFixed||s[1].rowFixed,s[1].rowFixed=s[0].rowFixed||s[1].rowFixed);i&&(s[0].colFixed=s[0].colFixed||s[1].colFixed,s[1].colFixed=s[0].colFixed||s[1].colFixed);return s}(o,n);return ga({zone:n,parts:r,sheetId:e.sheetId,prefixSheet:Boolean(i),invalidSheetName:e.invalidSheetName},t)}function ma(e){const t={left:-1,top:-1,right:-1,bottom:-1};return{sheetId:"",zone:t,unboundedZone:t,parts:[],invalidXc:e,prefixSheet:!1}}function fa(e){return Bs(e.unboundedZone)}function va(e){return zs(e.unboundedZone)}function ba(e,t,s,o={useBoundedReference:!1,useFixedReference:!1}){if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return Mi.InvalidReference;if(e.zone.left<0||e.zone.top<0)return Mi.InvalidReference;const i=e.sheetId!==t||e.invalidSheetName||e.prefixSheet;let n="";if(i&&(n=e.invalidSheetName?e.invalidSheetName:Ye(s(e.sheetId))),i&&!n)return Mi.InvalidReference;let r=_a(e,0,o);return e.parts&&2===e.parts.length&&(e.zone.top!==e.zone.bottom||e.zone.left!==e.zone.right||e.parts[0].rowFixed||e.parts[0].colFixed||e.parts[1].rowFixed||e.parts[1].colFixed)&&(r+=":",r+=_a(e,1,o)),`${i?n+"!":""}${r}`}function Sa(e,t,s){const o=s.sheetId===e?t:s.sheetId;return{...s,sheetId:o}}function Ca(e,t,s){if(!s)return;const o=e.getRangeFromSheetXC(t,s);return o.invalidSheetName||o.invalidXc?void 0:o}function ya(e){const t=[];for(const s of e)for(const e of Ms(s.zone))t.push({...e,sheetId:s.sheetId});return t}function Ia(e){return wa.get(e.type)?.(e)}const wa=new class extends n{add(e,t){return super.add(e,t),this}get(e){return this.content[e]}};function Ea(e){const t="COL"===e.dimension?"left":"top",s="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows",i=[...e.elements];i.sort(((e,t)=>t-e));const n=Qe(i);return i=>{if(!ua(i.sheetId,e.sheetId))return{changeType:"NONE"};let r=i,a="NONE";for(const e of n){const n=Vt(e),l=kt(e);if(i.zone[t]<=n&&n<=i.zone[s]){const e=Math.min(i.zone[s],l)-n+1;a="RESIZE",r=Da(r,o,a,-e)}else if(i.zone[t]>=n&&i.zone[s]<=l)a="REMOVE",r=ma(Mi.InvalidReference);else if(i.zone[t]<=l&&i.zone[s]>=l){const e=l-i.zone[t]+1;a="RESIZE",r=Da(r,o,a,-e),r=Da(r,o,"MOVE",-(i.zone[t]-n))}else n<i.zone[t]&&(a="MOVE",r=Da(r,o,a,-(l-n+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}}function Ra(e){const t="COL"===e.dimension?"left":"top",s="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";return i=>{if(i.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(i.zone[t]<=e.base&&e.base<i.zone[s])return{changeType:"RESIZE",range:Da(i,o,"RESIZE",e.quantity)};if(e.base<i.zone[t])return{changeType:"MOVE",range:Da(i,o,"MOVE",e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[s])return{changeType:"RESIZE",range:Da(i,o,"RESIZE",e.quantity)};if(e.base<=i.zone[t])return{changeType:"MOVE",range:Da(i,o,"MOVE",e.quantity)}}return{changeType:"NONE"}}}function xa(e){return t=>{if(t.sheetId!==e.sheetId&&t.invalidSheetName!==e.sheetName)return{changeType:"NONE"};const s=e.sheetName;return{changeType:"REMOVE",range:t={...ma(Mi.InvalidReference),invalidSheetName:s}}}}function Ta(e){return t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.newName&&t.invalidSheetName===e.newName){const s=void 0,o=e.sheetId;return{changeType:"CHANGE",range:{...t,sheetId:o,invalidSheetName:s}}}if(e.oldName&&t.invalidSheetName===e.oldName){const s=void 0,o=e.sheetId;return{changeType:"CHANGE",range:{...t,sheetId:o,invalidSheetName:s}}}return{changeType:"NONE"}}}function Aa(e){const t=e.target[0];return s=>{if(s.sheetId!==e.sheetId||!_s(s.zone,t))return{changeType:"NONE"};const o=e.targetSheetId,i=Da(s,"both","MOVE",[e.col-t.left,e.row-t.top]),n=e.sheetId!==o||i.prefixSheet;return{changeType:"MOVE",range:{...i,sheetId:o,prefixSheet:n}}}}function Da(e,t,s,o){return{...e,unboundedZone:ks(e.unboundedZone,t,s,o),zone:ks(e.zone,t,s,o)}}function _a(e,t,s={useBoundedReference:!1,useFixedReference:!1}){const o=e.parts[t]?.colFixed||s.useFixedReference?"$":"",i=Xt(0===t?e.zone.left:e.zone.right),n=e.parts[t]?.rowFixed||s.useFixedReference?"$":"",r=String(0===t?e.zone.top+1:e.zone.bottom+1);let a="";return a=Bs(e.unboundedZone)&&!s.useBoundedReference?0===t&&e.unboundedZone.hasHeader?o+i+n+r:o+i:zs(e.unboundedZone)&&!s.useBoundedReference?0===t&&e.unboundedZone.hasHeader?o+i+n+r:n+r:o+i+n+r,a}function Fa(e,t,s){const o=[];return t.forEach((t=>{const i=function(e,t){e=e.toLocaleLowerCase();let s=0,o=0;const i=(t=t.toLocaleLowerCase()).length;let n=0;for(let r=0;r<i;r++)t[r]===e[n]?(n++,o+=100+o-r/200):o=0,s+=o;return n===e.length?s:0}(e,s(t));i>0&&o.push({score:i,elem:t})})),o.sort(((e,t)=>t.score-e.score)),o.map((e=>e.elem))}function Oa(e,t=1){return t*(e+ae)-ae}function Pa(e,t,s,o){const i=Wa(e,t,s,"wrap"===s?.wrapping?o-2*ae:void 0).length;return Oa(Ba(s),i)+2*le}function Ma(e,t=!1,s=!1){return`${s?"italic":""} ${t?"bold":""} ${e}px ${ve}`}wa.add("REMOVE_COLUMNS_ROWS",(e=>({applyChange:Ea(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}))).add("ADD_COLUMNS_ROWS",(e=>({applyChange:Ra(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}))).add("DELETE_SHEET",(e=>({applyChange:xa(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}))).add("RENAME_SHEET",(e=>({applyChange:Ta(e),sheetId:e.sheetId,sheetName:{old:e.oldName,current:e.newName}}))).add("MOVE_RANGES",(e=>({applyChange:Aa(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})));const Na={};function La(e,t,s,o="pt"){return ka(e,t,za(s,o))}function ka(e,t,s){if(Na[s]||(Na[s]={}),void 0===Na[s][t]){const o=e.font;e.font=s,Na[s][t]=e.measureText(t).width,e.font=o}return Na[s][t]}const Va={};function Ua(e,t,s,o="pt"){const i=za(s,o);e.save(),e.font=i;const n=function(e,t){const s=e.font;Va[s]||(Va[s]={});if(void 0===Va[s][t]){const o=e.measureText(t),i=o.width,n=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent;Va[s][t]={width:i,height:n}}return Va[s][t]}(e,t);return e.restore(),n}function Ha(e){return Math.round(96*e/72)}function za(e,t="pt"){return`${e.italic?"italic ":""}${e.bold?"bold":me} ${("pt"===t?Ba(e):e.fontSize)??fe}px ${ve}`}function Ba(e){return Ha(e?.fontSize||fe)}function Ga(e,t,s,o){if(La(e,t,o)<=s)return[t];const i=[];let n="";for(const r of t){La(e,n+r,o)>s?(i.push(n),n=r):n+=r}return i.push(n),i}function Wa(e,t,s,o){s||(s={}),it(t)&&(t=at(t).label);const i=[],n=t.includes(Ne)?t.split(Ne):[t];for(const t of n){const n=t.includes(" ")?t.split(" "):[t];if(!o){i.push(t);continue}let r="",a=o;for(const t of n){const n=Ga(e,t,o,s),l=n.pop(),c=La(e,l,s);if(n.length)""!==r&&(i.push(r),r="",a=o),n.forEach((e=>{i.push(e)})),r=l,a=o-c;else{const t=""===r?l:" "+l,n=La(e,t,s);n<=a?(r+=t,a-=n):(i.push(r),r=l,a=o-c)}}""!==r&&i.push(r)}return i}function $a(e){return e?e.toLowerCase():""}const qa=/([0-9\.]*)px/;function Za(e,t,s){let o=ka(e,t,e.font);if(o<=s)return t;const i=ka(e,"…",e.font);if(o<=i)return t;let n=t.length;for(;o>=s-i&&n-- >0;)o=ka(e,t=t.substring(0,n),e.font);return t+"…"}function ja(e,t,s,o=!1,i=!1,n=function(e){return Number(e.match(qa)?.[1])}(e.font)/10){if(e.fillText(t,s.x,s.y),!o&&!i)return;const r=e.measureText(t),a=r.width,l=r.actualBoundingBoxAscent+r.actualBoundingBoxDescent,c=r.fontBoundingBoxAscent+r.fontBoundingBoxDescent;let{x:h,y:d}=s,u=d,g=d;switch(e.textAlign){case"center":h-=a/2;break;case"right":h-=a}switch(e.textBaseline){case"top":g+=c-2*n,u+=c/2-n;break;case"middle":g+=c/2-n;break;case"alphabetic":g+=2*n,u-=3*n;break;case"bottom":g=d,u-=l/2-n/2}o&&(e.lineWidth=n,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(h,g),e.lineTo(h+a,g),e.stroke()),i&&(e.lineWidth=n,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(h,u),e.lineTo(h+a,u),e.stroke())}function Ya(e,t,s,o,i="pt"){if(La(e,s,o,i)<=t)return s;const n=La(e,"...",o,i);if(n>=t)return"";let r,a=1,l=s.length;for(;a<=l;){const c=Math.floor((a+l)/2);r=La(e,s.slice(0,c),o,i),r+n>t?l=c-1:a=c+1}const c=s.slice(0,Math.max(0,a-1));return c?c+"...":""}class Xa{smallUuid(){return window.crypto?"10000000-1000".replace(/[01]/g,(e=>{const t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)})):"xxxxxxxx-xxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}uuidv4(){return window.crypto?"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>{const t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)})):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}}class Ka{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 Ja extends Ka{copy(e,t,s="copyPaste"){}pasteFromCopy(e,t,s,o){if(1===t.length)for(const i of Xs(t,s))this.pasteZone(e,i.left,i.top,s,o);else for(const i of ls(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 Qa extends Ka{copy(e){}}const el=["%"],tl="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(el);function sl(e,t=w){e=At(e);const s=new Ut(e),o=[],i=Rt.test(e)?pl:ml;for(;!s.isOver();){let e=fl(s)||i(s)||rl(s,t)||nl(s)||al(s)||hl(s)||ol(s)||vl(s)||cl(s,t)||gl(s);e||(e={type:"UNKNOWN",value:s.shift()}),o.push(e)}return o}function ol(e){return"?"===e.current?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const il={"(":{type:"LEFT_PAREN",value:"("},")":{type:"RIGHT_PAREN",value:")"}};function nl(e){if("("===e.current||")"===e.current){const t=e.shift();return il[t]}return null}function rl(e,t){if(e.current===t.formulaArgSeparator){return{type:"ARG_SEPARATOR",value:e.shift()}}return null}function al(e){for(const t of tl)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:"OPERATOR",value:t};return null}const ll=new Set("0123456789");function cl(e,t){if(!ll.has(e.current)&&e.current!==t.decimalSeparator)return null;const s=e.remaining().match(Ai(t.decimalSeparator));return s?(e.advanceBy(s[0].length),{type:"NUMBER",value:s[0]}):null}function hl(e){if('"'===e.current){const t=e.shift();let s=t;for(;e.current&&(e.current!==t||"\\"===s[s.length-1]);)s+=e.shift();return'"'===e.current&&(s+=e.shift()),{type:"STRING",value:s}}return null}const dl=/\p{L}|\p{N}|_|\.|!|\$/u,ul=new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$");function gl(e){let t="";if("'"===e.current){let s=e.shift();for(t+=s;e.current;)if(s=e.shift(),t+=s,"'"===s){if(!e.current||"'"!==e.current)break;s=e.shift(),t+=s}if("'"!==s)return{type:"UNKNOWN",value:t}}for(;e.current&&(ul.has(e.current)||e.current.match(dl));)t+=e.shift();if(t.length){const e=t;return ea.test(e)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function pl(e){let t="";for(;" "===e.current||e.current&&e.current.match(Rt);)t+=e.shift();return t?{type:"SPACE",value:t}:null}function ml(e){let t="";for(;" "===e.current;)t+=e.shift();return t?{type:"SPACE",value:t}:null}function fl(e){let t=0;for(;e.current===Ne;)t++,e.shift();return t?{type:"SPACE",value:Ne.repeat(t)}:null}function vl(e){return e.currentStartsWith(Mi.InvalidReference)?(e.advanceBy(Mi.InvalidReference.length),{type:"INVALID_REFERENCE",value:Mi.InvalidReference}):null}function bl(e){if(!e||"object"!=typeof e||e.thousandsSeparator&&"string"!=typeof e.thousandsSeparator)return!1;for(const t of["code","name","decimalSeparator","dateFormat","timeFormat","formulaArgSeparator"])if(!e[t]||"string"!=typeof e[t])return!1;if(e.formulaArgSeparator===e.decimalSeparator)return!1;if(e.thousandsSeparator===e.decimalSeparator)return!1;try{or(1,{locale:e,format:"#,##0.00"}),or(1,{locale:e,format:e.dateFormat}),or(1,{locale:e,format:e.timeFormat})}catch{return!1}return!0}function Sl(e,t){return Gt(e)?wl(e,t):xl(e,t)}function Cl(e,t){return Gt(e)?wl(e,t):function(e,t){if(gi(e,t)){const s=Yi(e,t);let o=w.dateFormat;return Number.isInteger(s)||(o+=" "+w.timeFormat),or(s,{locale:w,format:o})}return xl(e,t)}(e,t)}function yl(e,t){return e.startsWith("=")?El(e,t):function(e,t){if(gi(e,w)){const s=Yi(e,w);let o=t.dateFormat;return Number.isInteger(s)||(o+=" "+t.timeFormat),or(s,{locale:t,format:o})}return function(e,t){if("."===t.decimalSeparator||!_i(e,w))return e;const s=pr(w);return e.replace(s,(e=>e.replace(".",t.decimalSeparator)))}(e,t)}(e,t)}function Il(e,t){return Gt(e)?wl(e,t):xl(e,t)}function wl(e,t){return Rl(e.startsWith("+")?"="+e.slice(1):e,t,w)}function El(e,t){return Rl(e,w,t)}function Rl(e,t,s){if(t.formulaArgSeparator===s.formulaArgSeparator&&t.decimalSeparator===s.decimalSeparator)return e;const o=sl(e,t);let i="";for(const e of o)"NUMBER"===e.type?i+=e.value.replace(t.decimalSeparator,s.decimalSeparator):"ARG_SEPARATOR"===e.type?i+=s.formulaArgSeparator:i+=e.value;return i}function xl(e,t){return"."!==t.decimalSeparator&&_i(e,t)?(t.thousandsSeparator&&(e=e.replaceAll(t.thousandsSeparator,"")),e.replace(t.decimalSeparator,".")):e}function Tl(e,t){return _l(e,(e=>Cl(e,t)))}function Al(e,t){return _l(e,(e=>yl(e,t)))}function Dl(e,t){const s=qe(e);return s.criterion.values=s.criterion.values.map((e=>yl(e,t))),s}function _l(e,t){switch((e=qe(e)).type){case"CellIsRule":switch(e.operator){case"isBetween":case"isNotBetween":case"isEqual":case"isNotEqual":case"isGreaterThan":case"isGreaterOrEqualTo":case"isLessThan":case"isLessOrEqualTo":case"customFormula":return e.values=e.values.map((e=>t(e))),e;case"beginsWithText":case"containsText":case"endsWithText":case"notContainsText":case"isEmpty":case"isNotEmpty":return e}case"DataBarRule":return e;case"ColorScaleRule":return e.minimum=Fl(e.minimum,t),e.maximum=Fl(e.maximum,t),e.midpoint&&(e.midpoint=Fl(e.midpoint,t)),e;case"IconSetRule":return e.lowerInflectionPoint.value=t(e.lowerInflectionPoint.value),e.upperInflectionPoint.value=t(e.upperInflectionPoint.value),e}}function Fl(e,t){if(!e?.value)return e;const s=t("formula"===e.type?"="+e.value:e.value),o="formula"===e.type?s.slice(1):s;return{...e,value:o}}function Ol(e){return e.dateFormat+" "+e.timeFormat}function Pl(e){let t=!1,s=!0;return Sn(e,(e=>(t=!0,s=s&&e,s))),{foundBoolean:t,result:s}}function Ml(e){let t=!1,s=!1;return Sn(e,(e=>(t=!0,s=s||e,!s))),{foundBoolean:t,result:s}}function Nl(e,t){return gn(e,((e,t)=>e+t),0,t)}function Ll(e){return un(e,((e,t)=>_n(t)?e.add(t?.value):e),new Set).size}function kl(e,t){if(!e)throw new Li(t)}function Vl(e,t=Go("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")){if(0===e)throw new Gi(t)}function Ul(e){return 1===e.length||1===e[0].length}function Hl(...e){if(e.every(R)){const t=e[0].length,s=e[0][0].length;for(const o of e)if(o.length!==t||o[0].length!==s)return!1;return!0}return!e.some((e=>Array.isArray(e)&&(1!==e.length||1!==e[0].length)))}function zl(e){return e.length===e[0].length}const Bl=e=>Go("The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.",e);function Gl(e){const t=Array(e);for(let s=0;s<e;s++)t[s]=Array(e).fill(0),t[s][s]=1;return t}function Wl(e){if(e.length<1||e[0].length<1)throw new Error("invertMatrix: an empty matrix cannot be inverted.");if(e.length!==e[0].length)throw new Error("invertMatrix: only square matrices are invertible");let t=1;const s=e.length,o=Gl(s),i=e.map((e=>e.slice()));for(let e=0;e<s;e++){let n=i[e][e];if(0===n){for(let n=e+1;n<s;n++)if(0!==i[e][n]){$l(i,e,n),$l(o,e,n),t*=-1;break}if(n=i[e][e],0===n)return{determinant:0}}for(let t=0;t<s;t++)i[t][e]=i[t][e]/n,o[t][e]=o[t][e]/n;t*=n;for(let t=0;t<s;t++){if(t===e)continue;const n=i[e][t];for(let r=0;r<s;r++)i[r][t]-=n*i[r][e],o[r][t]-=n*o[r][e]}}return{inverted:o,determinant:t}}function $l(e,t,s){for(let o=0;o<e.length;o++){const i=e[o][t];e[o][t]=e[o][s],e[o][s]=i}}function ql(e,t){if(e.length<1||t.length<1)throw new Error("multiplyMatrices: empty matrices cannot be multiplied.");if(e.length!==t[0].length)throw new Error("multiplyMatrices: incompatible matrices size.");const s=e[0].length,o=t.length,i=e.length,n=Array(o);for(let r=0;r<o;r++){n[r]=Array(s);for(let o=0;o<s;o++){let s=0;for(let n=0;n<i;n++)s+=e[n][o]*t[r][n];n[r][o]=s}}return n}function Zl(e){if(!R(e))return e;if(!jl(e))throw new Error("The value should be a scalar or a 1x1 matrix");return e[0][0]}function jl(e){return 1===e.length&&1===e[0].length}function Yl(e){return R(e)&&!jl(e)}function Xl(...e){const t=e[0].length;e.forEach(((e,s)=>kl(e.length===t,Go("[[FUNCTION_NAME]] has mismatched dimensions for argument %s (%s vs %s).",s.toString(),t.toString(),e.length.toString()))))}function Kl(e,t){let s=0;const o=gn(e,((e,t)=>(s+=1,e+t)),0,t);return Vl(s),o/s}function Jl(e,t){let s=0;for(const o of e)if(R(o))for(const e of o)for(const t of e)"number"==typeof t.value&&(s+=1);else{const e=o?.value;qi(e)||"string"==typeof e&&!_i(e,t)&&!mi(e,t)||(s+=1)}return s}function Ql(e){return un(e,((e,t)=>void 0!==t&&null!==t.value?e+1:e),0)}function ec(e,t){let s={value:-1/0};return hn(e,(e=>{e.value>=s.value&&(s=e)}),t),s.value===-1/0?{value:0}:s}function tc(e,t){let s={value:1/0};return hn(e,(e=>{e.value<=s.value&&(s=e)}),t),s.value===1/0?{value:0}:s}function sc(e,t,s){const o=e[0].length?e:[Je(1,t.flat().length+1)],i=o.length;let n=s[0].length?s:o;return n=n.length===i?vn(n):n,{_X:o,_newX:n}}function oc(e,t,s=!0,o=!1){const i=t.flat(),n=i.length;let{_X:r}=sc(e,t,[[]]);r=r.length===n?vn(r):r.slice(),Xl(r[0],i);const a=r.length,l=n-a-(s?1:0),c=[i],h=vn(r.reverse()),d=[];for(let e=0;e<a;e++)if(d.push(0),s){for(const t of r[e])d[e]+=t;d[e]/=n}let u=0;if(s){for(const e of i)u+=e;u/=n}const g=h.map((e=>e.map(((e,t)=>e-d[t]))));s&&h.forEach((e=>e.push(1)));const p=nc(h,c);if(s||p.push([0]),!o)return p;const m=ql(g,vn(g)),{inverted:f}=Wl(m);if(void 0===f)throw new Li(Go("Matrix is not invertible"));let v=0,b=0;for(let e=0;e<n;e++){const t=i[e]-u;let s=0;for(let t=0;t<a;t++){s+=g[e][t]*p[t][0]}const o=t-s;v+=o*o,b+=s*s}const S=Math.sqrt(v/l),C=b/(b+v),y=b/a/(v/l),I=[];for(let e=0;e<a;e++)I.push(S*Math.sqrt(f[e][e]));if(s){const e=ql(f,[d]),t=ql(vn([d]),e);I.push(S*Math.sqrt(t[0][0]+1/i.length))}const w=[[p[0][0],I[0],C,y,b],[p[1][0],I[1],S,l,v]];for(let e=2;e<a;e++)w.push([p[e][0],I[e],"","",""]);return s?w.push([p[a][0],I[a],"","",""]):w.push([0,"","","",""]),w}function ic(e,t,s,o){Xl(t,e),kl(s>=1,Go("Function [[FUNCTION_NAME]] A regression of order less than 1 cannot be possible."));const i=[e],n=t.map((e=>Je(0,s).map((t=>Math.pow(e,s-t)))));o&&n.forEach((e=>e.push(1)));const r=nc(n,i);return o||r.push([0]),r}function nc(e,t){const s=ql(e,vn(e)),{inverted:o}=Wl(s);if(void 0===o)throw new Li(Go("Matrix is not invertible"));const i=ql(e,t);return vn(ql(o,i))}function rc(e,t,s){return e.reduce(((e,o,i)=>e+o*Math.pow(t,s-i)),0)}function ac(e){return e.map((e=>e.map((e=>Math.exp(e)))))}function lc(e){return e.map((e=>e.map((e=>Math.log(e)))))}function cc(e,t,s,o){const{_X:i,_newX:n}=sc(t,e,s),r=oc(i,e,o,!1),a=r.length-1,l=n.map((e=>{let t=0;for(let s=0;s<a;s++)t+=r[s][0]*e[a-s-1];return t+=r[a][0],[t]}));return l.length===s.length?l:vn(l)}const hc=new n;function dc(e){return hc.get(e)}const uc={normalizeFunctionValue:e=>Yi(e,w),toValueAndFormat:(e,t)=>({value:Yi(e,w),format:"dd mmm yyyy"}),toFunctionValue(e){const t=rn(e,w);return`DATE(${t.getFullYear()},${t.getMonth()+1},${t.getDate()})`}},gc={normalizeFunctionValue(e){const t=Yi(e,w);if(t<1||t>31)throw new Li(Go("%s is not a valid day of month (it should be a number between 1 and 31)",t));return t},toValueAndFormat:e=>({value:Yi(e,w),format:"0"}),toFunctionValue:e=>`${e}`},pc={normalizeFunctionValue(e){const t=Yi(e,w);if(t<1||t>7)throw new Li(Go("%s is not a valid day of week (it should be a number between 1 and 7)",t));return t},toValueAndFormat(e,t){const s=(e-1+(t||w).weekStart)%7;return{value:tr[s].toString(),format:"@"}},toFunctionValue:e=>`${e}`},mc={normalizeFunctionValue(e){const t=Yi(e,w);if(t<0||t>53)throw new Li(Go("%s is not a valid week (it should be a number between 0 and 53)",t));return t},toValueAndFormat:e=>({value:Yi(e,w),format:"0"}),toFunctionValue:e=>`${e}`},fc={normalizeFunctionValue(e){const t=Yi(e,w);if(t<1||t>12)throw new Li(Go("%s is not a valid month (it should be a number between 1 and 12)",t));return t},toValueAndFormat:e=>({value:er[Yi(e,w)-1].toString(),format:"@"}),toFunctionValue:e=>`${e}`},vc={normalizeFunctionValue:e=>or(Yi(e,w),{locale:w,format:"mm/yyyy"}),toValueAndFormat:e=>({value:Yi(e,w),format:"mmmm yyyy"}),toFunctionValue(e){const t=rn(e,w);return`DATE(${t.getFullYear()},${t.getMonth()+1},1)`}},bc={normalizeFunctionValue(e){const t=Yi(e,w);if(t<1||t>4)throw new Li(Go("%s is not a valid quarter (it should be a number between 1 and 4)",t));return t},toValueAndFormat:e=>({value:Go("Q%(quarter_number)s",{quarter_number:e}),format:"@"}),toFunctionValue:e=>`${e}`},Sc={normalizeFunctionValue(e){const t=Yi(e,w);return t>3e3?rn(t,w).getFullYear():t},toValueAndFormat:e=>({value:Yi(e,w),format:"0"}),toFunctionValue:e=>`${e}`},Cc={normalizeFunctionValue(e){const t=Yi(e,w);if(t<0||t>23)throw new Li(Go("%s is not a valid hour (it should be a number between 0 and 23)",t));return t},toValueAndFormat:e=>({value:Go("%(hour_number)sh",{hour_number:e}),format:"@"}),toFunctionValue:e=>`${e}`},yc={normalizeFunctionValue(e){const t=Yi(e,w);if(t<0||t>59)throw new Li(Go("%s is not a valid minute (it should be a number between 0 and 59)",t));return t},toValueAndFormat:e=>({value:Go("%(minute_number)s'",{minute_number:e}),format:"@"}),toFunctionValue:e=>`${e}`},Ic={normalizeFunctionValue(e){const t=Yi(e,w);if(t<0||t>59)throw new Li(Go("%s is not a valid second (it should be a number between 0 and 59)",t));return t},toValueAndFormat:e=>({value:Go("%(second_number)s''",{second_number:e}),format:"@"}),toFunctionValue:e=>`${e}`};function wc(e){return{normalizeFunctionValue:t=>null===t?null:e.normalizeFunctionValue(t),toValueAndFormat:(t,s)=>null===t?{value:Go("(Undefined)")}:e.toValueAndFormat(t,s),toFunctionValue:t=>null===t?"false":e.toFunctionValue(t)}}hc.add("day",wc(uc)).add("year",wc(Sc)).add("day_of_month",wc(gc)).add("iso_week_number",wc(mc)).add("month_number",wc(fc)).add("month",wc(vc)).add("quarter_number",wc(bc)).add("day_of_week",wc(pc)).add("hour_number",wc(Cc)).add("minute_number",wc(yc)).add("second_number",wc(Ic));const Ec={count:Go("Count"),count_distinct:Go("Count Distinct"),bool_and:Go("Boolean And"),bool_or:Go("Boolean Or"),max:Go("Maximum"),min:Go("Minimum"),avg:Go("Average"),sum:Go("Sum")},Rc=["max","min","avg","sum","count_distinct","count"],xc={integer:Rc,char:Rc,datetime:Rc,boolean:["count_distinct","count","bool_and","bool_or"]},Tc={};for(const e in xc){Tc[e]={};for(const t of xc[e])Tc[e][t]=Ec[t]}const Ac={count:e=>({value:Ql([e]),format:"0"}),count_distinct:e=>({value:Ll([e]),format:"0"}),bool_and:e=>({value:Pl([e]).result}),bool_or:e=>({value:Ml([e]).result}),max:(e,t)=>ec([e],t),min:(e,t)=>tc([e],t),avg:(e,t)=>({value:Kl([e],t),format:$i(e)}),sum:(e,t)=>({value:Nl([e],t),format:$i(e)})};function Dc(e){const t=Object.keys(e);if(!t.length)return 0;const s=t.map((e=>parseInt(e,10)));return Math.max(...s)}const _c={year:Go("Year"),quarter:Go("Quarter & Year"),month:Go("Month & Year"),week:Go("Week & Year"),day:Go("Day"),quarter_number:Go("Quarter"),month_number:Go("Month"),iso_week_number:Go("Week"),day_of_month:Go("Day of Month"),day_of_week:Go("Day of Week"),hour_number:Go("Hour"),minute_number:Go("Minute"),second_number:Go("Second")},Fc=["date","datetime"];function Oc(e){const[t,s]=e.split(":");return s?{fieldName:t,granularity:s}:{fieldName:t}}function Pc(e){return Fc.includes(e.type)}function Mc(e,t,s){const o=[e];s&&o.push(`"${s}"`);for(const{field:e,value:s,type:i}of t){if("measure"===e){o.push('"measure"',`"${s}"`);continue}const{granularity:t}=Oc(e),n=Uc(s,{type:i,granularity:t});o.push(`"${e}"`,n)}return o}function Nc(e,t){let s=0,o=0;const i=t.columns.map((e=>e.nameWithGranularity)),n=t.rows.map((e=>e.nameWithGranularity));for(;void 0!==e[s]&&e[s]===n[o];)s++,o++;for(o=0;void 0!==e[s]&&e[s]===i[o];)s++,o++;return e.length===s}function Lc(e,t){switch(t.type){case"HEADER":return`=PIVOT.HEADER(${Mc(e,t.domain).join(",")})`;case"VALUE":return`=PIVOT.VALUE(${Mc(e,t.domain,t.measure).join(",")})`;case"MEASURE_HEADER":return`=PIVOT.HEADER(${Mc(e,[...t.domain,{field:"measure",value:t.measure,type:"char"}]).join(",")})`}return""}function kc(e,t){if(null===t||"null"===t)return null;const s="object"==typeof t?t.value:t;if(qi(s))return s;if("custom"===e.type)return an(t)??null;const o="boolean"==typeof t?tn(t).toLocaleLowerCase():tn(t);if("null"===o)return null;if(!zc.contains(e.type))throw new Li(Go("Field %(field)s is not supported because of its type (%(type)s)",{field:e.displayName,type:e.type}));if("false"===o.toLowerCase())return!1;return zc.get(e.type)(o,e.granularity)}function Vc(e,t){return dc(t??"month").normalizeFunctionValue(e)}function Uc(e,t){return null===e?'"null"':Bc.contains(t.type)?Bc.get(t.type)(e,t.granularity):`"${e}"`}function Hc(e,t){return dc(t??"month").toFunctionValue(e)}const zc=new n;zc.add("date",Vc).add("datetime",Vc).add("integer",(e=>Yi(e,w))).add("boolean",(e=>nn(e))).add("char",(e=>tn(e))).add("custom",(e=>e));const Bc=new n;function Gc(e){return e.displayName+(e.granularity?` (${_c[e.granularity]})`:"")}function Wc(e,t){try{if(!t.getMeasure(e.measure))return!1;const s=t.definition.columns;for(let o=0;o<e.domain.length;o++){if(s[o].nameWithGranularity!==e.domain[o].field)return!1;const i=t.getPossibleFieldValues(s[o]).map((e=>e.value));if(!(i.includes(e.domain[o].value)||null===e.domain[o].value&&i.includes("")))return!1}return!0}catch(e){return!1}}function $c(e,t){return Bt(e,t.groups.map((e=>e.name)),{compute:(e,t)=>`${e}${t}`,start:2})}function qc(e,t){return Bt(e,Object.values(t).map((e=>[e?.name,e?.string])).flat().filter(ut),{compute:(e,t)=>`${e}${t}`,start:2})}function Zc(e,t){const s={};for(const o of Object.values(e.customFields||{})){t[o.parentField]&&(s[o.name]={type:"custom",isCustomField:!0,name:o.name,string:o.name,customGroups:o.groups,parentField:o.parentField})}return s}function jc(e,t){t.groups=t.groups.filter((t=>!t.values.some((t=>e.includes(t)))))}function Yc(e,t,s){const o=e.rows.some((e=>e.fieldName===t))?e.rows:e.columns,i=o.findIndex((e=>e.fieldName===t));return-1===i||o.some((e=>e.fieldName===s))||o.splice(i,0,{fieldName:s}),e}function Xc(e,t,s){return Object.values(e.customFields||{}).find((e=>e.parentField===t.name))||{parentField:t.name,name:qc(t.string,s),groups:[]}}Bc.add("date",Hc).add("datetime",Hc).add("integer",(e=>`${Yi(e,w)}`)).add("boolean",(e=>nn(e)?"TRUE":"FALSE")).add("char",(e=>`"${tn(e).replace(/"/g,'\\"')}"`)).add("custom",(e=>"string"==typeof e?`"${e}"`:String(e)));class Kc extends Ja{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((!St(g,c)||!l)&&t&&!e.zones.some((e=>_s(t,e)))){const e=this.getters.getPivotCellFromPosition(c),t=Lc(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&&!St(g,c)){const e=n.includes(g.row)&&r.includes(g.col)?"":or(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 Xs(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:Xs(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=Il(e[s]||"",t);o.push({content:i,evaluatedCell:{formattedValue:i}})}s.cells.push(o)}return s}}const Jc={figureHandlers:new n,cellHandlers:new n};function Qc(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?ws(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?Cs(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):e}function eh(e,t){const s="DELETE_SHEET"===t.type&&t.sheetId;if("sheetId"in t&&e._sheetId!==t.sheetId)return e;{const o=Qc(e._zone,t);if(o&&s!==e._sheetId)return{...e,_zone:o}}}Jc.figureHandlers.add("chart",class extends Qa{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 Xa).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 Xa).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 Qa{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=qe(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 Xa).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=qe(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 Qa{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 Xa).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 Xa,g=qe(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"}}),Jc.cellHandlers.add("dataValidation",class extends Ja{uuidGenerator=new Xa;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=Us(t),i=Us(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=>St(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking));const i=this.queuedChanges[e];return!o&&i&&(o=i.find((e=>St(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=ls(i,s),r=ls([...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",Kc).add("sheet",class extends Ja{isPasteAllowed(e,t,s,o){if(!("cells"in s))return"Success";const{xSplit:i,ySplit:n}=this.getters.getPaneDivisions(e);return Ws(Xs(t,s.cells),i,n)?"FrozenPaneOverlap":"Success"}}).add("merge",class extends Ja{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(ut);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 Ja{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=>_s(u,e)))){a.add(h.id);let{numberOfRows:e}=Fs(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,...wt(s)},border:{...o,...wt(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=Fs(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 Ja{uuidGenerator=new Xa;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=Us(e.position),i=Us(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&&St(e.rule,t.rule)));const o=this.queuedChanges[e];return!s&&o&&(s=o.find((e=>e.cf.stopIfTrue===t.stopIfTrue&&St(e.cf.rule,t.rule)))?.cf),s||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}}).add("references",class extends Ja{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 Ja{copy(e){const t=e.sheetId;if(0===e.zones.length)return;const s=[];let o=0;for(const i of Qe(e.columnsIndexes)){let n=0;for(const r of Qe(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 Ys(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=St(e.horizontal,e.vertical),s=St(e.left,e.right,e.top,e.bottom);return t&&s&&St(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]]}});class th{subscriptions={};on(e,t,s){if(!s)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:s})}trigger(e,t){const s=this.subscriptions[e]||[];for(let e=0,o=s.length;e<o;e++){const o=s[e];o.callback.call(o.owner,t)}}off(e,t){const s=this.subscriptions[e];s&&(this.subscriptions[e]=s.filter((e=>e.owner!==t)))}clear(){this.subscriptions={}}}class sh extends th{dependencies=new Map;factory=new oh(this.get.bind(this));inject(e,t){if(this.dependencies.has(e)&&this.dependencies.get(e)!==t)throw new Error(`Store ${e.name} already has an instance`);this.dependencies.set(e,t)}get(e){return this.dependencies.has(e)||this.dependencies.set(e,this.instantiate(e)),this.dependencies.get(e)}instantiate(e,...t){return this.factory.build(e,...t)}resetStores(){this.dependencies.clear()}dispose(){for(const e of this.dependencies.values())"dispose"in e&&"function"==typeof e.dispose&&e.dispose()}}class oh{get;pendingBuilds=new Set;constructor(e){this.get=e}build(e,...t){if(this.pendingBuilds.has(e))throw new Error(`Circular dependency detected: ${[...this.pendingBuilds,e].map((e=>e.name)).join(" -> ")}`);this.pendingBuilds.add(e);const s=new e(this.get,...t);return this.pendingBuilds.delete(e),s}}class ih{get;disposeCallbacks=[];constructor(e){this.get=e}onDispose(e){this.disposeCallbacks.push(e)}dispose(){this.disposeCallbacks.forEach((e=>e()))}}function nh(){const e=t.useEnv();if(e.__spreadsheet_stores__ instanceof sh)return e.__spreadsheet_stores__;const s=new sh;return t.useSubEnv({__spreadsheet_stores__:s,getStore:e=>ch(s.get(e),(()=>s.trigger("store-updated")))}),t.onWillUnmount((()=>s.dispose())),s}function rh(e){const s=hh(t.useEnv()),o=s.get(e);return lh(s,o)}function ah(e,...s){const o=hh(t.useEnv()),i=o.instantiate(e,...s);return t.onWillUnmount((()=>i.dispose())),lh(o,i)}function lh(e,s){const o=t.useComponent();return ch(s,(()=>{"mounted"===t.status(o)&&e.trigger("store-updated")}))}function ch(e,t){return new Proxy(e,{get(s,o,i){const n=s,r=Reflect.get(s,o,n);if(e.mutators?.includes(o)){const e=new Proxy(r,{apply(e,s,o){"noStateChange"!==Reflect.apply(e,n,o)&&t()}});return e}return r}})}function hh(e){const t=e.__spreadsheet_stores__;if(!(t instanceof sh))throw new Error("No store provider found. Did you forget to call useStoreProvider()?");return t}const dh=(uh="Model",class{constructor(e){throw new Error(`This is a abstract store for ${uh}, it cannot be instantiated.\nDid you forget to inject your store instance?\n\nconst stores = useStoreProvider();\nstores.inject(MyMetaStore, storeInstance);\n`)}});var uh;class gh{mutators=["register","unRegister","draw","startAnimation","stopAnimation"];renderers={};model;context=void 0;animationFrameId=null;registeredAnimations=new Set;constructor(e){this.model=e(dh)}register(e){if(e.renderingLayers.length)for(const t of e.renderingLayers)this.renderers[t]||(this.renderers[t]=[]),this.renderers[t].push(e)}unRegister(e){for(const t of Object.keys(this.renderers))this.renderers[t]=this.renderers[t].filter((t=>t!==e))}drawLayer(e,t,s){const o=this.renderers[t];if(o)for(const i of o)e.ctx.save(),i.drawLayer(e,t,s),e.ctx.restore();return"noStateChange"}draw(e,t){if(!(e=e||this.context))throw new Error("Rendering context is not defined");this.context=e;for(const s of $t())this.model.drawLayer(e,s),this.drawLayer(e,s,t);return"noStateChange"}startAnimation(e){if(this.registeredAnimations.add(e),!this.animationFrameId){const e=t=>{this.animationFrameId=requestAnimationFrame(e),this.draw(void 0,t)};this.animationFrameId=requestAnimationFrame(e)}return"noStateChange"}stopAnimation(e){return this.registeredAnimations.delete(e),0===this.registeredAnimations.size&&null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),"noStateChange"}dispose(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}}class ph extends ih{model=this.get(dh);getters=this.model.getters;renderer=this.get(gh);constructor(e){super(e),this.model.on("command-dispatched",this,this.handle),this.model.on("command-finalized",this,this.finalize),this.renderer.register(this),this.onDispose((()=>{this.model.off("command-dispatched",this),this.model.off("command-finalized",this),this.renderer.unRegister(this)}))}get renderingLayers(){return[]}handle(e){}finalize(){}drawLayer(e,t,s){}}const mh={id:"void-composer",get editionMode(){return"inactive"},startEdition:()=>{throw new Error("No composer is registered")},stopEdition:()=>{throw new Error("No composer is registered")},setCurrentContent:()=>{throw new Error("No composer is registered")}};class fh extends ph{mutators=["focusComposer","focusActiveComposer"];activeComposer=mh;_focusMode="inactive";get focusMode(){return"inactive"===this.activeComposer.editionMode?"inactive":this._focusMode}focusComposer(e,t){if(this.activeComposer=e,this.getters.isReadonly())return"noStateChange";this._focusMode=t.focusMode||"contentFocus","inactive"!==this._focusMode&&this.setComposerContent(t)}focusActiveComposer(e){if(this.getters.isReadonly())return"noStateChange";if(!this.activeComposer)throw new Error("No composer is registered");this._focusMode=e.focusMode||"contentFocus","inactive"!==this._focusMode&&this.setComposerContent(e)}setComposerContent({content:e,selection:t}){"inactive"===this.activeComposer.editionMode?this.activeComposer.startEdition(e,t):e&&this.activeComposer.setCurrentContent(e,t)}}const vh=new n;function bh(){if(window.Chart&&!window.Chart.registry.plugins.get("chartShowValuesPlugin"))for(const e of vh.getAll())e.register(window.Chart)}class Sh extends ph{mutators=["disableAnimationForChart","enableAnimationForChart"];animationPlayed={};disableAnimationForChart(e,t){return this.animationPlayed[e]=t,"noStateChange"}enableAnimationForChart(e){return this.animationPlayed[e]=void 0,"noStateChange"}}function Ch(){return class extends window.Chart.BarController{static id="funnel";static defaults={...window.Chart?.BarController.defaults,dataElementType:"funnel",animation:{duration:e=>{if("data"!==e.type)return 1e3;return e.raw[1]/Math.max(...e.dataset.data.map((e=>e[1])))*1e3}}};updateElements(e,t,s,o){super.updateElements(e,t,s,o);for(let i=t;i<t+s;i++){const t=e[i];this.updateElement(t,i,{nextElement:e[i+1]},o)}}}}function yh(){return class extends window.Chart.BarElement{static id="funnel";draw(e){e.save();const{x:t,y:s,height:o,nextElement:i,base:n,options:r}=this.getProps(["x","y","width","height","nextElement","base","options"]),a=Ih(this),l=(a-(i?Ih(i):0))/2,c=Math.min(t,n),h=s-o/2;e.fillStyle=r.backgroundColor,e.beginPath(),e.moveTo(c,h),e.lineTo(c+a,h),e.lineTo(c+a-l,h+o),e.lineTo(c+l,h+o),e.closePath(),e.fill(),r.borderWidth&&(e.strokeStyle=r.borderColor,e.lineWidth=r.borderWidth,e.stroke()),e.restore()}inRange(e,t){const{x:s,y:o,height:i,nextElement:n,base:r}=this.getProps(["x","y","width","height","nextElement","base","options"]),a=Ih(this),l=n?Ih(n):0,c=Math.min(s,r),h=o-i/2;if(t<h||t>h+i)return!1;const d=(a-l)/2;return!(e<c+d*(t-h)/i||e>c+a-d*(t-h)/i)}}}function Ih(e){const{x:t,base:s}=e.getProps(["x","base"]),o=Math.min(t,s);return Math.max(t,s)-o}const wh=function(e){if(!e.length)return{x:0,y:0};const t=e[0].element,{x:s,y:o,base:i,width:n,height:r}=t.getProps(["x","y","width","height","base"]);return{x:Math.min(s,i)+2*n/3,y:o-r/2+r/2}},Eh="000000",Rh={arrows:"3Arrows",smiley:"3Symbols",dots:"3TrafficLights1"},xh={styleSheet:"http://schemas.openxmlformats.org/spreadsheetml/2006/main",sst:"http://schemas.openxmlformats.org/spreadsheetml/2006/main",Relationships:"http://schemas.openxmlformats.org/package/2006/relationships",Types:"http://schemas.openxmlformats.org/package/2006/content-types",worksheet:"http://schemas.openxmlformats.org/spreadsheetml/2006/main",workbook:"http://schemas.openxmlformats.org/spreadsheetml/2006/main",drawing:"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing",table:"http://schemas.openxmlformats.org/spreadsheetml/2006/main",revision:"http://schemas.microsoft.com/office/spreadsheetml/2014/revision",revision3:"http://schemas.microsoft.com/office/spreadsheetml/2016/revision3",markupCompatibility:"http://schemas.openxmlformats.org/markup-compatibility/2006"},Th="http://schemas.openxmlformats.org/drawingml/2006/main",Ah="http://schemas.openxmlformats.org/drawingml/2006/chart",Dh={workbook:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",macroEnabledWorkbook:"application/vnd.ms-excel.sheet.macroEnabled.main+xml",templateWorkbook:"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml",macroEnabledTemplateWorkbook:"application/vnd.ms-excel.template.macroEnabled.main+xml",excelAddInWorkbook:"application/vnd.ms-excel.addin.macroEnabled.main+xml",sheet:"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",metadata:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml",sharedStrings:"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",styles:"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",drawing:"application/vnd.openxmlformats-officedocument.drawing+xml",chart:"application/vnd.openxmlformats-officedocument.drawingml.chart+xml",themes:"application/vnd.openxmlformats-officedocument.theme+xml",table:"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",pivot:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml",externalLink:"application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml"},_h={document:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",sheet:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",metadata:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata",sharedStrings:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",styles:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",drawing:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",chart:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",theme:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",table:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/table",hyperlink:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",image:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"},Fh="bdbb8cdc-fa1e-496e-a857-3c3f30c029c3",Oh="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Ph=.75,Mh=.143,Nh=8.43,Lh=12.75,kh=30,Vh=100,Uh=164,Hh=50,zh={FLOOR:[{type:"NUMBER",value:1}],CEILING:[{type:"NUMBER",value:1}],ROUND:[{type:"NUMBER",value:0}],ROUNDUP:[{type:"NUMBER",value:0}],ROUNDDOWN:[{type:"NUMBER",value:0}]},Bh=["ACOT","ACOTH","AGGREGATE","ARABIC","BASE","BETA.DIST","BETA.INV","BINOM.DIST","BINOM.DIST.RANGE","BINOM.INV","BITAND","BITLSHIFT","BITOR","BITRSHIFT","BITXOR","BYCOL","BYROW","CEILING.MATH","CEILING.PRECISE","CHISQ.DIST","CHISQ.DIST.RT","CHISQ.INV","CHISQ.INV.RT","CHISQ.TEST","CHOOSECOLS","CHOOSEROWS","COMBINA","CONCAT","CONFIDENCE.NORM","CONFIDENCE.T","COT","COTH","COVARIANCE.P","COVARIANCE.S","CSC","CSCH","DAYS","DECIMAL","DROP","ERF.PRECISE","ERFC.PRECISE","EXPAND","EXPON.DIST","F.DIST","F.DIST.RT","F.INV","F.INV.RT","F.TEST","FIELDVALUE","FILTERXML","FLOOR.MATH","FLOOR.PRECISE","FORECAST.ETS","FORECAST.ETS.CONFINT","FORECAST.ETS.SEASONALITY","FORECAST.ETS.STAT","FORECAST.LINEAR","FORMULATEXT","GAMMA","GAMMA.DIST","GAMMA.INV","GAMMALN.PRECISE","GAUSS","HSTACK","HYPGEOM.DIST","IFNA","IFS","IMCOSH","IMCOT","IMCSC","IMCSCH","IMSEC","IMSECH","IMSINH","IMTAN","ISFORMULA","ISOMITTED","ISOWEEKNUM","LAMBDA","LET","LOGNORM.DIST","LOGNORM.INV","MAKEARRAY","MAP","MAXIFS","MINIFS","MODE.MULT","MODE.SNGL","MUNIT","NEGBINOM.DIST","NORM.DIST","NORM.INV","NORM.S.DIST","NORM.S.INV","NUMBERVALUE","PDURATION","PERCENTILE.EXC","PERCENTILE.INC","PERCENTRANK.EXC","PERCENTRANK.INC","PERMUTATIONA","PHI","POISSON.DIST","PQSOURCE","PYTHON_STR","PYTHON_TYPE","PYTHON_TYPENAME","QUARTILE.EXC","QUARTILE.INC","QUERYSTRING","RANDARRAY","RANK.AVG","RANK.EQ","REDUCE","RRI","SCAN","SEC","SECH","SEQUENCE","SHEET","SHEETS","SKEW.P","SORTBY","STDEV.P","STDEV.S","SWITCH","T.DIST","T.DIST.2T","T.DIST.RT","T.INV","T.INV.2T","T.TEST","TAKE","TEXTAFTER","TEXTBEFORE","TEXTJOIN","TEXTSPLIT","TOCOL","TOROW","UNICHAR","UNICODE","UNIQUE","VAR.P","VAR.S","VSTACK","WEBSERVICE","WEIBULL.DIST","WRAPCOLS","WRAPROWS","XLOOKUP","XOR","Z.TEST"],Gh="[Content_Types].xml",Wh=/(.*?)\((.*?)\)(.*)/,$h=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META","RANGE<META>"];function qh(e,t="",s){return function(e,t,s){const o=e.match(Wh),i=o[1].trim();if(!i)throw new Error(`Function argument definition is missing a name: '${e}'.`);const n=[];let r,a=!1,l=!1;for(const e of o[2].split(",")){const t=e.trim().toUpperCase(),s=$h.find((e=>t===e));s?n.push(s):"RANGE<ANY>"===t?n.push("RANGE"):"OPTIONAL"===t?a=!0:"REPEATING"===t?l=!0:t.startsWith("DEFAULT=")&&(r=e.trim().slice(8))}const c={name:i,description:t,type:n};(n.includes("ANY")||n.includes("RANGE"))&&(c.acceptErrors=!0);a&&(c.optional=!0);l&&(c.repeating=!0);void 0!==r&&(c.default=!0,c.defaultValue=r);n.some((e=>e.startsWith("RANGE")))&&(c.acceptMatrix=!0);n.every((e=>e.startsWith("RANGE")))&&(c.acceptMatrixOnly=!0);s&&s.length>0&&(c.proposalValues=s);return c}(e,t,s)}const Zh={};function jh(e,t){const s=e.name,o=Zh[s]?.[t];return o||(Zh[s]||(Zh[s]={}),Zh[s][t]||(Zh[s][t]=function(e,t){const s={},o=e.nbrArgRepeating?Math.floor((t-e.minArgRequired)/e.nbrArgRepeating):0,i=e.nbrArgRepeating*o,n=t-e.minArgRequired-i;let r=0,a=0;for(let t=0;t<e.args.length;t++){const i=e.args[t];if(i.optional||i.default)a<n&&(s[r]=t,r++),a++;else if(i.repeating){for(let i=0;i<o;i++)for(let o=0;o<e.nbrArgRepeating;o++)s[r]=t+o,r++;t+=e.nbrArgRepeating-1}else s[r]=t,r++}return e=>s[e]}(e,t)),Zh[s][t])}const Yh=["META","RANGE<META>"];const Xh=new n,Kh={description:Go("Returns a result array constrained to a specific width and height."),args:[qh("input_range (any, range<any>)",Go("The range to constrain.")),qh("rows (number)",Go("The number of rows in the constrained array.")),qh("columns (number)",Go("The number of columns in the constrained array."))],compute:function(e,t,s){const o=An(e),i=Qi(t?.value,this.locale),n=Qi(s?.value,this.locale);if(i<=0)return new Li(Go("The rows argument (%s) must be strictly positive.",i.toString()));if(n<=0)return new Li(Go("The columns argument (%s) must be strictly positive.",n.toString()));const r=Math.min(i,o[0].length);return mn(Math.min(n,o.length),r,((e,t)=>o[e][t]))},isExported:!1},Jh={description:Go("Creates a new array from the selected columns in the existing range."),args:[qh("array (any, range<any>)",Go("The array that contains the columns to be returned.")),qh("col_num (number, range<number>)",Go("The first column index of the columns to be returned.")),qh("col_num2 (number, range<number>, repeating)",Go("The columns indexes of the columns to be returned."))],compute:function(e,...t){const s=An(e),o=Dn(t,(e=>Qi(e?.value,this.locale))),i=o.filter((e=>0===e||s.length<Math.abs(e)));if(0!==i.length)return new Li(Go("The columns arguments must be between -%s and %s (got %s), excluding 0.",s.length.toString(),s.length.toString(),i.join(",")));const n=Array(o.length);for(let e=0;e<o.length;e++)o[e]>0?n[e]=s[o[e]-1]:n[e]=s[s.length+o[e]];return n},isExported:!0},Qh={description:Go("Creates a new array from the selected rows in the existing range."),args:[qh("array (any, range<any>)",Go("The array that contains the rows to be returned.")),qh("row_num (number, range<number>)",Go("The first row index of the rows to be returned.")),qh("row_num2 (number, range<number>, repeating)",Go("The rows indexes of the rows to be returned."))],compute:function(e,...t){const s=An(e),o=Dn(t,(e=>Qi(e?.value,this.locale))),i=s.length,n=o.filter((e=>0===e||s[0].length<Math.abs(e)));return 0!==n.length?new Li(Go("The rows arguments must be between -%s and %s (got %s), excluding 0.",s[0].length.toString(),s[0].length.toString(),n.join(","))):mn(i,o.length,((e,t)=>o[t]>0?s[e][o[t]-1]:s[e][s[e].length+o[t]]))},isExported:!0},ed={description:Go("Expands or pads an array to specified row and column dimensions."),args:[qh("array (any, range<any>)",Go("The array to expand.")),qh("rows (number)",Go("The number of rows in the expanded array. If missing, rows will not be expanded.")),qh("columns (number, optional)",Go("The number of columns in the expanded array. If missing, columns will not be expanded.")),qh("pad_with (any, default=0)",Go("The value with which to pad."))],compute:function(e,t,s,o={value:0}){const i=An(e),n=Qi(t?.value,this.locale),r=void 0!==s?Qi(s.value,this.locale):i.length;return n<i[0].length?new Li(Go("The rows arguments (%s) must be greater or equal than the number of rows of the array.",n.toString())):r<i.length?new Li(Go("The columns arguments (%s) must be greater or equal than the number of columns of the array.",r.toString())):mn(r,n,((e,t)=>e>=i.length||t>=i[e].length?o:i[e][t]))},isExported:!0},td={description:Go("Flattens all the values from one or more ranges into a single column."),args:[qh("range (any, range<any>)",Go("The first range to flatten.")),qh("range2 (any, range<any>, repeating)",Go("Additional ranges to flatten."))],compute:function(...e){return[Dn(e,(e=>void 0===e?{value:""}:e))]},isExported:!1},sd={description:Go("Calculates the frequency distribution of a range."),args:[qh("data (range<number>)",Go("The array of ranges containing the values to be counted.")),qh("classes (number, range<number>)",Go("The range containing the set of classes."))],compute:function(e,t){const s=Dn([e],(e=>e.value)).filter((e=>"number"==typeof e)),o=Dn([t],(e=>e.value)).filter((e=>"number"==typeof e)),i=o.map(((e,t)=>({initialIndex:t,value:e,count:0}))).sort(((e,t)=>e.value-t.value));i.push({initialIndex:i.length,value:1/0,count:0});const n=s.sort(((e,t)=>e-t));let r=0;for(const e of n){for(;e>i[r].value&&r<i.length-1;)r++;i[r].count++}return[i.sort(((e,t)=>e.initialIndex-t.initialIndex)).map((e=>e.count))]},isExported:!0},od={description:Go("Appends ranges horizontally and in sequence to return a larger array."),args:[qh("range1 (any, range<any>)",Go("The first range to be appended.")),qh("range2 (any, range<any>, repeating)",Go("Additional ranges to add to range1."))],compute:function(...e){const t=Math.max(...e.map((e=>e?.[0]?.length??0))),s=[];for(const o of e){const e=An(o);for(let o=0;o<e.length;o++){const i=Array(t).fill({value:null});for(let t=0;t<e[o].length;t++)i[t]=e[o][t];s.push(i)}}return s},isExported:!0},id={description:Go("Returns the matrix determinant of a square matrix."),args:[qh("square_matrix (number, range<number>)",Go("An range with an equal number of rows and columns representing a matrix whose determinant will be calculated."))],compute:function(e){const t=Ki(e,"square_matrix");return zl(t)?Wl(t).determinant:new Li(Go("The argument square_matrix must have the same number of columns and rows."))},isExported:!0},nd={description:Go("Returns the multiplicative inverse of a square matrix."),args:[qh("square_matrix (number, range<number>)",Go("An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated."))],compute:function(e){const t=Ki(e,"square_matrix");if(!zl(t))return new Li(Go("The argument square_matrix must have the same number of columns and rows."));const{inverted:s}=Wl(t);return s||new Li(Go("The matrix is not invertible."))},isExported:!0},rd={description:Go("Calculates the matrix product of two matrices."),args:[qh("matrix1 (number, range<number>)",Go("The first matrix in the matrix multiplication operation.")),qh("matrix2 (number, range<number>)",Go("The second matrix in the matrix multiplication operation."))],compute:function(e,t){const s=Ki(e,"matrix1"),o=Ki(t,"matrix2");return 0===s.length||0===o.length?new Li(Go("The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.")):s.length!==o[0].length?new Li(Go("In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).",s.length.toString(),o[0].length.toString())):ql(s,o)},isExported:!0},ad={description:Go("Calculates the sum of the products of corresponding entries in equal-sized ranges."),args:[qh("range1 (number, range<number>)",Go("The first range whose entries will be multiplied with corresponding entries in the other ranges.")),qh("range2 (number, range<number>, repeating)",Go("The other range whose entries will be multiplied with corresponding entries in the other ranges."))],compute:function(...e){if(!Hl(...e))return new Li(Go("All the ranges must have the same dimensions."));const t=e.map(An);let s=0;for(let e=0;e<t[0].length;e++)for(let o=0;o<t[0][e].length;o++){if(!t.every((t=>"number"==typeof t[e][o].value)))continue;let i=1;for(const s of t)i*=Yi(s[e][o],this.locale);s+=i}return s},isExported:!0};function ld(e,t,s){if(!Hl(e,t))return new Li(Go("The arguments array_x and array_y must have the same dimensions."));const o=An(e),i=An(t);let n=!1,r=0;for(const e in o)for(const t in o[e]){const a=o[e][t].value,l=i[e][t].value;"number"==typeof a&&"number"==typeof l&&(n=!0,r+=s(a,l))}return n?r:new Li(Go("The arguments array_x and array_y must contain at least one pair of numbers."))}const cd={description:Go("Calculates the sum of the difference of the squares of the values in two array."),args:[qh("array_x (number, range<number>)",Go("The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.")),qh("array_y (number, range<number>)",Go("The array or range of values whose squares will be subtracted from the squares of corresponding entries in array_x and added together."))],compute:function(e,t){return ld(e,t,((e,t)=>e**2-t**2))},isExported:!0},hd={description:Go("Calculates the sum of the sum of the squares of the values in two array."),args:[qh("array_x (number, range<number>)",Go("The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.")),qh("array_y (number, range<number>)",Go("The array or range of values whose squares will be added to the squares of corresponding entries in array_x and added together."))],compute:function(e,t){return ld(e,t,((e,t)=>e**2+t**2))},isExported:!0},dd={description:Go("Calculates the sum of squares of the differences of values in two array."),args:[qh("array_x (number, range<number>)",Go("The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.")),qh("array_y (number, range<number>)",Go("The array or range of values that will be subtracted from corresponding entries in array_x, the result squared, and all such results added together."))],compute:function(e,t){return ld(e,t,((e,t)=>(e-t)**2))},isExported:!0},ud=!1,gd=[qh("array (any, range<any>)",Go("The array which will be transformed.")),qh("ignore (number, default=0)",Go("Whether to ignore certain types of values. By default, no values are ignored."),[{value:0,label:Go("Keep all values (default)")},{value:1,label:Go("Ignore blanks")},{value:2,label:Go("Ignore errors")},{value:3,label:Go("Ignore blanks and errors")}]),qh("scan_by_column (number, default=false)",Go("Scan the array by column. By default, the array is scanned by row."),[{value:!1,label:Go("Scan by row (default)")},{value:!0,label:Go("Scan by column")}])];function pd(e){const t=Math.trunc(e);if(0===t)return()=>!0;if(1===t)return e=>null!==e.value;if(2===t)return e=>!qi(e.value);if(3===t)return e=>null!==e.value&&!qi(e.value);throw new Li(Go("Argument ignore must be between 0 and 3"))}const md={description:Go("Transforms a range of cells into a single column."),args:gd,compute:function(e,t={value:0},s={value:ud}){const o=An(e),i=Yi(t.value,this.locale),n=(nn(s.value)?o:vn(o)).flat().filter(pd(i));return 0===n.length?new Hi(Go("No results for the given arguments of TOCOL.")):[n]},isExported:!0},fd={description:Go("Transforms a range of cells into a single row."),args:gd,compute:function(e,t={value:0},s={value:ud}){const o=An(e),i=Yi(t.value,this.locale),n=(nn(s.value)?o:vn(o)).flat().filter(pd(i)).map((e=>[e]));return 0===n.length||0===n[0].length?new Hi(Go("No results for the given arguments of TOROW.")):n},isExported:!0},vd={description:Go("Transposes the rows and columns of a range."),args:[qh("range (any, range<any>)",Go("The range to be transposed."))],compute:function(e){const t=An(e);return mn(t[0].length,t.length,((e,s)=>t[s][e]))},isExported:!0},bd={description:Go("Appends ranges vertically and in sequence to return a larger array."),args:[qh("range1 (any, range<any>)",Go("The first range to be appended.")),qh("range2 (any, range<any>, repeating)",Go("Additional ranges to add to range1."))],compute:function(...e){const t=Math.max(...e.map((e=>An(e).length))),s=e.reduce(((e,t)=>e+An(t)[0].length),0),o=Array(t).fill([]).map((()=>Array(s).fill({value:0})));let i=0;for(const t of e){const e=An(t);for(let t=0;t<e.length;t++)for(let s=0;s<e[t].length;s++)o[t][i+s]=e[t][s];i+=e[0].length}return o},isExported:!0},Sd={description:Go("Wraps the provided row or column of cells by columns after a specified number of elements to form a new array."),args:[qh("range (any, range<any>)",Go("The range to wrap.")),qh("wrap_count (number)",Go("The maximum number of cells for each column, rounded down to the nearest whole number.")),qh("pad_with (any, default=0)",Go("The value with which to fill the extra cells in the range."))],compute:function(e,t,s={value:0}){const o=An(e),i=Qi(t?.value,this.locale);if(!Ul(o))return new Li(Go("Argument range must be a single row or column."));const n=o.flat();return mn(Math.ceil(n.length/i),i,((e,t)=>{const o=e*i+t;return o<n.length?n[o]:s}))},isExported:!0},Cd={description:Go("Wraps the provided row or column of cells by rows after a specified number of elements to form a new array."),args:[qh("range (any, range<any>)",Go("The range to wrap.")),qh("wrap_count (number)",Go("The maximum number of cells for each row, rounded down to the nearest whole number.")),qh("pad_with (any, default=0)",Go("The value with which to fill the extra cells in the range."))],compute:function(e,t,s={value:0}){const o=An(e),i=Qi(t?.value,this.locale);if(!Ul(o))return new Li(Go("Argument range must be a single row or column."));const n=o.flat(),r=Math.ceil(n.length/i);return mn(i,r,((e,t)=>{const o=t*i+e;return o<n.length?n[o]:s}))},isExported:!0};var yd=Object.freeze({__proto__:null,ARRAY_CONSTRAIN:Kh,CHOOSECOLS:Jh,CHOOSEROWS:Qh,EXPAND:ed,FLATTEN:td,FREQUENCY:sd,HSTACK:od,MDETERM:id,MINVERSE:nd,MMULT:rd,SUMPRODUCT:ad,SUMX2MY2:cd,SUMX2PY2:hd,SUMXMY2:dd,TOCOL:md,TOROW:fd,TRANSPOSE:vd,VSTACK:bd,WRAPCOLS:Sd,WRAPROWS:Cd});const Id={description:Go("Apply a large number format"),args:[qh("value (number)",Go("The number.")),qh("unit (string, optional)",Go("The formatting unit. Use 'k', 'm', or 'b' to force the unit"),[{value:"k",label:Go("Thousand")},{value:"m",label:Go("Million")},{value:"b",label:Go("Billion")}])],compute:function(e,t){return{value:Yi(e,this.locale),format:Er(e,t,this.locale)}}};var wd=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:Id});class Ed{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return"Success"}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const s of e){let e=s.call(this,t);Array.isArray(e)||(e=[e]);const o=e.filter((e=>"Success"!==e));if(o.length)return o}return"Success"}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}class Rd extends Ed{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:s,canDispatch:o,uiActions:i,selection:n}){super(t),this.getters=e,this.ui=i,this.selection=n,this.dispatch=s,this.canDispatch=o}drawLayer(e,t){}}function xd(e){return e.isFormula&&e.compiledFormula.tokens.some((e=>"SYMBOL"===e.type&&"SUBTOTAL"===e.value.toUpperCase()))}const Td=/^-?[a-z0-9]+$/i,Ad={description:Go("Absolute value of a number."),args:[qh("value (number)",Go("The number of which to return the absolute value."))],compute:function(e){return Math.abs(Yi(e,this.locale))},isExported:!0},Dd={description:Go("Inverse cosine of a value, in radians."),args:[qh("value (number)",Go("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],compute:function(e){const t=Yi(e,this.locale);return Math.abs(t)>1?new Li(Go("The value (%s) must be between -1 and 1 inclusive.",t)):Math.acos(t)},isExported:!0},_d={description:Go("Inverse hyperbolic cosine of a number."),args:[qh("value (number)",Go("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1."))],compute:function(e){const t=Yi(e,this.locale);return t<1?new Li(Go("The value (%s) must be greater than or equal to 1.",t)):Math.acosh(t)},isExported:!0},Fd={description:Go("Inverse cotangent of a value."),args:[qh("value (number)",Go("The value for which to calculate the inverse cotangent."))],compute:function(e){const t=Yi(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Od={description:Go("Inverse hyperbolic cotangent of a value."),args:[qh("value (number)",Go("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive."))],compute:function(e){const t=Yi(e,this.locale);return Math.abs(t)<=1?new Li(Go("The value (%s) cannot be between -1 and 1 inclusive.",t)):Math.log((t+1)/(t-1))/2},isExported:!0},Pd={description:Go("Inverse sine of a value, in radians."),args:[qh("value (number)",Go("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],compute:function(e){const t=Yi(e,this.locale);return Math.abs(t)>1?new Li(Go("The value (%s) must be between -1 and 1 inclusive.",t)):Math.asin(t)},isExported:!0},Md={description:Go("Inverse hyperbolic sine of a number."),args:[qh("value (number)",Go("The value for which to calculate the inverse hyperbolic sine."))],compute:function(e){return Math.asinh(Yi(e,this.locale))},isExported:!0},Nd={description:Go("Inverse tangent of a value, in radians."),args:[qh("value (number)",Go("The value for which to calculate the inverse tangent."))],compute:function(e){return Math.atan(Yi(e,this.locale))},isExported:!0},Ld={description:Go("Angle from the X axis to a point (x,y), in radians."),args:[qh("x (number)",Go("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),qh("y (number)",Go("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis."))],compute:function(e,t){const s=Yi(e,this.locale),o=Yi(t,this.locale);return 0===s&&0===o?new Gi(Go("Function [[FUNCTION_NAME]] caused a divide by zero error.")):Math.atan2(o,s)},isExported:!0},kd={description:Go("Inverse hyperbolic tangent of a number."),args:[qh("value (number)",Go("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],compute:function(e){const t=Yi(e,this.locale);return Math.abs(t)>=1?new Li(Go("The value (%s) must be between -1 and 1 exclusive.",t)):Math.atanh(t)},isExported:!0},Vd={description:Go("Rounds number up to nearest multiple of factor."),args:[qh("value (number)",Go("The value to round up to the nearest integer multiple of factor.")),qh("factor (number, default=1)",Go("The number to whose multiples value will be rounded."))],compute:function(e,t={value:1}){const s=Yi(e,this.locale),o=Yi(t,this.locale);return o<0&&s>0?new Li(Go("The factor (%s) must be positive when the value (%s) is positive.",o,s)):{value:o?Math.ceil(s/o)*o:0,format:e?.format}},isExported:!0};function Ud(e,t,s=0){return 0===t?0:(t=Math.abs(t),e>=0?Math.ceil(e/t)*t:0===s?-Math.floor(Math.abs(e)/t)*t:-Math.ceil(Math.abs(e)/t)*t)}const Hd={description:Go("Rounds number up to nearest multiple of factor."),args:[qh("number (number)",Go("The value to round up to the nearest integer multiple of significance.")),qh("significance (number, default=1)",Go("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),qh("mode (number, default=0)",Go("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero."))],compute:function(e,t={value:1},s={value:0}){const o=Yi(t,this.locale);return{value:Ud(Yi(e,this.locale),o,Yi(s,this.locale)),format:e?.format}},isExported:!0},zd={description:Go("Rounds number up to nearest multiple of factor."),args:[qh("number (number)",Go("The value to round up to the nearest integer multiple of significance.")),qh("significance (number, default=1)",Go("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){const s=Yi(t,this.locale);return{value:Ud(Yi(e,this.locale),s),format:e?.format}},isExported:!0},Bd={description:Go("Cosine of an angle provided in radians."),args:[qh("angle (number)",Go("The angle to find the cosine of, in radians."))],compute:function(e){return Math.cos(Yi(e,this.locale))},isExported:!0},Gd={description:Go("Hyperbolic cosine of any real number."),args:[qh("value (number)",Go("Any real value to calculate the hyperbolic cosine of."))],compute:function(e){return Math.cosh(Yi(e,this.locale))},isExported:!0},Wd={description:Go("Cotangent of an angle provided in radians."),args:[qh("angle (number)",Go("The angle to find the cotangent of, in radians."))],compute:function(e){const t=Yi(e,this.locale);return 0===t?new Gi(Go("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.tan(t)},isExported:!0},$d={description:Go("Hyperbolic cotangent of any real number."),args:[qh("value (number)",Go("Any real value to calculate the hyperbolic cotangent of."))],compute:function(e){const t=Yi(e,this.locale);return 0===t?new Gi(Go("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.tanh(t)},isExported:!0},qd={description:Go("Number of empty values."),args:[qh("value1 (any, range)",Go("The first value or range in which to count the number of blanks.")),qh("value2 (any, range, repeating)",Go("Additional values or ranges in which to count the number of blanks."))],compute:function(...e){return un(e,((e,t)=>void 0===t||null===t.value||""===t.value?e+1:e),0)},isExported:!0},Zd={description:Go("A conditional count across a range."),args:[qh("range (range)",Go("The range that is tested against criterion.")),qh("criterion (string)",Go("The pattern or test to apply to range."))],compute:function(...e){let t=0;return wn(e,((e,s)=>{t+=1}),this.locale),t},isExported:!0},jd={description:Go("Count values depending on multiple criteria."),args:[qh("criteria_range1 (range)",Go("The range to check against criterion1.")),qh("criterion1 (string)",Go("The pattern or test to apply to criteria_range1.")),qh("criteria_range2 (any, range, repeating)",Go("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),qh("criterion2 (string, repeating)",Go("Additional criteria to check."))],compute:function(...e){let t=0;return wn(e,((e,s)=>{t+=1}),this.locale),t},isExported:!0},Yd={description:Go("Counts number of unique values in a range."),args:[qh("value1 (any, range)",Go("The first value or range to consider for uniqueness.")),qh("value2 (any, range, repeating)",Go("Additional values or ranges to consider for uniqueness."))],compute:function(...e){return Ll(e)}},Xd={description:Go("Counts number of unique values in a range, filtered by a set of criteria."),args:[qh("range (range)",Go("The range of cells from which the number of unique values will be counted.")),qh("criteria_range1 (range)",Go("The range of cells over which to evaluate criterion1.")),qh("criterion1 (string)",Go("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),qh("criteria_range2 (any, range, repeating)",Go("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),qh("criterion2 (string, repeating)",Go("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){const s=new Set;return wn(t,((t,o)=>{const i=e[t]?.[o];_n(i)&&s.add(i.value)}),this.locale),s.size}},Kd={description:Go("Cosecant of an angle provided in radians."),args:[qh("angle (number)",Go("The angle to find the cosecant of, in radians."))],compute:function(e){const t=Yi(e,this.locale);return 0===t?new Gi(Go("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.sin(t)},isExported:!0},Jd={description:Go("Hyperbolic cosecant of any real number."),args:[qh("value (number)",Go("Any real value to calculate the hyperbolic cosecant of."))],compute:function(e){const t=Yi(e,this.locale);return 0===t?new Gi(Go("Function [[FUNCTION_NAME]] caused a divide by zero error.")):1/Math.sinh(t)},isExported:!0},Qd={description:Go("Converts from another base to decimal."),args:[qh("value (string)",Go("The number to convert.")),qh("base (number)",Go("The base to convert the value from."))],compute:function(e,t){let s=Yi(t,this.locale);if(s=Math.floor(s),2>s||s>36)return new Li(Go("The base (%s) must be between 2 and 36 inclusive.",s));const o=tn(e);if(""===o)return 0;if(!Td.test(o))return new Li(Go("The value (%s) must be a valid base %s representation.",o,s));const i=parseInt(o,s);return isNaN(i)?new Li(Go("The value (%s) must be a valid base %s representation.",o,s)):i},isExported:!0},eu={description:Go("Converts an angle value in radians to degrees."),args:[qh("angle (number)",Go("The angle to convert from radians to degrees."))],compute:function(e){return 180*Yi(e,this.locale)/Math.PI},isExported:!0},tu={description:Go("Euler's number, e (~2.718) raised to a power."),args:[qh("value (number)",Go("The exponent to raise e."))],compute:function(e){return Math.exp(Yi(e,this.locale))},isExported:!0},su={description:Go("Rounds number down to nearest multiple of factor."),args:[qh("value (number)",Go("The value to round down to the nearest integer multiple of factor.")),qh("factor (number, default=1)",Go("The number to whose multiples value will be rounded."))],compute:function(e,t={value:1}){const s=Yi(e,this.locale),o=Yi(t,this.locale);return o<0&&s>0?new Li(Go("The factor (%s) must be positive when the value (%s) is positive.",o,s)):{value:o?Math.floor(s/o)*o:0,format:e?.format}},isExported:!0};function ou(e,t,s=0){return 0===t?0:(t=Math.abs(t),e>=0?Math.floor(e/t)*t:0===s?-Math.ceil(Math.abs(e)/t)*t:-Math.floor(Math.abs(e)/t)*t)}const iu={description:Go("Rounds number down to nearest multiple of factor."),args:[qh("number (number)",Go("The value to round down to the nearest integer multiple of significance.")),qh("significance (number, default=1)",Go("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),qh("mode (number, default=0)",Go("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero."))],compute:function(e,t={value:1},s={value:0}){const o=Yi(t,this.locale);return{value:ou(Yi(e,this.locale),o,Yi(s,this.locale)),format:e?.format}},isExported:!0},nu={description:Go("Rounds number down to nearest multiple of factor."),args:[qh("number (number)",Go("The value to round down to the nearest integer multiple of significance.")),qh("significance (number, default=1)",Go("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){const s=Yi(t,this.locale);return{value:ou(Yi(e,this.locale),s),format:e?.format}},isExported:!0},ru={description:Go("Whether the provided value is even."),args:[qh("value (number)",Go("The value to be verified as even."))],compute:function(e){const t=Ji(e,this.locale);return!(1&Math.floor(Math.abs(t)))},isExported:!0},au={description:Go("Rounds number up to nearest multiple of factor."),args:[qh("number (number)",Go("The value to round up to the nearest integer multiple of significance.")),qh("significance (number, default=1)",Go("The number to whose multiples number will be rounded."))],compute:function(e,t={value:1}){return{value:Ud(Yi(e,this.locale),Yi(t,this.locale)),format:e?.format}},isExported:!0},lu={description:Go("Whether the provided value is even."),args:[qh("value (number)",Go("The value to be verified as even."))],compute:function(e){const t=Ji(e,this.locale);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},cu={description:Go("The logarithm of a number, base e (euler's number)."),args:[qh("value (number)",Go("The value for which to calculate the logarithm, base e."))],compute:function(e){const t=Yi(e,this.locale);return t<=0?new Li(Go("The value (%s) must be strictly positive.",t)):Math.log(t)},isExported:!0},hu={description:Go("The logarithm of a number, for a given base."),args:[qh("value (number)",Go("The value for which to calculate the logarithm.")),qh("base (number, default=10)",Go("The base of the logarithm."))],compute:function(e,t={value:10}){const s=Yi(e,this.locale),o=Yi(t,this.locale);return s<=0?new Li(Go("The value (%s) must be strictly positive.",s)):o<=0?new Li(Go("The base (%s) must be strictly positive.",o)):1===o?new Li(Go("The base must be different from 1.")):Math.log10(s)/Math.log10(o)},isExported:!0};function du(e,t){Vl(t,Go("The divisor must be different from 0."));const s=e%t;return s>0&&t<0||s<0&&t>0?s+t:s}const uu={description:Go("Modulo (remainder) operator."),args:[qh("dividend (number)",Go("The number to be divided to find the remainder.")),qh("divisor (number)",Go("The number to divide by."))],compute:function(e,t){const s=Yi(t,this.locale);return{value:du(Yi(e,this.locale),s),format:e?.format}},isExported:!0},gu={description:Go("Returns a n x n unit matrix, where n is the input dimension."),args:[qh("dimension (number)",Go("An integer specifying the dimension size of the unit matrix. It must be positive."))],compute:function(e){const t=Qi(e,this.locale);return t<1?new Li(Go("The argument dimension must be positive")):Gl(t)},isExported:!0},pu={description:Go("Rounds a number up to the nearest odd integer."),args:[qh("value (number)",Go("The value to round to the next greatest odd number."))],compute:function(e){const t=Yi(e,this.locale);let s=Math.ceil(Math.abs(t));return s=1&s?s:s+1,{value:t<0?-s:s,format:e?.format}},isExported:!0},mu={description:Go("The number pi."),args:[],compute:function(){return Math.PI},isExported:!0},fu={description:Go("A number raised to a power."),args:[qh("base (number)",Go("The number to raise to the exponent power.")),qh("exponent (number)",Go("The exponent to raise base to."))],compute:function(e,t){const s=Yi(e,this.locale),o=Yi(t,this.locale);return s<0&&!Number.isInteger(o)?new Li(Go("The exponent (%s) must be an integer when the base is negative.",o)):{value:Math.pow(s,o),format:e?.format}},isExported:!0},vu={description:Go("Result of multiplying a series of numbers together."),args:[qh("factor1 (number, range<number>)",Go("The first number or range to calculate for the product.")),qh("factor2 (number, range<number>, repeating)",Go("More numbers or ranges to calculate for the product."))],compute:function(...e){let t=0,s=1;for(const o of e)if(R(o))for(const e of o)for(const o of e){const e=o.value;if("number"==typeof e&&(s*=e,t+=1),qi(e))return o}else void 0!==o&&null!==o.value&&(s*=Ji(o,this.locale),t+=1);return{value:0===t?0:s,format:$i(e[0])}},isExported:!0},bu={description:Go("A random number between 0 inclusive and 1 exclusive."),args:[],compute:function(){return Math.random()},isExported:!0},Su={description:Go("Returns a grid of random numbers between 0 inclusive and 1 exclusive."),args:[qh("rows (number, default=1)",Go("The number of rows to be returned.")),qh("columns (number, default=1)",Go("The number of columns to be returned.")),qh("min (number, default=0)",Go("The minimum number you would like returned.")),qh("max (number, default=1)",Go("The maximum number you would like returned.")),qh("whole_number (boolean, default=FALSE)",Go("Return a whole number or a decimal value."),[{value:!1,label:Go("Decimal (default)")},{value:!0,label:Go("Integer")}])],compute:function(e={value:1},t={value:1},s={value:0},o={value:1},i={value:!1}){const n=Qi(t,this.locale),r=Qi(e,this.locale),a=Yi(s,this.locale),l=Yi(o,this.locale),c=nn(i);if(n<1)return new Li(Go("The number of columns (%s) must be positive.",n));if(r<1)return new Li(Go("The number of rows (%s) must be positive.",r));if(a>l)return new Li(Go("The maximum (%s) must be greater than or equal to the minimum (%s).",l,a));if(c&&(!Number.isInteger(a)||!Number.isInteger(l)))return new Li(Go("The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.",l.toString(),a.toString()));const h=Array(n);for(let e=0;e<n;e++){h[e]=Array(r);for(let t=0;t<r;t++)h[e][t]=c?Math.floor(Math.random()*(l-a+1)+a):a+Math.random()*(l-a)}return h},isExported:!0},Cu={description:Go("Random integer between two values, inclusive."),args:[qh("low (number)",Go("The low end of the random range.")),qh("high (number)",Go("The high end of the random range."))],compute:function(e,t){let s=Yi(e,this.locale);Number.isInteger(s)||(s=Math.ceil(s));let o=Yi(t,this.locale);return Number.isInteger(o)||(o=Math.floor(o)),s>o?new Li(Go("The high (%s) must be greater than or equal to the low (%s).",o,s)):{value:s+Math.ceil((o-s+1)*Math.random())-1,format:e?.format}},isExported:!0},yu={description:Go("Rounds a number according to standard rules."),args:[qh("value (number)",Go("The value to round to places number of places.")),qh("places (number, default=0)",Go("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const s=Yi(e,this.locale);let o=Yi(t,this.locale);const i=Math.abs(s);let n;return 0===o?n=Math.round(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.round(i*Math.pow(10,o))/Math.pow(10,o)),{value:s>=0?n:-n,format:e?.format}},isExported:!0},Iu={description:Go("Rounds down a number."),args:[qh("value (number)",Go("The value to round to places number of places, always rounding down.")),qh("places (number, default=0)",Go("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const s=Yi(e,this.locale);let o=Yi(t,this.locale);const i=Math.abs(s);let n;return 0===o?n=Math.floor(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.floor(i*Math.pow(10,o))/Math.pow(10,o)),{value:s>=0?n:-n,format:e?.format}},isExported:!0},wu={description:Go("Rounds up a number."),args:[qh("value (number)",Go("The value to round to places number of places, always rounding up.")),qh("places (number, default=0)",Go("The number of decimal places to which to round."))],compute:function(e,t={value:0}){const s=Yi(e,this.locale);let o=Yi(t,this.locale);const i=Math.abs(s);let n;return 0===o?n=Math.ceil(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.ceil(i*Math.pow(10,o))/Math.pow(10,o)),{value:s>=0?n:-n,format:e?.format}},isExported:!0},Eu={description:Go("Secant of an angle provided in radians."),args:[qh("angle (number)",Go("The angle to find the secant of, in radians."))],compute:function(e){return 1/Math.cos(Yi(e,this.locale))},isExported:!0},Ru={description:Go("Hyperbolic secant of any real number."),args:[qh("value (number)",Go("Any real value to calculate the hyperbolic secant of."))],compute:function(e){return 1/Math.cosh(Yi(e,this.locale))},isExported:!0},xu={description:Go("Returns a sequence of numbers."),args:[qh("rows (number)",Go("The number of rows to return")),qh("columns (number, optional, default=1)",Go("The number of columns to return")),qh("start (number, optional, default=1)",Go("The first number in the sequence")),qh("step (number, optional, default=1)",Go("The amount to increment each value in the sequence"))],compute:function(e,t={value:1},s={value:1},o={value:1}){const i=Yi(s,this.locale),n=Yi(o,this.locale),r=Qi(e,this.locale),a=Qi(t,this.locale);return a<1?new Li(Go("The number of columns (%s) must be positive.",a)):r<1?new Li(Go("The number of rows (%s) must be positive.",r)):mn(a,r,((e,t)=>({value:i+t*a*n+e*n})))},isExported:!0},Tu={description:Go("Sine of an angle provided in radians."),args:[qh("angle (number)",Go("The angle to find the sine of, in radians."))],compute:function(e){return Math.sin(Yi(e,this.locale))},isExported:!0},Au={description:Go("Hyperbolic sine of any real number."),args:[qh("value (number)",Go("Any real value to calculate the hyperbolic sine of."))],compute:function(e){return Math.sinh(Yi(e,this.locale))},isExported:!0},Du={description:Go("Positive square root of a positive number."),args:[qh("value (number)",Go("The number for which to calculate the positive square root."))],compute:function(e){const t=Yi(e,this.locale);return t<0?new Li(Go("The value (%s) must be positive or null.",t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},_u={1:"AVERAGE",2:"COUNT",3:"COUNTA",4:"MAX",5:"MIN",6:"PRODUCT",7:"STDEV",8:"STDEVP",9:"SUM",10:"VAR",11:"VARP"},Fu=Object.entries(_u).map((([e,t])=>({value:parseInt(e),label:Go("%s (include manually-hidden rows)",t)}))),Ou=Object.entries(_u).map((([e,t])=>({value:parseInt(e)+100,label:Go("%s (exclude manually-hidden rows)",t)}))),Pu={description:Go("Returns a subtotal for a vertical range of cells using a specified aggregation function."),args:[qh("function_code (number)",Go("The function to use in subtotal aggregation."),[...Fu,...Ou]),qh("ref1 (meta, range<meta>)",Go("The range or reference for which you want the subtotal.")),qh("ref2 (meta, range<meta>, repeating)",Go("Additional ranges or references for which you want the subtotal."))],compute:function(e,...t){let s=Qi(e,this.locale),o=!0;if(s>100&&(s-=100,o=!1),s<1||s>11)return new Li(Go("The function code (%s) must be between 1 to 11 or 101 to 111.",s));const i=[];for(const e of t){const t=e[0][0],s=na(t.value).sheetName,n=s?this.getters.getSheetIdByName(s):this.__originSheetId;if(!n)continue;const{top:r,left:a}=ms(t.value),l=a+e.length-1,c=r+e[0].length-1;for(let e=r;e<=c;e++)if(!this.getters.isRowFiltered(n,e)&&(o||!this.getters.isRowHiddenByUser(n,e)))for(let t=a;t<=l;t++){const s=this.getters.getCell({sheetId:n,col:t,row:e});s&&xd(s)||i.push(this.getters.getEvaluatedCell({sheetId:n,col:t,row:e}))}}return this[_u[s]].apply(this,[[i]])},isExported:!0},Mu={description:Go("Sum of a series of numbers and/or cells."),args:[qh("value1 (number, range<number>)",Go("The first number or range to add together.")),qh("value2 (number, range<number>, repeating)",Go("Additional numbers or ranges to add to value1."))],compute:function(...e){const t=e[0];return{value:Nl(e,this.locale),format:$i(t)}},isExported:!0},Nu={description:Go("A conditional sum across a range."),args:[qh("criteria_range (range)",Go("The range which is tested against criterion.")),qh("criterion (string)",Go("The pattern or test to apply to range.")),qh("sum_range (range, default=criteria_range)",Go("The range to be summed, if different from range."))],compute:function(e,t,s){void 0===s&&(s=e);let o=0;return wn([e,t],((e,t)=>{const i=s[e]?.[t]?.value;"number"==typeof i&&(o+=i)}),this.locale),o},isExported:!0},Lu={description:Go("Sums a range depending on multiple criteria."),args:[qh("sum_range (range)",Go("The range to sum.")),qh("criteria_range1 (range)",Go("The range to check against criterion1.")),qh("criterion1 (string)",Go("The pattern or test to apply to criteria_range1.")),qh("criteria_range2 (any, range, repeating)",Go("Additional ranges to check.")),qh("criterion2 (string, repeating)",Go("Additional criteria to check."))],compute:function(e,...t){let s=0;return wn(t,((t,o)=>{const i=e[t]?.[o]?.value;"number"==typeof i&&(s+=i)}),this.locale),s},isExported:!0},ku={description:Go("Tangent of an angle provided in radians."),args:[qh("angle (number)",Go("The angle to find the tangent of, in radians."))],compute:function(e){return Math.tan(Yi(e,this.locale))},isExported:!0},Vu={description:Go("Hyperbolic tangent of any real number."),args:[qh("value (number)",Go("Any real value to calculate the hyperbolic tangent of."))],compute:function(e){return Math.tanh(Yi(e,this.locale))},isExported:!0};function Uu(e,t){return 0===t?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*Math.pow(10,t))/Math.pow(10,t))}const Hu={description:Go("Truncates a number."),args:[qh("value (number)",Go("The value to be truncated.")),qh("places (number, default=0)",Go("The number of significant digits to the right of the decimal point to retain."))],compute:function(e,t={value:0}){return{value:Uu(Yi(e,this.locale),Yi(t,this.locale)),format:e?.format}},isExported:!0},zu={description:Go("Rounds a number down to the nearest integer that is less than or equal to it."),args:[qh("value (number)",Go("The number to round down to the nearest integer."))],compute:function(e){return Math.floor(Yi(e,this.locale))},isExported:!0};var Bu=Object.freeze({__proto__:null,ABS:Ad,ACOS:Dd,ACOSH:_d,ACOT:Fd,ACOTH:Od,ASIN:Pd,ASINH:Md,ATAN:Nd,ATAN2:Ld,ATANH:kd,CEILING:Vd,CEILING_MATH:Hd,CEILING_PRECISE:zd,COS:Bd,COSH:Gd,COT:Wd,COTH:$d,COUNTBLANK:qd,COUNTIF:Zd,COUNTIFS:jd,COUNTUNIQUE:Yd,COUNTUNIQUEIFS:Xd,CSC:Kd,CSCH:Jd,DECIMAL:Qd,DEGREES:eu,EXP:tu,FLOOR:su,FLOOR_MATH:iu,FLOOR_PRECISE:nu,INT:zu,ISEVEN:ru,ISODD:lu,ISO_CEILING:au,LN:cu,LOG:hu,MOD:uu,MUNIT:gu,ODD:pu,PI:mu,POWER:fu,PRODUCT:vu,RAND:bu,RANDARRAY:Su,RANDBETWEEN:Cu,ROUND:yu,ROUNDDOWN:Iu,ROUNDUP:wu,SEC:Eu,SECH:Ru,SEQUENCE:xu,SIN:Tu,SINH:Au,SQRT:Du,SUBTOTAL:Pu,SUM:Mu,SUMIF:Nu,SUMIFS:Lu,TAN:ku,TANH:Vu,TRUNC:Hu});const Gu=[{value:!0,label:Go("b is calculated normally")},{value:!1,label:Go("b is forced to 1")}],Wu=[{value:!1,label:Go("do not return additional regression statistics")},{value:!0,label:Go("return additional regression statistics")}],$u=[{value:1,label:Go("order 1 (Linear)")},{value:2,label:Go("order 2 (Quadratic)")},{value:3,label:Go("order 3 (Cubic)")},{value:4,label:Go("order 4 (Quartic)")},{value:5,label:Go("order 5 (Quintic)")},{value:6,label:Go("order 6 (Sextic)")}],qu=[{value:!0,label:Go("Compute intercept")},{value:!1,label:Go("Force intercept to 0")}],Zu=[{value:0,label:Go("Minimum value")},{value:1,label:Go("First quartile (25th percentile)")},{value:2,label:Go("Median value (50th percentile)")},{value:3,label:Go("Third quartile (75th percentile)")},{value:4,label:Go("Maximum value")}];function ju(e,t){const s=[],o=[];let i=0,n=0;cn([e],(e=>{s.push(e),i+=1})),cn([t],(e=>{o.push(e),n+=1})),kl(i===n,Go("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",i,n));const r=[],a=[];for(let e=0;e<i;e++){const t=s[e]?.value,i=o[e]?.value;"number"==typeof t&&"number"==typeof i&&(a.push(t),r.push(i))}return{flatDataX:r,flatDataY:a}}function Yu(e,t,s){const{flatDataX:o,flatDataY:i}=ju(e,t),n=i.length;Vl(n),s&&Vl(n-1);let r=0,a=0;for(let e=0;e<n;e++)r+=i[e],a+=o[e];const l=r/n,c=a/n;let h=0;for(let e=0;e<n;e++)h+=(i[e]-l)*(o[e]-c);return h/(n-(s?1:0))}function Xu(e,t,s,o){let i=0;const n=s?pn:gn,r=n(e,((e,t)=>(i+=1,e+t)),0,o);Vl(i),t&&Vl(i-1);const a=r/i;return n(e,((e,t)=>e+Math.pow(t-a,2)),0,o)/(i-(t?1:0))}function Ku(e,t,s,o){const i=Yi(t,o);kl(s?0<=i&&i<=1:0<i&&i<1,Go("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));const n=[];let r,a=0;return cn(e,(e=>{const t=e?.value;"number"==typeof t&&(r=En(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(r+1,0,t),a++)})),kl(0!==a,Fn),s||kl(1/(a+1)<=i&&i<=a/(a+1),Go("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),Pi(n,i,s)}const Ju={description:Go("Average magnitude of deviations from mean."),args:[qh("value1 (number, range<number>)",Go("The first value or range of the sample.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to include in the sample."))],compute:function(...e){let t=0;const s=gn(e,((e,s)=>(t+=1,e+s)),0,this.locale);if(0===t)return new Gi(Go("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const o=s/t;return gn(e,((e,t)=>e+Math.abs(o-t)),0,this.locale)/t},isExported:!0},Qu={description:Go("Numerical average value in a dataset, ignoring text."),args:[qh("value1 (number, range<number>)",Go("The first value or range to consider when calculating the average value.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to consider when calculating the average value."))],compute:function(...e){return{value:Kl(e,this.locale),format:$i(e[0])}},isExported:!0},eg=Go("[[FUNCTION_NAME]] has mismatched range sizes."),tg=Go("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),sg={description:Go("Weighted average."),args:[qh("values (number, range<number>)",Go("Values to average.")),qh("weights (number, range<number>)",Go("Weights for each corresponding value.")),qh("additional_values (number, range<number>, repeating)",Go("Additional values to average.")),qh("additional_weights (number, range<number>, repeating)",Go("Additional weights."))],compute:function(...e){let t=0,s=0;for(let o=0;o<e.length-1;o+=2){const i=e[o],n=e[o+1];if(!Hl(i,n))return new Li(eg);if(R(i))for(let e=0;e<i.length;e++)for(let o=0;o<i[0].length;o++){const r=i[e][o].value,a=R(n)?n?.[e][o].value:Yi(n,this.locale),l="number"==typeof r,c="number"==typeof a;if(l&&c){if(a<0)return new Li(tg);t+=r*a,s+=a}else if(l!==c)return new Li(Go("[[FUNCTION_NAME]] expects number values."))}else{const e=Yi(i,this.locale),o=R(n)?n?.[0][0].value:Yi(n,this.locale);if("number"==typeof o){if(o<0)return new Li(tg);t+=e*o,s+=o}}}return 0===s?new Gi(Go("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):{value:t/s,format:$i(e[0])}}},og={description:Go("Numerical average value in a dataset."),args:[qh("value1 (number, range<number>)",Go("The first value or range to consider when calculating the average value.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to consider when calculating the average value."))],compute:function(...e){let t=0;const s=pn(e,((e,s)=>(t+=1,e+s)),0,this.locale);return 0===t?new Gi(Go("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):{value:s/t,format:$i(e[0])}},isExported:!0},ig={description:Go("Average of values depending on criteria."),args:[qh("criteria_range (number, range<number>)",Go("The range to check against criterion.")),qh("criterion (string)",Go("The pattern or test to apply to criteria_range.")),qh("average_range (number, range<number>, default=criteria_range)",Go("The range to average. If not included, criteria_range is used for the average instead."))],compute:function(e,t,s){const o=An(void 0===s?e:s);let i=0,n=0;return wn([e,t],((e,t)=>{const s=o[e]?.[t]?.value;"number"==typeof s&&(i+=1,n+=s)}),this.locale),0===i?new Gi(Go("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):n/i},isExported:!0},ng={description:Go("Average of values depending on multiple criteria."),args:[qh("average_range (range)",Go("The range to average.")),qh("criteria_range1 (range)",Go("The range to check against criterion1.")),qh("criterion1 (string)",Go("The pattern or test to apply to criteria_range1.")),qh("criteria_range2 (any, range, repeating)",Go("Additional criteria_range and criterion to check.")),qh("criterion2 (string, repeating)",Go("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){const s=An(e);let o=0,i=0;return wn(t,((e,t)=>{const n=s[e]?.[t]?.value;"number"==typeof n&&(o+=1,i+=n)}),this.locale),0===o?new Gi(Go("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")):i/o},isExported:!0},rg={description:Go("The number of numeric values in dataset."),args:[qh("value1 (number, any, range<number>)",Go("The first value or range to consider when counting.")),qh("value2 (number, any, range<number>, repeating)",Go("Additional values or ranges to consider when counting."))],compute:function(...e){return Jl(e,this.locale)},isExported:!0},ag={description:Go("The number of values in a dataset."),args:[qh("value1 (any, range)",Go("The first value or range to consider when counting.")),qh("value2 (any, range, repeating)",Go("Additional values or ranges to consider when counting."))],compute:function(...e){return Ql(e)},isExported:!0},lg={description:Go("The covariance of a dataset."),args:[qh("data_y (any, range)",Go("The range representing the array or matrix of dependent data.")),qh("data_x (any, range)",Go("The range representing the array or matrix of independent data."))],compute:function(e,t){return Yu(e,t,!1)},isExported:!0},cg={description:Go("The covariance of a dataset."),args:[qh("data_y (any, range)",Go("The range representing the array or matrix of dependent data.")),qh("data_x (any, range)",Go("The range representing the array or matrix of independent data."))],compute:function(e,t){return Yu(e,t,!1)},isExported:!0},hg={description:Go("The sample covariance of a dataset."),args:[qh("data_y (any, range)",Go("The range representing the array or matrix of dependent data.")),qh("data_x (any, range)",Go("The range representing the array or matrix of independent data."))],compute:function(e,t){return Yu(e,t,!0)},isExported:!0},dg={description:Go("Calculates the expected y-value for a specified x based on a linear regression of a dataset."),args:[qh("x (number, range<number>)",Go("The value(s) on the x-axis to forecast.")),qh("data_y (range<number>)",Go("The range representing the array or matrix of dependent data.")),qh("data_x (range<number>)",Go("The range representing the array or matrix of independent data."))],compute:function(e,t,s){const{flatDataX:o,flatDataY:i}=ju(t,s);return 0===o.length||0===i.length?new Hi(Fn):cc([i],[o],fn(An(e),(e=>Yi(e,this.locale))),!0)},isExported:!0},ug={description:Go("Fits points to exponential growth trend."),args:[qh("known_data_y (range<number>)",Go("The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.")),qh("known_data_x (range<number>, default={1;2;3;...})",Go("The values of the independent variable(s) corresponding with known_data_y.")),qh("new_data_x (any, range, default=known_data_x)",Go("The data points to return the y values for on the ideal curve fit.")),qh("b (boolean, default=TRUE)",Go("Given a general exponential form of y = b*m^x for a curve fit, calculates b if TRUE or forces b to be 1 and only calculates the m values if FALSE."),Gu)],compute:function(e,t=[[]],s=[[]],o={value:!0}){return 0===e.length||0===e[0].length?new Li(On("known_data_y")):ac(cc(lc(Ki(e,"the first argument (known_data_y)")),Ki(t,"the second argument (known_data_x)"),Ki(s,"the third argument (new_data_y)"),nn(o)))}},gg={description:Go("Compute the intercept of the linear regression."),args:[qh("data_y (range<number>)",Go("The range representing the array or matrix of dependent data.")),qh("data_x (range<number>)",Go("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:s,flatDataY:o}=ju(e,t);if(0===s.length||0===o.length)return new Hi(Fn);const[[],[i]]=oc([s],[o]);return i},isExported:!0},pg={description:Go("Nth largest element from a data set."),args:[qh("data (any, range)",Go("Array or range containing the dataset to consider.")),qh("n (number)",Go("The rank from largest to smallest of the element to return."))],compute:function(e,t){const s=Math.trunc(Yi(t?.value,this.locale)),o=[];let i,n=0;cn([e],(e=>{"number"==typeof e?.value&&(i=En(o,e,"nextSmaller","asc",o.length,((e,t)=>e[t].value)),o.splice(i+1,0,e),n++,n>s&&(o.shift(),n--))}));const r=o.shift();return void 0===r?new Li(Fn):n<s?new Li(Go("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s)):r},isExported:!0},mg={description:Go("Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method."),args:[qh("data_y (range<number>)",Go("The range representing the array or matrix of dependent data.")),qh("data_x (range<number>, default={1;2;3;...})",Go("The range representing the array or matrix of independent data.")),qh("calculate_b (boolean, default=TRUE)",Go("A flag specifying whether to compute the slope or not"),Gu),qh("verbose (boolean, default=FALSE)",Go("A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept"),Wu)],compute:function(e,t=[[]],s={value:!0},o={value:!1}){return 0===e.length||0===e[0].length?new Li(On("data_y")):oc(Ki(t,"the first argument (data_y)"),Ki(e,"the second argument (data_x)"),nn(s),nn(o))},isExported:!0},fg={description:Go("Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve."),args:[qh("data_y (range<number>)",Go("The range representing the array or matrix of dependent data.")),qh("data_x (range<number>, optional, default={1;2;3;...})",Go("The range representing the array or matrix of independent data.")),qh("calculate_b (boolean, default=TRUE)",Go("A flag specifying whether to compute the slope or not"),Gu),qh("verbose (boolean, default=FALSE)",Go("A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept"),Wu)],compute:function(e,t=[[]],s={value:!0},o={value:!1}){if(0===e.length||0===e[0].length)return new Li(On("data_y"));const i=oc(Ki(t,"the second argument (data_x)"),lc(Ki(e,"the first argument (data_y)")),nn(s),nn(o));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},vg={description:Go("Compute the Matthews correlation coefficient of a dataset."),args:[qh("data_x (range)",Go("The range representing the array or matrix of observed data.")),qh("data_y (range)",Go("The range representing the array or matrix of predicted data."))],compute:function(e,t){const s=e.flat(),o=t.flat();if(Xl(s,o),0===s.length||0===o.length)return new Hi(Fn);const i=s.length;let n=0,r=0,a=0,l=0;for(let e=0;e<i;++e){const t=nn(s[e]);t===nn(o[e])?t?r++:n++:t?l++:a++}return(r*n-a*l)/Math.sqrt((r+a)*(r+l)*(n+a)*(n+l))},isExported:!1},bg={description:Go("Maximum value in a numeric dataset."),args:[qh("value1 (number, range<number>)",Go("The first value or range to consider when calculating the maximum value.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to consider when calculating the maximum value."))],compute:function(...e){return ec(e,this.locale)},isExported:!0},Sg={description:Go("Maximum numeric value in a dataset."),args:[qh("value1 (any, range)",Go("The first value or range to consider when calculating the maximum value.")),qh("value2 (any, range, repeating)",Go("Additional values or ranges to consider when calculating the maximum value."))],compute:function(...e){const t=pn(e,((e,t)=>Math.max(t,e)),-1/0,this.locale);return{value:t===-1/0?0:t,format:$i(e[0])}},isExported:!0},Cg={description:Go("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:[qh("range (range)",Go("The range of cells from which the maximum will be determined.")),qh("criteria_range1 (range)",Go("The range of cells over which to evaluate criterion1.")),qh("criterion1 (string)",Go("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),qh("criteria_range2 (any, range, repeating)",Go("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),qh("criterion2 (string, repeating)",Go("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){let s=-1/0;return wn(t,((t,o)=>{const i=e[t]?.[o]?.value;"number"==typeof i&&(s=s<i?i:s)}),this.locale),s===-1/0?0:s},isExported:!0},yg={description:Go("Median value in a numeric dataset."),args:[qh("value1 (any, range)",Go("The first value or range to consider when calculating the median value.")),qh("value2 (any, range, repeating)",Go("Additional values or ranges to consider when calculating the median value."))],compute:function(...e){const t=[];return hn(e,(e=>{t.push(e)}),this.locale),{value:Ku(t,{value:.5},!0,this.locale),format:$i(t[0])}},isExported:!0},Ig={description:Go("Minimum value in a numeric dataset."),args:[qh("value1 (number, range<number>)",Go("The first value or range to consider when calculating the minimum value.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to consider when calculating the minimum value."))],compute:function(...e){return tc(e,this.locale)},isExported:!0},wg={description:Go("Minimum numeric value in a dataset."),args:[qh("value1 (number, range<number>)",Go("The first value or range to consider when calculating the minimum value.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to consider when calculating the minimum value."))],compute:function(...e){const t=pn(e,((e,t)=>Math.min(t,e)),1/0,this.locale);return{value:t===1/0?0:t,format:$i(e[0])}},isExported:!0},Eg={description:Go("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:[qh("range (range)",Go("The range of cells from which the minimum will be determined.")),qh("criteria_range1 (range)",Go("The range of cells over which to evaluate criterion1.")),qh("criterion1 (string)",Go("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),qh("criteria_range2 (any, range, repeating)",Go("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),qh("criterion2 (string, repeating)",Go("The pattern or test to apply to criteria_range2."))],compute:function(e,...t){let s=1/0;return wn(t,((t,o)=>{const i=e[t]?.[o]?.value;"number"==typeof i&&(s=s>i?i:s)}),this.locale),s===1/0?0:s},isExported:!0};function Rg(e,t){const{flatDataX:s,flatDataY:o}=ju(e,t);if(0===s.length||0===o.length)return new Hi(Fn);const i=s.length;let n=0,r=0,a=0,l=0,c=0;for(let e=0;e<i;e++){const t=s[e],i=o[e];n+=t,r+=i,a+=t*i,l+=t*t,c+=i*i}return(i*a-n*r)/Math.sqrt((i*l-n*n)*(i*c-r*r))}const xg={description:Go("Compute the Pearson product-moment correlation coefficient of a dataset."),args:[qh("data_y (range<number>)",Go("The range representing the array or matrix of dependent data.")),qh("data_x (range<number>)",Go("The range representing the array or matrix of independent data."))],compute:function(e,t){return Rg(e,t)},isExported:!0},Tg=xg,Ag={description:Go("Value at a given percentile of a dataset."),args:[qh("data (any, range)",Go("The array or range containing the dataset to consider.")),qh("percentile (number)",Go("The percentile whose value within data will be calculated and returned."))],compute:function(e,t){return _g.compute.bind(this)(e,t)},isExported:!0},Dg={description:Go("Value at a given percentile of a dataset exclusive of 0 and 1."),args:[qh("data (any, range)",Go("The array or range containing the dataset to consider.")),qh("percentile (number)",Go("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned."))],compute:function(e,t){return{value:Ku([e],t,!1,this.locale),format:$i(e)}},isExported:!0},_g={description:Go("Value at a given percentile of a dataset."),args:[qh("data (any, range)",Go("The array or range containing the dataset to consider.")),qh("percentile (number)",Go("The percentile whose value within data will be calculated and returned."))],compute:function(e,t){return{value:Ku([e],t,!0,this.locale),format:$i(e)}},isExported:!0},Fg={description:Go("Compute the coefficients of polynomial regression of the dataset."),args:[qh("data_y (range<number>)",Go("The range representing the array or matrix of dependent data.")),qh("data_x (range<number>)",Go("The range representing the array or matrix of independent data.")),qh("order (number)",Go("The order of the polynomial to fit the data, between 1 and 6."),$u),qh("intercept (boolean, default=TRUE)",Go("A flag specifying whether to compute the intercept or not."),qu)],compute:function(e,t,s,o={value:!0}){const{flatDataX:i,flatDataY:n}=ju(e,t);return 0===i.length||0===n.length?new Hi(Fn):ic(n,i,Yi(s,this.locale),nn(o))},isExported:!1},Og={description:Go("Predict value by computing a polynomial regression of the dataset."),args:[qh("x (number, range<number>)",Go("The value(s) on the x-axis to forecast.")),qh("data_y (range<number>)",Go("The range representing the array or matrix of dependent data.")),qh("data_x (range<number>)",Go("The range representing the array or matrix of independent data.")),qh("order (number)",Go("The order of the polynomial to fit the data, between 1 and 6."),$u),qh("intercept (boolean, default=TRUE)",Go("A flag specifying whether to compute the intercept or not."),qu)],compute:function(e,t,s,o,i={value:!0}){const n=Yi(o,this.locale),{flatDataX:r,flatDataY:a}=ju(t,s);if(0===r.length||0===a.length)return new Hi(Fn);const l=ic(a,r,n,nn(i)).flat();return fn(An(e),(e=>rc(l,Yi(e,this.locale),n)))},isExported:!1},Pg={description:Go("Value nearest to a specific quartile of a dataset."),args:[qh("data (any, range)",Go("The array or range containing the dataset to consider.")),qh("quartile_number (number)",Go("Which quartile value to return."),Zu)],compute:function(e,t){return Ng.compute.bind(this)(e,t)},isExported:!0},Mg={description:Go("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:[qh("data (any, range)",Go("The array or range containing the dataset to consider.")),qh("quartile_number (number)",Go("Which quartile value, exclusive of 0 and 4, to return."),[{value:1,label:Go("First quartile (25th percentile)")},{value:2,label:Go("Median value (50th percentile)")},{value:3,label:Go("Third quartile (75th percentile)")}])],compute:function(e,t){return{value:Ku([e],{value:.25*Math.trunc(Yi(t,this.locale))},!1,this.locale),format:$i(e)}},isExported:!0},Ng={description:Go("Value nearest to a specific quartile of a dataset."),args:[qh("data (any, range)",Go("The array or range containing the dataset to consider.")),qh("quartile_number (number)",Go("Which quartile value to return."),Zu)],compute:function(e,t){return{value:Ku([e],{value:.25*Math.trunc(Yi(t,this.locale))},!0,this.locale),format:$i(e)}},isExported:!0},Lg={description:Go("Returns the rank of a specified value in a dataset."),args:[qh("value (number)",Go("The value whose rank will be determined.")),qh("data (range)",Go("The range containing the dataset to consider.")),qh("is_ascending (boolean, default=FALSE)",Go("Whether to consider the values in data in descending or ascending order."),[{value:!1,label:Go("Descending")},{value:!0,label:Go("Ascending")}])],compute:function(e,t,s={value:!1}){const o=nn(s),i=Yi(e,this.locale);let n=1,r=!1;for(const e of t)for(const t of e){if("number"!=typeof t.value)continue;const e=Yi(t,this.locale);e===i?r=!0:e>i!==o&&n++}return r?n:new Hi(Go("Value not found in the given data."))},isExported:!0},kg={description:Go("Compute the square of r, the Pearson product-moment correlation coefficient of a dataset."),args:[qh("data_y (range<number>)",Go("The range representing the array or matrix of dependent data.")),qh("data_x (range<number>)",Go("The range representing the array or matrix of independent data."))],compute:function(e,t){const s=Rg(e,t);if(s instanceof Error)throw s;return Math.pow(s,2)},isExported:!0},Vg={description:Go("Compute the slope of the linear regression."),args:[qh("data_y (range<number>)",Go("The range representing the array or matrix of dependent data.")),qh("data_x (range<number>)",Go("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:s,flatDataY:o}=ju(e,t);if(0===s.length||0===o.length)return new Hi(Fn);const[[i]]=oc([s],[o]);return i},isExported:!0},Ug={description:Go("Nth smallest element in a data set."),args:[qh("data (any, range)",Go("The array or range containing the dataset to consider.")),qh("n (number)",Go("The rank from smallest to largest of the element to return."))],compute:function(e,t){const s=Math.trunc(Yi(t?.value,this.locale)),o=[];let i,n=0;cn([e],(e=>{"number"==typeof e?.value&&(i=En(o,e,"nextSmaller","asc",o.length,((e,t)=>e[t].value)),o.splice(i+1,0,e),n++,n>s&&(o.pop(),n--))}));const r=o.pop();return void 0===r?new Li(Fn):n<s?new Li(Go("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s)):r},isExported:!0},Hg={description:Go("Compute the Spearman rank correlation coefficient of a dataset."),args:[qh("data_y (range<number>)",Go("The range representing the array or matrix of dependent data.")),qh("data_x (range<number>)",Go("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:s,flatDataY:o}=ju(t,e);if(0===s.length||0===o.length)return new Hi(Fn);const i=s.length,n=s.map(((e,t)=>[e,o[t]]));n.sort(((e,t)=>e[0]-t[0]));for(let e=0;e<i;++e)n[e][0]=e;n.sort(((e,t)=>e[1]-t[1]));let r=0;for(let e=0;e<i;++e)r+=(n[e][0]-e)**2;return 1-6*r/(i**3-i)},isExported:!1},zg={description:Go("Standard deviation."),args:[qh("value1 (number, range<number>)",Go("The first value or range of the sample.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to include in the sample."))],compute:function(...e){return Math.sqrt(Yg.compute.bind(this)(...e))},isExported:!0},Bg={description:Go("Standard deviation of entire population."),args:[qh("value1 (number, range<number>)",Go("The first value or range of the population.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to include in the population."))],compute:function(...e){return Math.sqrt(Xg.compute.bind(this)(...e))},isExported:!0},Gg={description:Go("Standard deviation."),args:[qh("value1 (number, range<number>)",Go("The first value or range of the sample.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to include in the sample."))],compute:function(...e){return Math.sqrt(Kg.compute.bind(this)(...e))},isExported:!0},Wg={description:Go("Standard deviation of sample (text as 0)."),args:[qh("value1 (number, range<number>)",Go("The first value or range of the sample.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to include in the sample."))],compute:function(...e){return Math.sqrt(Jg.compute.bind(this)(...e))},isExported:!0},$g={description:Go("Standard deviation of entire population."),args:[qh("value1 (number, range<number>)",Go("The first value or range of the population.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to include in the population."))],compute:function(...e){return Math.sqrt(Qg.compute.bind(this)(...e))},isExported:!0},qg={description:Go("Standard deviation of entire population (text as 0)."),args:[qh("value1 (number, range<number>)",Go("The first value or range of the population.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to include in the population."))],compute:function(...e){return Math.sqrt(ep.compute.bind(this)(...e))},isExported:!0},Zg={description:Go("Calculates the standard error of the predicted y-value for each x in the regression of a dataset."),args:[qh("data_y (range<number>)",Go("The range representing the array or matrix of dependent data.")),qh("data_x (range<number>)",Go("The range representing the array or matrix of independent data."))],compute:function(e,t){const{flatDataX:s,flatDataY:o}=ju(e,t);if(0===s.length||0===o.length)return new Hi(Fn);return oc([s],[o],!0,!0)[1][2]},isExported:!0},jg={description:Go("Fits points to linear trend derived via least-squares."),args:[qh("known_data_y (number, range<number>)",Go("The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.")),qh("known_data_x (number, range<number>, optional, default={1;2;3;...})",Go("The values of the independent variable(s) corresponding with known_data_y.")),qh("new_data_x (number, range<number>, optional, default=known_data_x)",Go("The data points to return the y values for on the ideal curve fit.")),qh("b (boolean, optional, default=TRUE)",Go("Given a general linear form of y = m*x+b for a curve fit, calculates b if TRUE or forces b to be 0 and only calculates the m values if FALSE, i.e. forces the curve fit to pass through the origin."),Gu)],compute:function(e,t=[[]],s=[[]],o={value:!0}){return 0===e.length||0===e[0].length?new Li(On("known_data_y")):cc(Ki(e,"the first argument (known_data_y)"),Ki(t,"the second argument (known_data_x)"),Ki(s,"the third argument (new_data_y)"),nn(o))}},Yg={description:Go("Variance."),args:[qh("value1 (number, range<number>)",Go("The first value or range of the sample.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to include in the sample."))],compute:function(...e){return Xu(e,!0,!1,this.locale)},isExported:!0},Xg={description:Go("Variance of entire population."),args:[qh("value1 (number, range<number>)",Go("The first value or range of the population.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to include in the population."))],compute:function(...e){return Xu(e,!1,!1,this.locale)},isExported:!0},Kg={description:Go("Variance."),args:[qh("value1 (number, range<number>)",Go("The first value or range of the sample.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to include in the sample."))],compute:function(...e){return Xu(e,!0,!1,this.locale)},isExported:!0},Jg={description:Go("Variance of sample (text as 0)."),args:[qh("value1 (number, range<number>)",Go("The first value or range of the sample.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to include in the sample."))],compute:function(...e){return Xu(e,!0,!0,this.locale)},isExported:!0},Qg={description:Go("Variance of entire population."),args:[qh("value1 (number, range<number>)",Go("The first value or range of the population.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to include in the population."))],compute:function(...e){return Xu(e,!1,!1,this.locale)},isExported:!0},ep={description:Go("Variance of entire population (text as 0)."),args:[qh("value1 (number, range<number>)",Go("The first value or range of the population.")),qh("value2 (number, range<number>, repeating)",Go("Additional values or ranges to include in the population."))],compute:function(...e){return Xu(e,!1,!0,this.locale)},isExported:!0};var tp=Object.freeze({__proto__:null,AVEDEV:Ju,AVERAGE:Qu,AVERAGEA:og,AVERAGEIF:ig,AVERAGEIFS:ng,AVERAGE_WEIGHTED:sg,CORREL:Tg,COUNT:rg,COUNTA:ag,COVAR:lg,COVARIANCE_P:cg,COVARIANCE_S:hg,FORECAST:dg,GROWTH:ug,INTERCEPT:gg,LARGE:pg,LINEST:mg,LOGEST:fg,MATTHEWS:vg,MAX:bg,MAXA:Sg,MAXIFS:Cg,MEDIAN:yg,MIN:Ig,MINA:wg,MINIFS:Eg,PEARSON:xg,PERCENTILE:Ag,PERCENTILE_EXC:Dg,PERCENTILE_INC:_g,POLYFIT_COEFFS:Fg,POLYFIT_FORECAST:Og,QUARTILE:Pg,QUARTILE_EXC:Mg,QUARTILE_INC:Ng,RANK:Lg,RSQ:kg,SLOPE:Vg,SMALL:Ug,SPEARMAN:Hg,STDEV:zg,STDEVA:Wg,STDEVP:$g,STDEVPA:qg,STDEV_P:Bg,STDEV_S:Gg,STEYX:Zg,TREND:jg,VAR:Yg,VARA:Jg,VARP:Qg,VARPA:ep,VAR_P:Xg,VAR_S:Kg});function sp(e,t,s,o){const i=new Map,n=e.length;for(let t=n-1;t>=0;t--)i.set(tn(e[t][0]).toUpperCase(),t);const r=t?.value;if("number"!=typeof r&&"string"!=typeof r)throw new Li(Go("The field must be a number or a string"));let a;if("number"==typeof r){if(a=Math.trunc(r)-1,a<0||n-1<a)throw new Li(Go("The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.",{fieldValue:r.toString(),dimRowDB:n.toString()}))}else{const e=tn(t).toUpperCase();if(a=i.get(e)??-1,-1===a)throw new Li(Go("The field (%s) must be one of %s.",tn(t),[...i.keys()].toString()))}const l=s[0].length;if(l<2)throw new Li(Go("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const h=e[0].length;for(let t=1;t<l;t++){const n=[];let r=!0;for(let o=0;o<s.length;o++){const a=tn(s[o][0]).toUpperCase(),l=i.get(a),c=s[o][t];if(null!==c.value){if(void 0===l){r=!1;break}n.push([e[l].slice(1,h)]),n.push(c)}}if(r){if(!(n.length>0)){c=new Set(Array(h-1).keys());break}wn(n,((e,t)=>{c.add(t)}),o,!0)}}const d=e[a];return[...c].map((e=>d[e+1]))}const op=[qh("database (range)",Go("The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.")),qh("field (number, string)",Go("Indicates which column in database contains the values to be extracted and operated on.")),qh("criteria (range)",Go("An array or range containing zero or more criteria to filter the database values by before operating."))],ip={description:Go("Average of a set of values from a table-like range."),args:op,compute:function(e,t,s){const o=sp(e,t,s,this.locale);return Qu.compute.bind(this)([o])},isExported:!0},np={description:Go("Counts values from a table-like range."),args:op,compute:function(e,t,s){const o=sp(e,t,s,this.locale);return rg.compute.bind(this)([o])},isExported:!0},rp={description:Go("Counts values and text from a table-like range."),args:op,compute:function(e,t,s){const o=sp(e,t,s,this.locale);return ag.compute.bind(this)([o])},isExported:!0},ap={description:Go("Single value from a table-like range."),args:op,compute:function(e,t,s){const o=sp(e,t,s,this.locale);return 1!==o.length?new Li(Go("More than one match found in DGET evaluation.")):o[0]},isExported:!0},lp={description:Go("Maximum of values from a table-like range."),args:op,compute:function(e,t,s){const o=sp(e,t,s,this.locale);return bg.compute.bind(this)([o])},isExported:!0},cp={description:Go("Minimum of values from a table-like range."),args:op,compute:function(e,t,s){const o=sp(e,t,s,this.locale);return Ig.compute.bind(this)([o])},isExported:!0},hp={description:Go("Product of values from a table-like range."),args:op,compute:function(e,t,s){const o=sp(e,t,s,this.locale);return vu.compute.bind(this)([o])},isExported:!0},dp={description:Go("Standard deviation of population sample from table."),args:op,compute:function(e,t,s){const o=sp(e,t,s,this.locale);return zg.compute.bind(this)([o])},isExported:!0},up={description:Go("Standard deviation of entire population from table."),args:op,compute:function(e,t,s){const o=sp(e,t,s,this.locale);return $g.compute.bind(this)([o])},isExported:!0},gp={description:Go("Sum of values from a table-like range."),args:op,compute:function(e,t,s){const o=sp(e,t,s,this.locale);return Mu.compute.bind(this)([o])},isExported:!0},pp={description:Go("Variance of population sample from table-like range."),args:op,compute:function(e,t,s){const o=sp(e,t,s,this.locale);return Yg.compute.bind(this)([o])},isExported:!0},mp={description:Go("Variance of a population from a table-like range."),args:op,compute:function(e,t,s){const o=sp(e,t,s,this.locale);return Qg.compute.bind(this)([o])},isExported:!0};var fp=Object.freeze({__proto__:null,DAVERAGE:ip,DCOUNT:np,DCOUNTA:rp,DGET:ap,DMAX:lp,DMIN:cp,DPRODUCT:hp,DSTDEV:dp,DSTDEVP:up,DSUM:gp,DVAR:pp,DVARP:mp});const vp=Go("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."),bp=Go("There must be both positive and negative values in cashflow_amounts."),Sp=e=>Go("The cost (%s) must be positive or null.",e),Cp=e=>Go("The frequency (%s) must be one of %s",e,[1,2,4].toString()),yp=e=>Go("The day_count_convention (%s) must be between 0 and 4 inclusive.",e),Ip=e=>Go("The depreciation factor (%s) must be strictly positive.",e),wp=e=>Go("The discount (%s) must be strictly positive.",e),Ep=e=>Go("The discount (%s) must be smaller than 1.",e),Rp=e=>Go("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e),xp=(e,t)=>Go("The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).",{first:e,last:t}),Tp=e=>Go("The first_period (%s) must be strictly positive.",e),Ap=e=>Go("The investment (%s) must be strictly positive.",e),Dp=(e,t)=>Go("The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).",{last:e,nPeriods:t}),_p=e=>Go("The last_period (%s) must be strictly positive.",e),Fp=e=>Go("The life (%s) must be strictly positive.",e),Op=(e,t)=>Go("The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).",{maturity:t,settlement:e}),Pp=e=>Go("The number_of_periods (%s) must be strictly positive.",e),Mp=e=>Go("The period must be between 1 and number_of_periods (%s)",e),Np=e=>Go("The periods_by_year (%s) must be strictly positive.",e),Lp=(e,t)=>Go("The period (%(period)s) must be less than or equal life (%(life)s).",{period:e,life:t}),kp=e=>Go("The period (%s) must be strictly positive.",e),Vp=e=>Go("The present_value (%s) must be strictly positive.",e),Up=e=>Go("The price (%s) must be strictly positive.",e),Hp=e=>Go("The rate_guess (%s) must be strictly greater than -1.",e),zp=e=>Go("The rate (%s) must be positive or null.",e),Bp=e=>Go("The rate (%s) must be strictly positive.",e),Gp=e=>Go("The redemption (%s) must be strictly positive.",e),Wp=e=>Go("The salvage (%s) must be positive or null.",e),$p=(e,t)=>Go("The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).",{settlement:e,maturity:t}),qp=e=>Go("The unit (%s) must be strictly positive.",e),Zp=e=>Go("The yield (%s) must be positive or null.",e);function jp(e){return e.some((e=>e>0))&&e.some((e=>e<0))}function Yp(e){return![0,1,2,3,4].includes(e)}function Xp(e){return![1,2,4].includes(e)}function Kp(e,t,s){const o=rn(e,s),i=rn(t,s),n=rn(e,s);return n.setFullYear(o.getFullYear()+1),i.getTime()<=n.getTime()}const Jp=[{value:0,label:Go("US (NASD) 30/360")},{value:1,label:Go("Actual/Actual")},{value:2,label:Go("Actual/360")},{value:3,label:Go("Actual/365")},{value:4,label:Go("European 30/360")}];var Qp;!function(e){e.WHOLE_YEARS="Y",e.WHOLE_MONTHS="M",e.WHOLE_DAYS="D",e.DAYS_WITHOUT_WHOLE_MONTHS="MD",e.MONTH_WITHOUT_WHOLE_YEARS="YM",e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR="YD"}(Qp||(Qp={}));const em={description:Go("Converts year/month/day into a date."),args:[qh("year (number)",Go("The year component of the date.")),qh("month (number)",Go("The month component of the date.")),qh("day (number)",Go("The day component of the date."))],compute:function(e,t,s){let o=Math.trunc(Yi(e,this.locale));const i=Math.trunc(Yi(t,this.locale)),n=Math.trunc(Yi(s,this.locale));if(o<0||o>9999)return new Li(Go("The year (%s) must be between 0 and 9999 inclusive.",o.toString()));o<1900&&(o+=1900);const r=vi(new Qo(o,i-1,n));return r<0?new Li(Go("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")):{value:r,format:this.locale.dateFormat}},isExported:!0},tm={description:Go("Calculates the number of days, months, or years between two dates."),args:[qh("start_date (date)",Go("The start date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.")),qh("end_date (date)",Go("The end date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.")),qh("unit (string)",Go("A text abbreviation for unit of time."),[{value:"Y",label:Go("The number of whole years between start_date and end_date")},{value:"M",label:Go("The number of whole months between start_date and end_date")},{value:"D",label:Go("The number of days between start_date and end_date")},{value:"MD",label:Go("The number of days between start_date and end_date after subtracting whole months")},{value:"YM",label:Go("The number of whole months between start_date and end_date after subtracting whole years")},{value:"YD",label:Go("The number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart")}])],compute:function(e,t,s){const o=tn(s).toUpperCase();if(!Object.values(Qp).includes(o))return new Li(((e,t)=>{const s=e.map((e=>`'${e}'`)).join(", ");return Go("The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.",t,s)})(Object.values(Qp),tn(s)));const i=Math.trunc(Yi(e,this.locale)),n=Math.trunc(Yi(t,this.locale)),r=fi(i),a=fi(n);if(n<i)return new Li(Go("start_date (%s) should be on or before end_date (%s).",r.toLocaleDateString(),a.toLocaleDateString()));switch(o){case Qp.WHOLE_YEARS:return xi(r,a);case Qp.WHOLE_MONTHS:return Ei(r,a);case Qp.WHOLE_DAYS:return Ri(r,a);case Qp.MONTH_WITHOUT_WHOLE_YEARS:return Ei(r,a)-12*xi(r,a);case Qp.DAYS_WITHOUT_WHOLE_MONTHS:let e=a.getDate()-r.getDate();if(e<0){e=Si(new Qo(a.getFullYear(),a.getMonth()-1,1))-Math.abs(e)}return e;case Qp.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR:{if(function(e,t){return wi(e,t,1)<1}(i,n))return Ri(r,a);const e=new Qo(r.getFullYear(),a.getMonth(),a.getDate());let t=Ri(r,e);return t<0&&(e.setFullYear(r.getFullYear()+1),t=Ri(r,e)),t}}},isExported:!0},sm={description:Go("Converts a date string to a date value."),args:[qh("date_string (string)",Go("The string representing the date."))],compute:function(e){const t=tn(e),s=mi(t,this.locale);return null===s?new Li(Go("The date_string (%s) cannot be parsed to date/time.",t.toString())):Math.trunc(s.value)},isExported:!0},om={description:Go("Day of the month that a specific date falls on."),args:[qh("date (string)",Go("The date from which to extract the day."))],compute:function(e){return rn(e,this.locale).getDate()},isExported:!0},im={description:Go("Number of days between two dates."),args:[qh("end_date (date)",Go("The end of the date range.")),qh("start_date (date)",Go("The start of the date range."))],compute:function(e,t){const s=rn(e,this.locale),o=rn(t,this.locale),i=s.getTime()-o.getTime();return Math.round(i/ti)},isExported:!0},nm={description:Go("Number of days between two dates on a 360-day year (months of 30 days)."),args:[qh("start_date (date)",Go("The start date to consider in the calculation.")),qh("end_date (date)",Go("The end date to consider in the calculation.")),qh("method (boolean, default=false)",Go("An indicator of what day count method to use."),[{value:!1,label:Go("U.S. NASD method (default)")},{value:!0,label:Go("European method")}])],compute:function(e,t,s={value:false}){const o=Math.trunc(Yi(e,this.locale)),i=Math.trunc(Yi(t,this.locale)),n=wi(o,i,nn(s)?4:0);return Math.sign(i-o)*Math.round(360*n)},isExported:!0},rm={description:Go("Date a number of months before/after another date."),args:[qh("start_date (date)",Go("The date from which to calculate the result.")),qh("months (number)",Go("The number of months before (negative) or after (positive) 'start_date' to calculate."))],compute:function(e,t){return{value:vi(yi(rn(e,this.locale),Math.trunc(Yi(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},am={description:Go("Last day of a month before or after a date."),args:[qh("start_date (date)",Go("The date from which to calculate the result.")),qh("months (number)",Go("The number of months before (negative) or after (positive) 'start_date' to consider."))],compute:function(e,t){const s=rn(e,this.locale),o=Math.trunc(Yi(t,this.locale)),i=s.getFullYear(),n=s.getMonth();return{value:vi(new Qo(i,n+o+1,0)),format:this.locale.dateFormat}},isExported:!0},lm={description:Go("Hour component of a specific time."),args:[qh("time (date)",Go("The time from which to calculate the hour component."))],compute:function(e){return rn(e,this.locale).getHours()},isExported:!0},cm={description:Go("ISO week number of the year."),args:[qh("date (date)",Go("The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number."))],compute:function(e){const t=rn(e,this.locale),s=t.getFullYear();let o=1;for(;4!==new Qo(s,0,o).getDay();)o+=1;const i=new Qo(s,0,o-3);let n=31;for(;4!==new Qo(s,11,n).getDay();)n-=1;const r=new Qo(s,11,n+3);let a,l;switch(a=i.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=i;break;case 1:l=new Qo(s,11,n+3+1);break;case-1:let e=1;for(;4!==new Qo(s-1,0,e).getDay();)e+=1;l=new Qo(s-1,0,e-3)}const c=(t.getTime()-l.getTime())/ti;return Math.floor(c/7)+1},isExported:!0},hm={description:Go("Minute component of a specific time."),args:[qh("time (date)",Go("The time from which to calculate the minute component."))],compute:function(e){return rn(e,this.locale).getMinutes()},isExported:!0},dm={description:Go("Month of the year a specific date falls in"),args:[qh("date (date)",Go("The date from which to extract the month."))],compute:function(e){return rn(e,this.locale).getMonth()+1},isExported:!0},um={description:Go("Net working days between two provided days."),args:[qh("start_date (date)",Go("The start date of the period from which to calculate the number of net working days.")),qh("end_date (date)",Go("The end date of the period from which to calculate the number of net working days.")),qh("holidays (date, range<date>, optional)",Go("A range or array constant containing the date serial numbers to consider holidays."))],compute:function(e,t,s){return mm.compute.bind(this)(e,t,{value:1},s)},isExported:!0};function gm(e){const t=e?.value;if("string"==typeof t){kl(7===t.length&&[...t].every((e=>"0"===e||"1"===e)),Go('When weekend is a string (%s) it must be composed of "0" or "1".',t));const e=[];for(let s=0;s<7;s++)"1"===t[s]&&e.push((s+1)%7);return e}if("number"==typeof t)return kl(1<=t&&t<=7||11<=t&&t<=17,Go("The weekend (%s) must be a string or a number in the range 1-7 or 11-17.",t.toString())),t<=7?[t-2==-1?6:t-2,t-1]:[t-11];throw new Li(Go("The weekend must be a number or a string."))}const pm=[{value:1,label:Go("Saturday/Sunday are weekends")},{value:2,label:Go("Sunday/Monday are weekends")},{value:3,label:Go("Monday/Tuesday are weekends")},{value:4,label:Go("Tuesday/Wednesday are weekends")},{value:5,label:Go("Wednesday/Thursday are weekends")},{value:6,label:Go("Thursday/Friday are weekends")},{value:7,label:Go("Friday/Saturday are weekends")},{value:11,label:Go("Sunday is the only weekend")},{value:12,label:Go("Monday is the only weekend")},{value:13,label:Go("Tuesday is the only weekend")},{value:14,label:Go("Wednesday is the only weekend")},{value:15,label:Go("Thursday is the only weekend")},{value:16,label:Go("Friday is the only weekend")},{value:17,label:Go("Saturday is the only weekend")}],mm={description:Go("Net working days between two dates (specifying weekends)."),args:[qh("start_date (date)",Go("The start date of the period from which to calculate the number of net working days.")),qh("end_date (date)",Go("The end date of the period from which to calculate the number of net working days.")),qh("weekend (any, default=1)",Go("A number or string representing which days of the week are considered weekends."),pm),qh("holidays (date, range<date>, optional)",Go("A range or array constant containing the dates to consider as holidays."))],compute:function(e,t,s={value:1},o){const i=rn(e,this.locale),n=rn(t,this.locale),r=gm(s),a=new Set;void 0!==o&&cn([o],(e=>{const t=rn(e,this.locale);a.add(t.getTime())}));const l=i.getTime()>n.getTime(),c=Qo.fromTimestamp((l?i:n).getTime()),h=Qo.fromTimestamp((l?n:i).getTime()),d=c.getTime();let u=h.getTime(),g=0;for(;u<=d;)r.includes(h.getDay())||a.has(u)||(g+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-g:g},isExported:!0},fm={description:Go("Current date and time as a date value."),args:[],compute:function(){const e=Qo.now(),t=e.getTime()-ei.getTime(),s=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/ti)+s,format:Ol(this.locale)}},isExported:!0},vm={description:Go("Minute component of a specific time."),args:[qh("time (date)",Go("The time from which to calculate the second component."))],compute:function(e){return rn(e,this.locale).getSeconds()},isExported:!0},bm={description:Go("Converts hour/minute/second into a time."),args:[qh("hour (number)",Go("The hour component of the time.")),qh("minute (number)",Go("The minute component of the time.")),qh("second (number)",Go("The second component of the time."))],compute:function(e,t,s){let o=Math.trunc(Yi(e,this.locale)),i=Math.trunc(Yi(t,this.locale)),n=Math.trunc(Yi(s,this.locale));return i+=Math.floor(n/60),n=n%60+(n<0?60:0),o+=Math.floor(i/60),i=i%60+(i<0?60:0),o%=24,o<0?new Li(Go("The function [[FUNCTION_NAME]] result cannot be negative")):{value:o/24+i/1440+n/86400,format:this.locale.timeFormat}},isExported:!0},Sm={description:Go("Converts a time string into its serial number representation."),args:[qh("time_string (string)",Go("The string that holds the time representation."))],compute:function(e){const t=tn(e),s=mi(t,this.locale);if(null===s)return new Li(Go("The time_string (%s) cannot be parsed to date/time.",t));const o=s.value-Math.trunc(s.value);return o<0?1+o:o},isExported:!0},Cm={description:Go("Current date as a date value."),args:[],compute:function(){const e=Qo.now();return{value:vi(new Qo(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},ym={description:Go("Day of the week of the date provided (as number)."),args:[qh("date (date)",Go("The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),qh("type (number, default=1)",Go("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1."),[{value:1,label:Go("Numbers 1 (Sunday) trough 7 (Saturday)")},{value:2,label:Go("Numbers 1 (Monday) trough 7 (Sunday)")},{value:3,label:Go("Numbers 0 (Monday) trough 6 (Sunday)")},{value:11,label:Go("Numbers 1 (Monday) trough 7 (Sunday)")},{value:12,label:Go("Numbers 1 (Tuesday) trough 7 (Monday)")},{value:13,label:Go("Numbers 1 (Wednesday) trough 7 (Tuesday)")},{value:14,label:Go("Numbers 1 (Thursday) trough 7 (Wednesday)")},{value:15,label:Go("Numbers 1 (Friday) trough 7 (Thursday)")},{value:16,label:Go("Numbers 1 (Saturday) trough 7 (Friday)")},{value:17,label:Go("Numbers 1 (Sunday) trough 7 (Saturday)")}])],compute:function(e,t={value:1}){const s=rn(e,this.locale),o=Math.round(Yi(t,this.locale)),i=s.getDay();if(!(1<=o&&o<=3||11<=o&&o<=17))return new Li(Go("The type (%s) must be between 1 and 3 or between 11 and 17.",o));switch(o){case 1:return i+1;case 2:return 0===i?7:i;case 3:return 0===i?6:i-1}const n=(i+1-(o-10)+7)%7;return 0===n?7:n},isExported:!0},Im={description:Go("Week number of the year."),args:[qh("date (date)",Go("The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),qh("type (number, default=1)",Go("A number representing the day that a week starts on. Sunday = 1."),[{value:1,label:Go("Sunday")},{value:2,label:Go("Monday")},{value:11,label:Go("Monday")},{value:12,label:Go("Tuesday")},{value:13,label:Go("Wednesday")},{value:14,label:Go("Thursday")},{value:15,label:Go("Friday")},{value:16,label:Go("Saturday")},{value:17,label:Go("Sunday")},{value:21,label:Go("ISO week number (Monday as first day of the week)")}])],compute:function(e,t={value:1}){const s=rn(e,this.locale),o=Math.round(Yi(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(o))return new Li(Go("The type (%s) is out of range.",o.toString()));if(21===o)return cm.compute.bind(this)(e);let i;i=1===o||2===o?o-1:o-10==7?0:o-10;const n=s.getFullYear();let r=1,a=new Qo(n,0,r);for(;a.getDay()!==i;)r+=1,a=new Qo(n,0,r);const l=(s.getTime()-a.getTime())/ti;return l<0?1:Math.floor(l/7)+(1===r?1:2)},isExported:!0},wm={description:Go("Date after a number of workdays."),args:[qh("start_date (date)",Go("The date from which to begin counting.")),qh("num_days (number)",Go("The number of working days to advance from start_date. If negative, counts backwards.")),qh("holidays (date, range<date>, optional)",Go("A range or array constant containing the dates to consider holidays."))],compute:function(e,t,s={value:null}){return Em.compute.bind(this)(e,t,{value:1},s)},isExported:!0},Em={description:Go("Date after a number of workdays (specifying weekends)."),args:[qh("start_date (date)",Go("The date from which to begin counting.")),qh("num_days (number)",Go("The number of working days to advance from start_date. If negative, counts backwards.")),qh("weekend (any, default=1)",Go("A number or string representing which days of the week are considered weekends."),pm),qh("holidays (date, range<date>, optional)",Go("A range or array constant containing the dates to consider holidays."))],compute:function(e,t,s={value:1},o){const i=rn(e,this.locale),n=Math.trunc(Yi(t,this.locale));if("1111111"===s.value)return new Li(Go("The weekend must be different from '1111111'."));const r=gm(s),a=new Set;void 0!==o&&cn([o],(e=>{const t=rn(e,this.locale);a.add(t.getTime())}));const l=Qo.fromTimestamp(i.getTime());let c=l.getTime();const h=Math.sign(n);let d=Math.abs(n);for(;d>0;)l.setDate(l.getDate()+h),c=l.getTime(),r.includes(l.getDay())||a.has(c)||(d-=1);const u=c-ei.getTime();return{value:Math.round(u/ti),format:this.locale.dateFormat}},isExported:!0},Rm={description:Go("Year specified by a given date."),args:[qh("date (date)",Go("The date from which to extract the year."))],compute:function(e){return rn(e,this.locale).getFullYear()},isExported:!0},xm={description:Go("Exact number of years between two dates."),args:[qh("start_date (date)",Go("The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),qh("end_date (date)",Go("The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),qh("day_count_convention (number, default=0)",Go("An indicator of what day count method to use."),Jp)],compute:function(e,t,s={value:0}){const o=Math.trunc(Yi(e,this.locale)),i=Math.trunc(Yi(t,this.locale)),n=Math.trunc(Yi(s,this.locale));return o<0?new Li(Go("The start_date (%s) must be positive or null.",o)):i<0?new Li(Go("The end_date (%s) must be positive or null.",i)):0>n||n>4?new Li(Go("The day_count_convention (%s) must be between 0 and 4 inclusive.",n)):wi(o,i,n)}},Tm={description:Go("First day of the month preceding a date."),args:[qh("date (date)",Go("The date from which to calculate the result."))],compute:function(e){const t=rn(e,this.locale),s=t.getFullYear(),o=t.getMonth();return{value:vi(new Qo(s,o,1)),format:this.locale.dateFormat}}},Am={description:Go("Last day of the month following a date."),args:[qh("date (date)",Go("The date from which to calculate the result."))],compute:function(e){return am.compute.bind(this)(e,{value:0})}},Dm={description:Go("Quarter of the year a specific date falls in"),args:[qh("date (date)",Go("The date from which to extract the quarter."))],compute:function(e){return Math.ceil((rn(e,this.locale).getMonth()+1)/3)}},_m={description:Go("First day of the quarter of the year a specific date falls in."),args:[qh("date (date)",Go("The date from which to calculate the start of quarter."))],compute:function(e){const t=Dm.compute.bind(this)(e),s=Rm.compute.bind(this)(e);return{value:vi(new Qo(s,3*(t-1),1)),format:this.locale.dateFormat}}},Fm={description:Go("Last day of the quarter of the year a specific date falls in."),args:[qh("date (date)",Go("The date from which to calculate the end of quarter."))],compute:function(e){const t=Dm.compute.bind(this)(e),s=Rm.compute.bind(this)(e);return{value:vi(new Qo(s,3*t,0)),format:this.locale.dateFormat}}},Om={description:Go("First day of the year a specific date falls in."),args:[qh("date (date)",Go("The date from which to calculate the start of the year."))],compute:function(e){const t=Rm.compute.bind(this)(e);return{value:vi(new Qo(t,0,1)),format:this.locale.dateFormat}}},Pm={description:Go("Last day of the year a specific date falls in."),args:[qh("date (date)",Go("The date from which to calculate the end of the year."))],compute:function(e){const t=Rm.compute.bind(this)(e);return{value:vi(new Qo(t+1,0,0)),format:this.locale.dateFormat}}};var Mm=Object.freeze({__proto__:null,DATE:em,DATEDIF:tm,DATEVALUE:sm,DAY:om,DAYS:im,DAYS360:nm,EDATE:rm,EOMONTH:am,HOUR:lm,ISOWEEKNUM:cm,MINUTE:hm,MONTH:dm,MONTH_END:Am,MONTH_START:Tm,NETWORKDAYS:um,NETWORKDAYS_INTL:mm,NOW:fm,QUARTER:Dm,QUARTER_END:Fm,QUARTER_START:_m,SECOND:vm,TIME:bm,TIMEVALUE:Sm,TODAY:Cm,WEEKDAY:ym,WEEKNUM:Im,WORKDAY:wm,WORKDAY_INTL:Em,YEAR:Rm,YEARFRAC:xm,YEAR_END:Pm,YEAR_START:Om});const Nm={description:Go("Compare two numeric values, returning 1 if they're equal."),args:[qh("number1 (number)",Go("The first number to compare.")),qh("number2 (number, default=0)",Go("The second number to compare."))],compute:function(e,t={value:0}){return Yi(e,this.locale)===Yi(t,this.locale)?1:0},isExported:!0};var Lm=Object.freeze({__proto__:null,DELTA:Nm});const km=[r.number,r.error,r.text,r.boolean];function Vm(e){const t="asc"===e?1:-1;return(e,s)=>{if(e.type===r.empty)return s.type===r.empty?0:1;if(s.type===r.empty)return-1;let o=km.indexOf(e.type)-km.indexOf(s.type);return 0===o&&(o=e.type===r.text||e.type===r.error?e.value.localeCompare(s.value):e.value-s.value),t*o}}function Um(e,t,s,o,i){let n=o.right>o.left;if(e.model.getters.doesIntersectMerge(t,o)){let s;n=!1;for(let i=o.top;i<=o.bottom;i++){s=[];for(let n=o.left;n<=o.right;n++){const o=e.model.getters.getMerge({sheetId:t,col:n,row:i});o&&!s.includes(o.id.toString())&&s.push(o.id.toString())}if(s.length>=2){n=!0;break}}}if(n)return void Hm(e,t,s,o,i);const r=e.model.getters.getContiguousZone(t,o);xs(r,o)?Hm(e,t,s,o,i):e.askConfirmation(Go("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),(()=>Hm(e,t,s,r,i)),(()=>Hm(e,t,s,o,i)))}function Hm(e,t,s,o,i,n){const r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:s.col,row:s.row,zone:o,sortDirection:i,sortOptions:n});if(r.isCancelledBecause("InvalidSortZone")){const{col:t,row:i}=s;e.model.selection.selectZone({cell:{col:t,row:i},zone:o}),e.raiseError(Go("Cannot sort. To sort, select only cells or only merges that have the same size."))}if(r.isCancelledBecause("SortZoneWithArrayFormulas")){const{col:t,row:i}=s;e.model.selection.selectZone({cell:{col:t,row:i},zone:o}),e.raiseError(Go("Cannot sort a zone with array formulas."))}}function zm(e,t,...s){for(let e=0;e<s.length;e++){const t=e%2==0?"sort_column":"is_ascending";kl(void 0!==s[e],Go("Value for parameter %s is missing in [[FUNCTION_NAME]].",t))}const o=[],i=[],n=e.length;for(let r=0;r<s.length;r+=2){o.push(nn(Zl(s[r+1])?.value)?"asc":"desc");const a=s[r];if(R(a)&&(a.length>1||a[0].length>1))kl(1===a.length&&a[0].length===n,Go("Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.",`sort_column${r+1}`,n,a.length,a[0].length)),i.push(a.flat().map((e=>e.value)));else{const s=Yi(Zl(a)?.value,t);if(s<1||s>e[0].length)return e;i.push(e.map((e=>e[s-1].value)))}}if(0===i.length)for(let t=0;t<e[0].length;t++)i.push(e.map((e=>e[t].value))),o.push("asc");const a={desc:Vm("desc"),asc:Vm("asc")},l=Je(0,e.length);return l.sort(((e,t)=>{for(const[s,n]of i.entries()){const i=n[e],l=n[t],c={value:i,type:null===i?r.empty:"string"==typeof i?r.text:typeof i},h={value:l,type:null===l?r.empty:"string"==typeof l?r.text:typeof l},d=a[o[s]](c,h);if(0!==d)return d}return 0})),l.map((t=>e[t]))}const Bm={description:Go("Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions."),args:[qh("range (any, range<any>)",Go("The data to be filtered.")),qh("condition1 (boolean, range<boolean>)",Go("A column or row containing true or false values corresponding to the first column or row of range.")),qh("condition2 (boolean, range<boolean>, repeating)",Go("Additional column or row containing true or false values."))],compute:function(e,...t){let s=An(e);const o=t.map((e=>fn(An(e),(e=>e.value))));for(const e of o)if(!Ul(e))return new Li(Go("The arguments condition must be a single column or row."));if(!Hl(...t))return new Li(Go("The arguments conditions must have the same dimensions."));const i=o.map((e=>e.flat())),n=1===o[0].length?"row":"col";if(s="row"===n?vn(s):s,i.some((e=>e.length!==s.length)))return new Li(Go("FILTER has mismatched sizes on the range and conditions."));const r=[];for(let e=0;e<s.length;e++){const t=s[e];i.every((t=>("boolean"==typeof t[e]||"number"==typeof t[e])&&t[e]))&&r.push(t)}return r.length?"row"===n?vn(r):r:new Hi(Go("No match found in FILTER evaluation"))},isExported:!1},Gm={description:Go("Sorts the rows of a given array or range by the values in one or more columns."),args:[qh("range (range)",Go("The data to be sorted.")),qh("sort_column (any, range<number>, repeating)",Go("The index of the column in range or a range outside of range containing the values by which to sort.")),qh("is_ascending (boolean, repeating)",Go("TRUE or FALSE indicating whether to sort sort_column in ascending order."),[{value:!0,label:Go("Ascending")},{value:!1,label:Go("Descending")}])],compute:function(e,...t){const s=vn(e);return vn(zm(s,this.locale,...t))},isExported:!0},Wm={description:Go("Returns the first n items in a data set after performing a sort."),args:[qh("range (range)",Go("The data to be sorted.")),qh("n (number)",Go("The number of items to return.")),qh("display_ties_mode (number, default=0)",Go("A number representing the way to display ties.")),qh("sort_column (number, range<number>, repeating)",Go("The index of the column in range or a range outside of range containing the values by which to sort.")),qh("is_ascending (boolean, repeating)",Go("TRUE or FALSE indicating whether to sort sort_column in ascending order."),[{value:!0,label:Go("Ascending")},{value:!1,label:Go("Descending")}])],compute:function(e,t,...s){const o=Yi(t?.value??1,this.locale),i=s.length%2==0?0:Yi(s[0]?.value,this.locale),n=s.length%2==0?s:s.slice(1);if(o<0)return new Li(Go("Wrong value of 'n'. Expected a positive number. Got %s.",o));if(i<0||i>3)return new Li(Go("Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.",i));const r=zm(vn(e),this.locale,...n),a=(e,t)=>JSON.stringify(r[e].map((e=>e.value)))===JSON.stringify(r[t].map((e=>e.value)));switch(i){case 0:return vn(r.slice(0,o));case 1:for(let e=o;e<r.length;e++)if(!a(e,o-1))return vn(r.slice(0,e));return vn(r);case 2:{const e=[r[0]];for(let t=1;t<r.length;t++)for(let s=0;s<t&&!a(t,s);s++)s===t-1&&e.push(r[t]);return vn(e.slice(0,o))}case 3:{const e=[r[0]];let t=1;for(let s=1;s<r.length&&(a(s,s-1)||t++,!(t>o));s++)e.push(r[s]);return vn(e)}}},isExported:!1},$m={description:Go("Unique rows in the provided source range."),args:[qh("range (any, range<any>)",Go("The data to filter by unique entries.")),qh("by_column (boolean, default=FALSE)",Go("Whether to filter the data by columns or by rows."),[{value:!0,label:Go("Return unique columns")},{value:!1,label:Go("Return unique rows")}]),qh("exactly_once (boolean, default=FALSE)",Go("Whether to return only entries with no duplicates."),[{value:!0,label:Go("Return items that appear exactly once")},{value:!1,label:Go("Return every distinct item")}])],compute:function(e={value:""},t,s){if(!R(e))return[[e]];const o=nn(t?.value)||!1,i=nn(s?.value)||!1;o||(e=vn(e));const n=new Map;for(const t of e){const e=JSON.stringify(t.map((e=>e.value))),s=n.get(e);s?s.count++:n.set(e,{data:t,count:1})}const r=[];for(const e of n.values())i&&e.count>1||r.push(e.data);return r.length?o?r:vn(r):new Li(Go("No unique values found"))},isExported:!0};var qm=Object.freeze({__proto__:null,FILTER:Bm,SORT:Gm,SORTN:Wm,UNIQUE:$m});const Zm=[{value:1,label:Go("Annual")},{value:2,label:Go("Semi-annual")},{value:4,label:Go("Quarterly")}],jm=[{value:0,label:Go("End of period (default)")},{value:1,label:Go("Beginning of period")}],Ym=[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("frequency (number)",Go("The number of interest or coupon payments per year (1, 2, or 4)."),Zm),qh("day_count_convention (number, default=0 )",Go("An indicator of what day count method to use."),Jp)];function Xm(e,t,s,o,i=1e-10,n){let r,a,l,c,h=s,d=!1,u=0;do{l=e(h),isNaN(l)?(kl(u<o&&void 0!==n,Go("Function [[FUNCTION_NAME]] didn't find any result.")),u++,h=n(c),c=h):(r=h-l/t(h),a=Math.abs(r-h),h=r,d=a<i||Math.abs(l)<i,kl(u<o,Go("Function [[FUNCTION_NAME]] didn't find any result.")),u++)}while(!d);return h}const Km={description:Go("Accrued interest of security paying at maturity."),args:[qh("issue (date)",Go("The date the security was initially issued.")),qh("maturity (date)",Go("The maturity date of the security.")),qh("rate (number)",Go("The annualized rate of interest.")),qh("redemption (number)",Go("The redemption amount per 100 face value, or par.")),qh("day_count_convention (number, default=0 )",Go("An indicator of what day count method to use."),Jp)],compute:function(e,t,s,o,i={value:0}){const n=Math.trunc(Yi(e,this.locale)),r=Math.trunc(Yi(t,this.locale)),a=Yi(o,this.locale),l=Yi(s,this.locale),c=Math.trunc(Yi(i,this.locale));if(n<0)return new Li((e=>Go("The issue (%s) must be positive or null.",e))(n));if(n>=r)return new Li(Op(n,r));if(Yp(c))return new Li(yp(c));if(a<=0)return new Li(Gp(a));if(l<=0)return new Li(Bp(l));return a*l*wi(n,r,c)},isExported:!0},Jm={description:Go("Depreciation for an accounting period."),args:[qh("cost (number)",Go("The initial cost of the asset.")),qh("purchase_date (date)",Go("The date the asset was purchased.")),qh("first_period_end (date)",Go("The date the first period ended.")),qh("salvage (number)",Go("The value of the asset at the end of depreciation.")),qh("period (number)",Go("The single period within life for which to calculate depreciation.")),qh("rate (number)",Go("The deprecation rate.")),qh("day_count_convention (number, optional)",Go("An indicator of what day count method to use."),Jp)],compute:function(e,t,s,o,i,n,r={value:0}){r=r||0;const a=Yi(e,this.locale),l=Math.trunc(Yi(t,this.locale)),c=Math.trunc(Yi(s,this.locale)),h=Yi(o,this.locale),d=Yi(i,this.locale),u=Yi(n,this.locale),g=Math.trunc(Yi(r,this.locale));if(a<=0)return new Li((e=>Go("The cost (%s) must be strictly positive.",e))(a));if(l<0)return new Li((e=>Go("The purchase_date (%s) must be positive or null.",e))(l));if(h<0)return new Li(Wp(h));if(h>a)return new Li(((e,t)=>Go("The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).",{salvage:e,cost:t}))(h,a));if(d<0)return new Li((e=>Go("The period (%s) must be positive or null.",e))(d));if(u<=0)return new Li(Bp(u));if(Yp(g))return new Li(yp(g));if(l>c)return new Li(((e,t)=>Go("The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).",{purchaseDate:e,firstPeriodEnd:t}))(l,c));const p=d<1&&d>0?1:Math.trunc(d),m=a*u,f=wi(l,c,g),v=l===c?m:m*f,b=a-v-m*p;return b>=h?0===p?v:m:h-b<m?m-(h-b):0},isExported:!0},Qm={description:Go("Days in coupon period containing settlement date."),args:Ym,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(Yi(e,this.locale)),n=Math.trunc(Yi(t,this.locale)),r=Math.trunc(Yi(s,this.locale)),a=Math.trunc(Yi(o,this.locale));if(i>=n)return new Li(Op(i,n));if(Xp(r))return new Li(Cp(r));if(Yp(a))return new Li(yp(a));if(1===a){const i=nf.compute.bind(this)(e,t,s,o).value;return Yi(sf.compute.bind(this)(e,t,s,o).value,this.locale)-Yi(i,this.locale)}return(3===a?365:360)/r},isExported:!0},ef={description:Go("Days from settlement until next coupon."),args:Ym,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(Yi(e,this.locale)),n=Math.trunc(Yi(t,this.locale)),r=Math.trunc(Yi(s,this.locale)),a=Math.trunc(Yi(o,this.locale));if(i>=n)return new Li(Op(i,n));if(Xp(r))return new Li(Cp(r));if(Yp(a))return new Li(yp(a));const l=Yi(nf.compute.bind(this)(e,t,s,o).value,this.locale);if([1,2,3].includes(a))return i-l;if(4===a){const e=wi(l,i,a);return Math.round(360*e)}const c=rn(i,this.locale),h=rn(l,this.locale),d=h.getFullYear(),u=c.getFullYear(),g=h.getMonth()+1,p=c.getMonth()+1;let m=h.getDate(),f=c.getDate();return 2===g&&2===p&&Ci(h)&&Ci(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&Ci(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},tf={description:Go("Days from settlement until next coupon."),args:Ym,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(Yi(e,this.locale)),n=Math.trunc(Yi(t,this.locale)),r=Math.trunc(Yi(s,this.locale)),a=Math.trunc(Yi(o,this.locale));if(i>=n)return new Li(Op(i,n));if(Xp(r))return new Li(Cp(r));if(Yp(a))return new Li(yp(a));const l=Yi(sf.compute.bind(this)(e,t,s,o).value,this.locale);if([1,2,3].includes(a))return l-i;if(4===a){const e=wi(i,l,a);return Math.round(360*e)}const c=ef.compute.bind(this)(e,t,s,o);return Yi(Qm.compute.bind(this)(e,t,s,o),this.locale)-Yi(c,this.locale)},isExported:!0},sf={description:Go("Next coupon date after the settlement date."),args:Ym,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(Yi(e,this.locale)),n=Math.trunc(Yi(t,this.locale)),r=Math.trunc(Yi(s,this.locale)),a=Math.trunc(Yi(o,this.locale));if(i>=n)return new Li(Op(i,n));if(Xp(r))return new Li(Cp(r));if(Yp(a))return new Li(yp(a));const l=12/r,c=of.compute.bind(this)(e,t,s,o);return{value:vi(yi(rn(n,this.locale),-(Yi(c,this.locale)-1)*l,!0)),format:this.locale.dateFormat}},isExported:!0},of={description:Go("Number of coupons between settlement and maturity."),args:Ym,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(Yi(e,this.locale)),n=Math.trunc(Yi(t,this.locale)),r=Math.trunc(Yi(s,this.locale)),a=Math.trunc(Yi(o,this.locale));if(i>=n)return new Li(Op(i,n));if(Xp(r))return new Li(Cp(r));if(Yp(a))return new Li(yp(a));let l=1,c=n;const h=12/r;for(;c>i;)c=vi(yi(rn(c,this.locale),-h,!1)),l++;return l-1},isExported:!0},nf={description:Go("Last coupon date prior to or on the settlement date."),args:Ym,compute:function(e,t,s,o={value:0}){o=o||0;const i=Math.trunc(Yi(e,this.locale)),n=Math.trunc(Yi(t,this.locale)),r=Math.trunc(Yi(s,this.locale)),a=Math.trunc(Yi(o,this.locale));if(i>=n)return new Li(Op(i,n));if(Xp(r))return new Li(Cp(r));if(Yp(a))return new Li(yp(a));const l=12/r,c=of.compute.bind(this)(e,t,s,o);return{value:vi(yi(rn(n,this.locale),-c*l,!0)),format:this.locale.dateFormat}},isExported:!0},rf={description:Go("Cumulative interest paid over a set of periods."),args:[qh("rate (number)",Go("The interest rate.")),qh("number_of_periods (number)",Go("The number of payments to be made.")),qh("present_value (number)",Go("The current value of the annuity.")),qh("first_period (number)",Go("The number of the payment period to begin the cumulative calculation.")),qh("last_period (number)",Go("The number of the payment period to end the cumulative calculation.")),qh("end_or_beginning (number, default=0)",Go("The timing of the payment payments are due for each period."),jm)],compute:function(e,t,s,o,i,n={value:0}){const r=Yi(o,this.locale),a=Yi(i,this.locale),l=Yi(e,this.locale),c=Yi(s,this.locale),h=Yi(t,this.locale),d=nn(n)?1:0;if(h<=0)return new Li(Pp(h));if(r<=0)return new Li(Tp(r));if(a<=0)return new Li(_p(a));if(r>a)return new Li(xp(r,a));if(a>h)return new Li(Dp(a,h));if(l<=0)return new Li(Bp(l));if(c<=0)return new Li(Vp(c));let u=0;for(let e=r;e<=a;e++)u+=Cf(l,e,h,c,0,d);return u},isExported:!0},af={description:Go("Cumulative principal paid over a set of periods."),args:[qh("rate (number)",Go("The interest rate.")),qh("number_of_periods (number)",Go("The number of payments to be made.")),qh("present_value (number)",Go("The current value of the annuity.")),qh("first_period (number)",Go("The number of the payment period to begin the cumulative calculation.")),qh("last_period (number)",Go("The number of the payment period to end the cumulative calculation.")),qh("end_or_beginning (number, default=0)",Go("The timing of the payment payments are due for each period."),jm)],compute:function(e,t,s,o,i,n={value:0}){const r=Yi(o,this.locale),a=Yi(i,this.locale),l=Yi(e,this.locale),c=Yi(s,this.locale),h=Yi(t,this.locale),d=nn(n)?1:0;if(h<=0)return new Li(Pp(h));if(r<=0)return new Li(Tp(r));if(a<=0)return new Li(_p(a));if(r>a)return new Li(xp(r,a));if(a>h)return new Li(Dp(a,h));if(l<=0)return new Li(Bp(l));if(c<=0)return new Li(Vp(c));let u=0;for(let e=r;e<=a;e++)u+=Pf(l,e,h,c,0,d);return u},isExported:!0},lf={description:Go("Depreciation via declining balance method."),args:[qh("cost (number)",Go("The initial cost of the asset.")),qh("salvage (number)",Go("The value of the asset at the end of depreciation.")),qh("life (number)",Go("The number of periods over which the asset is depreciated.")),qh("period (number)",Go("The single period within life for which to calculate depreciation.")),qh("month (number, optional)",Go("The number of months in the first year of depreciation."))],compute:function(e,t,s,o,...i){const n=Yi(e,this.locale),r=Yi(t,this.locale),a=Yi(s,this.locale),l=Math.trunc(Yi(o,this.locale)),c=i.length?Math.trunc(Yi(i[0],this.locale)):12,h=a+(12===c?0:1);if(n<0)return new Li(Sp(n));if(r<0)return new Li(Wp(r));if(l<=0)return new Li(kp(l));if(a<=0)return new Li(Fp(a));if(1>c||c>12)return new Li(Go("The month (%s) must be between 1 and 12 inclusive.",c));if(l>h)return new Li(((e,t)=>Go("The period (%(period)s) must be less than or equal to %(lifeLimit)s.",{period:e,lifeLimit:t}))(l,h));const d=c/12;let u=1-Math.pow(r/n,1/a);u=Math.round(1e3*u)/1e3;let g=n,p=n*(1-u*d);for(let e=1;e<l;e++)g=p,p=g*(1-u),e===a&&(p=g*(1-u*(1-d)));return{value:g-p,format:"#,##0.00"}},isExported:!0},cf="#,##0.00",hf={description:Go("Depreciation via double-declining balance method."),args:[qh("cost (number)",Go("The initial cost of the asset.")),qh("salvage (number)",Go("The value of the asset at the end of depreciation.")),qh("life (number)",Go("The number of periods over which the asset is depreciated.")),qh("period (number)",Go("The single period within life for which to calculate depreciation.")),qh("factor (number, default=2)",Go("The factor by which depreciation decreases."))],compute:function(e,t,s,o,i={value:2}){const n=Yi(e,this.locale),r=Yi(t,this.locale),a=Yi(s,this.locale),l=Yi(o,this.locale),c=Yi(i,this.locale);if(n<0)return new Li(Sp(n));if(r<0)return new Li(Wp(r));if(l<=0)return new Li(kp(l));if(a<=0)return new Li(Fp(a));if(l>a)return new Li(Lp(l,a));if(c<=0)return new Li(Ip(c));if(0===n||r>=n)return{value:0,format:cf};const h=c/a;if(h>1)return{value:1===l?n-r:0,format:cf};if(l<=1)return{value:n*h,format:cf};const d=n*Math.pow(1-h,l-1),u=n*Math.pow(1-h,l),g=u<r?d-r:d-u;return{value:Math.max(g,0),format:cf}},isExported:!0},df={description:Go("Discount rate of a security based on price."),args:[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("price (number)",Go("The price at which the security is bought per 100 face value.")),qh("redemption (number)",Go("The redemption amount per 100 face value, or par.")),qh("day_count_convention (number, default=0 )",Go("An indicator of what day count method to use."),Jp)],compute:function(e,t,s,o,i={value:0}){i=i||0;const n=Math.trunc(Yi(e,this.locale)),r=Math.trunc(Yi(t,this.locale)),a=Yi(s,this.locale),l=Yi(o,this.locale),c=Math.trunc(Yi(i,this.locale));if(n>=r)return new Li(Op(n,r));if(Yp(c))return new Li(yp(c));if(a<=0)return new Li(Up(a));if(l<=0)return new Li(Gp(l));return(l-a)/l/wi(n,r,c)},isExported:!0},uf={description:Go("Convert a decimal fraction to decimal value."),args:[qh("fractional_price (number)",Go("The price quotation given using fractional decimal conventions.")),qh("unit (number)",Go("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],compute:function(e,t){const s=Yi(e,this.locale),o=Math.trunc(Yi(t,this.locale));if(o<=0)return new Li(qp(o));const i=Math.trunc(s);return i+(s-i)*(10**Math.ceil(Math.log10(o))/o)},isExported:!0},gf={description:Go("Convert a decimal value to decimal fraction."),args:[qh("decimal_price (number)",Go("The price quotation given as a decimal value.")),qh("unit (number)",Go("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],compute:function(e,t){const s=Yi(e,this.locale),o=Math.trunc(Yi(t,this.locale));if(o<=0)return new Li(qp(o));const i=Math.trunc(s);return i+(s-i)*(o/10**Math.ceil(Math.log10(o)))},isExported:!0},pf={description:Go("Number of periods for an investment to reach a value."),args:[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("rate (number)",Go("The annualized rate of interest.")),qh("yield (number)",Go("The expected annual yield of the security.")),qh("frequency (number)",Go("The number of interest or coupon payments per year (1, 2, or 4)."),Zm),qh("day_count_convention (number, default=0 )",Go("An indicator of what day count method to use."),Jp)],compute:function(e,t,s,o,i,n={value:0}){const r=Math.trunc(Yi(e,this.locale)),a=Math.trunc(Yi(t,this.locale)),l=Yi(s,this.locale),c=Yi(o,this.locale),h=Math.trunc(Yi(i,this.locale)),d=Math.trunc(Yi(n,this.locale));if(r>=a)return new Li(Op(r,a));if(Xp(h))return new Li(Cp(h));if(Yp(d))return new Li(yp(d));if(l<0)return new Li(zp(l));if(c<0)return new Li(Zp(c));const u=wi(r,a,d),g=u-Math.trunc(u)||1/h,p=Math.ceil(u*h),m=l/h,f=c/h;let v=0,b=0;for(let e=1;e<=p;e++){const t=(m+(e===p?1:0))/(1+f)**e;b+=(g+(e-1)/h)*t,v+=t}return 0===v?0:b/v},isExported:!0},mf={description:Go("Annual effective interest rate."),args:[qh("nominal_rate (number)",Go("The nominal interest rate per year.")),qh("periods_per_year (number)",Go("The number of compounding periods per year."))],compute:function(e,t){const s=Yi(e,this.locale),o=Math.trunc(Yi(t,this.locale));return s<=0?new Li(Go("The nominal_rate (%s) must be strictly positive.",s)):o<=0?new Li(Np(o)):Math.pow(1+s/o,o)-1},isExported:!0};function ff(e,t,s,o,i){return 0===e?-(o+s*t):-o*(1+e)**t-s*(1+e*i)*((1+e)**t-1)/e}const vf={description:Go("Future value of an annuity investment."),args:[qh("rate (number)",Go("The interest rate.")),qh("number_of_periods (number)",Go("The number of payments to be made.")),qh("payment_amount (number)",Go("The amount per period to be paid.")),qh("present_value (number, default=0)",Go("The current value of the annuity.")),qh("end_or_beginning (number, default=0)",Go("The timing of the payment payments are due for each period."),jm)],compute:function(e,t,s,o={value:0},i={value:0}){o=o||0,i=i||0;return{value:ff(Yi(e,this.locale),Yi(t,this.locale),Yi(s,this.locale),Yi(o,this.locale),nn(i)?1:0),format:"#,##0.00"}},isExported:!0},bf={description:Go("Future value of principal from series of rates."),args:[qh("principal (number)",Go("The amount of initial capital or value to compound against.")),qh("rate_schedule (number, range<number>)",Go("A series of interest rates to compound against the principal."))],compute:function(e,t){return un([t],((e,t)=>e*(1+Yi(t,this.locale))),Yi(e,this.locale))},isExported:!0},Sf={description:Go("Calculates effective interest rate."),args:[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("investment (number)",Go("The amount invested in the security.")),qh("redemption (number)",Go("The amount to be received at maturity.")),qh("day_count_convention (number, default=0 )",Go("An indicator of what day count method to use."),Jp)],compute:function(e,t,s,o,i={value:0}){const n=Math.trunc(Yi(e,this.locale)),r=Math.trunc(Yi(t,this.locale)),a=Yi(o,this.locale),l=Yi(s,this.locale),c=Math.trunc(Yi(i,this.locale));if(n>=r)return new Li(Op(n,r));if(l<=0)return new Li(Ap(l));if(a<=0)return new Li(Gp(a));if(Yp(c))return new Li(yp(c));return(a-l)/l/wi(n,r,c)},isExported:!0};function Cf(e,t,s,o,i,n){return Ff(e,s,o,i,n)-Pf(e,t,s,o,i,n)}const yf={description:Go("Payment on the principal of an investment."),args:[qh("rate (number)",Go("The annualized rate of interest.")),qh("period (number)",Go("The amortization period, in terms of number of periods.")),qh("number_of_periods (number)",Go("The number of payments to be made.")),qh("present_value (number)",Go("The current value of the annuity.")),qh("future_value (number, default=0)",Go("The future value remaining after the final payment has been made.")),qh("end_or_beginning (number, default=0)",Go("The timing of the payment payments are due for each period."),jm)],compute:function(e,t,s,o,i={value:0},n={value:0}){return{value:Cf(Yi(e,this.locale),Yi(t,this.locale),Yi(s,this.locale),Yi(o,this.locale),Yi(i,this.locale),nn(n)?1:0),format:"#,##0.00"}},isExported:!0},If={description:Go("Internal rate of return given periodic cashflows."),args:[qh("cashflow_amounts (number, range<number>)",Go("An array or range containing the income or payments associated with the investment.")),qh("rate_guess (number, default=0.1)",Go("An estimate for what the internal rate of return will be."))],compute:function(e,t={value:.1}){const s=Yi(t,this.locale);if(s<=-1)return new Li(Hp(s));let o=!1,i=!1;const n=[];if(hn([e],(({value:e})=>{e>0&&(o=!0),e<0&&(i=!0),n.push(e)}),this.locale),!o||!i)return new Li(bp);const r=n.shift();return{value:Xm((function(e){return function(e,t,s){const o=s.length;let i=0;return s.reduce(((t,s)=>(i++,t+s*e**(o-i))),t*e**o)}(e,r,n)}),(function(e){return function(e,t,s){const o=s.length;let i=0;return s.reduce(((t,s)=>(i++,t+s*(o-i)*e**(o-i-1))),t*o*e**(o-1))}(e,r,n)}),s+1,20,1e-5)-1,format:"0%"}},isExported:!0},wf={description:Go("Returns the interest paid at a particular period of an investment."),args:[qh("rate (number)",Go("The interest rate.")),qh("period (number)",Go("The period for which you want to view the interest payment.")),qh("number_of_periods (number)",Go("The number of payments to be made.")),qh("present_value (number)",Go("The current value of the annuity."))],compute:function(e,t,s,o){const i=Yi(e,this.locale),n=Yi(t,this.locale),r=Yi(s,this.locale),a=Yi(o,this.locale);if(0===r)return new Li(Go("The number_of_periods (%s) must be different from zero.",r));return-1*(a-a*(n/r))*i},isExported:!0},Ef={description:Go("Modified Macaulay duration."),args:[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("rate (number)",Go("The annualized rate of interest.")),qh("yield (number)",Go("The expected annual yield of the security.")),qh("frequency (number)",Go("The number of interest or coupon payments per year (1, 2, or 4)."),Zm),qh("day_count_convention (number, default=0 )",Go("An indicator of what day count method to use."))],compute:function(e,t,s,o,i,n={value:0}){const r=pf.compute.bind(this)(e,t,s,o,i,n),a=Yi(o,this.locale),l=Math.trunc(Yi(i,this.locale));return Yi(r,this.locale)/(1+a/l)},isExported:!0},Rf={description:Go("Modified internal rate of return."),args:[qh("cashflow_amounts (range<number>)",Go("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),qh("financing_rate (number)",Go("The interest rate paid on funds invested.")),qh("reinvestment_return_rate (number)",Go("The return (as a percentage) earned on reinvestment of income received from the investment."))],compute:function(e,t,s){const o=Yi(t,this.locale),i=Yi(s,this.locale),n=vn(e).flat().filter((e=>null!==e.value)).map((e=>Yi(e,this.locale))),r=n.length;let a=0,l=0;for(const e of Je(0,r)){const t=n[e];t>=0?a+=t*(i+1)**(r-e-1):l+=t/(o+1)**e}if(0===l||0===a)return new Li(bp);return(-a/l)**(1/(r-1))-1},isExported:!0},xf={description:Go("Annual nominal interest rate."),args:[qh("effective_rate (number)",Go("The effective interest rate per year.")),qh("periods_per_year (number)",Go("The number of compounding periods per year."))],compute:function(e,t){const s=Yi(e,this.locale),o=Math.trunc(Yi(t,this.locale));return s<=0?new Li(Go("The effective_rate (%s) must be strictly positive.",s)):o<=0?new Li(Np(o)):(Math.pow(s+1,1/o)-1)*o},isExported:!0},Tf={description:Go("Number of payment periods for an investment."),args:[qh("rate (number)",Go("The interest rate.")),qh("payment_amount (number)",Go("The amount of each payment made.")),qh("present_value (number)",Go("The current value of the annuity.")),qh("future_value (number, default=0)",Go("The future value remaining after the final payment has been made.")),qh("end_or_beginning (number, default=0)",Go("The timing of the payment payments are due for each period."),jm)],compute:function(e,t,s,o={value:0},i={value:0}){o=o||0,i=i||0;const n=Yi(e,this.locale),r=Yi(t,this.locale),a=Yi(s,this.locale),l=Yi(o,this.locale),c=nn(i)?1:0;if(0===n)return-(l+a)/r;const h=r*(1+n*c)/n;return Math.log((h-l)/(a+h))/Math.log(1+n)},isExported:!0};function Af(e,t,s,o){let i=0;return gn(s,((t,s)=>(i++,t+s/(1+e)**i)),t,o)}const Df={description:Go("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:[qh("discount (number)",Go("The discount rate of the investment over one period.")),qh("cashflow1 (number, range<number>)",Go("The first future cash flow.")),qh("cashflow2 (number, range<number>, repeating)",Go("Additional future cash flows."))],compute:function(e,...t){const s=Yi(e,this.locale);return-1===s?new Li((e=>Go("The discount (%s) must be different from -1.",e))(s)):{value:Af(s,0,t,this.locale),format:"#,##0.00"}},isExported:!0},_f={description:Go("Computes the number of periods needed for an investment to reach a value."),args:[qh("rate (number)",Go("The rate at which the investment grows each period.")),qh("present_value (number)",Go("The investment's current value.")),qh("future_value (number)",Go("The investment's desired future value."))],compute:function(e,t,s){const o=Yi(e,this.locale),i=Yi(t,this.locale),n=Yi(s,this.locale);return o<=0?new Li(Bp(o)):i<=0?new Li(Vp(i)):n<=0?new Li(Go("The future_value (%s) must be strictly positive.",n)):(Math.log(n)-Math.log(i))/Math.log(1+o)},isExported:!0};function Ff(e,t,s,o,i){if(t<=0)throw new Li(Pp(t));if(0===e)return-(o+s)/t;let n=-(s*(1+e)**t+o);return n=n*e/((1+e*i)*((1+e)**t-1)),n}const Of={description:Go("Periodic payment for an annuity investment."),args:[qh("rate (number)",Go("The annualized rate of interest.")),qh("number_of_periods (number)",Go("The number of payments to be made.")),qh("present_value (number)",Go("The current value of the annuity.")),qh("future_value (number, default=0)",Go("The future value remaining after the final payment has been made.")),qh("end_or_beginning (number, default=0)",Go("The timing of the payment payments are due for each period."),jm)],compute:function(e,t,s,o={value:0},i={value:0}){const n=Yi(t,this.locale),r=Yi(e,this.locale),a=nn(i)?1:0,l=Yi(o,this.locale);return{value:Ff(r,n,Yi(s,this.locale),l,a),format:"#,##0.00"}},isExported:!0};function Pf(e,t,s,o,i,n){if(s<=0)throw new Li(Pp(s));if(t<=0||t>s)throw new Li(Mp(s));const r=Ff(e,s,o,i,n);if(1===n&&1===t)return r;return r+-ff(e,0===n?t-1:t-2,r,o+r*n,0)*e}const Mf={description:Go("Payment on the principal of an investment."),args:[qh("rate (number)",Go("The annualized rate of interest.")),qh("period (number)",Go("The amortization period, in terms of number of periods.")),qh("number_of_periods (number)",Go("The number of payments to be made.")),qh("present_value (number)",Go("The current value of the annuity.")),qh("future_value (number, default=0)",Go("The future value remaining after the final payment has been made.")),qh("end_or_beginning (number, default=0)",Go("The timing of the payment payments are due for each period."),jm)],compute:function(e,t,s,o,i={value:0},n={value:0}){const r=Yi(s,this.locale),a=Yi(e,this.locale),l=Yi(t,this.locale),c=nn(n)?1:0,h=Yi(i,this.locale);return{value:Pf(a,l,r,Yi(o,this.locale),h,c),format:"#,##0.00"}},isExported:!0},Nf={description:Go("Present value of an annuity investment."),args:[qh("rate (number)",Go("The interest rate.")),qh("number_of_periods (number)",Go("The number of payments to be made.")),qh("payment_amount (number)",Go("The amount per period to be paid.")),qh("future_value (number, default=0)",Go("The future value remaining after the final payment has been made.")),qh("end_or_beginning (number, default=0)",Go("The timing of the payment payments are due for each period."),jm)],compute:function(e,t,s,o={value:0},i={value:0}){o=o||0,i=i||0;const n=Yi(e,this.locale),r=Yi(t,this.locale),a=Yi(s,this.locale),l=Yi(o,this.locale),c=nn(i)?1:0;return{value:n?-(a*(1+n*c)*((1+n)**r-1)/n+l)/(1+n)**r:-(l+a*r),format:"#,##0.00"}},isExported:!0},Lf={description:Go("Price of a security paying periodic interest."),args:[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("rate (number)",Go("The annualized rate of interest.")),qh("yield (number)",Go("The expected annual yield of the security.")),qh("redemption (number)",Go("The redemption amount per 100 face value, or par.")),qh("frequency (number)",Go("The number of interest or coupon payments per year (1, 2, or 4)."),Zm),qh("day_count_convention (number, default=0 )",Go("An indicator of what day count method to use."),Jp)],compute:function(e,t,s,o,i,n,r={value:0}){r=r||0;const a=Math.trunc(Yi(e,this.locale)),l=Math.trunc(Yi(t,this.locale)),c=Yi(s,this.locale),h=Yi(o,this.locale),d=Yi(i,this.locale),u=Math.trunc(Yi(n,this.locale)),g=Math.trunc(Yi(r,this.locale));if(a>=l)return new Li(Op(a,l));if(Xp(u))return new Li(Cp(u));if(Yp(g))return new Li(yp(g));if(c<0)return new Li(zp(c));if(h<0)return new Li(Zp(h));if(d<=0)return new Li(Gp(d));const p=wi(a,l,g)*u,m=Math.ceil(p),f=p-Math.floor(p)||1,v=1+h/u,b=100*c/u;if(1===m)return(b+d)/(f*h/u+1)-b*(1-f);let S=0;for(let e=1;e<=m;e++)S+=b/v**(e-1+f);return d/v**(m-1+f)+S-b*(1-f)},isExported:!0},kf={description:Go("Price of a discount security."),args:[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("discount (number)",Go("The discount rate of the security at time of purchase.")),qh("redemption (number)",Go("The redemption amount per 100 face value, or par.")),qh("day_count_convention (number, default=0 )",Go("An indicator of what day count method to use."),Jp)],compute:function(e,t,s,o,i={value:0}){i=i||0;const n=Math.trunc(Yi(e,this.locale)),r=Math.trunc(Yi(t,this.locale)),a=Yi(s,this.locale),l=Yi(o,this.locale),c=Math.trunc(Yi(i,this.locale));if(n>=r)return new Li(Op(n,r));if(Yp(c))return new Li(yp(c));if(a<=0)return new Li(wp(a));if(l<=0)return new Li(Gp(l));return l-a*l*wi(n,r,c)},isExported:!0},Vf={description:Go("Calculates the price of a security paying interest at maturity, based on expected yield."),args:[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("issue (date)",Go("The date the security was initially issued.")),qh("rate (number)",Go("The annualized rate of interest.")),qh("yield (number)",Go("The expected annual yield of the security.")),qh("day_count_convention (number, default=0 )",Go("An indicator of what day count method to use."),Jp)],compute:function(e,t,s,o,i,n={value:0}){n=n||0;const r=Math.trunc(Yi(e,this.locale)),a=Math.trunc(Yi(t,this.locale)),l=Math.trunc(Yi(s,this.locale)),c=Yi(o,this.locale),h=Yi(i,this.locale),d=Math.trunc(Yi(n,this.locale));if(r<=l)return new Li(((e,t)=>Go("The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).",{settlement:e,issue:t}))(r,l));if(r>=a)return new Li(Op(r,a));if(Yp(d))return new Li(yp(d));if(c<0)return new Li(zp(c));if(h<0)return new Li(Zp(h));const u=wi(r,a,d),g=wi(r,l,d);return(100+wi(l,a,d)*c*100)/(1+u*h)-g*c*100},isExported:!0},Uf=.1,Hf={description:Go("Interest rate of an annuity investment."),args:[qh("number_of_periods (number)",Go("The number of payments to be made.")),qh("payment_per_period (number)",Go("The amount per period to be paid.")),qh("present_value (number)",Go("The current value of the annuity.")),qh("future_value (number, default=0)",Go("The future value remaining after the final payment has been made.")),qh("end_or_beginning (number, default=0)",Go("The timing of the payment payments are due for each period."),jm),qh("rate_guess (number, default=0.1)",Go("An estimate for what the interest rate will be."))],compute:function(e,t,s,o={value:0},i={value:0},n={value:Uf}){const r=Yi(e,this.locale),a=Yi(t,this.locale),l=nn(i)?1:0,c=Yi(n,this.locale)||Uf;let h=Yi(o,this.locale),d=Yi(s,this.locale);if(r<=0)return new Li(Pp(r));if(!jp([a,d,h]))return new Li(Go("There must be both positive and negative values in [payment_amount, present_value, future_value]."));if(c<=-1)return new Li(Hp(c));h-=a*l,d+=a*l;return{value:Xm((e=>{const t=Math.pow(1+e,r);return h+d*t+a*((t-1)/e)}),(e=>{const t=Math.pow(1+e,r-1),s=Math.pow(1+e,r);return d*r*t+a*(r*t/e-(s-1)/e/e)}),c,40,1e-5),format:"0%"}},isExported:!0},zf={description:Go("Amount received at maturity for a security."),args:[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("investment (number)",Go("The amount invested (irrespective of face value of each security).")),qh("discount (number)",Go("The discount rate of the security invested in.")),qh("day_count_convention (number, default=0 )",Go("An indicator of what day count method to use."),Jp)],compute:function(e,t,s,o,i={value:0}){i=i||0;const n=Math.trunc(Yi(e,this.locale)),r=Math.trunc(Yi(t,this.locale)),a=Yi(s,this.locale),l=Yi(o,this.locale),c=Math.trunc(Yi(i,this.locale));if(n>=r)return new Li(Op(n,r));if(Yp(c))return new Li(yp(c));if(a<=0)return new Li(Ap(a));if(l<=0)return new Li(wp(l));return a/(1-l*wi(n,r,c))},isExported:!0},Bf={description:Go("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[qh("number_of_periods (number)",Go("The number of periods.")),qh("present_value (number)",Go("The present value of the investment.")),qh("future_value (number)",Go("The future value of the investment."))],compute:function(e,t,s){const o=Yi(e,this.locale),i=Yi(t,this.locale),n=Yi(s,this.locale);return o<=0?new Li(Pp(o)):(n/i)**(1/o)-1},isExported:!0},Gf={description:Go("Depreciation of an asset using the straight-line method."),args:[qh("cost (number)",Go("The initial cost of the asset.")),qh("salvage (number)",Go("The value of the asset at the end of depreciation.")),qh("life (number)",Go("The number of periods over which the asset is depreciated."))],compute:function(e,t,s){return{value:(Yi(e,this.locale)-Yi(t,this.locale))/Yi(s,this.locale),format:"#,##0.00"}},isExported:!0},Wf={description:Go("Depreciation via sum of years digit method."),args:[qh("cost (number)",Go("The initial cost of the asset.")),qh("salvage (number)",Go("The value of the asset at the end of depreciation.")),qh("life (number)",Go("The number of periods over which the asset is depreciated.")),qh("period (number)",Go("The single period within life for which to calculate depreciation."))],compute:function(e,t,s,o){const i=Yi(e,this.locale),n=Yi(t,this.locale),r=Yi(s,this.locale),a=Yi(o,this.locale);if(a<=0)return new Li(kp(a));if(r<=0)return new Li(Fp(r));if(a>r)return new Li(Lp(a,r));return{value:(r-a+1)/(r*(r+1)/2)*(i-n),format:"#,##0.00"}},isExported:!0};function $f(e,t,s){return 100*(1-s*wi(e,t,2))}const qf={description:Go("Price of a US Treasury bill."),args:[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("discount (number)",Go("The discount rate of the bill at time of purchase."))],compute:function(e,t,s){const o=Math.trunc(Yi(e,this.locale)),i=Math.trunc(Yi(t,this.locale)),n=Yi(s,this.locale);return o>=i?new Li(Op(o,i)):Kp(o,i,this.locale)?n<=0?new Li(wp(n)):n>=1?new Li(Ep(n)):$f(o,i,n):new Li($p(o,i))},isExported:!0},Zf={description:Go("Equivalent rate of return for a US Treasury bill."),args:[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("discount (number)",Go("The discount rate of the bill at time of purchase."))],compute:function(e,t,s){const o=Math.trunc(Yi(e,this.locale)),i=Math.trunc(Yi(t,this.locale)),n=Yi(s,this.locale);if(o>=i)return new Li(Op(o,i));if(!Kp(o,i,this.locale))return new Li($p(o,i));if(n<=0)return new Li(wp(n));if(n>=1)return new Li(Ep(n));const r=im.compute.bind(this)({value:i},{value:o});if(r<=182)return 365*n/(360-n*r);const a=$f(o,i,n)/100,l=r/(366===r?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},jf={description:Go("The yield of a US Treasury bill based on price."),args:[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("price (number)",Go("The price at which the security is bought per 100 face value."))],compute:function(e,t,s){const o=Math.trunc(Yi(e,this.locale)),i=Math.trunc(Yi(t,this.locale)),n=Yi(s,this.locale);if(o>=i)return new Li(Op(o,i));if(!Kp(o,i,this.locale))return new Li($p(o,i));if(n<=0)return new Li(Up(n));return(100-n)/n*(1/wi(o,i,2))},isExported:!0},Yf={description:Go("Variable declining balance. WARNING : does not handle decimal periods."),args:[qh("cost (number)",Go("The initial cost of the asset.")),qh("salvage (number)",Go("The value of the asset at the end of depreciation.")),qh("life (number)",Go("The number of periods over which the asset is depreciated.")),qh("start (number)",Go("Starting period to calculate depreciation.")),qh("end (number)",Go("Ending period to calculate depreciation.")),qh("factor (number, default=2)",Go("The number of months in the first year of depreciation.")),qh("no_switch (number, default=false)",Go("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation."),[{value:!1,label:Go("Switch to straight-line depreciation")},{value:!0,label:Go("Do not switch to straight-line depreciation")}])],compute:function(e,t,s,o,i,n={value:2},r={value:false}){n=n||0;const a=Yi(e,this.locale),l=Yi(t,this.locale),c=Yi(s,this.locale),h=Math.trunc(Yi(o,this.locale)),d=Math.trunc(Yi(i,this.locale)),u=Yi(n,this.locale),g=nn(r);if(a<0)return new Li(Sp(a));if(l<0)return new Li(Wp(l));if(c<=0)return new Li(Fp(c));if(h<0)return new Li((e=>Go("The start_period (%s) must be positive or null.",e))(h));if(d<0)return new Li((e=>Go("The end_period (%s) must be positive or null.",e))(d));if(h>d)return new Li(Go("The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).",{start:h,end:d}));if(d>c)return new Li(((e,t)=>Go("The end_period (%(end)s) must be smaller or equal to the life (%(life)s).",{end:e,life:t}))(d,c));if(u<=0)return new Li(Ip(u));if(0===a)return 0;if(l>=a)return h<1?a-l:0;const p=u/c;if(p>=1)return h<1?a-l:0;let m=a,f=0,v=0,b=!1;for(let e=0;e<d;e++){if(!b||g){const t=m*p,s=(m-l)/(c-e);!g&&s>t?(b=!0,f=s):f=t}const t=Math.max(m-f,l);e>=h&&(v+=m-t),m=t}return v},isExported:!0},Xf={description:Go("Internal rate of return given non-periodic cash flows."),args:[qh("cashflow_amounts (range<number>)",Go("An range containing the income or payments associated with the investment.")),qh("cashflow_dates (range<number>)",Go("An range with dates corresponding to the cash flows in cashflow_amounts.")),qh("rate_guess (number, default=0.1)",Go("An estimate for what the internal rate of return will be."))],compute:function(e,t,s={value:Uf}){const o=Yi(s,this.locale);if(!Hl(e,t))return new Li(vp);const i=e.flat().map((e=>Yi(e,this.locale))),n=t.flat().map((e=>Yi(e,this.locale)));if(!jp(i))return new Li(bp);if(n.some((e=>e<n[0])))return new Li(Rp(n[0]));if(o<=-1)return new Li(Hp(o));const r=new Map;for(const e of Je(0,n.length)){const t=n[e];r.has(t)?r.set(t,r.get(t)+i[e]):r.set(t,i[e])}const a=Array.from(r.keys()),l=a.map((e=>r.get(e)));return Xm((e=>{let t=l[0];for(const s of Je(1,l.length)){const o=(a[0]-a[s])/365;t+=l[s]*(1+e)**o}return t}),(e=>{let t=0;for(const s of Je(1,l.length)){const o=(a[0]-a[s])/365;t+=o*l[s]*(1+e)**(o-1)}return t}),o,40,1e-5,(e=>e?e/10-.9:-.9))},isExported:!0},Kf={description:Go("Net present value given to non-periodic cash flows.."),args:[qh("discount (number)",Go("The discount rate of the investment over one period.")),qh("cashflow_amounts (number, range<number>)",Go("An range containing the income or payments associated with the investment.")),qh("cashflow_dates (number, range<number>)",Go("An range with dates corresponding to the cash flows in cashflow_amounts."))],compute:function(e,t,s){const o=Yi(e,this.locale);if(!Hl(t,s))return new Li(vp);const i=An(t).flat().map((e=>Ji(e,this.locale))),n=An(s).flat().map((e=>Ji(e,this.locale)));if(n.some((e=>e<n[0])))return new Li(Rp(n[0]));if(o<=0)return new Li(Bp(o));if(1===i.length)return i[0];const r=new Map;for(const e of Je(0,n.length)){const t=n[e];r.has(t)?r.set(t,r.get(t)+i[e]):r.set(t,i[e])}const a=Array.from(r.keys()),l=a.map((e=>r.get(e)));let c=l[0];for(const e of Je(1,l.length)){const t=(a[0]-a[e])/365;c+=l[e]*(1+o)**t}return c},isExported:!0},Jf={description:Go("Annual yield of a security paying periodic interest."),args:[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("rate (number)",Go("The annualized rate of interest.")),qh("price (number)",Go("The price at which the security is bought per 100 face value.")),qh("redemption (number)",Go("The redemption amount per 100 face value, or par.")),qh("frequency (number)",Go("The number of interest or coupon payments per year (1, 2, or 4)."),Zm),qh("day_count_convention (number, default=0 )",Go("An indicator of what day count method to use."),Jp)],compute:function(e,t,s,o,i,n,r={value:0}){r=r||0;const a=Math.trunc(Yi(e,this.locale)),l=Math.trunc(Yi(t,this.locale)),c=Yi(s,this.locale),h=Yi(o,this.locale),d=Yi(i,this.locale),u=Math.trunc(Yi(n,this.locale)),g=Math.trunc(Yi(r,this.locale));if(a>=l)return new Li(Op(a,l));if(Xp(u))return new Li(Cp(u));if(Yp(g))return new Li(yp(g));if(c<0)return new Li(zp(c));if(h<=0)return new Li(Up(h));if(d<=0)return new Li(Gp(d));const p=wi(a,l,g)*u,m=Math.ceil(p),f=p-Math.floor(p)||1,v=100*c/u;if(1===m){const e=h+v*(1-f);return(d+v-e)*u*(1/f)/e}const b=Xm((function(e){return function(e,t,s,o,i,n){let r=n-(e+i*(1-t))*o**(s-1+t);for(let e=1;e<=s;e++)r+=i*o**(e-1);return r}(h,f,m,e,v,d)}),(function(e){return function(e,t,s,o,i){let n=-(e+i*(1-t))*(s-1+t)*o**(s-2+t);for(let e=1;e<=s;e++)n+=i*(e-1)*o**(e-2);return n}(h,f,m,e,v)}),1+(c+1)/u,100,1e-5);return(b-1)*u},isExported:!0},Qf={description:Go("Annual yield of a discount security."),args:[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("price (number)",Go("The price at which the security is bought per 100 face value.")),qh("redemption (number)",Go("The redemption amount per 100 face value, or par.")),qh("day_count_convention (number, default=0 )",Go("An indicator of what day count method to use."),Jp)],compute:function(e,t,s,o,i={value:0}){i=i||0;const n=Math.trunc(Yi(e,this.locale)),r=Math.trunc(Yi(t,this.locale)),a=Yi(s,this.locale),l=Yi(o,this.locale),c=Math.trunc(Yi(i,this.locale));if(n>=r)return new Li(Op(n,r));if(Yp(c))return new Li(yp(c));if(a<=0)return new Li(Up(a));if(l<=0)return new Li(Gp(l));return(l/a-1)/wi(n,r,c)},isExported:!0},ev={description:Go("Annual yield of a security paying interest at maturity."),args:[qh("settlement (date)",Go("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),qh("maturity (date)",Go("The maturity or end date of the security, when it can be redeemed at face, or par value.")),qh("issue (date)",Go("The date the security was initially issued.")),qh("rate (number)",Go("The annualized rate of interest.")),qh("price (number)",Go("The price at which the security is bought.")),qh("day_count_convention (number, default=0 )",Go("An indicator of what day count method to use."),Jp)],compute:function(e,t,s,o,i,n={value:0}){n=n||0;const r=Math.trunc(Yi(e,this.locale)),a=Math.trunc(Yi(t,this.locale)),l=Math.trunc(Yi(s,this.locale)),c=Yi(o,this.locale),h=Yi(i,this.locale),d=Math.trunc(Yi(n,this.locale));if(r>=a)return new Li(Op(r,a));if(Yp(d))return new Li(yp(d));if(r<l)return new Li(((e,t)=>Go("The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).",{settlement:e,issue:t}))(r,l));if(c<0)return new Li(zp(c));if(h<=0)return new Li(Up(h));return(100*(1+c*wi(l,a,d))/(h+100*c*wi(l,r,d))-1)/wi(r,a,d)},isExported:!0};var tv,sv=Object.freeze({__proto__:null,ACCRINTM:Km,AMORLINC:Jm,COUPDAYBS:ef,COUPDAYS:Qm,COUPDAYSNC:tf,COUPNCD:sf,COUPNUM:of,COUPPCD:nf,CUMIPMT:rf,CUMPRINC:af,DB:lf,DDB:hf,DISC:df,DOLLARDE:uf,DOLLARFR:gf,DURATION:pf,EFFECT:mf,FV:vf,FVSCHEDULE:bf,INTRATE:Sf,IPMT:yf,IRR:If,ISPMT:wf,MDURATION:Ef,MIRR:Rf,NOMINAL:xf,NPER:Tf,NPV:Df,PDURATION:_f,PMT:Of,PPMT:Mf,PRICE:Lf,PRICEDISC:kf,PRICEMAT:Vf,PV:Nf,RATE:Hf,RECEIVED:zf,RRI:Bf,SLN:Gf,SYD:Wf,TBILLEQ:Zf,TBILLPRICE:qf,TBILLYIELD:jf,VDB:Yf,XIRR:Xf,XNPV:Kf,YIELD:Jf,YIELDDISC:Qf,YIELDMAT:ev});!function(e){e[e.LeftRef=0]="LeftRef",e[e.RightRef=1]="RightRef",e[e.Separator=2]="Separator",e[e.FullColumnSeparator=3]="FullColumnSeparator",e[e.FullRowSeparator=4]="FullRowSeparator",e[e.RightColumnRef=5]="RightColumnRef",e[e.RightRowRef=6]="RightRowRef",e[e.Found=7]="Found"}(tv||(tv={}));const ov=(e,t=(()=>!0))=>[{goTo:e,guard:t}],iv=(e,t=(()=>!0))=>({goTo:e,guard:t}),nv={[tv.LeftRef]:{REFERENCE:ov(tv.Separator),NUMBER:ov(tv.FullRowSeparator),SYMBOL:[iv(tv.FullColumnSeparator,(e=>{return t=e.value,Jr.test(t);var t})),iv(tv.FullRowSeparator,(e=>ta(e.value)))]},[tv.FullColumnSeparator]:{SPACE:ov(tv.FullColumnSeparator),OPERATOR:ov(tv.RightColumnRef,(e=>":"===e.value))},[tv.FullRowSeparator]:{SPACE:ov(tv.FullRowSeparator),OPERATOR:ov(tv.RightRowRef,(e=>":"===e.value))},[tv.Separator]:{SPACE:ov(tv.Separator),OPERATOR:ov(tv.RightRef,(e=>":"===e.value))},[tv.RightRef]:{SPACE:ov(tv.RightRef),NUMBER:ov(tv.Found),REFERENCE:ov(tv.Found,(e=>ia(e.value))),SYMBOL:ov(tv.Found,(e=>sa(e.value)||oa(e.value)))},[tv.RightColumnRef]:{SPACE:ov(tv.RightColumnRef),SYMBOL:ov(tv.Found,(e=>sa(e.value))),REFERENCE:ov(tv.Found,(e=>ia(e.value)))},[tv.RightRowRef]:{SPACE:ov(tv.RightRowRef),NUMBER:ov(tv.Found),REFERENCE:ov(tv.Found,(e=>ia(e.value))),SYMBOL:ov(tv.Found,(e=>oa(e.value)))},[tv.Found]:{}};function rv(e){let t=0,s=nv[tv.LeftRef],o="";for(;void 0!==s;){const i=e[t++];if(!i)return null;const n=s[i.type]?.find((e=>e.guard(i))),r=n?n.goTo:void 0;switch(r){case void 0:return null;case tv.Found:return o+=i.value,e.splice(0,t),{type:"REFERENCE",value:o};default:s=nv[r],o+=i.value}}return null}function av(e,t=w){const s=sl(e,t),o=[];for(;s.length;)o.push(rv(s)||s.shift());return o}const lv=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,cv=["-","+"],hv=["%"];class dv{tokens;currentIndex=0;current;length;constructor(e){this.tokens=e,this.current=e[0],this.length=e.length}shift(){const e=this.tokens[this.currentIndex];return this.current=this.tokens[++this.currentIndex],e}get next(){return this.tokens[this.currentIndex+1]}}const uv={"%":40,"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function gv(e){const t=e.shift();if(!t)throw new ki;switch(t.type){case"DEBUGGER":const s=fv(e,1e3);return s.debug=!0,s;case"NUMBER":return{type:"NUMBER",value:Oi(t.value,w),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"STRING":return{type:"STRING",value:je(t.value),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"INVALID_REFERENCE":return{type:"REFERENCE",value:Mi.InvalidReference,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"REFERENCE":if(":"===e.current?.value&&"REFERENCE"===e.next?.type){e.shift();const s=e.shift();return{type:"REFERENCE",value:`${t.value}:${s?.value}`,tokenStartIndex:t.tokenIndex,tokenEndIndex:s.tokenIndex}}return{type:"REFERENCE",value:t.value,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"SYMBOL":const o=t.value,i=e.current;if("LEFT_PAREN"===i?.type&&lv.test(t.value)&&o===je(o,"'")){const{args:s,rightParen:i}=function(e){mv(e,"LEFT_PAREN",Go("Missing opening parenthesis"));const t=e.current;if("RIGHT_PAREN"===t?.type){return{args:[],rightParen:mv(e,"RIGHT_PAREN")}}const s=[];s.push(pv(e));for(;"RIGHT_PAREN"!==e.current?.type;)mv(e,"ARG_SEPARATOR",Go("Wrong function call")),s.push(pv(e));const o=mv(e,"RIGHT_PAREN");return{args:s,rightParen:o}}(e);return{type:"FUNCALL",value:o,args:s,tokenStartIndex:t.tokenIndex,tokenEndIndex:i.tokenIndex}}const n=o.toUpperCase();return"TRUE"===n||"FALSE"===n?{type:"BOOLEAN",value:"TRUE"===n,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:{type:"SYMBOL",value:je(t.value,"'"),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case"LEFT_PAREN":const r=fv(e),a=mv(e,"RIGHT_PAREN",Go("Missing closing parenthesis"));return{...r,tokenStartIndex:t.tokenIndex,tokenEndIndex:a.tokenIndex};case"OPERATOR":const l=t.value;if(cv.includes(l)){const s=fv(e,uv[l]);return{type:"UNARY_OPERATION",value:l,operand:s,tokenStartIndex:t.tokenIndex,tokenEndIndex:s.tokenEndIndex}}throw new ki(Go("Unexpected token: %s",t.value));default:throw new ki(Go("Unexpected token: %s",t.value))}}function pv(e){const t=e.current;return"ARG_SEPARATOR"===t?.type||"RIGHT_PAREN"===t?.type?{type:"EMPTY",value:"",tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:fv(e)}function mv(e,t,s){const o=e.shift();if(!o||o.type!==t)throw new ki(s);return o}function fv(e,t=0){if(0===e.length)throw new ki;let s=gv(e);for(;"OPERATOR"===e.current?.type&&uv[e.current.value]>t;){const t=e.shift(),o=t.value;if(hv.includes(o))s={type:"UNARY_OPERATION",value:o,operand:s,postfix:!0,tokenStartIndex:s.tokenStartIndex,tokenEndIndex:t.tokenIndex};else{const t=fv(e,uv[o]);s={type:"BIN_OPERATION",value:o,left:s,right:t,tokenStartIndex:s.tokenStartIndex,tokenEndIndex:t.tokenEndIndex}}}return s}function vv(e){return bv(av(e))}function bv(e){const t=e.map(((e,t)=>({type:e.type,value:e.value,tokenIndex:t}))).filter((e=>"SPACE"!==e.type)),s=new dv(t);"="===s.current?.value&&s.shift();const o=fv(s);if(s.current)throw new ki;return o}function Sv(e,t,s){return Iv(e,(e=>e.type===t?s(e):e))}function Cv(e){return Array.from(yv(e))}function*yv(e){switch(yield e,e.type){case"FUNCALL":for(const t of e.args)yield*yv(t);break;case"UNARY_OPERATION":yield*yv(e.operand);break;case"BIN_OPERATION":yield*yv(e.left),yield*yv(e.right)}}function Iv(e,t){switch((e=t(e)).type){case"FUNCALL":return{...e,args:e.args.map((e=>Iv(e,t)))};case"UNARY_OPERATION":return{...e,operand:Iv(e.operand,t)};case"BIN_OPERATION":return{...e,right:Iv(e.right,t),left:Iv(e.left,t)};default:return e}}function wv(e,t){return function(e){for(const t of e)if(t.functionContext){const{argsTokens:e,args:s}=t.functionContext;if(delete t.functionContext.argsTokens,s.length||!e)continue;"LEFT_PAREN"===e[0]?.[0]?.type&&(e[0]=e[0].slice(1));for(const t of e){let e=t;"ARG_SEPARATOR"===e.at(0)?.type&&(e=e.slice(1));try{s.push(bv(e))}catch(e){s.push(void 0)}}}return e}(function(e){const t=[];let s="";function o(e){if(0===t.length)return;const s=t.at(-1);if(s&&s.argsTokens){const{argsTokens:t,argPosition:o}=s;t[o]||(t[o]=[]),t[o].push({value:e.value,type:e.type})}}return e.map(((e,i)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(s=""),e.type){case"SYMBOL":o(e),s=e.value;break;case"LEFT_PAREN":t.push({parent:s,argPosition:0,argsTokens:[],args:[]}),o(e),s="";break;case"RIGHT_PAREN":const i=t.pop();i?.argsTokens?.flat().forEach(o),o(e);break;case"ARG_SEPARATOR":t.length&&t[t.length-1].argPosition++,o(e);break;default:o(e)}if(t.length){const s=t[t.length-1];s.parent&&(e.functionContext=Object.assign({},s))}return e}))}(function(e){const t=[];let s=0;return e.map(((o,i)=>{if("LEFT_PAREN"===o.type){t.push(s+1),s=0;for(let s=i-1;s>=0;s--){if("SPACE"!==e[s].type){"SYMBOL"===e[s].type&&(e[s].parenthesesCode=t.join(":"));break}e[s].parenthesesCode=t.join(":")}}return o.parenthesesCode=t.join(":"),"RIGHT_PAREN"===o.type&&t.length&&(s=t.pop()),o}))}(function(e){let t=0;return e.map((e=>{const s=e.value.toString().length,o=Object.assign({},e,{start:t,end:t+s,length:s});return t=o.end,o}))}(av(e,t)))))}function Ev(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:s}=na(e.value),[o,i]=t.split(":"),n=Rv(o),r=i?`:${Rv(i)}`:"";return{...e,value:ra(s,n+r)}}function Rv(e){switch(function(e){if(function(e){return e.startsWith("$")&&e.length>1&&e.slice(1).includes("$")}(e))return"colrow";if(function(e){return e.startsWith("$")}(e))return"col";if(function(e){return e.includes("$",1)}(e))return"row";return"none"}(e)){case"none":e=xv(e,"colrow");break;case"colrow":e=xv(e,"row");break;case"row":e=xv(e,"col");break;case"col":e=xv(e,"none")}return e}function xv(e,t){let s;({sheetName:s,xc:e}=na(e)),s=s?s+"!":"";const o=(e=e.replace(/\$/g,"")).indexOf(":");return o>=0?`${s}${Tv(e.slice(0,o),t)}:${Tv(e.slice(o+1),t)}`:s+Tv(e,t)}function Tv(e,t){const s=e.search(/[0-9]/),o=0!==s,i=s>=0;switch(t){case"col":return o?"$"+e:e;case"row":return i?e.slice(0,s)+"$"+e.slice(s):e;case"colrow":return i&&o?"$"+e.slice(0,s)+"$"+e.slice(s):"$"+e;case"none":return e}}function Av(e,t,s){const o=(t.startsWith("=")?wv(t,s):[]).filter((t=>t.start<=e.start&&t.end>=e.start||t.start>=e.start&&t.start<e.end)),i=o.filter((e=>"REFERENCE"===e.type));if(0===i.length)return;const n=o.map(Ev).map((e=>e.value)).join(""),r=o[0].start,a=o[o.length-1].end,l=t.slice(0,r)+n+t.slice(a),c=l.length-t.length,h={start:i[0].start,end:i[i.length-1].end+c};return 1===i.length&&e.start===e.end&&(h.start=h.end),{content:l,selection:h}}const Dv=[{value:"address",label:Go("Returns an absolute reference as plain text of the top left cell in reference.")},{value:"col",label:Go("Returns the column number of the cell in reference.")},{value:"contents",label:Go("Returns the value contained in the top left cell in reference.")},{value:"format",label:Go("Returns the format of the top left cell in reference.")},{value:"row",label:Go("Returns the row number of the top left cell in reference.")},{value:"type",label:Go('Returns the type of data in the cell in reference. The following values are returned: "b" for a blank cell, "l" (for label) if the cell contains plain text, and "v" (for value) if the cell contains any other type of data.')}],_v={description:Go("Gets information about a cell."),args:[qh("info_type (string)",Go("The type of information requested."),Dv),qh("reference (meta, range<meta>)",Go("The reference to the cell."))],compute:function(e,t){const s=tn(e).toLowerCase();if(!Dv.map((e=>e.value)).includes(s))return new Li(Go("The info_type should be one of %s.",Dv.join(", ")));const o=this.__originSheetId,i=t[0][0].value;let{sheetName:n,xc:a}=na(i);n=n===this.getters.getSheetName(o)?void 0:n;const l=ra(n,xv(a,"colrow")),c=this.getters.getRangeFromSheetXC(o,l);switch(s){case"address":return this.getters.getRangeString(c,o);case"col":return c.zone.left+1;case"contents":{const e={sheetId:c.sheetId,col:c.zone.left,row:c.zone.top};return this.getters.getEvaluatedCell(e).value}case"format":{const e={sheetId:c.sheetId,col:c.zone.left,row:c.zone.top};return this.getters.getEvaluatedCell(e).format||""}case"row":return c.zone.top+1;case"type":{const e={sheetId:c.sheetId,col:c.zone.left,row:c.zone.top},t=this.getters.getEvaluatedCell(e).type;return t===r.empty?"b":t===r.text?"l":"v"}}return""},isExported:!0},Fv={description:Go("Whether a value is an error other than #N/A."),args:[qh("value (any)",Go("The value to be verified as an error type."))],compute:function(e){const t=e?.value;return qi(t)&&t!==Mi.NotAvailable},isExported:!0},Ov={description:Go("Whether a value is an error."),args:[qh("value (any)",Go("The value to be verified as an error type."))],compute:function(e){const t=e?.value;return qi(t)},isExported:!0},Pv={description:Go("Whether a value is `true` or `false`."),args:[qh("value (any)",Go("The value to be verified as a logical TRUE or FALSE."))],compute:function(e){return"boolean"==typeof e?.value},isExported:!0},Mv={description:Go("Whether a value is the error #N/A."),args:[qh("value (any)",Go("The value to be verified as an error type."))],compute:function(e){return e?.value===Mi.NotAvailable},isExported:!0},Nv={description:Go("Whether a value is non-textual."),args:[qh("value (any)",Go("The value to be checked."))],compute:function(e){return!kv.compute.bind(this)(e)},isExported:!0},Lv={description:Go("Whether a value is a number."),args:[qh("value (any)",Go("The value to be verified as a number."))],compute:function(e){return"number"==typeof e?.value},isExported:!0},kv={description:Go("Whether a value is text."),args:[qh("value (any)",Go("The value to be verified as text."))],compute:function(e){return"string"==typeof e?.value&&!1===qi(e?.value)},isExported:!0},Vv={description:Go("Whether the referenced cell is empty"),args:[qh("value (any)",Go("Reference to the cell that will be checked for emptiness."))],compute:function(e){return null===e?.value},isExported:!0},Uv={description:Go("Returns the error value #N/A."),args:[],compute:function(){return{value:Mi.NotAvailable}},isExported:!0};var Hv=Object.freeze({__proto__:null,CELL:_v,ISBLANK:Vv,ISERR:Fv,ISERROR:Ov,ISLOGICAL:Pv,ISNA:Mv,ISNONTEXT:Nv,ISNUMBER:Lv,ISTEXT:kv,NA:Uv});const zv={description:Go("Logical `and` operator."),args:[qh("logical_expression1 (boolean, range<boolean>)",Go("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),qh("logical_expression2 (boolean, range<boolean>, repeating)",Go("More expressions that represent logical values."))],compute:function(...e){const{result:t,foundBoolean:s}=Pl(e);return s?t:new Li(Fn)},isExported:!0},Bv={description:Go("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},Gv={description:Go("Returns value depending on logical expression."),args:[qh("logical_expression (boolean, range<boolean>)",Go("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")),qh("value_if_true (any, range)",Go("The value the function returns if logical_expression is TRUE.")),qh("value_if_false (any, range, default=FALSE)",Go("The value the function returns if logical_expression is FALSE."))],compute:function(e,t,s){if(Yl(e))return bn(Gv.compute,[e,t,s]);return(nn(Zl(e))?t:s)??{value:0}},isExported:!0},Wv={description:Go("Value if it is not an error, otherwise 2nd argument."),args:[qh("value (any, range)",Go("The value to return if value itself is not an error.")),qh('value_if_error (any, range, default="empty")',Go("The value the function returns if value is an error."))],compute:function(e,t){if(Yl(e))return bn(Wv.compute,[e,t]);return(qi(Zl(e)?.value)?t:e)??{value:0}},isExported:!0},$v={description:Go("Value if it is not an #N/A error, otherwise 2nd argument."),args:[qh("value (any, range)",Go("The value to return if value itself is not #N/A an error.")),qh('value_if_error (any, range, default="empty")',Go("The value the function returns if value is an #N/A error."))],compute:function(e,t){if(Yl(e))return bn($v.compute,[e,t]);return(Zl(e)?.value===Mi.NotAvailable?t:e)??{value:0}},isExported:!0},qv={description:Go("Returns a value depending on multiple logical expressions."),args:[qh("condition1 (boolean, range<boolean>)",Go("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")),qh("value1 (any, range)",Go("The returned value if condition1 is TRUE.")),qh("condition2 (boolean, any, range, repeating)",Go("Additional conditions to be evaluated if the previous ones are FALSE.")),qh("value2 (any, range, repeating)",Go("Additional values to be returned if their corresponding conditions are TRUE."))],compute:function(...e){if(e.length%2!=0)return new Li(Go("Wrong number of arguments. Expected an even number of arguments."));for(;e.length>0;){if(Yl(e[0]))return bn(qv.compute,e);const t=nn(Zl(e.shift())),s=e.shift();if(t)return s??{value:0}}return new Li(Go("No match."))},isExported:!0},Zv={description:Go("Returns opposite of provided logical value."),args:[qh("logical_expression (boolean)",Go("An expression or reference to a cell holding an expression that represents some logical value."))],compute:function(e){return!nn(e)},isExported:!0},jv={description:Go("Logical `or` operator."),args:[qh("logical_expression1 (boolean, range<boolean>)",Go("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),qh("logical_expression2 (boolean, range<boolean>, repeating)",Go("More expressions that evaluate to logical values."))],compute:function(...e){const{result:t,foundBoolean:s}=Ml(e);return s?t:new Li(Fn)},isExported:!0},Yv={description:Go("Returns a value by comparing cases to an expression."),args:[qh("expression (number, boolean, string)",Go("The value to be checked.")),qh("case1 (number, boolean, string)",Go("The first case to be checked against expression.")),qh("value1 (any)",Go("The corresponding value to be returned if case1 matches expression.")),qh("case2 (any, repeating)",Go("Additional cases to try if the previous ones don't match expression.")),qh("value2 (any, repeating)",Go("Additional values to be returned if their corresponding cases match expression.")),qh('default (any, default="empty")',Go("An optional default value to be returned if none of the cases match expression."))],compute:function(e,...t){const s=t.length%2==0?Zi(e):t.pop();for(let s=0;s<t.length;s+=2){const o=t[s];if(o&&qi(o.value))return o;if(e?.value===o?.value)return t[s+1]||{value:0}}return s||{value:0}},isExported:!0},Xv={description:Go("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},Kv={description:Go("Logical `xor` operator."),args:[qh("logical_expression1 (boolean, range<boolean>)",Go("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),qh("logical_expression2 (boolean, range<boolean>, repeating)",Go("More expressions that evaluate to logical values."))],compute:function(...e){let t=!1,s=!1;return Sn(e,(e=>(t=!0,s=s?!e:e,!0))),t?s:new Li(Fn)},isExported:!0};var Jv=Object.freeze({__proto__:null,AND:zv,FALSE:Bv,IF:Gv,IFERROR:Wv,IFNA:$v,IFS:qv,NOT:Zv,OR:jv,SWITCH:Yv,TRUE:Xv,XOR:Kv});const Qv={Errors:{InvalidRange:Go("The range is invalid"),FirstArgMissing:Go("The argument is missing. Please provide a value"),SecondArgMissing:Go("The second argument is missing. Please provide a value"),MinNaN:Go("The minpoint must be a number"),MidNaN:Go("The midpoint must be a number"),MaxNaN:Go("The maxpoint must be a number"),ValueUpperInflectionNaN:Go("The first value must be a number"),ValueLowerInflectionNaN:Go("The second value must be a number"),MinBiggerThanMax:Go("Minimum must be smaller then Maximum"),MinBiggerThanMid:Go("Minimum must be smaller then Midpoint"),MidBiggerThanMax:Go("Midpoint must be smaller then Maximum"),LowerBiggerThanUpper:Go("Lower inflection point must be smaller than upper inflection point"),MinInvalidFormula:Go("Invalid Minpoint formula"),MaxInvalidFormula:Go("Invalid Maxpoint formula"),MidInvalidFormula:Go("Invalid Midpoint formula"),ValueUpperInvalidFormula:Go("Invalid upper inflection point formula"),ValueLowerInvalidFormula:Go("Invalid lower inflection point formula"),EmptyRange:Go("A range needs to be defined"),ValueCellIsInvalidFormula:Go("At least one of the provided values is an invalid formula"),Unexpected:Go("The rule is invalid for an unknown reason")},ColorScale:Go("Color scale"),IconSet:Go("Icon set"),DataBar:Go("Data bar")},eb={Series:Go("Series"),BackgroundColor:Go("Background color"),StackedBarChart:Go("Stacked bar chart"),StackedLineChart:Go("Stacked line chart"),StackedAreaChart:Go("Stacked area chart"),StackedColumnChart:Go("Stacked column chart"),CumulativeData:Go("Cumulative data"),TreatLabelsAsText:Go("Treat labels as text"),AggregatedChart:Go("Aggregate"),Errors:{Unexpected:Go("The chart definition is invalid for an unknown reason"),InvalidDataSet:Go("The dataset is invalid"),InvalidLabelRange:Go("Labels are invalid"),InvalidScorecardKeyValue:Go("The key value is invalid"),InvalidScorecardBaseline:Go("The baseline value is invalid"),InvalidGaugeDataRange:Go("The data range is invalid"),EmptyGaugeRangeMin:Go("A minimum range limit value is needed"),GaugeRangeMinNaN:Go("The minimum range limit value must be a number"),EmptyGaugeRangeMax:Go("A maximum range limit value is needed"),GaugeRangeMaxNaN:Go("The maximum range limit value must be a number"),GaugeLowerInflectionPointNaN:Go("The lower inflection point value must be a number"),GaugeUpperInflectionPointNaN:Go("The upper inflection point value must be a number")},GeoChart:{ColorScales:{blues:Go("Blues"),cividis:Go("Cividis"),greens:Go("Greens"),greys:Go("Greys"),oranges:Go("Oranges"),purples:Go("Purples"),rainbow:Go("Rainbow"),reds:Go("Reds"),viridis:Go("Viridis")}}},tb={Custom:Go("Custom")},sb=Go("Merged cells are preventing this operation. Unmerge those cells and try again."),ob=Go("The header row of a table can't be moved."),ib={Errors:{Unexpected:Go("Cannot split the selection for an unknown reason"),NoSplitSeparatorInSelection:Go("There is no match for the selected separator in the selection"),MoreThanOneColumnSelected:Go("Only a selection from a single column can be split"),SplitWillOverwriteContent:Go("Splitting will overwrite existing content")}},nb={Errors:{Unexpected:Go("Cannot remove duplicates for an unknown reason"),MoreThanOneRangeSelected:Go("Please select only one range of cells"),EmptyTarget:Go("Please select a range of cells containing values."),NoColumnsProvided:Go("Please select at latest one column to analyze."),WillRemoveExistingMerge:Go("This operation is not possible due to a merge. Please remove the merges first than try again.")}},rb={DateIs:{today:Go("today"),yesterday:Go("yesterday"),tomorrow:Go("tomorrow"),lastWeek:Go("in the past week"),lastMonth:Go("in the past month"),lastYear:Go("in the past year")},DateIsBefore:{today:Go("today"),yesterday:Go("yesterday"),tomorrow:Go("tomorrow"),lastWeek:Go("one week ago"),lastMonth:Go("one month ago"),lastYear:Go("one year ago")},CriterionError:{notEmptyValue:Go("The value must not be empty"),numberValue:Go("The value must be a number"),dateValue:Go("The value must be a date"),validRange:Go("The value must be a valid range"),validFormula:Go("The formula must be valid")},Errors:{InvalidRange:Go("The range is invalid."),InvalidDataValidationCriterionValue:Go("One or more of the provided criteria values are invalid. Please review and correct them."),InvalidNumberOfCriterionValues:Go("One or more of the provided criteria values are missing."),Unexpected:Go("The rule is invalid for an unknown reason.")}},ab={Errors:{Unexpected:Go("The table zone is invalid for an unknown reason"),TableOverlap:Go("You cannot create overlapping tables."),NonContinuousTargets:Go("A table can only be created on a continuous selection."),InvalidRange:Go("The range is invalid"),TargetOutOfSheet:Go("The range is out of the sheet")},Checkboxes:{hasFilters:Go("Filter button"),headerRow:Go("Header row(s)"),bandedRows:Go("Banded rows"),firstColumn:Go("First column"),lastColumn:Go("Last column"),bandedColumns:Go("Banded columns"),automaticAutofill:Go("Automatically autofill formulas"),totalRow:Go("Total row"),isDynamic:Go("Auto-adjust to formula result")},Tooltips:{filterWithoutHeader:Go("Cannot have filters without a header row"),isDynamic:Go("For tables based on array formulas only")}},lb={labels:{no_calculations:Go("No calculations"),"%_of_grand_total":Go("% of grand total"),"%_of_col_total":Go("% of column total"),"%_of_row_total":Go("% of row total"),"%_of":Go("% of"),"%_of_parent_row_total":Go("% of parent row total"),"%_of_parent_col_total":Go("% of parent column total"),"%_of_parent_total":Go("% of parent total"),difference_from:Go("Difference from"),"%_difference_from":Go("% difference from"),running_total:Go("Running total"),"%_running_total":Go("% Running total"),rank_asc:Go("Rank smallest to largest"),rank_desc:Go("Rank largest to smallest"),index:Go("Index")},descriptions:{"%_of_grand_total":()=>Go("Displayed as % of grand total"),"%_of_col_total":()=>Go("Displayed as % of column total"),"%_of_row_total":()=>Go("Displayed as % of row total"),"%_of":e=>Go('Displayed as % of "%s"',e),"%_of_parent_row_total":e=>Go('Displayed as % of parent row total of "%s"',e),"%_of_parent_col_total":()=>Go("Displayed as % of parent column total"),"%_of_parent_total":e=>Go('Displayed as % of parent "%s" total',e),difference_from:e=>Go('Displayed as difference from "%s"',e),"%_difference_from":e=>Go('Displayed as % difference from "%s"',e),running_total:e=>Go('Displayed as running total based on "%s"',e),"%_running_total":e=>Go('Displayed as % running total based on "%s"',e),rank_asc:e=>Go('Displayed as rank from smallest to largest based on "%s"',e),rank_desc:e=>Go('Displayed as rank largest to smallest based on "%s"',e),index:()=>Go("Displayed as index")},documentation:{no_calculations:Go("Displays the value that is entered in the field."),"%_of_grand_total":Go("Displays values as a percentage of the grand total of all the values or data points in the report."),"%_of_col_total":Go("Displays all the values in each column or series as a percentage of the total for the column or series."),"%_of_row_total":Go("Displays the value in each row or category as a percentage of the total for the row or category."),"%_of":Go("Displays values as a percentage of the value of the Base item in the Base field."),"%_of_parent_row_total":Go("Calculates values as follows:\n(value for the item) / (value for the parent item on rows)"),"%_of_parent_col_total":Go("Calculates values as follows:\n(value for the item) / (value for the parent item on columns)"),"%_of_parent_total":Go("Calculates values as follows:\n(value for the item) / (value for the parent item of the selected Base field)"),difference_from:Go("Displays values as the difference from the value of the Base item in the Base field."),"%_difference_from":Go("Displays values as the percentage difference from the value of the Base item in the Base field."),running_total:Go("Displays the value for successive items in the Base field as a running total."),"%_running_total":Go("Calculates the value as a percentage for successive items in the Base field that are displayed as a running total."),rank_asc:Go("Displays the rank of selected values in a specific field, listing the smallest item in the field as 1, and each larger value with a higher rank value."),rank_desc:Go("Displays the rank of selected values in a specific field, listing the largest item in the field as 1, and each smaller value with a higher rank value."),index:Go("Calculates values as follows:\n((value in cell) x (Grand Total of Grand Totals)) / ((Grand Row Total) x (Grand Column Total))")}};function cb(e,t){const s=or(e,{format:"0,00",locale:t});return Go("Oops—this pivot table is quite large (%s cells). Try simplifying it using the side panel.",s)}function hb(e,t){const s=t.getPivotId(e);if(!s)throw new Li(Go('There is no pivot with id "%s"',e));return s}function db(e){if(e.length%2!=0)throw new Li(Go("Function PIVOT takes an even number of arguments."))}function ub(e,t,s){const o=[];if("SPREADSHEET"===t.type&&t.dataSet){const{sheetId:s,zone:i}=t.dataSet,n=Ss(i),r=e.getters.getRangeFromSheetXC(s,n);if(void 0===r||r.invalidXc||r.invalidSheetName)throw new Ui;if(e.__originCellPosition&&r.sheetId===e.__originSheetId&&_s(Us(e.__originCellPosition),i))throw new Vi;o.push(r)}for(const t of s)if(t.computedBy){const s=e.getters.getMeasureCompiledFormula(t);o.push(...s.dependencies.filter((e=>!e.invalidXc)))}const i=e.__originCellPosition;i&&o.length&&(e.updateDependencies?.(i),e.addDependencies?.(i,o))}const gb=!0,pb=[{value:!0,label:Go("A1 style (default)")},{value:!1,label:Go("R1C1 style")}],mb=[{value:!0,label:Go("Approximate match (default)")},{value:!1,label:Go("Exact match")}],fb={description:Go("Returns a cell reference as a string. "),args:[qh("row (number)",Go("The row number of the cell reference. ")),qh("column (number)",Go("The column number (not name) of the cell reference. A is column number 1. ")),qh("absolute_relative_mode (number, default=1)",Go("An indicator of whether the reference is row/column absolute."),[{value:1,label:Go("Absolute row and column (e.g. $A$1)")},{value:2,label:Go("Absolute row, relative column (e.g. A$1)")},{value:3,label:Go("Relative row, absolute column (e.g. $A1)")},{value:4,label:Go("Relative row and column (e.g. A1)")}]),qh("use_a1_notation (boolean, default=TRUE)",Go("A boolean indicating whether to use A1 style notation or R1C1 style notation."),pb),qh("sheet (string, optional)",Go("A string indicating the name of the sheet into which the address points."))],compute:function(e,t,s={value:1},o={value:!0},i){const n=en(e,this.locale),r=en(t,this.locale);if(n<1)return new Li(Bl(n));if(r<1)return new Li(Bl(r));const a=en(s,this.locale);if(![1,2,3,4].includes(a))return new Li((l=4,c=a,Go("The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.",1..toString(),l.toString(),c.toString())));var l,c;let h;if(nn(o)){h=as(r-1,n-1,{rowFixed:[1,2].includes(a),colFixed:[1,3].includes(a)})}else{h=([1,2].includes(a)?`R${n}`:`R[${n}]`)+([1,3].includes(a)?`C${r}`:`C[${r}]`)}return void 0!==i?ra(tn(i),h):h},isExported:!0},vb={description:Go("Column number of a specified cell."),args:[qh("cell_reference (meta, range<meta>, default='this cell')",Go("The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered."))],compute:function(e){if(void 0===e)return void 0===this.__originCellPosition?.col?new Li(Go("In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.")):this.__originCellPosition.col+1;if(void 0===e[0][0])return new Li(Go("The range is out of bounds."));if(e[0][0].value===Mi.InvalidReference)return e[0][0];const t=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),e[0][0].value).zone.left;return 1===e.length?t+1:mn(e.length,1,((e,s)=>({value:t+e+1})))},isExported:!0},bb={description:Go("Number of columns in a specified array or range."),args:[qh("range (any, range<any>)",Go("The range whose column count will be returned."))],compute:function(e){const t=An(e);return void 0===t[0][0]?new Li(Go("The range is out of bounds.")):t[0][0].value===Mi.InvalidReference?t[0][0]:t.length},isExported:!0},Sb={description:Go("Horizontal lookup"),args:[qh("search_key (string, number, boolean)",Go("The value to search for. For example, 42, 'Cats', or I24.")),qh("range (any, range)",Go("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")),qh("index (number)",Go("The row index of the value to be returned, where the first row in range is numbered 1.")),qh("is_sorted (boolean, default=true)",Go("Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned."),mb)],compute:function(e,t,s,o={value:gb}){const i=Math.trunc(Yi(s?.value,this.locale)),n=An(t);if(1>i||i>n[0].length)return new Li(Go("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const r=(e,t)=>e[t][0].value,a=n[nn(o.value)?En(n,e,"nextSmaller","asc",n.length,r):Rn(n,e,"wildcard",n.length,r,this.lookupCaches)];return void 0===a?Zi(e):a[i-1]},isExported:!0},Cb={description:Go("Returns the content of a cell, specified by row and column offset."),args:[qh("reference (any, range)",Go("The range of cells from which the values are returned.")),qh("row (number, default=0)",Go("The index of the row to be returned from within the reference range of cells.")),qh("column (number, default=0)",Go("The index of the column to be returned from within the reference range of cells."))],compute:function(e,t={value:0},s={value:0}){const o=An(e),i=Yi(t.value,this.locale),n=Yi(s.value,this.locale);return n<0||n-1>=o.length||i<0||i-1>=o[0].length?new Li(Go("Index out of range.")):0===i&&0===n?o:0===i?[o[n-1]]:0===n?o.map((e=>[e[i-1]])):o[n-1][i-1]},isExported:!0},yb={description:Go("Returns the content of a cell, specified by a string."),args:[qh("reference (string)",Go("The range of cells from which the values are returned.")),qh("use_a1_notation (boolean, default=TRUE)",Go("A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE)."),pb)],compute:function(e,t={value:!0}){const s=e?.value?.toString();if(!s)return new Ui(Go("Reference should be defined."));if(!nn(t))return new Li(Go("R1C1 notation is not supported."));const o=this.__originSheetId,i=this.__originCellPosition;i&&this.updateDependencies?.(i);const n=this.getters.getRangeFromSheetXC(o,s);if(void 0===n||n.invalidXc||n.invalidSheetName)return new Ui;i&&this.addDependencies?.(i,[n]);const r=[];for(let e=n.zone.left;e<=n.zone.right;e++){const t=[];for(let s=n.zone.top;s<=n.zone.bottom;s++){const o={sheetId:n.sheetId,col:e,row:s};t.push(this.getters.getEvaluatedCell(o))}r.push(t)}return 1===r.length&&1===r[0].length?r[0][0]:r},isExported:!0},Ib={description:Go("Look up a value."),args:[qh("search_key (string, number, boolean)",Go("The value to search for. For example, 42, 'Cats', or I24.")),qh("search_array (any, range)",Go("One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.")),qh("result_range (any, range, optional)",Go("The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method."))],compute:function(e,t,s){const o=An(t),i=An(s);let n=o.length,r=o[0].length;const a=r>=n,l=a?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,c=En(o,e,"nextSmaller","asc",a?r:n,l);return-1===c||a&&void 0===o[0][c]||!a&&void 0===o[c][r-1]?Zi(e):0===i[0].length?a?o[n-1][c]:o[c][r-1]:(n=i.length,r=i[0].length,1!==n&&1!==r?new Li(Go("The result_range must be a single row or a single column.")):n>1?c>n-1?new Li(Go("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",c+1)):i[c][0]:c>r-1?new Li(Go("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",c+1)):i[0][c])},isExported:!0},wb={description:Go("Position of item in range that matches value."),args:[qh("search_key (string, number, boolean)",Go("The value to search for. For example, 42, 'Cats', or I24.")),qh("range (any, range)",Go("The one-dimensional array to be searched.")),qh("search_type (number, default=1)",Go("The search method is a number 1, 0 or -1 indicating which value to return. 1 finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order."),[{value:1,label:Go("Ascending order (default)")},{value:0,label:Go("Exact match")},{value:-1,label:Go("Descending order")}])],compute:function(e,t,s={value:1}){let o=Yi(s,this.locale);const i=An(t),n=i.length,r=i[0].length;if(1!==n&&1!==r)return new Li(Go("The range must be a single row or a single column."));let a=-1;const l=1===n?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,c=1===n?i[0].length:i.length;switch(o=Math.sign(o),o){case 1:a=En(i,e,"nextSmaller","asc",c,l);break;case 0:a=Rn(i,e,"wildcard",c,l,this.lookupCaches);break;case-1:a=En(i,e,"nextGreater","desc",c,l)}return 1===n&&void 0===i[0][a]||1!==n&&void 0===i[a]?Zi(e):a+1},isExported:!0},Eb={description:Go("Row number of a specified cell."),args:[qh("cell_reference (meta, range<meta>, default='this cell')",Go("The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered."))],compute:function(e){if(void 0===e)return void 0===this.__originCellPosition?.row?new Li(Go("In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.")):this.__originCellPosition.row+1;if(void 0===e[0][0])return new Li(Go("The range is out of bounds."));if(e[0][0].value===Mi.InvalidReference)return e[0][0];const t=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),e[0][0].value).zone.top;return 1===e[0].length?t+1:mn(1,e[0].length,((e,s)=>({value:t+s+1})))},isExported:!0},Rb={description:Go("Number of rows in a specified array or range."),args:[qh("range (any, range<any>)",Go("The range whose row count will be returned."))],compute:function(e){const t=An(e);return void 0===t[0][0]?new Li(Go("The range is out of bounds.")):t[0][0].value===Mi.InvalidReference?t[0][0]:t[0].length},isExported:!0},xb={description:Go("Vertical lookup."),args:[qh("search_key (string, number, boolean)",Go("The value to search for. For example, 42, 'Cats', or I24.")),qh("range (any, range)",Go("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")),qh("index (number)",Go("The column index of the value to be returned, where the first column in range is numbered 1.")),qh("is_sorted (boolean, default=true)",Go("Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned."),mb)],compute:function(e,t,s,o={value:gb}){const i=Math.trunc(Yi(s?.value,this.locale)),n=An(t);if(1>i||i>n.length)return new Li(Go("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const r=(e,t)=>e[0][t].value,a=nn(o.value)?En(n,e,"nextSmaller","asc",n[0].length,r):Rn(n,e,"wildcard",n[0].length,r,this.lookupCaches),l=n[i-1][a];return void 0===l?Zi(e):l},isExported:!0},Tb={0:"strict",1:"nextGreater","-1":"nextSmaller",2:"wildcard"},Ab={description:Go("Search a range for a match and return the corresponding item from a second range."),args:[qh("search_key (string,number,boolean)",Go("The value to search for.")),qh("lookup_range (any, range)",Go("The range to consider for the search. Should be a single column or a single row.")),qh("return_range (any, range)",Go("The range containing the return value. Should have the same dimensions as lookup_range.")),qh("if_not_found (any, optional)",Go("If a valid match is not found, return this value.")),qh("match_mode (any, default=0)",Go("Specifies how to match search_key with the items in lookup_range. "),[{value:0,label:Go("Exact match (default)")},{value:-1,label:Go("Exact match or next smaller item")},{value:1,label:Go("Exact match or next larger item")},{value:2,label:Go("Wildcard character match")}]),qh("search_mode (any, default=1)",Go("Specifies the search mode to use. By default, a first to last search will be used."),[{value:1,label:Go("Search first to last (default)")},{value:-1,label:Go("Search last to first")},{value:2,label:Go("Binary search (sorted ascending order)")},{value:-2,label:Go("Binary search (sorted descending order)")}])],compute:function(e,t,s,o,i={value:0},n={value:1}){const r=Math.trunc(Yi(i.value,this.locale)),a=Math.trunc(Yi(n.value,this.locale)),l=An(t),c=An(s);if(1!==l.length&&1!==l[0].length)return new Li(Go("lookup_range should be either a single row or single column."));if(![1,-1,2,-2].includes(a))return new Li(Go("search_mode should be a value in [-1, 1, -2, 2]."));if(![-1,0,1,2].includes(r))return new Li(Go("match_mode should be a value in [-1, 0, 1, 2]."));const h=1===l.length?"col":"row";if(2===r&&[-2,2].includes(a))return new Li(Go("The search and match mode combination is not supported for XLOOKUP evaluation."));if("col"===h?c[0].length!==l[0].length:c.length!==l.length)return new Li(Go("return_range should have the same dimensions as lookup_range."));const d="col"===h?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,u="col"===h?l[0].length:l.length,g=Tb[r],p=-1===a,m=2===a||-2===a?En(l,e,g,2===a?"asc":"desc",u,d):Rn(l,e,g,u,d,this.lookupCaches,p);return-1!==m?"col"===h?c.map((e=>[e[m]])):[c[m]]:void 0===o?Zi(e):[[o]]},isExported:!0},Db={description:Go("Get the value from a pivot."),args:[qh("pivot_id (number,string)",Go("ID of the pivot.")),qh("measure_name (string)",Go("Name of the measure.")),qh("domain_field_name (string,repeating)",Go("Field name.")),qh("domain_value (number,string,boolean,repeating)",Go("Value."))],compute:function(e,t,...s){const o=tn(e),i=tn(t),n=hb(o,this.getters);!function(e,t,s){const{measures:o}=s.getPivotCoreDefinition(e);if(!o.find((e=>e.id===t))){const e=`(${o.map((e=>e.id)).join(", ")})`;throw new Li(Go("The argument %s is not a valid measure. Here are the measures: %s",t,e))}}(n,i,this.getters),db(s);const r=this.getters.getPivot(n),a=this.getters.getPivotCoreDefinition(n);ub(this,a,a.measures.filter((e=>e.id===i))),r.init({reload:r.needsReevaluation});const l=r.assertIsValid({throwOnError:!1});if(l)return l;if(!r.areDomainArgsFieldsValid(s)){const e=Go("Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.",`=PIVOT(${o})`);return{value:Mi.GenericError,message:Go("Dimensions don't match the pivot definition")+". "+e}}const c=r.parseArgsToPivotDomain(s);return this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(n)?.trackValue(i,c),r.getPivotCellValueAndFormat(i,c)}},_b={description:Go("Get the header of a pivot."),args:[qh("pivot_id (number,string)",Go("ID of the pivot.")),qh("domain_field_name (string,repeating)",Go("Field name.")),qh("domain_value (number,string,value,repeating)",Go("Value."))],compute:function(e,...t){const s=tn(e),o=hb(s,this.getters);db(t);const i=this.getters.getPivot(o);ub(this,this.getters.getPivotCoreDefinition(o),[]),i.init({reload:i.needsReevaluation});const n=i.assertIsValid({throwOnError:!1});if(n)return n;if(!i.areDomainArgsFieldsValid(t)){const e=Go("Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.",`=PIVOT(${s})`);return{value:Mi.GenericError,message:Go("Dimensions don't match the pivot definition")+". "+e}}const r=i.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(o)?.trackHeader(r);const a=r.at(-1);if("measure"===a?.field)return i.getPivotMeasureValue(tn(a.value),r);const{value:l,format:c}=i.getPivotHeaderValueAndFormat(r);return{value:l,format:a&&"measure"!==a.field&&"false"!==a.value?c:void 0}}},Fb={description:Go("Get a pivot table."),args:[qh("pivot_id (string)",Go("ID of the pivot.")),qh("row_count (number, optional)",Go("number of rows")),qh("include_total (boolean, default=TRUE)",Go("Whether to include total/sub-totals or not.")),qh("include_column_titles (boolean, default=TRUE)",Go("Whether to include the column titles or not.")),qh("column_count (number, optional)",Go("number of columns")),qh("include_measure_titles (boolean, default=TRUE)",Go("Whether to include the measure titles row or not."))],compute:function(e,t={value:1e4},s={value:!0},o={value:!0},i={value:Number.MAX_VALUE},n={value:!0}){const r=tn(e),a=Yi(t,this.locale);if(a<0)return new Li(Go("The number of rows must be positive."));const l=Yi(i,this.locale);if(l<0)return new Li(Go("The number of columns must be positive."));const c={displayColumnHeaders:nn(o),displayTotals:nn(s),displayMeasuresRow:nn(n)},h=hb(r,this.getters),d=this.getters.getPivot(h),u=this.getters.getPivotCoreDefinition(h);ub(this,u,u.measures),d.init({reload:d.needsReevaluation});const g=d.assertIsValid({throwOnError:!1});if(g)return g;const p=d.getCollapsedTableStructure();if(p.numberOfCells>Ve)return new Li(cb(p.numberOfCells,this.locale));const m=p.getPivotCells(c);let f=0;c.displayColumnHeaders&&(f=p.columns.length-1),c.displayMeasuresRow&&f++;const v=this.getters.getPivotName(h),b=Math.min(f+a,m[0].length);if(0===b)return[[{value:v}]];const S=Math.min(1+l,m.length),C=[];for(const e of Je(0,S)){C[e]=[];for(const t of Je(0,b)){const s=m[e][t];switch(s.type){case"EMPTY":C[e].push({value:""});break;case"HEADER":const t=d.getPivotHeaderValueAndFormat(s.domain);C[e].push((y=s.domain,I=t,0===y.length?I:{...I,format:(I.format||"@")+"* "}));break;case"MEASURE_HEADER":C[e].push(d.getPivotMeasureValue(s.measure,s.domain));break;case"VALUE":C[e].push(d.getPivotCellValueAndFormat(s.measure,s.domain))}}}var y,I;return(c.displayColumnHeaders||c.displayMeasuresRow)&&(C[0][0]={value:v}),C}},Ob={description:Go("Returns a range reference shifted by a specified number of rows and columns from a starting cell reference."),args:[qh("cell_reference (meta, range<meta>)",Go("The starting point from which to count the offset rows and columns.")),qh("offset_rows (number)",Go("The number of rows to offset by.")),qh("offset_columns (number)",Go("The number of columns to offset by.")),qh("height (number, default='height of cell_reference')",Go("The number of rows of the range to return starting at the offset target.")),qh("width (number, default='width of cell_reference')",Go("The number of columns of the range to return starting at the offset target."))],compute:function(e,t,s,o,i){if(qi(e[0][0].value))return e[0][0];const n=e[0][0].value;if(!n)return new Li("In this context, the function OFFSET needs to have a cell or range in parameter.");const r=ms(n);let a=e[0].length,l=e.length;if(o){const e=Yi(o,this.locale);if(e<1)return new Li(Go("Height value is %(_height)s. It should be greater than or equal to 1.",{_height:e}));a=e}if(i){const e=Yi(i,this.locale);if(e<1)return new Li(Go("Width value is %(_width)s. It should be greater than or equal to 1.",{_width:e}));l=e}const{sheetName:c}=na(n),h=c&&this.getters.getSheetIdByName(c)||this.getters.getActiveSheetId(),d=Yi(t,this.locale),u=Yi(s,this.locale),g=this.__originCellPosition;g&&this.updateDependencies?.(g);const p=r.left+u,m=r.top+d;if(p<0||m<0)return new Ui(Go("OFFSET evaluates to an out of bounds range."));const f={left:p,top:m,right:p+l-1,bottom:m+a-1},v=this.getters.getRangeFromZone(h,f);return v.invalidXc||v.invalidSheetName?new Ui:(g&&this.addDependencies?.(g,[v]),mn(l,a,((e,t)=>this.getters.getEvaluatedCell({sheetId:h,col:p+e,row:m+t}))))}};var Pb=Object.freeze({__proto__:null,ADDRESS:fb,COLUMN:vb,COLUMNS:bb,HLOOKUP:Sb,INDEX:Cb,INDIRECT:yb,LOOKUP:Ib,MATCH:wb,OFFSET:Ob,PIVOT:Fb,PIVOT_HEADER:_b,PIVOT_VALUE:Db,ROW:Eb,ROWS:Rb,VLOOKUP:xb,XLOOKUP:Ab});const Mb={description:Go("Sum of two numbers."),args:[qh("value1 (number)",Go("The first addend.")),qh("value2 (number)",Go("The second addend."))],compute:function(e,t){return{value:Yi(e,this.locale)+Yi(t,this.locale),format:e?.format||t?.format}}},Nb={description:Go("Concatenation of two values."),args:[qh("value1 (string)",Go("The value to which value2 will be appended.")),qh("value2 (string)",Go("The value to append to value1."))],compute:function(e,t){return tn(e)+tn(t)},isExported:!0},Lb={description:Go("One number divided by another."),args:[qh("dividend (number)",Go("The number to be divided.")),qh("divisor (number)",Go("The number to divide by."))],compute:function(e,t){const s=Yi(t,this.locale);return 0===s?new Gi(Go("The divisor must be different from zero.")):{value:Yi(e,this.locale)/s,format:e?.format||t?.format}}};function kb(e){return void 0===e||null===e.value}const Vb={number:0,string:"",boolean:!1};function Ub(e,t,s=2e-16){return Math.abs(e-t)<s}const Hb={description:Go("Equal."),args:[qh("value1 (string, number, boolean)",Go("The first value.")),qh("value2 (string, number, boolean)",Go("The value to test against value1 for equality."))],compute:function(e,t){if(qi(e?.value))return e;if(qi(t?.value))return t;let s=kb(e)?Vb[typeof t?.value]:e?.value,o=kb(t)?Vb[typeof e?.value]:t?.value;return"string"==typeof s&&(s=s.toUpperCase()),"string"==typeof o&&(o=o.toUpperCase()),"number"==typeof s&&"number"==typeof o?{value:Ub(s,o)}:{value:s===o}}};function zb(e,t,s){if(qi(e?.value))return e;if(qi(t?.value))return t;let o=kb(e)?Vb[typeof t?.value]:e?.value,i=kb(t)?Vb[typeof e?.value]:t?.value;"number"!=typeof o&&(o=tn(o).toUpperCase()),"number"!=typeof i&&(i=tn(i).toUpperCase());const n=typeof o,r=typeof i;return"string"===n&&"number"===r?{value:!0}:"string"===r&&"number"===n?{value:!1}:{value:s(o,i)}}const Bb={description:Go("Strictly greater than."),args:[qh("value1 (number, string, boolean)",Go("The value to test as being greater than value2.")),qh("value2 (number, string, boolean)",Go("The second value."))],compute:function(e,t){return zb(e,t,((e,t)=>"number"==typeof e&&"number"==typeof t?!Ub(e,t)&&e>t:e>t))}},Gb={description:Go("Greater than or equal to."),args:[qh("value1 (number, string, boolean)",Go("The value to test as being greater than or equal to value2.")),qh("value2 (number, string, boolean)",Go("The second value."))],compute:function(e,t){return zb(e,t,((e,t)=>"number"==typeof e&&"number"==typeof t?Ub(e,t)||e>t:e>=t))}},Wb={description:Go("Less than."),args:[qh("value1 (number, string, boolean)",Go("The value to test as being less than value2.")),qh("value2 (number, string, boolean)",Go("The second value."))],compute:function(e,t){const s=Gb.compute.bind(this)(e,t);return qi(s.value)?s:{value:!s.value}}},$b={description:Go("Less than or equal to."),args:[qh("value1 (number, string, boolean)",Go("The value to test as being less than or equal to value2.")),qh("value2 (number, string, boolean)",Go("The second value."))],compute:function(e,t){const s=Bb.compute.bind(this)(e,t);return qi(s.value)?s:{value:!s.value}}},qb={description:Go("Difference of two numbers."),args:[qh("value1 (number)",Go("The minuend, or number to be subtracted from.")),qh("value2 (number)",Go("The subtrahend, or number to subtract from value1."))],compute:function(e,t){return{value:Yi(e,this.locale)-Yi(t,this.locale),format:e?.format||t?.format}}},Zb={description:Go("Product of two numbers"),args:[qh("factor1 (number)",Go("The first multiplicand.")),qh("factor2 (number)",Go("The second multiplicand."))],compute:function(e,t){return{value:Yi(e,this.locale)*Yi(t,this.locale),format:e?.format||t?.format}}},jb={description:Go("Not equal."),args:[qh("value1 (string, number, boolean)",Go("The first value.")),qh("value2 (string, number, boolean)",Go("The value to test against value1 for inequality."))],compute:function(e,t){const s=Hb.compute.bind(this)(e,t);return qi(s.value)?s:{value:!s.value}}},Yb={description:Go("A number raised to a power."),args:[qh("base (number)",Go("The number to raise to the exponent power.")),qh("exponent (number)",Go("The exponent to raise base to."))],compute:function(e,t){return fu.compute.bind(this)(e,t)}},Xb={description:Go("A number with the sign reversed."),args:[qh("value (number)",Go("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],compute:function(e){return{value:-Yi(e,this.locale),format:e?.format}}},Kb={description:Go("Value interpreted as a percentage."),args:[qh("percentage (number)",Go("The value to interpret as a percentage."))],compute:function(e){return Yi(e,this.locale)/100}},Jb={description:Go("A specified number, unchanged."),args:[qh("value (any)",Go("The number to return."))],compute:function(e={value:null}){return e}};var Qb=Object.freeze({__proto__:null,ADD:Mb,CONCAT:Nb,DIVIDE:Lb,EQ:Hb,GT:Bb,GTE:Gb,LT:Wb,LTE:$b,MINUS:qb,MULTIPLY:Zb,NE:jb,POW:Yb,UMINUS:Xb,UNARY_PERCENT:Kb,UPLUS:Jb});const eS=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),tS={transform:e=>e,inverseTransform:e=>e},sS=1e-10,oS=.0254,iS=oS/72,nS=.3048,rS=.9144,aS=1609.34,lS=1852,cS=946073047258e4,hS={g:{...tS,category:"weight"},u:{...eS(166053e-29),category:"weight"},grain:{...eS(.0647989),category:"weight"},ozm:{...eS(28.3495),category:"weight"},lbm:{...eS(453.592),category:"weight"},stone:{...eS(6350.29),category:"weight"},sg:{...eS(14593.90294),category:"weight"},cwt:{...eS(45359.237),category:"weight"},uk_cwt:{...eS(50802.3),category:"weight"},ton:{...eS(907184.74),category:"weight"},uk_ton:{...eS(1016046.9),category:"weight"},m:{...tS,category:"distance"},km:{...eS(1e3),category:"distance"},ang:{...eS(sS),category:"distance"},Picapt:{...eS(iS),category:"distance"},pica:{...eS(oS/6),category:"distance"},in:{...eS(oS),category:"distance"},ft:{...eS(nS),category:"distance"},yd:{...eS(rS),category:"distance"},ell:{...eS(1.143),category:"distance"},mi:{...eS(aS),category:"distance"},survey_mi:{...eS(1609.34),category:"distance"},Nmi:{...eS(lS),category:"distance"},ly:{...eS(cS),category:"distance"},parsec:{...eS(0x6da012f95c9fd0),category:"distance"},sec:{...tS,category:"time"},min:{...eS(60),category:"time"},hr:{...eS(3600),category:"time"},day:{...eS(86400),category:"time"},yr:{...eS(31556952),category:"time"},Pa:{...tS,category:"pressure"},bar:{...eS(1e5),category:"pressure"},mmHg:{...eS(133.322),category:"pressure"},Torr:{...eS(133.322),category:"pressure"},psi:{...eS(6894.76),category:"pressure"},atm:{...eS(101325),category:"pressure"},N:{...tS,category:"force"},dyn:{...eS(1e-5),category:"force"},pond:{...eS(.00980665),category:"force"},lbf:{...eS(4.44822),category:"force"},J:{...tS,category:"energy"},eV:{...eS(160218e-24),category:"energy"},e:{...eS(1e-7),category:"energy"},flb:{...eS(1.3558179483),category:"energy"},c:{...eS(4.184),category:"energy"},cal:{...eS(4.1868),category:"energy"},BTU:{...eS(1055.06),category:"energy"},Wh:{...eS(3600),category:"energy"},HPh:{...eS(2684520),category:"energy"},W:{...tS,category:"power"},PS:{...eS(735.499),category:"power"},HP:{...eS(745.7),category:"power"},T:{...tS,category:"magnetism"},ga:{...eS(1e-4),category:"magnetism"},K:{...tS,category:"temperature"},C:{transform:e=>e+273.15,inverseTransform:e=>e-273.15,category:"temperature"},F:{transform:e=>5*(e-32)/9+273.15,inverseTransform:e=>9*(e-273.15)/5+32,category:"temperature"},Rank:{...eS(5/9),category:"temperature"},Reau:{transform:e=>1.25*e+273.15,inverseTransform:e=>(e-273.15)/1.25,category:"temperature"},"m^3":{...tS,category:"volume",order:3},"ang^3":{...eS(Math.pow(sS,3)),category:"volume",order:3},"Picapt^3":{...eS(Math.pow(iS,3)),category:"volume",order:3},tsp:{...eS(492892e-11),category:"volume"},tspm:{...eS(5e-6),category:"volume"},tbs:{...eS(14786764825785619e-21),category:"volume"},"in^3":{...eS(Math.pow(oS,3)),category:"volume",order:3},oz:{...eS(295735295625e-16),category:"volume"},cup:{...eS(237e-6),category:"volume"},pt:{...eS(.0004731765),category:"volume"},uk_pt:{...eS(568261e-9),category:"volume"},qt:{...eS(.0009463529),category:"volume"},l:{...eS(.001),category:"volume"},uk_qt:{...eS(.0011365225),category:"volume"},gal:{...eS(.0037854118),category:"volume"},uk_gal:{...eS(.00454609),category:"volume"},"ft^3":{...eS(Math.pow(nS,3)),category:"volume",order:3},bushel:{...eS(.0352390704),category:"volume"},barrel:{...eS(.158987295),category:"volume"},"yd^3":{...eS(Math.pow(rS,3)),category:"volume",order:3},MTON:{...eS(1.13267386368),category:"volume"},GRT:{...eS(2.83168),category:"volume"},"mi^3":{...eS(Math.pow(aS,3)),category:"volume",order:3},"Nmi^3":{...eS(Math.pow(lS,3)),category:"volume",order:3},"ly^3":{...eS(Math.pow(cS,3)),category:"volume",order:3},"m^2":{...tS,category:"area",order:2},"ang^2":{...eS(Math.pow(sS,2)),category:"area",order:2},"Picapt^2":{...eS(Math.pow(iS,2)),category:"area",order:2},"in^2":{...eS(Math.pow(oS,2)),category:"area",order:2},"ft^2":{...eS(Math.pow(nS,2)),category:"area",order:2},"yd^2":{...eS(Math.pow(rS,2)),category:"area",order:2},ar:{...eS(100),category:"area"},Morgen:{...eS(2500),category:"area"},uk_acre:{...eS(4046.8564224),category:"area"},us_acre:{...eS(4046.8726098743),category:"area"},ha:{...eS(1e4),category:"area"},"mi^2":{...eS(Math.pow(aS,2)),category:"area",order:2},"Nmi^2":{...eS(Math.pow(lS,2)),category:"area",order:2},"ly^2":{...eS(Math.pow(cS,2)),category:"area",order:2},bit:{...tS,category:"information"},byte:{...eS(8),category:"information"},"m/s":{...tS,category:"speed"},"m/hr":{...eS(1/3600),category:"speed"},"km/hr":{...eS(1/3.6),category:"speed"},mph:{...eS(.44704),category:"speed"},kn:{...eS(.5144444444),category:"speed"},admkn:{...eS(.5147733333),category:"speed"}},dS={shweight:"cwt",lcwt:"uk_cwt",hweight:"uk_cwt",LTON:"uk_ton",brton:"uk_ton",pc:"parsec",Pica:"Picapt",d:"day",mn:"min",s:"sec",p:"Pa",at:"atm",dy:"dyn",ev:"eV",hh:"HPh",wh:"Wh",btu:"BTU",h:"HP",cel:"C",fah:"F",kel:"K",us_pt:"pt",L:"l",lt:"l",ang3:"ang^3",ft3:"ft^3",in3:"in^3",ly3:"ly^3",m3:"m^3",mi3:"mi^3",yd3:"yd^3",Nmi3:"Nmi^3",Picapt3:"Picapt^3","Pica^3":"Picapt^3",Pica3:"Picapt^3",regton:"GRT",ang2:"ang^2",ft2:"ft^2",in2:"in^2",ly2:"ly^2",m2:"m^2",mi2:"mi^2",Nmi2:"Nmi^2",Picapt2:"Picapt^2","Pica^2":"Picapt^2",Pica2:"Picapt^2",yd2:"yd^2","m/h":"m/hr","m/sec":"m/s"},uS={"":1,Y:1e24,Z:1e21,E:1e18,P:1e15,T:1e12,G:1e9,M:1e6,k:1e3,h:100,da:10,e:10,d:.1,c:.01,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15,a:1e-18,z:1e-21,y:1e-21,Yi:Math.pow(2,80),Zi:Math.pow(2,70),Ei:Math.pow(2,60),Pi:Math.pow(2,50),Ti:Math.pow(2,40),Gi:Math.pow(2,30),Mi:Math.pow(2,20),ki:Math.pow(2,10)},gS={weight:Go("Weight"),distance:Go("Distance"),time:Go("Time"),pressure:Go("Pressure"),force:Go("Force"),energy:Go("Energy"),power:Go("Power"),magnetism:Go("Magnetism"),temperature:Go("Temperature"),volume:Go("Volume"),area:Go("Area"),information:Go("Information"),speed:Go("Speed")},pS=Object.entries(hS).map((([e,t])=>({value:e,label:mS(t.category)})));function mS(e){return gS[e]??""}function fS(e){for(const[t,s]of Object.entries(uS)){if(t&&!e.startsWith(t))continue;const o=e.slice(t.length);let i=hS[o];if(!i&&dS[o]&&(i=hS[dS[o]]),i)return{...i,factor:i.order?Math.pow(s,i.order):s}}}const vS={description:Go("Converts a numeric value to a different unit of measure."),args:[qh("value (number)",Go("the numeric value in start_unit to convert to end_unit")),qh("start_unit (string)",Go("The starting unit, the unit currently assigned to value"),pS),qh("end_unit (string)",Go("The unit of measure into which to convert value"),pS)],compute:function(e,t,s){const o=Yi(e,this.locale),i=tn(t),n=tn(s),r=fS(i),a=fS(n);return r?a?r.category!==a.category?{value:Mi.GenericError,message:Go("Incompatible units of measure ('%s' vs '%s')",mS(r.category),mS(a.category))}:{value:a.inverseTransform(r.factor*r.transform(o))/a.factor,format:e?.format}:{value:Mi.GenericError,message:Go("Invalid units of measure ('%s')",n)}:{value:Mi.GenericError,message:Go("Invalid units of measure ('%s')",i)}},isExported:!0};var bS=Object.freeze({__proto__:null,CONVERT:vS});const SS=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,CS=[{value:0,label:Go("Case-sensitive (default)")},{value:1,label:Go("Case-insensitive")}],yS=[{value:0,label:Go("Don't match to end (default)")},{value:1,label:Go("Match to end")}],IS={description:Go("Gets character associated with number."),args:[qh("table_number (number)",Go("The number of the character to look up from the current Unicode table in decimal format."))],compute:function(e){const t=Math.trunc(Yi(e,this.locale));return t<1?new Li(Go("The table_number (%s) is out of range.",t)):String.fromCharCode(t)},isExported:!0},wS={description:Go("Remove non-printable characters from a piece of text."),args:[qh("text (string)",Go("The text whose non-printable characters are to be removed."))],compute:function(e){const t=tn(e);let s="";for(const e of t)e&&e.charCodeAt(0)>31&&(s+=e);return s},isExported:!0},ES={description:Go("Appends strings to one another."),args:[qh("string1 (string, range<string>)",Go("The initial string.")),qh("string2 (string, range<string>, repeating)",Go("More strings to append in sequence."))],compute:function(...e){return un(e,((e,t)=>e+tn(t)),"")},isExported:!0},RS={description:Go("Tests whether two strings are identical."),args:[qh("string1 (string)",Go("The first string to compare.")),qh("string2 (string)",Go("The second string to compare."))],compute:function(e,t){return tn(e)===tn(t)},isExported:!0},xS={description:Go("First position of string found in text, case-sensitive."),args:[qh("search_for (string)",Go("The string to look for within text_to_search.")),qh("text_to_search (string)",Go("The text to search for the first occurrence of search_for.")),qh("starting_at (number, default=1)",Go("The character within text_to_search at which to start the search."))],compute:function(e,t,s={value:1}){const o=tn(e),i=tn(t),n=Yi(s,this.locale);if(""===i)return new Li(Go("The text_to_search must be non-empty."));if(n<1)return new Li(Go("The starting_at (%s) must be greater than or equal to 1.",n));const r=i.indexOf(o,n-1);return-1===r?new Li(Go("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,i)):r+1},isExported:!0},TS={description:Go("Concatenates elements of arrays with delimiter."),args:[qh("delimiter (string)",Go("The character or string to place between each concatenated value.")),qh("value_or_array1 (string, range<string>)",Go("The value or values to be appended using delimiter.")),qh("value_or_array2 (string, range<string>, repeating)",Go("More values to be appended using delimiter."))],compute:function(e,...t){const s=tn(e);return un(t,((e,t)=>(e?e+s:"")+tn(t)),"")}},AS={description:Go("Substring from beginning of specified string."),args:[qh("text (string)",Go("The string from which the left portion will be returned.")),qh("number_of_characters (number, optional)",Go("The number of characters to return from the left side of string."))],compute:function(e,...t){const s=t.length?Yi(t[0],this.locale):1;return s<0?new Li(Go("The number_of_characters (%s) must be positive or null.",s)):tn(e).substring(0,s)},isExported:!0},DS={description:Go("Length of a string."),args:[qh("text (string)",Go("The string whose length will be returned."))],compute:function(e){return tn(e).length},isExported:!0},_S={description:Go("Converts a specified string to lowercase."),args:[qh("text (string)",Go("The string to convert to lowercase."))],compute:function(e){return tn(e).toLowerCase()},isExported:!0},FS={description:Go("A segment of a string."),args:[qh("text (string)",Go("The string to extract a segment from.")),qh("starting_at (number)",Go("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),qh("extract_length (number)",Go("The length of the segment to extract."))],compute:function(e,t,s){const o=tn(e),i=Yi(t,this.locale),n=Yi(s,this.locale);return i<1?new Li(Go("The starting_at argument (%s) must be positive greater than one.",i.toString())):n<0?new Li(Go("The extract_length argument (%s) must be positive or null.",n)):o.slice(i-1,i+n-1)},isExported:!0},OS={description:Go("Capitalizes each word in a specified string."),args:[qh("text_to_capitalize (string)",Go("The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase."))],compute:function(e){return tn(e).replace(SS,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},PS={description:Go("Extract text from a string based on the supplied regular expression."),args:[qh("text (string)",Go("The string on which you want to extract text.")),qh("pattern (string)",Go("The regular expression pattern to match against the text.")),qh("return_mode (number, default=0)",Go("0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array."),[{value:0,label:Go("First match")},{value:1,label:Go("All matches")},{value:2,label:Go("Capture groups of first match")}]),qh("case_sensitivity (number, default=0)",Go("Whether the match is case-sensitive."),[{value:0,label:Go("Case-sensitive")},{value:1,label:Go("Case-insensitive")}])],compute:function(e,t,s={value:0},o={value:0}){const i=tn(e),n=tn(t),r=Yi(s,this.locale),a=Yi(o,this.locale);if(""===i||""===n)return{value:""};if(r<0||r>2)return new Li(Go("The return_mode (%s) must be 0, 1 or 2.",r));if(0!==a&&1!==a)return new Li(Go("The case_sensitivity (%s) must be 0 or 1.",a));const l=new RegExp(n,1===a?"gi":"g"),c=[...i.matchAll(l)];return 0===c.length?{value:Mi.NotAvailable,message:Go("No matches found.")}:0===r?c[0][0]:1===r?c.map((e=>[e[0]])):c[0].length<2?new Li(Go("No capturing groups found.")):c[0].slice(1).map((e=>[e]))},isExported:!0},MS={description:Go("Replaces part of a text string with different text."),args:[qh("text (string)",Go("The text, a part of which will be replaced.")),qh("position (number)",Go("The position where the replacement will begin (starting from 1).")),qh("length (number)",Go("The number of characters in the text to be replaced.")),qh("new_text (string)",Go("The text which will be inserted into the original text."))],compute:function(e,t,s,o){const i=Yi(t,this.locale);if(i<1)return new Li(Go("The position (%s) must be greater than or equal to 1.",i));const n=tn(e),r=Yi(s,this.locale),a=tn(o);return n.substring(0,i-1)+a+n.substring(i-1+r)},isExported:!0},NS={description:Go("A substring from the end of a specified string."),args:[qh("text (string)",Go("The string from which the right portion will be returned.")),qh("number_of_characters (number, optional)",Go("The number of characters to return from the right side of string."))],compute:function(e,...t){const s=t.length?Yi(t[0],this.locale):1;if(s<0)return new Li(Go("The number_of_characters (%s) must be positive or null.",s));const o=tn(e),i=o.length;return o.substring(i-s,i)},isExported:!0},LS={description:Go("First position of string found in text, ignoring case."),args:[qh("search_for (string)",Go("The string to look for within text_to_search.")),qh("text_to_search (string)",Go("The text to search for the first occurrence of search_for.")),qh("starting_at (number, default=1)",Go("The character within text_to_search at which to start the search."))],compute:function(e,t,s={value:1}){const o=tn(e).toLowerCase(),i=tn(t).toLowerCase(),n=Yi(s,this.locale);if(""===i)return{value:Mi.GenericError,message:Go("The text_to_search must be non-empty.")};if(n<1)return{value:Mi.GenericError,message:Go("The starting_at (%s) must be greater than or equal to 1.",n)};const r=i.indexOf(o,n-1);return-1===r?{value:Mi.GenericError,message:Go("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,i)}:{value:r+1}},isExported:!0},kS={description:Go("Split text by specific character delimiter(s)."),args:[qh("text (string)",Go("The text to divide.")),qh("delimiter (string)",Go("The character or characters to use to split text.")),qh("split_by_each (boolean, default=true})",Go("Whether or not to divide text around each character contained in delimiter.")),qh("remove_empty_text (boolean, default=true)",Go("Whether or not to remove empty text messages from the split results. The default behavior is to treat consecutive delimiters as one (if TRUE). If FALSE, empty cells values are added between consecutive delimiters."))],compute:function(e,t,s={value:true},o={value:true}){const i=tn(e),n=$e(tn(t)),r=nn(s),a=nn(o);if(n.length<=0)return new Li(Go("The delimiter (%s) must be not be empty.",n));const l=r?new RegExp(`[${n}]`,"g"):new RegExp(n,"g");let c=i.split(l);return a&&(c=c.filter((e=>""!==e))),vn([c])},isExported:!1},VS={description:Go("Replaces existing text with new text in a string."),args:[qh("text_to_search (string)",Go("The text within which to search and replace.")),qh("search_for (string)",Go("The string to search for within text_to_search.")),qh("replace_with (string)",Go("The string that will replace search_for.")),qh("occurrence_number (number, optional)",Go("The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced."))],compute:function(e,t,s,o){const i=Yi(o,this.locale);if(i<0)return new Li(Go("The occurrenceNumber (%s) must be positive or null.",i));const n=tn(e),r=tn(t);if(""===r)return n;const a=tn(s),l=new RegExp($e(r),"g");if(0===i)return n.replace(l,a);let c=0;return n.replace(l,(e=>++c===i?a:e))},isExported:!0},US={description:Go("Combines text from multiple strings and/or arrays."),args:[qh("delimiter (string)",Go(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")),qh("ignore_empty (boolean)",Go("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result."),[{value:!0,label:Go("Ignore empty cells")},{value:!1,label:Go("Include empty cells (default)")}]),qh("text1 (string, range<string>)",Go("Any text item. This could be a string, or an array of strings in a range.")),qh("text2 (string, range<string>, repeating)",Go("Additional text item(s)."))],compute:function(e,t={value:true},...s){const o=tn(e),i=nn(t);let n=0;return un(s,((e,t)=>i&&""===tn(t)?e:(n++?e+o:"")+tn(t)),"")},isExported:!0},HS={description:Go("Splits text into rows or columns using specified column and row delimiters."),args:[qh("text (string)",Go("The text to split.")),qh("col_delimiter (string, range<string>)",Go("Character or string to split columns by.")),qh("row_delimiter (string, range<string>, optional)",Go("Character or string to split rows by.")),qh("ignore_empty (boolean, default=false)",Go("Whether to ignore empty cells."),[{value:!1,label:Go("Include empty cells (default)")},{value:!0,label:Go("Ignore empty cells")}]),qh("match_mode (number, default=0)",Go("Searches the text for a delimiter match. By default, a case-sensitive match is done."),CS),qh(`pad_with (string, default="${Mi.NotAvailable}")`,Go("The value to use for padding empty cells."))],compute:function(e,t,s,o={value:false},i={value:0},n=new Hi){const r=tn(e);if(r.length<=0)return new Li(Go("No text to split."));if(void 0===t&&void 0===s)return new Li(Go("At least one delimiter must be provided."));const a=An(t).flat().map((e=>$e(tn(e)))),l=An(s).flat().map((e=>$e(tn(e))));if(a.some((e=>""===e))||l.some((e=>""===e)))return new Li(Go("The delimiters cannot be empty values."));const c=nn(o),h=Yi(i,this.locale);if(![0,1].includes(h))return new Li(Go("match_mode should be a value of 0 or 1."));const d=[],u=1===h?"gi":"g",g=l.filter((e=>!a.includes(e)));let p=g.length?r.split(new RegExp(g.join("|"),u)):[r];c&&(p=p.filter((e=>""!==e)));const m=new RegExp(a.join("|"),u);for(const e of p){let t=a.length?e.split(m):[e];c&&(t=t.filter((e=>""!==e))),d.push(t.map((e=>({value:e}))))}const f=Math.max(...d.map((e=>e.length)));for(const e of d)for(;e.length<f;)e.push(n);return vn(d)},isExported:!0},zS={description:Go("Removes space characters."),args:[qh("text (string)",Go("The text or reference to a cell containing text to be trimmed."))],compute:function(e){return Mt(tn(e))},isExported:!0},BS={description:Go("Converts a specified string to uppercase."),args:[qh("text (string)",Go("The string to convert to uppercase."))],compute:function(e){return tn(e).toUpperCase()},isExported:!0},GS={description:Go("Converts a number to text according to a specified format."),args:[qh("number (number)",Go("The number, date or time to format.")),qh("format (string)",Go('The case-sensitive format of the result, enclosed in quotation marks. Examples: "0.00" rounded to 2 decimal places, "hh:mm:ss" for hour:minutes:seconds.'))],compute:function(e,t){return or(Yi(e,this.locale),{format:tn(t),locale:this.locale})},isExported:!0},WS={description:Go("Converts a string to a numeric value."),args:[qh("value (number)",Go("the string to be converted"))],compute:function(e){return Yi(e,this.locale)},isExported:!0},$S={description:Go("Returns text that occurs after a given substring or delimiter."),args:[qh("text (string)",Go("The source text.")),qh("delimiter (string)",Go("The substring after which text will be returned.")),qh("instance_num (number, default=1)",Go("The desired instance of the delimiter after which we extract the text. A negative number searches from the end.")),qh("match_mode (number, default=0)",Go("Searches the text for a delimiter match. By default, a case-sensitive match is done."),CS),qh("match_end (number, default=0))",Go("Whether to treat the end of text as a delimiter."),yS),qh(`if_not_found (string, default="${Mi.NotAvailable}")`,Go("Value to return if the delimiter is not found."))],compute:function(e,t,s={value:1},o={value:0},i={value:0},n=new Hi){const r=tn(e),a=Yi(s,this.locale),l=Yi(o,this.locale),c=Yi(i,this.locale);if(0===a)return new Li(Go("The instance_num (%s) must not be zero.",a));if(0!==l&&1!==l)return new Li(Go("match_mode should have a value of 0 or 1."));if(0!==c&&1!==c)return new Li(Go("match_end should have a value of 0 or 1."));const h=tn(t);if(""===h)return Math.sign(a)>0?{value:r}:{value:""};const d=1===l?"gi":"g",u=$e(h),g=new RegExp(u,d);let p=[...r.matchAll(g)].map((e=>e.index+u.length));if(a<0&&(p=p.reverse()),c&&Math.abs(a)===p.length+1)return Math.sign(a)>0?{value:""}:{value:r};const m=p[Math.abs(a)-1];return void 0===m?n:{value:r.substring(m)}},isExported:!0},qS={description:Go("Returns text that occurs before a given substring or delimiter."),args:[qh("text (string)",Go("The source text.")),qh("delimiter (string)",Go("The substring after which text will be returned.")),qh("instance_num (number, default=1)",Go("The desired instance of the delimiter before which we extract the text. A negative number searches from the end.")),qh("match_mode (number, default=0)",Go("Searches the text for a delimiter match. By default, a case-sensitive match is done."),CS),qh("match_end (number, default=0))",Go("Whether to match a delimiter against the end of the text."),yS),qh(`if_not_found (string, default="${Mi.NotAvailable}")`,Go("Value to return if the delimiter is not found."))],compute:function(e,t,s={value:1},o={value:0},i={value:0},n=new Hi){const r=tn(e),a=Yi(s,this.locale),l=Yi(o,this.locale),c=Yi(i,this.locale);if(0===a)return new Li(Go("The instance_num (%s) must not be zero.",a));if(0!==l&&1!==l)return new Li(Go("match_mode should have a value of 0 or 1."));if(0!==c&&1!==c)return new Li(Go("match_end should have a value of 0 or 1."));const h=tn(t);if(""===h)return Math.sign(a)>0?{value:""}:{value:r};const d=1===l?"gi":"g",u=$e(h),g=new RegExp(u,d);let p=[...r.matchAll(g)].map((e=>e.index+u.length));if(a<0&&(p=p.reverse()),c&&Math.abs(a)===p.length+1)return Math.sign(a)>0?{value:r}:{value:""};const m=p[Math.abs(a)-1];return void 0===m?n:{value:r.substring(0,m-h.length)}},isExported:!0};var ZS=Object.freeze({__proto__:null,CHAR:IS,CLEAN:wS,CONCATENATE:ES,EXACT:RS,FIND:xS,JOIN:TS,LEFT:AS,LEN:DS,LOWER:_S,MID:FS,PROPER:OS,REGEXEXTRACT:PS,REPLACE:MS,RIGHT:NS,SEARCH:LS,SPLIT:kS,SUBSTITUTE:VS,TEXT:GS,TEXTAFTER:$S,TEXTBEFORE:qS,TEXTJOIN:US,TEXTSPLIT:HS,TRIM:zS,UPPER:BS,VALUE:WS});const jS={description:Go("Creates a hyperlink in a cell."),args:[qh("url (string)",Go("The full URL of the link enclosed in quotation marks.")),qh("link_label (string, optional)",Go("The text to display in the cell, enclosed in quotation marks."))],compute:function(e,t){const s=tn(e).trim(),o=tn(t)||s;return""===s?o:rt(o,s)},isExported:!0};var YS=Object.freeze({__proto__:null,HYPERLINK:jS});const XS=[{name:Go("Array"),functions:yd},{name:Go("Database"),functions:fp},{name:Go("Date"),functions:Mm},{name:Go("Filter"),functions:qm},{name:Go("Financial"),functions:sv},{name:Go("Info"),functions:Hv},{name:Go("Lookup"),functions:Pb},{name:Go("Logical"),functions:Jv},{name:Go("Math"),functions:Bu},{name:Go("Misc"),functions:wd},{name:Go("Operator"),functions:Qb},{name:Go("Statistical"),functions:tp},{name:Go("Text"),functions:ZS},{name:Go("Engineering"),functions:Lm},{name:Go("Web"),functions:YS},{name:Go("Parser"),functions:bS}],KS=/^[A-Z0-9\_\.]+$/;const JS=new class extends n{mapping={};add(e,t){if((e=e.toUpperCase())in this.content)throw new Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){if(e=e.toUpperCase(),!KS.test(e))throw new Error(Go("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const s=function(e,t){let s=0,o=0,i=0,n=0;for(const e of t.args)s++,e.optional||e.repeating||e.default||o++,e.repeating&&i++,(e.optional||e.default)&&n++;const r=t;return r.minArgRequired=o,r.maxArgPossible=i?1/0:s,r.nbrArgRepeating=i,r.nbrArgOptional=n,r.hidden=t.hidden||!1,r.name=e,r}(e,t);return function(e){if(e.nbrArgRepeating&&e.nbrArgOptional>=e.nbrArgRepeating)throw new Error(`Function ${e.name} has more optional arguments than repeatable ones.`);let t=!1,s=!1;for(const o of e.args){if(o.type.some((e=>Yh.includes(e)))&&o.type.some((e=>!Yh.includes(e))))throw new Error(`Function ${e.name} has a mix of META and non-META types in the same argument: ${o.type}.`);if(o.repeating){if(!s&&t)throw new Error(`Function ${e.name} has non-consecutive repeating arguments. All repeating arguments must be declared consecutively.`);t=!0,s=!0}else s=!1}}(s),this.mapping[e]=function(e){function t(...t){const o=[],i=jh(e,t.length);for(let s=0;s<t.length;s++){const n=i(s)??-1,r=e.args[n];if(!R(t[s])&&r.acceptMatrixOnly)throw new ki(Go("Function %s expects the parameter '%s' to be reference to a cell or range.",e.name,(s+1).toString()));o.push(!r.acceptMatrix)}return bn(s.bind(this),t,o)}function s(...t){for(let s=0;s<t.length;s++){const o=t[s],i=jh(e,t.length);if(!e.args[i(s)||s].acceptErrors&&!R(o)&&qi(o?.value))return o}try{return o.apply(this,t)}catch(t){return QS(t,e.name)}}function o(...t){this.debug;const s=e.compute.apply(this,t);return R(s)?"object"==typeof s[0][0]&&null!==s[0][0]&&"value"in s[0][0]?(function(e,t){const s=e.length,o=e[0]?.length??0;for(let i=0;i<s;i++)for(let s=0;s<o;s++)t(e[i][s])}(s,(t=>eC(t,e.name))),s):fn(s,(e=>({value:e}))):"object"==typeof s&&null!==s&&"value"in s?(eC(s,e.name),s):{value:s}}return t}(s),super.replace(e,s),this}};for(const e of XS){const t=e.functions;for(let s in t){const o=t[s];o.category=o.category||e.name,s=s.replace(/_/g,"."),JS.add(s,{isExported:!1,...o}),oC(s,o.args)}}function QS(e,t){return s=e,void 0!==s?.value&&"string"==typeof s.value&&qi(e.value)?(sC(e)&&eC(e,t),e):(console.error(e),new Li(tC+(sC(e)?" "+e.message:"")));var s}function eC(e,t){e.message?.includes("[[FUNCTION_NAME]]")&&(e.message=e.message.replace("[[FUNCTION_NAME]]",t))}const tC=Go("An unexpected error occurred. Submit a support ticket at odoo.com/help.");function sC(e){return void 0!==e?.message&&"string"==typeof e.message}function oC(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?Ge.STRING:Ge.NUMBER}],fuzzySearchKey:r,alwaysExpanded:!0})}return n};Xh.add(`${e}_function_${t[s].name}_argument_proposals`,{sequence:50,autoSelectFirstProposal:!0,selectProposal:iC,getProposals:i})}}function iC(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)}class nC{scope;code="";constructor(e=new aC){this.scope=e}append(...e){this.code+=e.map((e=>e.toString())).join("\n")+"\n"}return(e){return new rC(this.scope,this.code,e)}toString(){return lC(this.code)}}class rC{scope;returnExpression;code;constructor(e,t,s){this.scope=e,this.returnExpression=s,this.code=lC(t)}toString(){return this.code}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;const e=this.scope.nextVariableName(),t=new nC(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}}class aC{nextId=1;declaredVariables=new Set;nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function lC(e){let t="",s=0;const o=e.split("\n").map((e=>e.trim())).filter((e=>""!==e));for(const e of o)e.startsWith("}")&&s--,t+="\t".repeat(s)+e+"\n",e.endsWith("{")&&s++;return t.trim()}const cC=JS.content,hC={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},dC={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"},uC={};function gC(e){return pC(av(e))}function pC(e){try{return function(e){const{dependencies:t,literalValues:s,symbols:o}=function(e){const t={numbers:[],strings:[]},s=[],o=[];for(const i of e)switch(i.type){case"INVALID_REFERENCE":case"REFERENCE":s.push(i.value);break;case"STRING":const e=je(i.value);t.strings.push({value:e});break;case"NUMBER":{const e=Oi(i.value,w);t.numbers.push({value:e});break}case"SYMBOL":o.push(je(i.value,"'"))}return{dependencies:s,literalValues:t,symbols:o}}(e),i=function(e){let t="";for(const s of e)switch(s.type){case"STRING":t+="|S|";break;case"NUMBER":t+="|N|";break;case"REFERENCE":case"INVALID_REFERENCE":s.value.includes(":")?t+="|R|":t+="|C|";break;case"SPACE":break;default:t+=s.value}return t}(e);if(!uC[i]){const r=bv([...e]),a=new aC;let l=0,c=0,h=0;if("BIN_OPERATION"===r.type&&":"===r.value)throw new ki(Go("Invalid formula"));if("EMPTY"===r.type)throw new ki(Go("Invalid formula"));const d=m(r),u=new nC;u.append(`// ${i}`),u.append(d),u.append(`return ${d.returnExpression};`);const g=new Function("deps","ref","range","getSymbolValue","ctx",u.toString());function p(e){const{args:t}=e,s=e.value.toUpperCase(),o=cC[s];if(!o)throw new zi(Go('Unknown function: "%s"',e.value));!function(e){const t=e.args.length,s=e.value.toUpperCase(),o=cC[s],{nbrArgRepeating:i,minArgRequired:n}=o;if(t<n)throw new ki(Go("Invalid number of arguments for the %(functionName)s function. Expected %(minArgRequired)s minimum, but got %(nbrArgSupplied)s instead.",{functionName:s,minArgRequired:n,nbrArgSupplied:t}));if(t>o.maxArgPossible)throw new ki(Go("Invalid number of arguments for the %(functionName)s function. Expected %(maxArgPossible)s maximum, but got %(nbrArgSupplied)s instead.",{functionName:s,maxArgPossible:o.maxArgPossible,nbrArgSupplied:t}));if(i>1){const e=t-n-i*Math.floor((t-n)/i)-o.nbrArgOptional;if(e>0)throw new ki(Go("Invalid number of arguments for the %(functionName)s function. Repeatable arguments should be supplied in groups of %(nbrArgRepeating)s, with up to %(nbrArgOptional)s optional. Got %(nbrValueRemaining)s too many.",{functionName:s,nbrArgRepeating:i,nbrArgOptional:o.nbrArgOptional,nbrValueRemaining:e}))}}(e);const i=[],n=jh(o,t.length);for(let e=0;e<t.length;e++){const s=o.args[n(e)??-1],r=t[e],a=s.type||[],l=a.includes("META")||a.includes("RANGE<META>"),c=a.some((e=>mC(e)));i.push(m(r,l,c))}return i}function m(e,t=!1,s=!1){const i=new nC(a);if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&t)throw new ki(Go("Argument must be a reference to a cell or range."));switch(e.debug&&(i.append("debugger;"),i.append('ctx["debug"] = true;')),e.type){case"BOOLEAN":return i.return(`{ value: ${e.value} }`);case"NUMBER":return i.return(`this.literalValues.numbers[${c++}]`);case"STRING":return i.return(`this.literalValues.strings[${l++}]`);case"REFERENCE":return i.return(`${e.value.includes(":")||s?"range":"ref"}(deps[${h++}], ${t?"true":"false"})`);case"FUNCALL":const n=p(e).map((e=>e.assignResultToVariable()));i.append(...n);const r=e.value.toUpperCase();return i.return(`ctx['${r}'](${n.map((e=>e.returnExpression))})`);case"UNARY_OPERATION":{const t=dC[e.value],s=m(e.operand,!1,!1).assignResultToVariable();return i.append(s),i.return(`ctx['${t}'](${s.returnExpression})`)}case"BIN_OPERATION":{const t=hC[e.value],s=m(e.left,!1,!1).assignResultToVariable(),o=m(e.right,!1,!1).assignResultToVariable();return i.append(s),i.append(o),i.return(`ctx['${t}'](${s.returnExpression}, ${o.returnExpression})`)}case"SYMBOL":const a=o.indexOf(e.value);return i.return(`getSymbolValue(this.symbols[${a}])`);case"EMPTY":return i.return("undefined")}}uC[i]=g}const n={execute:uC[i],dependencies:t,literalValues:s,symbols:o,tokens:e,isBadExpression:!1,normalizedFormula:i};return n}(e)}catch(t){return{tokens:e,dependencies:[],execute:function(){return t},isBadExpression:!0,normalizedFormula:e.map((e=>e.value)).join("")}}}function mC(e){return e.startsWith("RANGE")}const fC=JS.content;function vC(e){try{return 0===Cv(bv(e)).filter((e=>"FUNCALL"===e.type&&!fC[e.value.toUpperCase()]?.isExported)).length}catch(e){return!1}}function bC(e,t){if(!e.some((e=>"SYMBOL"===e.type&&t.includes(e.value.toUpperCase()))))return[];let s;try{s=bv(e)}catch{return[]}return function(e,t){return Cv(e).filter((e=>"FUNCALL"===e.type&&t.includes(e.value.toUpperCase()))).map((e=>({functionName:e.value.toUpperCase(),args:e.args})))}(s,t)}function SC(e,t,s){if(!t.startsWith("="))return t;const o=av(t);for(let t=1;t<o.length;t++){if("REFERENCE"!==o[t].type)continue;const i=o[t].value,n=CC(e,i,s);i!==n&&(o[t]={value:n,type:"REFERENCE"})}return mt(o.map((e=>e.value)))}function CC(e,t,s){const o=na(t).sheetName;if(o?!ua(o,s.sheetName.old):e!==s.sheetId)return t;const i=function(e,t){if(!ea.test(e))return ma(e);return pa({xc:e,sheetId:t},yC)}(t,o?s.sheetId:e);if(i.invalidXc)return t;const n=s.applyChange(i);return"NONE"===n.changeType||"REMOVE"===n.changeType?t:ba(n.range,e,function(e){return t=>t===e.sheetId?e.sheetName.current:""}(s))}function yC(e){return{numberOfRows:Number.MAX_SAFE_INTEGER,numberOfCols:Number.MAX_SAFE_INTEGER}}const IC="x1",wC="xMovingAverage",EC={exponential:"exp",logarithmic:"log",polynomial:"poly",trailingMovingAverage:"movingAvg"};function RC(e,t,s,o){let i=!1;const n=[];for(const o in s){let r=s[o];if(r.labelCell){const e=AC(r.labelCell,t);r.labelCell!==e&&(i=!0,r={...r,labelCell:e})}const a=AC(r.dataRange,t);void 0===a||e.getRangeString(a,a.sheetId)===Mi.InvalidReference?(i=!0,r=void 0):a!==r.dataRange&&(i=!0,r={...r,dataRange:a}),n[o]=r}let r=o;const a=AC(r,t);a!==r&&(i=!0,r=a);return{isStale:i,dataSets:n.filter(ut),labelRange:r}}function xC(e,t,s){return s.map((s=>({dataRange:Sa(e,t,s.dataRange),labelCell:s.labelCell?Sa(e,t,s.labelCell):void 0})))}function TC(e,t,s){return s?Sa(e,t,s):void 0}function AC(e,t){if(!e)return;const s=t(e);switch(s.changeType){case"NONE":return e;case"REMOVE":return;default:return s.range}}function DC(e,t,s,o){const i=[];for(const n of t){const t=e.getRangeFromSheetXC(s,n.dataRange),{unboundedZone:r,sheetId:a,invalidSheetName:l,invalidXc:c}=t;if(!l&&!c)if(r.left!==r.right&&r.top!==r.bottom){if(void 0===r.right)continue;for(let t=r.left;t<=r.right;t++){const s={...r,left:t,right:t};i.push({..._C(e,a,s,o?{top:s.top,bottom:s.top,left:s.left,right:s.left}:void 0),backgroundColor:n.backgroundColor,rightYAxis:"y1"===n.yAxisId,customLabel:n.label,trend:n.trend})}}else i.push({..._C(e,a,r,o?{top:r.top,bottom:r.top,left:r.left,right:r.left}:void 0),backgroundColor:n.backgroundColor,rightYAxis:"y1"===n.yAxisId,customLabel:n.label,trend:n.trend})}return i}function _C(e,t,s,o){if(s.left!==s.right&&s.top!==s.bottom)throw new Error(`Zone should be a single column or row: ${Ss(s)}`);if(o){const i=Ss(s),n=Ss(o);return{labelCell:e.getRangeFromSheetXC(t,n),dataRange:e.getRangeFromSheetXC(t,i)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,Ss(s))}}function FC(e,t){const s=t.labelCell?.zone;let o=t.dataRange.zone;if(s){const{numberOfRows:e,numberOfCols:t}=Fs(o);1===e?o={...o,left:o.left+1}:1===t&&(o={...o,top:o.top+1})}const i=ga({...t.dataRange,zone:o},e.getSheetSize);let n,r={};return t.customLabel?r={text:t.customLabel}:t.labelCell&&(r={reference:e.getRangeString(t.labelCell,"forceSheetReference",{useBoundedReference:!0})}),t.trend?.type&&(n={type:"polynomial"===t.trend.type&&1===t.trend.order?"linear":EC[t.trend.type],color:t.trend.color,order:t.trend.order?Math.min(t.trend.order,6):void 0,window:t.trend.window||De}),{label:r,range:e.getRangeString(i,"forceSheetReference",{useBoundedReference:!0}),backgroundColor:t.backgroundColor,rightYAxis:t.rightYAxis,trend:n}}function OC(e,t,s){if(!t)return;const o={...t.zone};s&&t.zone.bottom>t.zone.top&&(o.top=o.top+1);const i=ga({...t,zone:o},e.getSheetSize);return e.getRangeString(i,"forceSheetReference",{useBoundedReference:!0})}function PC(e,t,s){let o;if(t.labelRange){const i=CC(e,t.labelRange,s);i!==Mi.InvalidReference&&(o=i)}const i=[];for(const o of t.dataSets){const t={...o},n=CC(e,o.dataRange,s);n!==Mi.InvalidReference&&(t.dataRange=n,i.push(t))}return{...t,dataSets:i,labelRange:o}}function MC(e){return e&&ho(e)<.3?"#FFFFFF":"#000000"}function NC(e){return e&&ho(e)<.3?"#C8C8C8":"#666666"}function LC(e){if(e.dataSets){const t=void 0!==e.dataSets.find((e=>!ea.test(e.dataRange)));if(t)return"InvalidDataSet";if(e.dataSets.map((e=>ps(e.dataRange))).some((e=>e.top!==e.bottom&&zs(e))))return"InvalidDataSet"}return"Success"}function kC(e){if(e.labelRange){if(!ea.test(e.labelRange||""))return"InvalidLabelRange"}return"Success"}function VC(e,t,s){if(!s)return!1;if(!e)return!1;if(!t)return!0;const o=Gs(t.dataRange.zone);return!(Gs(e.zone)<o)}function UC(e){let t=!1,s=!1;if("horizontal"in e&&e.horizontal)return{useLeftAxis:!0,useRightAxis:!1};for(const o of e.dataSets||[])"y1"===o.yAxisId?s=!0:t=!0;return t||=!s,{useLeftAxis:t,useRightAxis:s}}function HC(e,t,s=!1){return(o,i)=>{const n=e?.[i];return zC({format:n,locale:t},s)(o)}}function zC(e,t=!1){return s=>{if(s=Number(s),isNaN(s))return s;const{locale:o,format:i}=e;return WC(t?wr({value:s,format:i},o):or(s,{locale:o,format:!i&&Math.abs(s)>=1e3?"#,##":i}))}}const BC=[{value:"left",label:Go("Left")},{value:"right",label:Go("Right")}];function GC(e,t){const s=[],o=kt(t.map((e=>e.data.length)));for(let t=0;t<=o;t++)s.push(e.next());return s}function WC(e,t=Ie){return e?e.length>t?e.substring(0,t)+"…":e:""}function $C(e){return e===IC||e===wC}const qC={id:"chartShowValuesPlugin",afterDatasetsDraw(e,t,s){if(!s.showValues)return;const o=e._metasets?.[0]?.data;if(!o)return;const i=e.ctx;switch(i.save(),i.textAlign="center",i.textBaseline="middle",i.miterLimit=1,e.config.type){case"pie":case"doughnut":!function(e,t,s){for(const o of e._metasets)for(let e=0;e<o._parsed.length;e++){const i=Number(o._parsed[e]);if(isNaN(i)||0===i)continue;const n=o.data[e],{startAngle:r,endAngle:a,innerRadius:l,outerRadius:c}=n,h=(r+a)/2,d=(l+c)/2,u=n.x+d*Math.cos(h),g=n.y+d*Math.sin(h),p=t.callback(i,o,e),m=12,f=La(s,p,{fontSize:m},"px"),v=c-l;if(f>=v||v<m)continue;const b=a-r,S=2*d*Math.tan(b/2);b<Math.PI/2&&(f>=S||S<m)||(s.fillStyle=MC(t.background),s.strokeStyle=t.background||"#ffffff",ZC(p,u,g,s))}}(e,s,i);break;case"bar":case"line":case"radar":s.horizontal?jC(e,s,i):function(e,t,s){const o=e.chartArea.bottom,i=e.chartArea.top,n={};for(const r of e._metasets){if($C(r.xAxisID)||r.hidden)continue;const a=e.scales[r.yAxisID];for(let l=0;l<r._parsed.length;l++){const c=r._parsed[l],h=Number("radar"===e.config.type?c.r:c.y);if(isNaN(h))continue;const d=r.data[l],u=d.x;let g=0;if("line"===e.config.type||"radar"===e.config.type)g=h<0?d.y+10:d.y-10;else{const e=a.getPixelForValue(0),t=12;g=Math.abs(e-d.y)<t?h<0?e+t/2:e-t/2:h<0?d.y-d.height/2:d.y+d.height/2}g=Math.min(g,o),g=Math.max(g,i),n[u]||(n[u]=[]);for(const e of n[u]||[])Math.abs(e-g)<13&&(g=h<0?e+13:e-13);n[u].push(g),s.fillStyle=d.options.backgroundColor,s.strokeStyle=t.background||"#ffffff";ZC(t.callback(Number(h),r,l),u,g,s)}}}(e,s,i);break;case"funnel":jC(e,s,i)}i.restore()}};function ZC(e,t,s,o){o.lineWidth=3,o.strokeText(e,t,s),o.lineWidth=1,o.fillText(e,t,s)}function jC(e,t,s){const o=e.chartArea.right,i=e.chartArea.left,n={};for(const r of e._metasets){if($C(r.xAxisID))return;const a=e.scales[r.xAxisID].getPixelForValue(0);for(let e=0;e<r._parsed.length;e++){const l=Number(r._parsed[e].x);if(isNaN(l))continue;const c=t.callback(l,r,e),h=r.data[e],d=h.y,u=La(s,c,{fontSize:12},"px"),g=3;let p;Math.abs(h.x-a)<u?p=l<0?a-u/2-g:a+u/2+g:(p=l<0?h.x+h.width/2:h.x-h.width/2,p=Math.min(p,o),p=Math.max(p,i)),n[d]||(n[d]=[]);for(const e of n[d])Math.abs(e-p)<u&&(p=l<0?e-u-g:e+u+g);n[d].push(p),s.fillStyle=h.options.backgroundColor,s.strokeStyle=t.background||"#ffffff",ZC(c,p,d,s)}}}const YC={showHeaders:!0,headerDesign:{align:"center",fillColor:"#808080",bold:!0,fontSize:15},showValues:!0,showLabels:!0,valuesDesign:{align:"left",verticalAlign:"bottom",fontSize:12},coloringOptions:{type:"categoryColor",colors:[],useValueBasedGradient:!0}},XC="nullValue";function KC(e,t){const{dataSetsValues:s}=t,o=[],i=my(e,s.length),n=[];for(const r in s){let{label:a,data:l,hidden:c}=s[r];a=e.dataSets?.[r].label||a;const h=i.next(),d={label:a,data:l,hidden:c,borderColor:e.background||M,borderWidth:e.stacked?1:0,backgroundColor:h,yAxisID:e.horizontal?"y":e.dataSets?.[r].yAxisId||"y",xAxisID:"x"};o.push(d);const u=e.dataSets?.[r].trend,g=t.trendDataSetsValues?.[r];u?.display&&!e.horizontal&&g&&n.push(gy(d,u,g))}return o.push(...n),o}function JC(e,t){const{dataSetsValues:s,labels:o}=t,i=e.negativeValuesColor||z,n=e.positiveValuesColor||H,r=e.subTotalValuesColor||B,a=[],l=[],c={label:"",data:l,backgroundColor:a},h=[];let d=0;for(const t of s)if(!t.hidden){for(let c=0;c<t.data.length;c++){const u=t.data[c];if(h.push(o[c]),isNaN(Number(u))){l.push([d,d]),a.push("");continue}l.push([d,u+d]);let g=u>=0?n:i;0===c&&t===s[0]&&e.firstValueAsSubtotal&&(g=r),a.push(g),d+=u}e.showSubTotals&&(h.push(Go("Subtotal")),l.push([0,d]),a.push(r))}return{datasets:[c],labels:h}}function QC(e,t){const{dataSetsValues:s,axisType:o,labels:i}=t,n=[],r=!!e.fillArea,a=!!e.stacked,l=[],c=my(e,s.length);for(let h=0;h<s.length;h++){let{label:d,data:u,hidden:g}=s[h];d=e.dataSets?.[h].label||d;const p=c.next();o&&["linear","time"].includes(o)&&(u=u.map(((e,t)=>({x:i[t]||void 0,y:e}))));const m={label:d,data:u,hidden:g,tension:0,borderColor:p,backgroundColor:r?So(p,Te):p,pointBackgroundColor:p,fill:!!r&&py(h,a),pointRadius:e.hideDataMarkers?0:Ae,yAxisID:e.dataSets?.[h].yAxisId||"y"};n.push(m);const f=e.dataSets?.[h].trend,v=t.trendDataSetsValues?.[h];f?.display&&v&&l.push(gy(m,f,v))}return n.push(...l),n}function ey(e,t){const s=QC(e,t);for(const e of s)$C(e.xAxisID)||(e.showLine=!1);return s}function ty(e,t){const{dataSetsValues:s}=t,o=[],i=Math.max(0,...s.map((e=>e?.data?.length??0))),n=GC(new Oo(i),s);for(const{label:t,data:i,hidden:r}of s){if(r)continue;const s={label:t,data:i,borderColor:e.background||"#FFFFFF",backgroundColor:n,hoverOffset:10};o.push(s)}return o}function sy(e,t){const{dataSetsValues:s}=t,o=[],i=my(e,s.length),n=[];for(let r=0;r<s.length;r++){let{label:a,data:l,hidden:c}=s[r];a=e.dataSets?.[r].label||a;const h=e.dataSets?.[r],d=i.next(),u=h?.type??"line",g={label:a,data:l,hidden:c,borderColor:d,backgroundColor:d,yAxisID:e.dataSets?.[r].yAxisId||"y",xAxisID:"x",type:u,order:"bar"===u?s.length+r:r,pointRadius:e.hideDataMarkers?0:Ae};o.push(g);const p=e.dataSets?.[r].trend,m=t.trendDataSetsValues?.[r];p?.display&&m&&n.push(gy(g,p,m))}return o.push(...n),o}function oy(e,t){const{dataSetsValues:s}=t,o=[],i=e.fillArea??!1,n=my(e,s.length);for(let t=0;t<s.length;t++){let{label:r,data:a,hidden:l}=s[t];e.dataSets?.[t]?.label&&(r=e.dataSets[t].label);const c=n.next(),h={label:r,data:a,hidden:l,borderColor:c,backgroundColor:c,pointRadius:e.hideDataMarkers?0:Ae};i&&(h.backgroundColor=So(c,Te),h.fill="start"),o.push(h)}return o}function iy(e,t){const{availableRegions:s,dataSetsValues:o,labels:i}=t,n=e.region||s[0]?.id,r=n?t.getGeoJsonFeatures(n):void 0,a={outline:r,showOutline:!!r,data:[]};if(r&&n){const e={};if(o[0])for(let s=0;s<o[0].data.length;s++){if(!i[s]||void 0===o[0].data[s])continue;const r=t.geoFeatureNameToId(n,i[s]);r&&(e[r]={value:o[0].data[s],label:i[s]})}for(const t of r)t.id&&a.data.push({feature:{...t,properties:{name:e[t.id]?.label}},value:e[t.id]?.value})}return[a]}function ny(e,t){const s=t.dataSetsValues[0],o=t.labels;if(!s)return[];let{label:i,data:n}=s;i=e.dataSets?.[0].label||i;return[{label:i,data:n.map((e=>e<=0?[0,0]:[-e,e])),backgroundColor:ry(o,e.funnelColors),yAxisID:"y",xAxisID:"x",barPercentage:1,categoryPercentage:1,borderColor:e.background||M,borderWidth:3}]}function ry(e,t){const s=new Oo(e.length,t);return e.map((()=>s.next()))}function ay(e,t){const{dataSetsValues:s,labels:o}=t,i=hy(ly(s,o)),n=i[0]||[],r=new Oo(n.length,e.groupColors||[]),a=n.map((e=>({label:e.label,color:r.next()}))),l=[];for(let t=i.length-1;t>=0;t--){const s={groupColors:a,parsing:{key:"value"},data:i[t],borderColor:t=>{const s="data"===t.type?t.raw:void 0;return s&&s.label!==XC?e.background||M:U},backgroundColor:e=>{const t="data"===e.type?e.raw:void 0;if(!t||t.label===XC)return U;const s=t.groups[0];return a.find((e=>e.label===s))?.color},hoverOffset:10};l.push(s)}return l}function ly(e,t){const s=function(e,t){const s=[],o=Math.max(...e.map((e=>e.data.length)));for(let i=0;i<o;i++){s[i]={};for(let t=0;t<e.length;t++){const o=null===e[t].data[i]?XC:String(e[t].data[i]);s[i][t]=o}s[i].value=Number(t[i])}return s}(e,t);return cy(s,0,e.length,[])}function cy(e,t,s,o){if(t>=s)return[];const i=Object.groupBy(e,(e=>e[t]));return Object.keys(i).map((e=>{const n=i[e]?.reduce(((e,t)=>e+Number(t.value)),0)||0,r=[...o,e];return{label:e,value:n,children:cy(i[e]||[],t+1,s,[...o,e]),groups:r,depth:t}})).sort(((e,t)=>t.value-e.value))}function hy(e){const t=[],s=[...e];for(;s.length>0;){const e=s.shift();e&&(t[e.depth]||(t[e.depth]=[]),t[e.depth].push(e),e.children&&s.push(...e.children))}return t}function dy(e,t){const{dataSetsValues:s,labels:o,locale:i,axisFormats:n}=t,r={locale:i,format:n?.y};if(0===s.length)return[];const a=ly(s,o).sort(((e,t)=>t.value-e.value)),l=function(e,t){const s="categoryColor"===e.coloringOptions?.type?e.coloringOptions.colors:[],o=new Oo(t.length,s);return t.map((e=>({label:e.label,color:o.next()})))}(e,a),c=[],h=Math.max(...s.map((e=>e.data.length)));for(let e=0;e<h;e++){c[e]={};for(let t=0;t<s.length;t++)c[e][t]=s[t].data[e]?String(s[t].data[e]):void 0;c[e].value=Number(o[e])}const d=e.showLabels??YC.showLabels,u=e.showValues??YC.showValues,g=e.coloringOptions||YC.coloringOptions;let p;"colorScale"===g?.type&&(p=function(e,t){const s=hy(e),o=s[s.length-1],i=Math.min(...o.map((e=>e.value))),n=Math.max(...o.map((e=>e.value)));if(Number.isFinite(i)&&Number.isFinite(n)){const e=[{value:i,color:t.minColor}];if(t.midColor){const s=(i+n)/2;e.push({value:s,color:t.midColor})}return e.push({value:n,color:t.maxColor}),No(e)}return}(a,g));const m=[{data:[],tree:c,labels:{display:d||u,overflow:"hidden",...uy(e.valuesDesign,YC.valuesDesign),formatter:e=>[d?e.raw.g:void 0,u?or(e.raw.v,r):void 0].filter(ut)},captions:{display:e.showHeaders??YC.showHeaders,padding:6,...uy(e.headerDesign,YC.headerDesign)},key:"value",groups:Je(0,s.length).map((e=>String(e))),borderWidth:0,spacing:1,displayMode:"headerBoxes",groupColors:l,backgroundColor:t=>{if("data"!==t.type)return"transparent";if(!t.raw.isLeaf)return e.headerDesign?.fillColor||YC.headerDesign?.fillColor;if("colorScale"===g.type)return p?.(t.raw.v)||"#FF0000";if("categoryColor"===g.type)return function(e,t,s,o){const i=e.raw._data.children[0][0],n=o.find((e=>e.label===i))?.color;if(!n||!s.useValueBasedGradient)return n||"#FF0000";const r=t.find((e=>e.label===i));if(!r||!r.children.length)return n;const a=hy(r.children),l=a[a.length-1],c=Math.max(...l.map((e=>e.value))),h=Math.min(...l.map((e=>e.value)));if(h===c||!isFinite(h)||!isFinite(c))return n;const d=Number(e.raw.v)||0,u=(d-c)/(h-c)*.5;return Co(n,u)}(t,a,g,l);throw new Error("Unsupported coloring option type}")}}];return m}function uy(e,t){const s=e=>ho(e.element.options.backgroundColor)>.7?"#666666":"#FFFFFF";return{align:e?.align??t?.align,position:e?.verticalAlign??t?.verticalAlign,color:e?.color||s,hoverColor:e?.color||s,font:{weight:e?.bold??t?.bold?"bold":"normal",style:e?.italic??t?.italic?"italic":"normal",size:e?.fontSize??t?.fontSize}}}function gy(e,t,s){const o=go(e.backgroundColor);o.a=1;const i=t.color||Co(uo(o),.5);return{type:"line",xAxisID:"trailingMovingAverage"===t.type?wC:IC,yAxisID:e.yAxisID,label:e.label?Go("Trend line for %s",e.label):"",data:s,order:-1,showLine:!0,pointRadius:0,backgroundColor:i,borderColor:i,borderDash:[5,5],borderWidth:void 0,fill:!1,pointBackgroundColor:i}}function py(e,t){return t?0===e?"origin":"-1":"origin"}function my(e,t){return new Oo(t,e.dataSets?.map((e=>e.backgroundColor))||[])}const fy={id:"sunburstHoverPlugin",afterEvent(e,t,s){if(!s.enabled)return;const o=e.getActiveElements();let i=o.map((e=>({datasetIndex:e.datasetIndex,index:e.index})));for(const t of o){const s=e.data.datasets[t.datasetIndex].data[t.index];for(let t=0;t<e.data.datasets.length;t++){const o=e.data.datasets[t];for(let e=0;e<o.data.length;e++){const n=o.data[e];vy(s.groups,n.groups)&&i.push({datasetIndex:t,index:e})}}}i=i.filter((t=>{const{datasetIndex:s,index:o}=t;return e.data.datasets[s].data[o].label!==XC})),e.setActiveElements(i);for(const t of e.getSortedVisibleDatasetMetas())for(const e of t.data){const t=e.$context,{datasetIndex:s,index:o,dataset:n,raw:r}=t;if(r.label===XC)continue;const a="function"==typeof n.backgroundColor?n.backgroundColor(t):n.backgroundColor;i.length&&!i.some((e=>e.datasetIndex===s&&e.index===o))?e.options.backgroundColor=Co(a,.5):e.options.backgroundColor=a}}};function vy(e,t){return t.length>e.length&&e.every(((e,s)=>e===t[s]))}const by={id:"sunburstLabelsPlugin",afterDatasetsDraw(e,t,s){if(!s.showValues&&!s.showLabels||"doughnut"!==e.config.type)return;!function(e,t,s){const o=t.style,i=o.fontSize||13,n=i+3;for(const r of e._metasets)for(let a=0;a<r._dataset.data.length;a++){const l=r._dataset.data[a];if(l.label===XC)continue;const c=[t.showLabels?l.label:void 0,t.showValues?t.callback(l.value,"y"):void 0].filter(ut),h=r.data[a];let{startAngle:d,endAngle:u,innerRadius:g,outerRadius:p,circumference:m}=h;const f=h.options.offset/4,v=f*(1-Math.sin(Math.min(Math.PI,m||0)));g+=v,p+=v;const b=(d+u)/2,S=(g+p)/2,C=.9*(p-g),y=u-d;if((y>=Math.PI?p:Math.sin(y/2)*g*2)<c.length*n)continue;s.save();const I={x:Math.cos(b)*f,y:Math.sin(b)*f},w=e.chartArea.left+e.chartArea.width/2+I.x,E=e.chartArea.top+e.chartArea.height/2+I.y;let R;s.translate(w,E),b>Math.PI/2?(s.rotate(b-Math.PI),R=-S):(R=S,s.rotate(b));const x=ho(h.options.backgroundColor)>.7?"#666666":"#FFFFFF";s.fillStyle=o.textColor||x,s.textAlign="center",s.textBaseline="middle",s.font=Ma(i,o.bold,o.italic);const T=-(c.length-1)*n/2;for(let e=0;e<c.length;e++){const t=Ya(s,C,c[e],o,"px");s.fillText(t,R,T+e*n)}s.restore()}}(e,s,e.ctx)}};const Sy={id:"waterfallLinesPlugin",beforeDraw(e,t,s){if(!s.showConnectorLines)return;const o=e._metasets?.[0]?.data;if(!o)return;const i=e.ctx;i.save(),i.setLineDash([3,2]);for(let e=0;e<o.length;e++){const t=o[e];if(0===t.height)continue;const s=yy(o,e);if(!s)break;const n=Cy(t),r=Cy(s),a=t.$context.raw,l=a[1]-a[0],c=Math.round(l<0?n.bottom-1:n.top),h=Math.round(n.right),d=Math.round(r.left);i.strokeStyle="#999",i.beginPath(),i.moveTo(h+1,c+.5),i.lineTo(d,c+.5),i.stroke()}i.restore()}};function Cy(e){const t=e.base<e.y;return{left:e.x-e.width/2,right:e.x+e.width/2,bottom:t?e.base+e.height:e.y+e.height,top:t?e.base:e.y}}function yy(e,t){return e.find(((e,s)=>s>t&&0!==e.height))}vh.add("chartShowValuesPlugin",{register:e=>e.register(qC),unregister:e=>e.unregister(qC)}),vh.add("waterfallLinesPlugin",{register:e=>e.register(Sy),unregister:e=>e.unregister(Sy)}),vh.add("funnelController",{register:e=>e.register(Ch()),unregister:e=>e.unregister(Ch())}),vh.add("funnelElement",{register:e=>e.register(yh()),unregister:e=>e.unregister(yh())}),vh.add("funnelTooltipPositioner",{register:e=>e.Tooltip.positioners.funnelTooltipPositioner=wh,unregister:e=>e.Tooltip.positioners.funnelTooltipPositioner=void 0}),vh.add("sunburstLabelsPlugin",{register:e=>e.register(by),unregister:e=>e.unregister(by)}),vh.add("sunburstHoverPlugin",{register:e=>e.register(fy),unregister:e=>e.unregister(fy)});class Iy extends t.Component{static template="o-spreadsheet-ChartJsComponent";static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=t.useRef("graphContainer");chart;currentRuntime;animationStore;currentDevicePixelRatio=window.devicePixelRatio;get background(){return this.chartRuntime.background}get canvasStyle(){return`background-color: ${this.background}`}get chartRuntime(){const e=this.env.model.getters.getChartRuntime(this.props.chartId);if(!("chartJsConfig"in e))throw new Error("Unsupported chart runtime");return e}setup(){this.shouldAnimate&&(this.animationStore=rh(Sh)),t.onMounted((()=>{bh();const e=this.chartRuntime;this.currentRuntime=e,this.createChart(qe(e))})),t.onWillUnmount(this.unmount.bind(this)),t.useEffect((()=>{const e=this.chartRuntime;e!==this.currentRuntime?(e.chartJsConfig.type!==this.currentRuntime.chartJsConfig.type?(this.chart?.destroy(),this.createChart(qe(e))):this.updateChartJs(qe(e)),this.currentRuntime=e):this.currentDevicePixelRatio!==window.devicePixelRatio&&(this.currentDevicePixelRatio=window.devicePixelRatio,this.updateChartJs(qe(this.currentRuntime)))}))}unmount(){this.chart?.destroy()}get shouldAnimate(){return this.env.model.getters.isDashboard()}createChart(e){let t=e.chartJsConfig;if(this.shouldAnimate&&this.animationStore){const e=this.env.model.getters.getChart(this.props.chartId)?.type;e&&this.animationStore.animationPlayed[this.animationChartId]!==e&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}const s=this.canvas.el.getContext("2d");this.chart=new window.Chart(s,t)}updateChartJs(e){let t=e.chartJsConfig;if(this.shouldAnimate){const e=this.env.model.getters.getChart(this.props.chartId)?.type;e&&this.hasChartDataChanged()&&this.animationStore&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}t.data&&t.data.datasets?(this.chart.data=t.data,t.options?.plugins?.title&&(this.chart.config.options.plugins.title=t.options.plugins.title)):this.chart.data.datasets=[],this.chart.config.options=t.options,this.chart.update()}hasChartDataChanged(){return!St(this.currentRuntime.chartJsConfig.data,this.chartRuntime.chartJsConfig.data)}enableAnimationInChartData(e){return{...e,options:{...e.options,animation:{animateRotate:!0}}}}get animationChartId(){return this.props.isFullScreen?this.props.chartId+"-fullscreen":this.props.chartId}}class wy{sheetId;title;getters;humanize;constructor(e,t,s){this.title=e.title,this.sheetId=t,this.getters=s,this.humanize=e.humanize??!0}static validateChartDefinition(e,t){throw new Error("This method should be implemented by sub class")}static transformDefinition(e,t,s){throw new Error("This method should be implemented by sub class")}static getDefinitionFromContextCreation(e){throw new Error("This method should be implemented by sub class")}getCommonDataSetAttributesForExcel(e,t,s){return{dataSets:t.map((e=>FC(this.getters,e))).filter((e=>""!==e.range&&e.range!==Mi.InvalidReference)),labelRange:OC(this.getters,e,s)}}}function Ey(e,t,s,o,i){if("text"===t||"progress"===t||e?.type!==r.number||s?.type!==r.number)return;const n=s.value-e.value;return n>0?o:n<0?i:void 0}function Ry(e,t,s){if("text"===s||e?.type!==r.number||t?.type!==r.number)return"neutral";const o=t.value-e.value;return o>0?"up":o<0?"down":"neutral"}function xy(e){return e.keyValue&&!ea.test(e.keyValue)?"InvalidScorecardKeyValue":"Success"}function Ty(e){return e.baseline&&!ea.test(e.baseline)?"InvalidScorecardBaseline":"Success"}const Ay=new window.Path2D("M8.6 4.8a.5.5 0 0 1 0 .75l-3.9 3.9a.5 .5 0 0 1 -.75 0l-3.8 -3.9a.5 .5 0 0 1 0 -.75l.4-.4a.5.5 0 0 1 .75 0l2.3 2.4v-5.7c0-.25.25-.5.5-.5h.6c.25 0 .5.25.5.5v5.8l2.3 -2.4a.5.5 0 0 1 .75 0z"),Dy=new window.Path2D("M8.7 5.5a.5.5 0 0 0 0-.75l-3.8-4a.5.5 0 0 0-.75 0l-3.8 4a.5.5 0 0 0 0 .75l.4.4a.5.5 0 0 0 .75 0l2.3-2.4v5.8c0 .25.25.5.5.5h.6c.25 0 .5-.25.5-.5v-5.8l2.2 2.4a.5.5 0 0 0 .75 0z");let _y=class e extends wy{keyValue;keyDescr;baseline;baselineMode;baselineDescr;progressBar=!1;background;baselineColorUp;baselineColorDown;fontColor;humanize;type="scorecard";constructor(e,t,s){super(e,t,s),this.keyValue=Ca(s,t,e.keyValue),this.keyDescr=e.keyDescr,this.baseline=Ca(s,t,e.baseline),this.baselineMode=e.baselineMode,this.baselineDescr=e.baselineDescr,this.background=e.background,this.baselineColorUp=e.baselineColorUp??Re,this.baselineColorDown=e.baselineColorDown??xe,this.humanize=e.humanize??!0}static validateChartDefinition(e,t){return e.checkValidations(t,xy,Ty)}static getDefinitionFromContextCreation(e){return{background:e.background,type:"scorecard",keyValue:e.range?e.range[0].dataRange:void 0,title:e.title||{text:""},baselineMode:Ee,baselineColorUp:Re,baselineColorDown:xe,baseline:e.auxiliaryRange||"",humanize:e.humanize}}static transformDefinition(e,t,s){let o,i;if(t.baseline){const i=CC(e,t.baseline,s);i!==Mi.InvalidReference&&(o=i)}if(t.keyValue){const o=CC(e,t.keyValue,s);o!==Mi.InvalidReference&&(i=o)}return{...t,baseline:o,keyValue:i}}duplicateInDuplicatedSheet(t){const s=TC(this.sheetId,t,this.baseline),o=TC(this.sheetId,t,this.keyValue),i=this.getDefinitionWithSpecificRanges(s,o,t);return new e(i,t,this.getters)}copyInSheetId(t){const s=this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,t);return new e(s,t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue)}getContextCreation(){return{...this,range:this.keyValue?[{dataRange:this.getters.getRangeString(this.keyValue,this.sheetId)}]:void 0,auxiliaryRange:this.baseline?this.getters.getRangeString(this.baseline,this.sheetId):void 0}}getDefinitionWithSpecificRanges(e,t,s){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:"scorecard",background:this.background,baseline:e?this.getters.getRangeString(e,s||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,s||this.sheetId):void 0,keyDescr:this.keyDescr,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(t){const s=AC(this.baseline,t),o=AC(this.keyValue,t);if(this.baseline===s&&this.keyValue===o)return this;const i=this.getDefinitionWithSpecificRanges(s,o);return new e(i,this.sheetId,this.getters)}};function Fy(e,t){const s=t.getContext("2d"),o=window.devicePixelRatio||1;t.width=o*e.canvas.width,t.height=o*e.canvas.height,s.scale(o,o);const i=e.canvas.width-Y;if(s.fillStyle=e.canvas.backgroundColor,s.fillRect(0,0,e.canvas.width,e.canvas.height),e.title){s.font=e.title.style.font,s.fillStyle=e.title.style.color;const t=s.textBaseline;s.textBaseline="middle",s.fillText(Za(s,e.title.text,i-e.title.position.x),e.title.position.x,e.title.position.y),s.textBaseline=t}if(e.baseline&&(s.font=e.baseline.style.font,s.fillStyle=e.baseline.style.color,ja(s,e.baseline.text,e.baseline.position,e.baseline.style.underline,e.baseline.style.strikethrough)),e.baselineArrow&&e.baselineArrow.style.size>0){s.save(),s.fillStyle=e.baselineArrow.style.color,s.translate(e.baselineArrow.position.x,e.baselineArrow.position.y);const t=e.baselineArrow.style.size/10;switch(s.scale(t,t),e.baselineArrow.direction){case"down":s.fill(Ay);break;case"up":s.fill(Dy)}s.restore()}if(e.baselineDescr){const t=e.baselineDescr;s.font=t.style.font,s.fillStyle=t.style.color,s.fillText(Za(s,t.text,i-t.position.x),t.position.x,t.position.y)}if(e.key&&(s.font=e.key.style.font,s.fillStyle=e.key.style.color,ja(s,Za(s,e.key.text,i-e.key.position.x),e.key.position,e.key.style.underline,e.key.style.strikethrough)),e.keyDescr){const t=e.keyDescr;s.font=e.keyDescr?.style.font??t.style.font,s.fillStyle=t.style.color,s.fillText(Za(s,t.text,i-t.position.x),t.position.x,t.position.y)}if(e.progressBar){if(s.fillStyle=e.progressBar.style.backgroundColor,s.beginPath(),s.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width,e.progressBar.dimension.height,e.progressBar.dimension.height/2),s.fill(),s.fillStyle=e.progressBar.style.color,s.beginPath(),e.progressBar.value>0)s.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width*Math.max(0,Math.min(1,e.progressBar.value)),e.progressBar.dimension.height,e.progressBar.dimension.height/2);else{const t=e.progressBar.dimension.width*Math.max(0,Math.min(1,-e.progressBar.value));s.roundRect(e.progressBar.position.x+e.progressBar.dimension.width-t,e.progressBar.position.y,t,e.progressBar.dimension.height,e.progressBar.dimension.height/2)}s.fill()}}function Oy(e,t){let s,o="";const i=t.getLocale();if(e.keyValue){const n={sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top};s=t.getEvaluatedCell(n),o=function(e,t,s){return e?t?wr(e,s):e.formattedValue??String(e.value??""):""}(s,e.humanize??!0,i)}let n;const a=e.baseline;if(a){const e={sheetId:a.sheetId,col:a.zone.left,row:a.zone.top};n=t.getEvaluatedCell(e)}const{background:l,fontColor:c}=t.getStyleOfSingleCellChart(e.background,e.keyValue),h=function(e,t,s,o,i){if(!e)return"";if("text"===s||t?.type!==r.number||e.type!==r.number)return o?wr(e,i):e.formattedValue;let{value:n,format:a}=e;return"progress"===s?(n=t.value/n,a="0.0%"):(n=Math.abs(t.value-n),"percentage"===s&&0!==n&&(n/=e.value),"percentage"===s&&(a="0.0%"),a||(n=Math.round(100*n)/100)),o?wr({value:n,format:a},i):or(n,{format:a,locale:i})}(n,s,e.baselineMode,e.humanize??!0,i),d="progress"===e.baselineMode&&_i(h,i)?Yi(h,i):0;return{title:{...e.title,text:e.title.text?t.dynamicTranslate(e.title.text):""},keyValue:o,keyDescr:e.keyDescr?.text?t.dynamicTranslate(e.keyDescr.text):"",baselineDisplay:h,baselineArrow:Ry(n,s,e.baselineMode),baselineColor:Ey(n,e.baselineMode,s,e.baselineColorUp,e.baselineColorDown),baselineDescr:"progress"!==e.baselineMode&&e.baselineDescr?.text?t.dynamicTranslate(e.baselineDescr.text):"",fontColor:c,background:l,baselineStyle:{..."percentage"!==e.baselineMode&&"progress"!==e.baselineMode&&a?t.getCellComputedStyle({sheetId:a.sheetId,col:a.zone.left,row:a.zone.top}):void 0,fontSize:e.baselineDescr?.fontSize,align:e.baselineDescr?.align},baselineDescrStyle:{textColor:e.baselineDescr?.color,...e.baselineDescr},keyValueStyle:{...e.keyValue?t.getCellComputedStyle({sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top}):void 0,fontSize:e.keyDescr?.fontSize,align:e.keyDescr?.align},keyValueDescrStyle:{textColor:e.keyDescr?.color,...e.keyDescr},progressBar:"progress"===e.baselineMode?{value:d,color:d>0?e.baselineColorUp:e.baselineColorDown}:void 0}}const Py=.05;function My(e,t){const s=e||"";return t&&s?" "+s:s}function Ny({width:e,height:t},s){return new Ly({width:e,height:t},s).computeDesign()}class Ly{runtime;context;width;height;constructor({width:e,height:t},s){this.runtime=s;const o=document.createElement("canvas");this.width=o.width=e,this.height=o.height=t,this.context=o.getContext("2d")}computeDesign(){const e={canvas:{width:this.width,height:this.height,backgroundColor:this.backgroundColor}},t=this.getTextStyles();let s=0;if(this.title){let o,i;switch(({height:s,width:i}=this.getFullTextDimensions(this.title,t.title.font)),this.runtime.title.align){case"center":o=(this.width-i)/2;break;case"right":o=this.width-i-Y;break;default:o=Y}e.title={text:this.title,style:t.title,position:{x:o,y:X+s/2}}}const o=t.baselineArrow?.size??0;let{height:i,width:n}=this.getTextDimensions(this.baseline,t.baselineValue.font);this.baseline||(i=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).height);const r=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).width;let a;switch(this.runtime.baselineStyle?.align){case"right":a=this.width-Y-r-n;break;case"left":a=Y+o;break;default:a=(this.width-n-r+o)/2}if(this.baseline&&(e.baseline={text:this.baseline,style:t.baselineValue,position:{x:a,y:this.keyValue?this.height*(1-Py*(this.runtime.progressBar?1:2)):this.height-(this.height-s-i)/2-X}},t.baselineArrow&&!this.runtime.progressBar&&(e.baselineArrow={direction:this.baselineArrow,style:t.baselineArrow,position:{x:e.baseline.position.x-o,y:e.baseline.position.y-(i+o)/2}})),e.baseline&&this.baselineDescr){const s={x:e.baseline.position.x+n,y:e.baseline.position.y};e.baselineDescr={text:this.baselineDescr,style:t.baselineDescr,position:s}}let l=0;this.runtime.progressBar&&(l=.05*this.height,e.progressBar={position:{x:2*Y,y:.9*this.height-i-l},dimension:{height:l,width:this.width-4*Y},value:this.runtime.progressBar.value,style:{color:this.runtime.progressBar.color,backgroundColor:this.secondaryFontColor}});const{width:c,height:h}=this.getFullTextDimensions(this.keyValue,t.keyValue.font),d=this.getTextDimensions(this.keyDescr,t.keyDescr.font).width;let u;switch(this.runtime.keyValueStyle?.align){case"right":u=this.width-Y-d-c;break;case"left":u=Y;break;default:u=(this.width-c-d)/2}if(this.keyValue&&(e.key={text:this.keyValue,style:t.keyValue,position:{x:Math.max(Y,u),y:.4*this.height+X/2+(s+h/2)/2}}),e.key&&this.keyDescr){const s={x:e.key.position.x+c,y:e.key.position.y};e.keyDescr={text:this.keyDescr,style:t.keyDescr,position:s}}return e}get title(){return this.runtime.title.text??""}get keyValue(){return this.runtime.keyValue}get keyDescr(){return My(this.runtime.keyDescr,this.keyValue)}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){return My(this.runtime.baselineDescr,this.baseline)}get baselineArrow(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get secondaryFontColor(){return NC(this.backgroundColor)}getTextDimensions(e,t){this.context.font=t;const s=this.context.measureText(e);return{width:s.width,height:s.actualBoundingBoxAscent+s.actualBoundingBoxDescent}}getFullTextDimensions(e,t){this.context.font=t;const s=this.context.measureText(e);return{width:s.width,height:s.fontBoundingBoxAscent+s.fontBoundingBoxDescent}}getTextStyles(){const e=this.runtime.keyValueStyle?.fontSize??32,t=Math.floor(.9*e);let s=this.runtime.baselineStyle?.fontSize??16;const o=Math.floor(.9*s);return this.runtime.progressBar&&(s/=1.5),{title:{font:Ma(this.runtime.title.fontSize??14,this.runtime.title.bold,this.runtime.title.italic),color:this.runtime.title.color??this.secondaryFontColor},keyValue:{color:this.runtime.keyValueStyle?.textColor||this.runtime.fontColor,font:Ma(e,this.runtime.keyValueStyle?.bold,this.runtime.keyValueStyle?.italic),strikethrough:this.runtime.keyValueStyle?.strikethrough,underline:this.runtime.keyValueStyle?.underline},keyDescr:{color:this.runtime.keyValueDescrStyle?.textColor||this.runtime.fontColor,font:Ma(t,this.runtime.keyValueDescrStyle?.bold,this.runtime.keyValueDescrStyle?.italic),strikethrough:this.runtime.keyValueDescrStyle?.strikethrough,underline:this.runtime.keyValueDescrStyle?.underline},baselineValue:{font:Ma(s,this.runtime.baselineStyle?.bold,this.runtime.baselineStyle?.italic),strikethrough:this.runtime.baselineStyle?.strikethrough,underline:this.runtime.baselineStyle?.underline,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor},baselineDescr:{font:Ma(o,this.runtime.baselineDescrStyle?.bold,this.runtime.baselineDescrStyle?.italic),strikethrough:this.runtime.baselineDescrStyle?.strikethrough,underline:this.runtime.baselineDescrStyle?.underline,color:this.runtime.baselineDescrStyle?.textColor??this.secondaryFontColor},baselineArrow:"neutral"===this.baselineArrow||this.runtime.progressBar?void 0:{size:this.keyValue?.8*s:0,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor}}}}class ky extends t.Component{static template="o-spreadsheet-ScorecardChart";static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=t.useRef("chartContainer");get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}get title(){const e=this.env.model.getters.getChartDefinition(this.props.chartId).title.text;return e?this.env.model.getters.dynamicTranslate(e):""}setup(){t.useEffect(this.createChart.bind(this),(()=>{const e=this.canvas.el.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]}))}createChart(){const e=this.canvas.el;Fy(Ny(e.getBoundingClientRect(),this.runtime),e)}}const Vy=/Mac/i,Uy=["Shift","Control","Alt","Meta"];function Hy(e,t){return!!e&&(!!t.target&&e.contains(t.target))}function zy(){const e=document.querySelector(".o-grid-overlay");if(e){const{top:t,left:s}=e.getBoundingClientRect();return{top:t,left:s}}throw new Error("Can't find spreadsheet position")}function By(e){return e.el?Gy(e.el):{x:0,y:0,width:0,height:0}}function Gy(e){const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*Wy(e){if(yield e,e.hasChildNodes())for(const t of e.childNodes)yield*Wy(t)}function $y(e){const{startElement:t,endElement:s,startSelectionOffset:o,endSelectionOffset:i}=function(e){const t=document.getSelection();return{startElement:t.anchorNode||e,startSelectionOffset:t.anchorOffset,endElement:t.focusNode||e,endSelectionOffset:t.focusOffset}}(e);return{start:qy(e,t,o),end:qy(e,s,i)}}function qy(e,t,s){let o=0;const i=Wy(e);let n=i.next(),r=!0;for(;!n.done&&n.value!==t;)n.value.hasChildNodes()||n.value.textContent&&(o+=n.value.textContent.length),("P"===n.value.nodeName||"DIV"===n.value.nodeName&&n.value!==e)&&(r?r=!1:o++),n=i.next();if(n.value!==t)return 0;if(n.value.hasChildNodes()){const e=[...n.value.childNodes].slice(0,s);o+=e.reduce(((t,s,o)=>{if(null!==s.textContent){let i=s.textContent.length;return"P"===s.nodeName&&o!==e.length-1&&i++,t+i}return t}),0)}else o+=s;return"P"!==t.nodeName||r||""!==t.textContent||o++,o}const Zy=/^[a-zA-Z]$/;function jy(e,t="key"){let s="";Uy.includes(e.key)||(Xy(e)&&(s+="Ctrl+"),e.altKey&&(s+="Alt+"),e.shiftKey&&(s+="Shift+"));const o="key"===t?e.key:e.code;return s+=Zy.test(o)?o.toUpperCase():o,s}function Yy(){return Boolean(Vy.test(navigator.userAgent))}function Xy(e){return Yy()||eI()?e.metaKey:e.ctrlKey}function Ky(e){return 1===e.button||Xy(e)&&0===e.button}function Jy(e,t){const s=document.createElement("a");s.href=e,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s)}function Qy(){return/Firefox/i.test(navigator.userAgent)}function eI(){return/(iPad|iPhone|iPod)/i.test(navigator.userAgent)||"MacIntel"===navigator.platform&&(navigator.maxTouchPoints||1)>1}function tI(){return/Android/i.test(navigator.userAgent)||eI()||/(webOS|BlackBerry|Windows Phone)/i.test(navigator.userAgent)}function sI(e){return 8===(e=ro(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}const oI=30,iI=10,nI=20,rI=12,aI=80,lI="#F3F2F1",cI=6,hI=25;function dI(e,t){const s=e.getBoundingClientRect(),o=window.devicePixelRatio||1;e.width=o*s.width,e.height=o*s.height;const i=e.getContext("2d");i.scale(o,o);const n=function(e,t,s){const o=t.maxValue,i=t.minValue,n=vI(t,"animated"),r=function(e,t){const s=t?hI:0,o=e.height-nI-s-iI,i=e.width-2*oI;let n,r;i>2*o?(n=2*o,r=o):(n=i,r=i/2);const a=s+iI+(o-r)/2;return{x:oI+(i-n)/2,y:a,width:n,height:r}}(e,t.title.text),a=r.width/6,l=n?(n-i.value)/(o.value-i.value):0,c={x:e.width/2,y:r.y+r.height-r.height/12};let h=aI;r.height<300&&(h*=r.height/300);const d=r.width/2,u=t.gaugeValue?.label||"-";La(s,u,{fontSize:h},"px")>d&&(h=function(e,t,s,o=.25){let i=1;if(s(i)>e)return i;if(s(t)<e)return t;let n=(i+t)/2,r=s(n),a=0;for(;Math.abs(r-e)>o&&a<20;)r>=e?t=(i+t)/2:i=(i+t)/2,n=(i+t)/2,r=s(n),a++;return n}(d,h,(e=>La(s,u,{fontSize:e},"px"))));const g={x:r.x+a/2,y:r.y+r.height+rI},p={x:r.x+r.width-a/2,y:r.y+r.height+rI},m=NC(t.background),f=function(e,t,s,o){const i=e.maxValue,n=e.minValue,r={x:t.x+t.width/2,y:t.y+t.height},a={fontSize:rI},l=[],c=[];for(const h of e.inflectionValues){const e=(h.value-n.value)/(i.value-n.value),d=La(o,h.label,a,"px"),u=Math.PI-Math.PI*e,g=fI(u,t.height+cI,r.x,r.y,d+2,rI),p=c.some((e=>mI(e,g)))?rI:0;c.push(g),l.push({rotation:u,label:h.label,fontSize:rI,color:s,offset:p})}return l}(t,r,m,s);let v=0,b=0,S=0;t.title.text&&({width:b,height:S}=Ua(s,t.title.text,{fontSize:J,...t.title},"px"));switch(t.title.align){case"right":v=e.width-b-Y;break;case"center":v=(e.width-b)/2;break;default:v=Y}return{width:e.width,height:e.height,title:{label:t.title.text??"",fontSize:t.title.fontSize??J,textPosition:{x:v,y:K+S/2},color:t.title.color??m,bold:t.title.bold,italic:t.title.italic},backgroundColor:t.background,gauge:{rect:r,arcWidth:a,percentage:Ke(l,0,1),color:uI(t)},inflectionValues:f,gaugeValue:{label:u,textPosition:c,fontSize:h,color:m},minLabel:{label:t.minValue.label,textPosition:g,fontSize:rI,color:m},maxLabel:{label:t.maxValue.label,textPosition:p,fontSize:rI,color:m}}}(s,t,i);!function(e,t){e.save(),e.fillStyle=t.backgroundColor,e.fillRect(0,0,t.width,t.height),e.restore()}(i,n),function(e,t){e.save();const s=t.gauge,o=s.rect.x+s.rect.width/2,i=s.rect.y+s.rect.height,n=s.rect.height-s.arcWidth/2;if(n<0)return;const r=1===s.percentage?0:Math.PI*(1+s.percentage);e.strokeStyle=lI,e.beginPath(),e.lineWidth=s.arcWidth,e.arc(o,i,n,r,0),e.stroke(),e.strokeStyle=s.color,e.beginPath(),e.arc(o,i,n,Math.PI,r),e.stroke(),e.restore()}(i,n),function(e,t){const{x:s,y:o,width:i,height:n}=t.gauge.rect;for(const r of t.inflectionValues){e.save(),e.translate(s+i/2-.5,o+n-.5),e.rotate(Math.PI/2-r.rotation),e.lineWidth=2,e.strokeStyle=NC(t.backgroundColor)+"aa",e.beginPath(),e.moveTo(0,-(n-t.gauge.arcWidth)),e.lineTo(0,-n-3),e.stroke(),e.textAlign="center",e.font=`${r.fontSize}px ${ve}`,e.fillStyle=r.color;const a=-n-cI-r.offset;e.fillText(r.label,0,a),e.restore()}}(i,n),function(e,t){for(const s of[t.minLabel,t.maxLabel,t.gaugeValue])e.save(),e.textAlign="center",e.fillStyle=s.color,e.font=`${s.fontSize}px ${ve}`,e.fillText(s.label,s.textPosition.x,s.textPosition.y),e.restore()}(i,n),function(e,t){e.save();const s=t.title;e.font=Ma(s.fontSize,s.bold,s.italic),e.textBaseline="middle",e.fillStyle=s.color,e.fillText(s.label,s.textPosition.x,s.textPosition.y),e.restore()}(i,n)}function uI(e){const t=vI(e,"final");if(void 0===t)return lI;for(let s=0;s<e.inflectionValues.length;s++){const o=e.inflectionValues[s];if("<"===o.operator&&t<o.value)return e.colors[s];if("<="===o.operator&&t<=o.value)return e.colors[s]}return e.colors.at(-1)}function gI(e){return[{start:e.topLeft,end:e.topRight},{start:e.topRight,end:e.bottomRight},{start:e.bottomRight,end:e.bottomLeft},{start:e.bottomLeft,end:e.topLeft}]}function pI(e,t){const s=e.start,o=e.end,i=t.start,n=t.end;function r(e,t,s){return(s.y-e.y)*(t.x-e.x)>(t.y-e.y)*(s.x-e.x)}return r(s,i,n)!==r(o,i,n)&&r(s,o,i)!==r(s,o,n)}function mI(e,t){const s=gI(e),o=gI(t);for(const e of s)for(const t of o)if(pI(e,t))return!0;return!1}function fI(e,t,s,o,i,n){const r=Math.cos(e),a=Math.sin(e),l=r*t,c=a*t,h=a*(i/2),d=r*(i/2),u=r*(t+n),g=a*(t+n);return{bottomLeft:{x:l-h+s,y:o-(c+d)},bottomRight:{x:l+h+s,y:o-(c-d)},topRight:{x:u+h+s,y:o-(g-d)},topLeft:{x:u-h+s,y:o-(g+d)}}}function vI(e,t){return"animated"===t&&void 0!==e.animationValue?e.animationValue:e.gaugeValue?.value}const bI={responsive:!0,maintainAspectRatio:!1,elements:{line:{fill:!1},point:{hitRadius:15}},animation:!1,events:["mousemove","mouseout","click","touchstart","touchmove","mouseup"]};function SI(e,t,s){const o=document.createElement("div");o.style.width=`${t.width}px`,o.style.height=`${t.height}px`;const i=document.createElement("canvas");let n;if(o.append(i),i.setAttribute("width",t.width.toString()),i.setAttribute("height",t.height.toString()),document.body.append(o),"chartJsConfig"in e){const t=qe(e.chartJsConfig);t.plugins=[yI];const s=new window.Chart(i,t);n=s.toBase64Image(),s.destroy()}else if("scorecard"===s){Fy(Ny(t,e),i),n=i.toDataURL()}else"gauge"===s&&(dI(i,e),n=i.toDataURL());return o.remove(),n}async function CI(e,t,s){const o=document.createElement("div");o.style.width=`${t.width}px`,o.style.height=`${t.height}px`,o.style.position="fixed",o.style.opacity="0";const i=document.createElement("canvas");o.append(i),i.setAttribute("width",t.width.toString()),i.setAttribute("height",t.height.toString()),document.body.append(o);let n=null;if("chartJsConfig"in e){const t=qe(e.chartJsConfig);t.plugins=[yI];const s=new window.Chart(i,t);n=await new Promise((e=>i.toBlob(e,"image/png"))),s.destroy()}else if("scorecard"===s){Fy(Ny(t,e),i),n=await new Promise((e=>i.toBlob(e,"image/png")))}else"gauge"===s&&(dI(i,e),n=await new Promise((e=>i.toBlob(e,"image/png"))));return o.remove(),n?new File([n],"chart.png",{type:"image/png"}):void 0}const yI={id:"customCanvasBackgroundColor",beforeDraw:e=>{const{ctx:t}=e;t.save(),t.globalCompositeOperation="destination-over",t.fillStyle="#ffffff",t.fillRect(0,0,e.width,e.height),t.restore()}},II={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},wI={inSeconds:function(e){return Math.floor(e/II.second)},inMinutes:function(e){return Math.floor(e/II.minute)},inHours:function(e){return Math.floor(e/II.hour)},inDays:function(e){return Math.floor(e/II.day)},inMonths:function(e){return Math.floor(e/II.month)},inYears:function(e){return Math.floor(e/II.year)}},EI=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function RI(e,t,s){const o=function(e){const t=e.indexOf("h");e=t>=0?e.slice(0,t).replace(/m/g,"M")+e.slice(t):e.replace(/m/g,"M");e.includes("a")||(e=e.replace(/h/g,"H"));return e}(t),i=function(e,t,s){const o=e.map((e=>mi(e,s)?.jsDate));if(o.some((e=>void 0===e))||e.length<2)return;const i=o.map((e=>e.getTime())),n=kt(i)-Vt(i),r=function(e){if(e.includes("s"))return"second";if(e.includes("m"))return"minute";if(e.includes("h")||e.includes("H"))return"hour";if(e.includes("d"))return"day";if(e.includes("M"))return"month";return"year"}(t);if(II.second>=II[r]&&wI.inSeconds(n)<180)return"second";if(II.minute>=II[r]&&wI.inMinutes(n)<180)return"minute";if(II.hour>=II[r]&&wI.inHours(n)<96)return"hour";if(II.day>=II[r]&&wI.inDays(n)<90)return"day";if(II.month>=II[r]&&wI.inMonths(n)<36)return"month";return"year"}(e,o,s),n={};return i&&(n[i]=o),{parser:o,displayFormats:n,unit:i??!1}}function xI(e,t,s,o){let i=$I(o,t,s).formattedValues,n=ZI(o,t);VC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=BI(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=GI(i,n));const r=qI(o,t,"left"),a=qI(o,t,"right"),l=e.horizontal?{x:r||a}:{y:r,y1:a},c=[];for(const t in n){const{data:s}=n[t],o=e.dataSets?.[t].trend;if(!o?.display||e.horizontal){c.push(void 0);continue}const i=MI(o,s);c.push(i)}return{dataSetsValues:n,trendDataSetsValues:c,axisFormats:l,labels:i,locale:o.getLocale(),topPadding:YI(e,o)}}function TI(e,t,s,o){const i=xI(e,t.slice(0,2),s,o),n=i.dataSetsValues.filter((e=>!e.hidden)),r=[];if(n[0]){const e=n[0].data.map((e=>e>0?e:0));r.push({...n[0],data:e})}if(n[1]){const e=n[1].data.map((e=>e>0?-e:0));r.push({...n[1],data:e})}return{...i,dataSetsValues:r}}function AI(e,t,s,o){const i=function(e,t,s,o){if(function(e,t,s,o){return!e.labelsAsText&&VI(e,t,s,o)}(e,t,s,o)&&function(){if(!window.Chart)return!1;const e="luxon"===new window.Chart._adapters._date({})._id;e||HI||(HI=!0,console.warn("'chartjs-adapter-luxon' time adapter is not installed. Time scale axes are disabled."));return e}())return"time";if(function(e,t,s,o){return!e.labelsAsText&&UI(e,t,s,o)}(e,t,s,o))return"linear";return"category"}(e,t,s,o),n=$I(o,t,s);let r="linear"===i?n.values:n.formattedValues,a=ZI(o,t);const l=VC(s,t[0],e.dataSetsHaveTitle||!1);l&&r.shift(),({labels:r,dataSetsValues:a}=BI(r,a)),"time"===i&&({labels:r,dataSetsValues:a}=function(e,t){if(0===e.length||e.every((e=>!e)))return{labels:e,dataSetsValues:t};const s=[...e],o=qe(t);for(let e=0;e<s.length;e++)if(!s[e]){s[e]=vt(s,e);for(const t of o)t.data[e]=void 0}return{labels:s,dataSetsValues:o}}(r,a)),e.aggregated&&({labels:r,dataSetsValues:a}=GI(r,a)),e.cumulative&&(a=jI(a,"asc"));const c={y:qI(o,t,"left"),y1:qI(o,t,"right"),x:WI(o,s,l)},h=[];for(const t in a){const s=e.dataSets?.[t].trend;if(!s?.display){h.push(void 0);continue}const{data:n}=a[t];h.push(NI(s,n,r,i,o.getLocale()))}return{dataSetsValues:a,axisFormats:c,labels:r,locale:o.getLocale(),trendDataSetsValues:h,axisType:i,topPadding:YI(e,o)}}function DI(e,t,s,o){let i=$I(o,t,s).formattedValues,n=ZI(o,t);VC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=BI(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=GI(i,n)),({dataSetsValues:n,labels:i}=function(e,t){const s=Math.max(e.length,...t.map((e=>e.data?.length||0))),o=Je(0,s).filter((e=>t.some((t=>"number"==typeof t.data[e]&&t.data[e]>0))));return{labels:o.map((t=>e[t]||"")),dataSetsValues:t.map((e=>({...e,data:o.map((t=>"number"==typeof e.data[t]&&e.data[t]>0?e.data[t]:null))})))}}(i,n));return{dataSetsValues:n,axisFormats:{y:qI(o,t,"left")},labels:i,locale:o.getLocale(),topPadding:YI(e,o)}}function _I(e,t,s,o){let i=$I(o,t,s).formattedValues,n=ZI(o,t);VC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=BI(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=GI(i,n));return{dataSetsValues:n,axisFormats:{r:qI(o,t,"left")||qI(o,t,"right")},labels:i,locale:o.getLocale()}}function FI(e,t,s,o){const i=t.slice(0,1);let n=$I(o,i,s).formattedValues;VC(s,i[0],e.dataSetsHaveTitle||!1)&&n.shift();let r=ZI(o,i);({labels:n,dataSetsValues:r}=GI(n,r));return{dataSetsValues:r,axisFormats:{y:qI(o,i,"left")||qI(o,i,"right")},labels:n,locale:o.getLocale(),availableRegions:o.getGeoChartAvailableRegions(),geoFeatureNameToId:o.geoFeatureNameToId,getGeoJsonFeatures:o.getGeoJsonFeatures}}function OI(e,t,s,o){let i=$I(o,t,s).formattedValues,n=ZI(o,t);VC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=BI(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=GI(i,n)),e.cumulative&&(n=jI(n,"desc"));return{dataSetsValues:n,axisFormats:{x:qI(o,t,"left")||qI(o,t,"right")},labels:i,locale:o.getLocale()}}function PI(e,t,s,o){let i=$I(o,t,s).values,n=function(e,t){t=t.filter((t=>!e.isColHidden(t.dataRange.sheetId,t.dataRange.zone.left)));const s=t.map((()=>({data:[],label:""}))),o=t.map((t=>zI(e,t)));if(!o.length)return s;const i=Math.min(...o.map((e=>e.length)));let n=[];const r=t.length-1;for(let e=0;e<i;e++)for(let t=0;t<o.length;t++){let i=o[t][e];null==i&&t!==r&&(i=n[t]),i!==n[t]&&(n=n.slice(0,t),n[t]=i),s[t].data.push(i??null)}return s.filter((e=>e.data.some((e=>null!==e))))}(o,t);const r=VC(s,t[0],e.dataSetsHaveTitle||!1);return r&&i.shift(),({labels:i,dataSetsValues:n}=function(e,t){const s=[],o=[];for(let t=0;t<e.length;t++)Number(e[t])<=0?o.push(t):Number(e[t])>0&&s.push(t);const i=s.length?s:o;return{labels:i.map((t=>e[t])),dataSetsValues:t.map((e=>({...e,data:i.map((t=>e.data[t]))})))}}(i,n)),({labels:i,dataSetsValues:n}=function(e,t){const s=Math.max(e.length,...t.map((e=>e.data?.length||0))),o=e=>null==e||""===e,i=Je(0,s).filter((s=>{const i=t.map((e=>e.data?.[s]));if(o(i[0]))return!1;let n=!1;for(const e of i)if(n||=o(e),n&&!o(e))return!1;return e[s]&&!isNaN(Number(e[s]))}));return{labels:i.map((t=>e[t])),dataSetsValues:t.map((e=>({...e,data:i.map((t=>e.data[t]))})))}}(i,n)),{dataSetsValues:n,axisFormats:{y:WI(o,s,r)},labels:i,locale:o.getLocale()}}function MI(e,t){const s=[],o=[],i=[];for(let e=0;e<t.length;e++)"number"==typeof t[e]&&(s.push(t[e]),o.push(e+1)),i.push(e+1);const n=LI(e,s,o,Je(.5,i.length+.55,.2));return n.length?n:void 0}function NI(e,t,s,o,i){const n=[],r=[],a=[],l=t.length;if(l<2)return;switch(o){case"category":for(let e=0;e<l;e++)"number"==typeof t[e]&&(n.push(t[e]),r.push(e+1)),a.push(e+1);break;case"linear":for(let e=0;e<t.length;e++){const o=Number(s[e]);isNaN(o)||("number"==typeof t[e]&&(n.push(t[e]),r.push(o)),a.push(o))}break;case"time":for(let e=0;e<t.length;e++){const o=Yi({value:s[e]},i);null!==t[e]&&(n.push(t[e]),r.push(o)),a.push(o)}}const c=Math.min(...a),h=Math.max(...a);if(h===c)return;const d=(h-c)/(5*a.length),u=LI(e,n,r,Je(c,h+d/2,d));return u.length?u:void 0}function LI(e,t,s,o){if(t.length<2||s.length<2||0===o.length)return[];const{normalizedLabels:i,normalizedNewLabels:n}=function(e,t,s){let o=[],i=[];if("logarithmic"===s.type){const s=Math.max(...e.map(Math.abs));o=e.map((e=>e/s)),i=t.map((e=>e/s))}else{const s=Math.max(...e),n=Math.min(...e),r=s-n;o=e.map((e=>(e-s)/r)),i=t.map((e=>(e-s)/r))}return{normalizedLabels:o,normalizedNewLabels:i}}(s,o,e);try{switch(e.type){case"polynomial":{const s=e.order;if(!s)return o.map((e=>({x:e,y:NaN})));if(1===s)return cc([t],[i],[n],!0)[0].map(((e,t)=>({x:o[t],y:e})));const r=ic(t,i,s,!0).flat();return n.map(((e,t)=>({x:o[t],y:rc(r,e,s)})))}case"exponential":{const e=[],s=[];for(let o=0;o<t.length;o++)t[o]>0&&(e.push(Math.log(t[o])),s.push(i[o]));return s.length?ac(cc([e],[s],[n],!0))[0].map(((e,t)=>({x:o[t],y:e}))):o.map((e=>({x:e,y:NaN})))}case"logarithmic":return cc([t],lc([i]),lc([n]),!0)[0].map(((e,t)=>({x:o[t],y:e})));case"trailingMovingAverage":return function(e,t,s=De){const o=[];for(let e=0;e<s-1;e++)o.push({x:t[e],y:NaN});for(let i=0;i<=e.length-s;i++){let n=0;for(let t=i;t<i+s;t++)n+=e[t];o.push({x:t[i+s-1],y:n/s})}return o}(t,s,e.window);default:return o.map((e=>({x:e,y:NaN})))}}catch(e){return o.map((e=>({x:e,y:NaN})))}}function kI(e,t,s,o){return VI(e,t,s,o)||UI(e,t,s,o)}function VI(e,t,s,o){if(!s||!UI(e,t,s,o))return!1;const i=WI(o,s,VC(s,t[0],e.dataSetsHaveTitle||!1));return Boolean(i&&EI.test(i))}function UI(e,t,s,o){if(!s)return!1;const i=o.getRangeValues(s);return VC(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),!i.some((e=>isNaN(Number(e))&&e))&&!i.every((e=>!e))}let HI=!1;function zI(e,t){if(t.dataRange){const s=t.labelCell?[t.labelCell.zone]:[],o=ls([t.dataRange.zone],s)[0];if(void 0===o)return[];const i=e.getRangeFromZone(t.dataRange.sheetId,o);return e.getRangeValues(i).map((e=>""===e?void 0:e))}return[]}function BI(e,t){const s=Je(0,Math.max(e.length,...t.map((e=>e.data?.length||0)))).filter((s=>{const o=e[s],i=t.map((e=>e.data?.[s]));return o||i.some((e=>"number"==typeof e))}));return{labels:s.map((t=>e[t]||"")),dataSetsValues:t.map((e=>({...e,data:s.map((t=>"number"==typeof e.data[t]?e.data[t]:null))})))}}function GI(e,t){const s=new Set(e),o={};s.forEach((e=>{o[e]=new Array(t.length).fill(0)}));for(const s of Je(0,e.length)){const n=e[s];for(const e of Je(0,t.length))o[n][e]+="number"==typeof(i=t[e].data[s])?i:0}var i;return{labels:Array.from(s),dataSetsValues:t.map(((e,t)=>({...e,data:Array.from(s).map((e=>o[e][t]))})))}}function WI(e,t,s){if(!t)return;const{sheetId:o,zone:i}=t,n=Ms(i).map((t=>e.getEvaluatedCell({sheetId:o,...t}).format));return s&&n.shift(),n.find((e=>void 0!==e))}function $I(e,t,s){let o={values:[],formattedValues:[]};if(s){const{left:i}=s.zone;if(s.invalidXc||s.invalidSheetName||e.isColHidden(s.sheetId,i)){if(t[0]){o={formattedValues:Je(0,zI(e,t[0]).length).map((e=>e.toString())),values:o.formattedValues}}}else o={formattedValues:e.getRangeFormattedValues(s),values:e.getRangeValues(s).map((e=>String(e??"")))}}else if(1===t.length){const s=zI(e,t[0]).length;for(let e=0;e<s;e++)o.formattedValues.push(""),o.values.push("")}else if(t[0]){o={formattedValues:Je(0,zI(e,t[0]).length).map((e=>e.toString())),values:o.formattedValues}}return o}function qI(e,t,s){const o=t.filter((e=>"right"===s==!!e.rightYAxis));for(const t of o){const s=e.getRangeFormats(t.dataRange).find((e=>void 0!==e&&!ur(e)));if(s)return s}}function ZI(e,t){const s=[];for(const[o,i]of Object.entries(t)){let t=`${eb.Series} ${parseInt(o)+1}`,n=e.isColHidden(i.dataRange.sheetId,i.dataRange.zone.left);if(i.labelCell){const{sheetId:s,zone:o}=i.labelCell,n=e.getEvaluatedCell({sheetId:s,col:o.left,row:o.top});n&&(t=n.formattedValue)}let r=i.dataRange?zI(e,i):[];r.every((e=>!e||"string"==typeof e&&!qi(e)))&&r.filter((e=>"string"==typeof e)).length>1?r=r.map((e=>e&&!qi(e)?1:null)):r.every((e=>null==e||!_i(e.toString(),w)))&&(n=!0),s.push({data:r,label:t,hidden:n})}return s}function jI(e,t){return e.map((e=>{const s=[];let o=0;const i="asc"===t?Object.keys(e.data):Object.keys(e.data).reverse();for(const t of i)isNaN(parseFloat(e.data[t]))?s[t]=e.data[t]:(o+=parseFloat(e.data[t]),s[t]=o);return{...e,data:s}}))}function YI(e,t){const{title:s,legendPosition:o}=e,i=s&&s.text||"top"===o;return t.isDashboard()&&!i?30:0}function XI(e,t){return{padding:{left:Y,right:Y,top:Math.max(K,t.topPadding||0),bottom:X}}}function KI(e,t){return{display:"none"!==e.legendPosition,position:"none"!==e.legendPosition?e.legendPosition:void 0}}function JI(e,t){return{...rw,...KI(e),...aw(MC(e.background),{pointStyle:"rect",lineWidth:3})}}function QI(e,t){const s=e.fillArea,o=s?"rect":"line",i=s?2:3;return{...rw,...KI(e),...aw(MC(e.background),{pointStyle:o,lineWidth:i})}}function ew(e,t){const{dataSetsValues:s}=t,o=Math.max(0,...s.map((e=>e?.data?.length??0))),i=GC(new Oo(o),s),n=MC(e.background);return{...KI(e),labels:{usePointStyle:!0,generateLabels:e=>(e.data.labels?.map(((e,t)=>({text:WC(String(e)),strokeStyle:i[t],fillStyle:i[t],pointStyle:"rect",lineWidth:2,fontColor:n})))||[]).filter((e=>e.text)),filter:(e,t)=>!("datasetIndex"in e)||!t.datasets[e.datasetIndex].hidden}}}function tw(e,t){return{...rw,...KI(e),...aw(MC(e.background),{pointStyle:"circle",strokeStyle:e.background||"#ffffff",lineWidth:8})}}function sw(e,t){return{...rw,...KI(e),...aw(MC(e.background),{lineWidth:3})}}function ow(e,t){const s=MC(e.background),o=e.negativeValuesColor||z,i=e.positiveValuesColor||H,n=e.subTotalValuesColor||B;return{...KI(e),labels:{usePointStyle:!0,generateLabels:()=>{const t=[{text:Go("Positive values"),fontColor:s,fillStyle:i,strokeStyle:i,pointStyle:"rect"},{text:Go("Negative values"),fontColor:s,fillStyle:o,strokeStyle:o,pointStyle:"rect"}];return(e.showSubTotals||e.firstValueAsSubtotal)&&t.push({text:Go("Subtotals"),fontColor:s,fillStyle:n,strokeStyle:n,pointStyle:"rect"}),t},filter:(e,t)=>!("datasetIndex"in e)||!t.datasets[e.datasetIndex].hidden},onClick:()=>{}}}function iw(e,t){const s=e.fillArea??!1,o=s?"rect":"line",i=s?2:3;return{...rw,...KI(e),...aw(MC(e.background),{pointStyle:o,lineWidth:i})}}function nw(e,t){const s=MC(e.background);return{...KI(e),labels:{usePointStyle:!0,generateLabels:e=>{const t=e.data.datasets.at(-1);if(!t)return[];return t.groupColors.map((({color:e,label:t})=>({text:WC(t),fontColor:s,fillStyle:e,strokeStyle:e,pointStyle:"rect"})))}}}}const rw={onHover:e=>{const t=e.native?.target;t&&(t.style.cursor="pointer")},onLeave:e=>{const t=e.native?.target;t&&(t.style.cursor="default")},onClick:(e,t,s)=>{if("click"!==e.type)return;const o=t.datasetIndex;s.legendItems&&void 0!==o&&(s.chart.isDatasetVisible(o)?s.chart.hide(o):s.chart.show(o),e.native.preventDefault(),e.native.stopPropagation())}};function aw(e,t){return{labels:{color:e,usePointStyle:!0,generateLabels:s=>s.data.datasets.map(((o,i)=>$C(o.xAxisID)?{text:WC(o.label),fontColor:e,strokeStyle:o.borderColor,hidden:!s.isDatasetVisible(i),pointStyle:"line",datasetIndex:i,lineWidth:3}:{text:WC(o.label),fontColor:e,strokeStyle:o.borderColor,fillStyle:o.backgroundColor,hidden:!s.isDatasetVisible(i),pointStyle:"line"===o.type?"line":"rect",datasetIndex:i,...t})).filter((e=>e.text)),filter:(e,t)=>!("datasetIndex"in e)||!t.datasets[e.datasetIndex].hidden}}}function lw(e,t){let s={};const{trendDataSetsValues:o,locale:i,axisFormats:n}=t,r={stacked:e.stacked,locale:i};if(e.horizontal)s.x=bw(e,"bottom","values",{...r,format:n?.x}),s.y=bw(e,"left","labels",r);else{s.x=bw(e,"bottom","labels",r);const t={...r,format:n?.y};s.y=bw(e,"left","values",t);const o={...r,format:n?.y1};s.y1=bw(e,"right","values",o)}if(s=wt(s),o&&o.length&&o.some(ut)){const e=Math.max(...o.map((e=>e?.length||0)));s[IC]={...s.x,labels:Array(e).fill(""),offset:!1,display:!1},s[wC]={...s.x,offset:!0,display:!1}}return s}function cw(e,t){const{locale:s,axisType:o,trendDataSetsValues:i,labels:n,axisFormats:r}=t,a=r?.x,l=e.stacked;let c={x:bw(e,"bottom","labels",{locale:s}),y:bw(e,"left","values",{locale:s,stacked:l,format:r?.y}),y1:bw(e,"right","values",{locale:s,stacked:l,format:r?.y1})};if(c=wt(c),"time"===o&&n&&a){const e={type:"time",time:RI(n,a,s)};Object.assign(c.x,e),c.x.ticks.maxTicksLimit=15}else"linear"===o&&(c.x.type="linear",c.x.ticks.callback=e.humanize?e=>wr({value:e,format:a},s):e=>or(e,{format:a,locale:s}));if(i&&i.length&&i.some(ut)&&(c[IC]={...c.x,display:!1},c[wC]={...c.x,display:!1},"category"===o||"time"===o)){const e=Math.max(...i.map((e=>e?.length||0)));c[IC].type="category",c[IC].labels=Je(0,e).map((e=>e.toString())),c[IC].offset=!1,c[wC].type="category",c[wC].offset=!1}return c}function hw(e,t){const s=cw(e,t);return{...s,x:{...s.x,grid:{display:!0}}}}function dw(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;e.dataSets;const n={x:{...bw(e,"bottom","labels",{locale:s}),grid:{display:!1}},y:{position:e.verticalAxisPosition,ticks:{color:MC(e.background),callback:zC({locale:s,format:i},e.humanize)},grid:{lineWidth:e=>0===e.tick.value?2:1},title:vw(e.axesDesign?.y)}},r=n?.y||n?.y1;return r&&(r.grid={lineWidth:e=>0===e.tick.value?2:1}),n}function uw(e,t){const{dataSetsValues:s}=t,o=lw(e,t),i=o.x.ticks.callback;o.x.ticks.callback=e=>i(Math.abs(e));const n=Math.max(...s.map((e=>Math.max(...e.data.map(Math.abs)))));return o.x.suggestedMin=-n,o.x.suggestedMax=n,o}function gw(e,t){const{locale:s,axisFormats:o,dataSetsValues:i}=t,n=Math.min(...i.map((e=>Math.min(...e.data.filter((e=>!isNaN(e)))))));return{r:{beginAtZero:!0,ticks:{callback:zC({format:o?.r,locale:s},e.humanize),backdropColor:e.background||"#FFFFFF"},pointLabels:{color:MC(e.background),callback:e=>WC(e)},suggestedMin:n<0?n-1:0}}}function pw(e,t){const{locale:s,axisFormats:o,availableRegions:i}=t,n=function(e){switch(e){case"top":return"top-left";case"right":return"top-right";case"bottom":return"bottom-right";case"left":case"none":return"bottom-left"}}(e.legendPosition),r=e.region?i.find((t=>t.id===e.region)):i[0],a=o?.y||o?.y1;return{projection:{projection:fw(r?.defaultProjection||"mercator"),axis:"x"},color:{axis:"x",display:"none"!==e.legendPosition,border:{color:W},grid:{color:W},ticks:{color:MC(e.background),callback:zC({locale:s,format:a},e.humanize)},legend:{position:n,align:n.includes("right")?"left":"right",margin:Cw(e)},interpolate:Sw(e),missing:e.missingValueColor||"#ffffff"}}}function mw(e,t){const s=t.dataSetsValues[0];return{x:{display:!1},y:{grid:{offset:!1},ticks:{callback:function(e){return WC(this.getLabelForValue(e))}},border:{display:!1}},percentages:{position:"right",border:{display:!1},ticks:{callback:function(e,o,i){const n=s.data?.[o],r=s.data?.[0];return r&&void 0!==n?or(n/r,{format:"0%",locale:t.locale}):""}},grid:{display:!1}}}}function fw(e){return"conicConformal"===e?window.ChartGeo.geoConicConformal().rotate([100,0]):e}function vw(e){if(e?.title?.text){const{text:t,color:s,align:o,italic:i,bold:n}=e.title;return{display:!0,text:t,color:s,font:{style:i?"italic":"normal",weight:n?"bold":"normal",size:e.title.fontSize??Q},align:"left"===o?"start":"right"===o?"end":"center"}}}function bw(e,t,s,o){const{useLeftAxis:i,useRightAxis:n}=UC(e);if("left"===t&&!i||"right"===t&&!n)return;const r=MC(e.background);let a;if(a="bottom"===t?e.axesDesign?.x:"left"===t?e.axesDesign?.y:e.axesDesign?.y1,"values"===s){const s=!("right"===t&&i);return{position:t,title:vw(a),grid:{display:s},beginAtZero:!0,stacked:o?.stacked,ticks:{color:r,callback:zC(o,e.humanize)}}}return{ticks:{padding:5,color:r,callback:function(e,t,s){return WC(this.getLabelForValue(e))}},grid:{display:!1},stacked:o?.stacked,title:vw(a)}}function Sw(e){if(!e.colorScale||"string"==typeof e.colorScale)return e.colorScale||"oranges";const t=[{value:0,color:e.colorScale.minColor}];return e.colorScale.midColor&&t.push({value:.5,color:e.colorScale.midColor}),t.push({value:1,color:e.colorScale.maxColor}),No(t)}function Cw(e){switch(e.legendPosition){case"top":case"right":return{top:!!e.title.text?K+30:K,left:Y,right:Y};case"bottom":case"left":case"none":return{left:Y,right:Y,bottom:X}}}const yw={showValues:!1,showLabels:!0,valuesDesign:{align:"center",fontSize:13}};function Iw(e,t){const{axisFormats:s,locale:o}=t;return{horizontal:"horizontal"in e&&e.horizontal,showValues:"showValues"in e&&!!e.showValues,background:e.background,callback:(t,i)=>{const n=function(e,t){if(t.rAxisID)return t.rAxisID;const s="horizontal"in e&&e.horizontal?t.xAxisID:t.yAxisID;return s||"y"}(e,i);return HC(s,o,e.humanize)(t,n)}}}function ww(e,t){const{axisFormats:s,locale:o}=t;return{callback:HC(s,o,e.humanize),showLabels:e.showLabels??yw.showLabels,showValues:e.showValues??yw.showValues,style:{fontSize:e.valuesDesign?.fontSize??yw.valuesDesign.fontSize,align:e.valuesDesign?.align??yw.valuesDesign.align,bold:e.valuesDesign?.bold??yw.valuesDesign.bold,italic:e.valuesDesign?.italic??yw.valuesDesign.italic,textColor:e.valuesDesign?.color??yw.valuesDesign.color}}}function Ew(e,t){const{axisFormats:s,locale:o}=t;return{horizontal:!0,showValues:"showValues"in e&&!!e.showValues,background:e.background,callback:(e,t)=>0===(e=Math.abs(Number(e)))?"":HC(s,o)(e,t.xAxisID||"x")}}function Rw(e,t){const{axisFormats:s,locale:o,dataSetsValues:i}=t,n=i.reduce(((e,t)=>(e.push((e.at(-1)||-1)+t.data.length+1),e)),[]);return{showValues:"showValues"in e&&!!e.showValues,background:e.background,callback:(t,i,r)=>{const a=i._dataset.data[r],l=a[1]-a[0];let c=l>=0?"+":"";return e.showSubTotals&&n.includes(r)&&"+"===c&&(c=""),`${c}${HC(s,o,e.humanize)(l,i.yAxisID)}`}}}function xw(e,t){const s=e.title,o=NC(e.background);return{display:!!s.text,text:s.text?t.dynamicTranslate(s.text):"",color:s?.color??o,align:"center"===s.align?"center":"right"===s.align?"end":"start",font:{size:e.title.fontSize??J,weight:s.bold?"bold":"normal",style:s.italic?"italic":"normal"},padding:{bottom:"top"===e.legendPosition?0:Y}}}const Tw='\n<templates>\n <t t-name="o-spreadsheet-CustomTooltip">\n <div\n class="o-chart-custom-tooltip border rounded px-2 py-1 pe-none mw-100 position-absolute text-nowrap shadow opacity-100">\n <table class="overflow-hidden m-0">\n <thead t-if="title">\n <tr>\n <th class="o-tooltip-title align-baseline border-0 text-truncate" t-esc="title" t-attf-style="max-width: {{ labelsMaxWidth }}"/>\n </tr>\n </thead>\n <tbody>\n <tr t-foreach="tooltipItems" t-as="tooltipItem" t-key="tooltipItem_index">\n <td>\n <span\n class="badge ps-2 py-2 rounded-0 align-middle"\n t-attf-style="background-color: {{ tooltipItem.boxColor }}"\n > </span>\n <small\n t-if="tooltipItem.label"\n class="o-tooltip-label d-inline-block text-truncate align-middle smaller ms-2"\n t-esc="tooltipItem.label"\n t-attf-style="max-width: {{ labelsMaxWidth }}"\n />\n </td>\n <td class="o-tooltip-value ps-2 fw-bolder text-end">\n <small class="smaller d-inline-block text-truncate align-middle" t-attf-style="max-width: {{ valuesMaxWidth }}">\n <t t-esc="tooltipItem.value"/>\n <t t-if="tooltipItem.percentage">\n (\n <t t-esc="tooltipItem.percentage"/>\n %)\n </t>\n </small>\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n </t>\n</templates>\n';let Aw;function Dw(e,s={}){return function(e,s={}){Aw||(Aw=new t.App(t.Component,{templates:Tw,translateFn:Go}));const o=Aw.getTemplate(e),i=o(s,{}),n=document.createElement("div");return t.blockDom.mount(i,n),n}(e,s).innerHTML}function _w(e,t){return{enabled:!1,external:Hw,callbacks:{title:function(e){return e.some((e=>!$C(e.dataset.xAxisID)))?void 0:""},beforeLabel:e=>e.dataset?.label||e.label,label:function(s){const o=e.horizontal;let i=o?s.parsed.x:s.parsed.y;null==i&&(i=s.parsed);const n=o?s.dataset.xAxisID:s.dataset.yAxisID;return HC(t.axisFormats,t.locale,e.humanize)(i,n)}}}}function Fw(e,t){const{axisType:s,locale:o,axisFormats:i}=t,n=i?.x,r={enabled:!1,external:Hw,callbacks:{}};return r.callbacks.label="linear"===s?t=>{const s=t.parsed.y;let r=$C(t.dataset.xAxisID)?"":t.parsed.x;"string"==typeof r&&_i(r,o)&&(r=Yi(r,o));const a=sr(r,n,o,e.humanize),l=t.dataset.yAxisID||"y",c=sr(s,i?.[l],o,e.humanize);return a?`(${a}, ${c})`:`${c}`}:function(t){const s=t.parsed.y,n=t.dataset.yAxisID;return HC(i,o,e.humanize)(s,n)},r.callbacks.beforeLabel=e=>e.dataset?.label||e.label,r.callbacks.title=function(e){return"linear"!==s&&e.some((e=>!$C(e.dataset.xAxisID)))?void 0:""},r}function Ow(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;return{enabled:!1,external:Hw,callbacks:{title:function(e){return e[0].dataset.label},beforeLabel:e=>e.label||e.dataset.label,label:function(t){const o=function(e,t){const s=e.filter((e=>"number"==typeof e)).reduce(((e,t)=>e+t),0);if(!s)return"";const o=e[t]/s*100;return o.toFixed(2)}(t.dataset.data,t.dataIndex),n=t.parsed.y??t.parsed;return`${sr(n,!i&&n>=1e3?"#,##":i,s,e.humanize)} (${o}%)`}}}}function Pw(e,t){const{dataSetsValues:s,locale:o,axisFormats:i,labels:n}=t,r=i?.y||i?.y1,a=s.map((e=>e.label));return{enabled:!1,external:Hw,callbacks:{beforeLabel:function(e){const t=n.length?Math.floor(e.dataIndex/n.length):0;return a[t]},label:function(t){const[s,i]=t.raw,n=i-s;return sr(n,!r&&Math.abs(n)>1e3?"#,##":r,o,e.humanize)}}}}function Mw(e,t){const s=_w(e,t);return{...s,callbacks:{...s.callbacks,label:e=>{const t={...e,parsed:{y:e.parsed.y,x:Math.abs(e.parsed.x)}};return(s?.callbacks?.label)(t)}}}}function Nw(e,t){const{locale:s,axisFormats:o}=t;return{enabled:!1,external:Hw,callbacks:{beforeLabel:e=>e.dataset?.label||e.label,label:function(t){return sr(t.parsed.r,o?.r,s,e.humanize)}}}}function Lw(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;return{enabled:!1,external:Hw,filter:function(e){return void 0!==e.raw.value},callbacks:{beforeLabel:e=>e.raw.feature.properties.name,label:function(t){const o=t.raw.value;return sr(o,!i&&Math.abs(o)>=1e3?"#,##":i,s,e.humanize)}}}}function kw(e,t){return{enabled:!1,external:Hw,position:"funnelTooltipPositioner",callbacks:{title:()=>"",beforeLabel:e=>e.label,label:function(s){const o=s.parsed.x,i=s.dataset.xAxisID;return HC(t.axisFormats,t.locale,e.humanize)(o,i)}}}}function Vw(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;return{enabled:!1,external:Hw,filter:function(e){const t=e.raw;return t?.label!==XC},callbacks:{title:()=>"",beforeLabel:e=>e.raw.groups.join(" / "),label:function(t){const o=t.raw.value;return sr(o,!i&&o>=1e3?"#,##":i,s,e.humanize)}}}}function Uw(e,t){const{locale:s,axisFormats:o}=t,i=o?.y;return{enabled:!1,external:Hw,filter:(e,t,s)=>t===s.length-1,callbacks:{title:()=>"",beforeLabel:e=>{const t=e.raw._data.children[0];if(!t)return"";const s=[];for(let o=0;o<=e.raw.l;o++)s.push(t[o]);return s.join(" / ")},label:t=>{const o=t.raw.v;return sr(o,!i&&o>=1e3?"#,##":i,s,e.humanize)}}}}function Hw({chart:e,tooltip:t}){if(e.canvas.parentNode.querySelector("div.o-chart-custom-tooltip")?.remove(),0===t.opacity||0===t.dataPoints.length)return;const s=t.body.map(((e,s)=>{let o=e.before[0],i=e.lines[0];i||(i=o,o="");const n=t.labelColors[s].backgroundColor;return{label:o,value:i,boxColor:"string"==typeof n?So(n,1):n}})),o=Dw("o-spreadsheet-CustomTooltip",{labelsMaxWidth:Math.floor(.5*e.canvas.clientWidth)+"px",valuesMaxWidth:Math.floor(.25*e.canvas.clientWidth)+"px",title:t.title[0],tooltipItems:s}),i=Object.assign(document.createElement("template"),{innerHTML:o}).content.firstChild;e.canvas.parentNode?.appendChild(i),Object.assign(i.style,{left:zw(e,t,i.clientWidth)+"px",top:Math.floor(t.caretY-i.clientHeight/2)+"px"})}function zw(e,t,s){const o=t.caretX;return o+s>e.chartArea.right?Math.max(0,o-s):o}var Bw=Object.freeze({__proto__:null,GHOST_SUNBURST_VALUE:XC,INTERACTIVE_LEGEND_CONFIG:rw,canChartParseLabels:kI,getBarChartData:xI,getBarChartDatasets:KC,getBarChartLegend:JI,getBarChartScales:lw,getBarChartTooltip:_w,getChartColorsGenerator:my,getChartLabelFormat:WI,getChartLayout:XI,getChartShowValues:Iw,getChartTitle:xw,getComboChartDatasets:sy,getComboChartLegend:sw,getData:zI,getFunnelChartData:OI,getFunnelChartDatasets:ny,getFunnelChartScales:mw,getFunnelChartTooltip:kw,getFunnelLabelColors:ry,getGeoChartData:FI,getGeoChartDatasets:iy,getGeoChartScales:pw,getGeoChartTooltip:Lw,getHierarchalChartData:PI,getLineChartData:AI,getLineChartDatasets:QC,getLineChartLegend:QI,getLineChartScales:cw,getLineChartTooltip:Fw,getPieChartData:DI,getPieChartDatasets:ty,getPieChartLegend:ew,getPieChartTooltip:Ow,getPyramidChartData:TI,getPyramidChartScales:uw,getPyramidChartShowValues:Ew,getPyramidChartTooltip:Mw,getRadarChartData:_I,getRadarChartDatasets:oy,getRadarChartLegend:iw,getRadarChartScales:gw,getRadarChartTooltip:Nw,getScatterChartDatasets:ey,getScatterChartLegend:tw,getScatterChartScales:hw,getSunburstChartDatasets:ay,getSunburstChartLegend:nw,getSunburstChartTooltip:Vw,getSunburstShowValues:ww,getTopPaddingForDashboard:YI,getTreeMapChartDatasets:dy,getTreeMapChartTooltip:Uw,getTrendDatasetForBarChart:MI,getTrendDatasetForLineChart:NI,getWaterfallChartLegend:ow,getWaterfallChartScales:dw,getWaterfallChartShowValues:Rw,getWaterfallChartTooltip:Pw,getWaterfallDatasetAndLabels:JC,makeDatasetsCumulative:jI});class Gw extends wy{dataSets;labelRange;background;legendPosition;stacked;aggregated;type="bar";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=DC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ca(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.axesDesign=e.axesDesign,this.horizontal=e.horizontal,this.showValues=e.showValues,this.zoomable=e.zoomable}static transformDefinition(e,t,s){return PC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,LC,kC)}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:"bar",labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,showValues:e.showValues,horizontal:e.horizontal,zoomable:e.zoomable,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=xC(this.sheetId,e,this.dataSets),s=TC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new Gw(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Gw(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:"bar",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,axesDesign:this.axesDesign,horizontal:this.horizontal,showValues:this.showValues,zoomable:this.horizontal?void 0:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,VC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:sI(this.background||M),fontColor:sI(MC(this.background)),dataSets:e,labelRange:t,verticalAxis:UC(s)}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=RC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new Gw(i,this.sheetId,this.getters)}}function Ww(e,t){const s=e.getDefinition(),o=xI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:KC(s,o)},options:{...bI,indexAxis:e.horizontal?"y":"x",layout:XI(0,o),scales:lw(s,o),plugins:{title:xw(s,t),legend:JI(s),tooltip:_w(s,o),chartShowValuesPlugin:Iw(s,o)}}},background:e.background||M}}const $w=[IC,wC],qw=["x",...$w];class Zw extends ph{mutators=["resetAxisLimits","updateAxisLimits","updateTrendLineConfiguration","clearAxisLimits"];originalAxisLimits={};currentAxesLimits={};idConversion={};handle(e){switch(e.type){case"DELETE_FIGURE":if(e.figureId&&this.idConversion[e.figureId])for(const t of this.idConversion[e.figureId])delete this.originalAxisLimits[t],delete this.currentAxesLimits[t];break;case"UPDATE_CHART":const t=`${e.definition.type}-${e.figureId}`;this.idConversion[e.figureId]||(this.idConversion[e.figureId]=new Set),this.idConversion[e.figureId].add(t),"zoomable"in e.definition&&e.definition.zoomable||this.clearAxisLimits(t)}}clearAxisLimits(e){return delete this.originalAxisLimits[e],delete this.currentAxesLimits[e],"noStateChange"}resetAxisLimits(e,t){for(const s of qw)t?.[s]?(this.originalAxisLimits[e]?.[s]||(this.originalAxisLimits[e]={...this.originalAxisLimits[e],[s]:{}}),this.originalAxisLimits[e][s].min=t[s].min,this.originalAxisLimits[e][s].max=t[s].max):this.originalAxisLimits[e]?.[s]&&delete this.originalAxisLimits[e][s];return"noStateChange"}updateAxisLimits(e,t){if(void 0===t)return delete this.currentAxesLimits[e],"noStateChange";let{min:s,max:o}=t;return s>o&&([s,o]=[o,s]),this.currentAxesLimits[e]={x:{min:s,max:o}},"noStateChange"}updateTrendLineConfiguration(e){if(!this.originalAxisLimits[e])return"noStateChange";const t=this.originalAxisLimits[e].x;if(void 0===t)return"noStateChange";for(const s of $w){if(!this.originalAxisLimits[e][s])continue;if(this.currentAxesLimits[e]?.[s]||(this.currentAxesLimits[e]={...this.currentAxesLimits[e],[s]:{}}),void 0===this.currentAxesLimits[e]?.x)return"noStateChange";const o=t.max-t.min,i=this.originalAxisLimits[e][s],n=(i.max-i.min)/o,r=i.min-t.min*n,a=this.currentAxesLimits[e].x.min,l=this.currentAxesLimits[e].x.max;this.currentAxesLimits[e][s].min=a*n+r,this.currentAxesLimits[e][s].max=l*n+r}return"noStateChange"}}const jw={id:"zoomWindowPlugin",afterDatasetsDraw:function(e,t,s){if(!s.getLowerBound||!s.getUpperBound)return;const{ctx:o,chartArea:{left:i,right:n,top:r,bottom:a}}=e;let l=s.getLowerBound()??i,c=s.getUpperBound()??n;l>c&&([l,c]=[c,l]),l=Math.max(i,l),c=Math.min(n,c),l===i&&(l-=1),c===n&&(c+=1),o.save(),o.fillStyle="rgba(255,255,255,0.5)",o.beginPath(),o.rect(i,a,l-i,r-a),o.rect(c,a,n-c,r-a),o.fill(),o.beginPath(),o.strokeStyle="#bbb",o.rect(l,a,c-l,r-a),o.stroke(),o.lineWidth=2,o.beginPath(),o.moveTo(l-3,(r+a)/2-7),o.lineTo(l-3,(r+a)/2+7),o.stroke(),o.beginPath(),o.moveTo(c+3,(r+a)/2-7),o.lineTo(c+3,(r+a)/2+7),o.stroke(),o.restore()}};vh.add("zoomWindowPlugin",{register:e=>e.register(jw),unregister:e=>e.unregister(jw)});class Yw extends Iy{static template="o-spreadsheet-ZoomableChartJsComponent";store;masterChartCanvas=t.useRef("masterChartCanvas");masterChart;mode;hasLinearScale;isBarChart;chartId="";datasetBoundaries={xMin:0,xMax:0};removeEventListeners=()=>{};setup(){this.store=rh(Zw),super.setup()}unmount(){super.unmount(),this.masterChart?.destroy(),this.removeEventListeners()}get containerStyle(){return`\n height:${this.sliceable?"calc(100% - 60px)":"100%"};\n `}get sliceable(){if(this.props.isFullScreen)return!0;const e=this.env.model.getters.getChartDefinition(this.props.chartId);return("zoomable"in e&&e?.zoomable)??!1}get axisOffset(){return!this.hasLinearScale&&this.isBarChart?.5:0}getMasterChartConfiguration(e){const t=e;return{...t,options:{...t.options,plugins:{...t.options.plugins,zoomWindowPlugin:{getLowerBound:()=>this.lowerBound,getUpperBound:()=>this.upperBound}}}}}getDetailChartConfiguration(e){if(!this.sliceable)return e;const t=this.store.currentAxesLimits[this.chartId]?.x,s={...e.options.scales?.x};return void 0!==t?.min&&(s.min=this.hasLinearScale?t.min:Math.ceil(t.min)-this.axisOffset),void 0!==t?.max&&(s.max=this.hasLinearScale?t.max:Math.floor(t.max)-this.axisOffset),{...e,options:{...e.options,scales:{...e.options.scales,x:s},layout:{...e.options.layout,padding:{...e.options.layout?.padding,bottom:5}}}}}getAxisLimitsFromDataset(e){const t=e.data.datasets.map((e=>e.data)).flat().map(((e,t)=>"object"==typeof e&&null!==e?e.x:t));return{xMin:Math.min(...t),xMax:Math.max(...t)}}createChart(e){const t=e.chartJsConfig;if(this.isBarChart="bar"===t.type,this.chartId=`${t.type}-${this.props.chartId}`,this.datasetBoundaries=this.getAxisLimitsFromDataset(t),this.sliceable){const s=this.getDetailChartConfiguration(t);e.chartJsConfig=s}if(super.createChart(e),this.hasLinearScale="linear"===this.chart?.scales?.x.type,!this.sliceable||!("masterChartConfig"in e))return;this.masterChart?.destroy();const s=this.masterChartCanvas.el.getContext("2d");this.masterChart=new window.Chart(s,this.getMasterChartConfiguration(e.masterChartConfig)),this.resetAxesLimits(),this.chart?.options&&(this.chart.options.animation=!1)}updateChartJs(e){const t=e.chartJsConfig,s=this.getAxisLimitsFromDataset(t);if(this.datasetBoundaries.xMin===s.xMin&&this.datasetBoundaries.xMax===s.xMax||(this.store.clearAxisLimits(this.chartId),this.datasetBoundaries=s),this.isBarChart="bar"===t?.type,this.chartId=`${t.type}-${this.props.chartId}`,this.sliceable){const s=this.getDetailChartConfiguration(t);e.chartJsConfig=s}if(super.updateChartJs(e),this.hasLinearScale="linear"===this.chart?.scales?.x.type,this.sliceable&&"masterChartConfig"in e){const t=this.getMasterChartConfiguration(e.masterChartConfig);if(this.masterChart)this.masterChart.data=t.data,this.masterChart.config.options=t.options,this.masterChart.update();else{const e=this.masterChartCanvas.el.getContext("2d");this.masterChart=new window.Chart(e,t)}}else this.masterChart=void 0;this.resetAxesLimits(),this.chart?.options&&(this.chart.options.animation=!1)}resetAxesLimits(){if(!this.chart)return;const e=this.store.originalAxisLimits[this.chartId];if(void 0===e?.x?.min&&void 0===e?.x?.max){let e=this.masterChart?this.masterChart.scales:this.chart.scales;return!this.hasLinearScale&&e?.x&&(e={...e,x:{min:Math.ceil(e.x.min)-this.axisOffset,max:Math.floor(e.x.max)+this.axisOffset}}),void this.store.resetAxisLimits(this.chartId,e)}this.updateTrendingLineAxes(),this.chart.update(),this.masterChart&&this.masterChart.update()}updateTrendingLineAxes(){this.store.updateTrendLineConfiguration(this.chartId);const e=this.store.currentAxesLimits[this.chartId];for(const t of[IC,wC])this.chart?.config.options?.scales?.[t]&&e?.[t]&&(this.chart.config.options.scales[t].min=e[t].min,this.chart.config.options.scales[t].max=e[t].max)}get upperBound(){return this.computePosition(this.store.currentAxesLimits[this.chartId]?.x?.max)}get lowerBound(){return this.computePosition(this.store.currentAxesLimits[this.chartId]?.x?.min)}computePosition(e){if(void 0===e||!this.masterChart?.scales?.x)return;const t=this.masterChart.scales.x;if(this.hasLinearScale)return t.getPixelForValue(e);if(!this.masterChart.chartArea)return;const{left:s,right:o}=this.masterChart.chartArea,{min:i,max:n}=t,r=this.axisOffset;return s+(o-s)*(r+e-i)/(2*r+n-i)}computeCoordinate(e){if(!this.masterChart)return;const t=this.masterChart.scales.x;if(this.hasLinearScale){const s=t.getValueForPixel(e);if(void 0===s)return;return Math.round(100*s)/100}const{left:s,right:o}=this.masterChart.chartArea,i=this.axisOffset;return t.min-i+(t.max+2*i-t.min)*(e-s)/(o-s)}updateAxisLimits(e,t){this.hasLinearScale?(this.chart.config.options.scales.x.min=e,this.chart.config.options.scales.x.max=t):(this.chart.config.options.scales.x.min=Math.ceil(e),this.chart.config.options.scales.x.max=Math.floor(t)),this.store.updateAxisLimits(this.chartId,{min:e,max:t}),this.updateTrendingLineAxes(),this.masterChart?.update(),this.chart?.update()}onPointerDownInMasterChart(e){this.removeEventListeners();const t=e.offsetX;if(!this.masterChart?.chartArea||!this.chart?.scales?.x)return;const{left:s,right:o,top:i,bottom:n}=this.masterChart.chartArea,r=this.upperBound??o,a=this.lowerBound??s;if(t<s-5||t>o+5||e.offsetY<i||e.offsetY>n)return;let l,c,h;e.preventDefault(),e.stopPropagation();const d=e.clientX-(this.masterChartCanvas.el?.getBoundingClientRect().left??0);if((a!==s||r!==o)&&t>a+5&&t<r-5){l=e.offsetX-a,this.mode="moveInMaster";const t=this.store.currentAxesLimits[this.chartId]?.x;c=(t?.max??this.chart.scales.x.max)-(t?.min??this.chart.scales.x.min)}else this.mode="selectInMaster",l=Math.abs(t-a)<5?r:Math.abs(t-r)<5?a:Ke(t,s,o),h=this.computeCoordinate(l);const u=this.store.originalAxisLimits[this.chartId].x.min,g=this.store.originalAxisLimits[this.chartId].x.max,p=e=>{let t,s;const{left:o,right:i}=this.masterChart.chartArea;if("moveInMaster"===this.mode)t=this.computeCoordinate(e-l),t<u?t=u:t>g-c&&(t=g-c),s=t+c;else if("selectInMaster"===this.mode){const n=Ke(e,o,i);if(Math.abs(l-n)>5){const e=this.computeCoordinate(n);if(void 0===h||void 0===e)return{};t=Math.min(h,e),s=Math.max(h,e)}}return{min:t,max:s}},m=e=>{const t=e.clientX-(this.masterChartCanvas.el?.getBoundingClientRect().left??0);if(Math.abs(t-d)<5)return;const{min:s,max:o}=p(t);void 0!==s&&void 0!==o&&this.updateAxisLimits(s,o)},f=e=>{this.removeEventListeners();const t=e.clientX-(this.masterChartCanvas.el?.getBoundingClientRect().left??0);if(Math.abs(t-d)>5){let{min:e,max:s}=p(t);void 0!==e&&void 0!==s&&(this.hasLinearScale||("moveInMaster"===this.mode&&c&&!this.isBarChart?(e=Math.round(e)-this.axisOffset,s=e+c):(e=Math.ceil(e)-this.axisOffset,s=Math.floor(s)+this.axisOffset)),this.updateAxisLimits(e,s))}this.mode=void 0};this.removeEventListeners=()=>{window.removeEventListener("pointermove",m,!0),window.removeEventListener("pointerup",f,!0)},window.addEventListener("pointermove",m,!0),window.addEventListener("pointerup",f,!0)}onPointerMoveInMasterChart(e){const{offsetX:t,offsetY:s}=e;if(void 0===this.mode){const o=e.target;if(!this.masterChart?.chartArea)return void(o.style.cursor="default");const{left:i,right:n,top:r,bottom:a}=this.masterChart.chartArea,l=this.lowerBound??i,c=this.upperBound??n;s<r||s>a?o.style.cursor="default":Math.abs(l-t)<5||Math.abs(c-t)<5?o.style.cursor="ew-resize":o.style.cursor=l<t&&t<c&&(l!==i||c!==n)?"grab":"crosshair"}}onMouseLeaveMasterChart(e){const t=e.target;t&&(t.style.cursor="default")}onDoubleClickInMasterChart(e){this.mode=void 0;const t=e.offsetX;if(!this.masterChart?.chartArea||!this.chart?.scales.x)return;const{left:s,right:o,top:i,bottom:n}=this.masterChart.chartArea;let r=this.upperBound??o,a=this.lowerBound??s;if(r<a&&([r,a]=[a,r]),t<s-5||t>o+5||e.offsetY<i||e.offsetY>n)return;e.preventDefault(),e.stopPropagation();let{min:l,max:c}=this.store.currentAxesLimits[this.chartId]?.x??this.chart.scales.x;const h=this.store.originalAxisLimits[this.chartId].x;if(!h)return;let d=h.min,u=h.max;if(this.hasLinearScale&&(d=Math.ceil(d)-this.axisOffset,u=Math.floor(u)+this.axisOffset),Math.abs(t-a)<5)l=d;else if(Math.abs(t-r)<5)c=u;else{if(!(a<t&&t<r))return;l=d,c=u}this.updateAxisLimits(l,c)}}const Xw=new n;Xw.add("animatedBackgroundColorChange",{id:"animatedBackgroundColorChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>e?.style?.fillColor!==t?.style?.fillColor,updateAnimation:function(e,t,s,o){const i=No([{value:0,color:s.style.fillColor||"#ffffff"},{value:1,color:o.style.fillColor||"#ffffff"}]);t.style.fillColor=i(Kw[this.easingFn](e))}}),Xw.add("animatedTextColorChange",{id:"animatedTextColorChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>e?.style?.textColor!==t?.style?.textColor,updateAnimation:function(e,t,s,o){const i=No([{value:0,color:s.style.textColor||"#000000"},{value:1,color:o.style.textColor||"#000000"}]);t.style.textColor=i(Kw[this.easingFn](e))}}),Xw.add("animatedDataBar",{id:"animatedDataBar",easingFn:"easeOutCubic",hasAnimation:(e,t)=>e?.dataBarFill?.percentage!==t?.dataBarFill?.percentage,updateAnimation:function(e,t,s,o){const i=s?.dataBarFill?.percentage||0,n=i+((o?.dataBarFill?.percentage||0)-i)*Kw[this.easingFn](e);t.dataBarFill={color:o.dataBarFill?.color||s.dataBarFill?.color||"#ffffff",percentage:n}}}),Xw.add("textFadeIn",{id:"textFadeIn",easingFn:"easeInCubic",hasAnimation:(e,t)=>{const s=e?.content?.textLines?.join("\n"),o=t?.content?.textLines?.join("\n");return Boolean(!s&&o)},updateAnimation:function(e,t,s,o){t.textOpacity=Kw[this.easingFn](e)}}),Xw.add("textFadeOut",{id:"textFadeOut",easingFn:"easeOutCubic",hasAnimation:(e,t)=>{const s=e?.content?.textLines?.join("\n"),o=t?.content?.textLines?.join("\n");return Boolean(s&&!o)},updateAnimation:function(e,t,s,o){const i=1-Kw[this.easingFn](e),n={...s.style};delete n.fillColor,t.textOpacity=i,t.content=s.content,t.clipRect=s.clipRect,Object.assign(t.style,n)}}),Xw.add("iconFadeIn",{id:"iconFadeIn",easingFn:"easeInCubic",hasAnimation:(e,t)=>Boolean(!e?.icons?.left&&t?.icons?.left||!e?.icons?.right&&t?.icons?.right||!e?.icons?.center&&t?.icons?.center),updateAnimation:function(e,t,s,o){const i=Kw[this.easingFn](e);t.icons.left&&o.icons.left&&!s.icons.left&&(t.icons.left.opacity=i),t.icons.right&&o.icons.right&&!s.icons.right&&(t.icons.right.opacity=i),t.icons.center&&o.icons.center&&!s.icons.center&&(t.icons.center.opacity=i)}}),Xw.add("iconFadeOut",{id:"iconFadeOut",easingFn:"easeOutCubic",hasAnimation:(e,t)=>Boolean(e?.icons?.left&&!t?.icons?.left||e?.icons?.right&&!t?.icons?.right||e?.icons?.center&&!t?.icons?.center),updateAnimation:function(e,t,s,o){const i=1-Kw[this.easingFn](e);t.icons||(t.icons={}),s.icons.left&&!o.icons.left&&(t.icons.left={...s.icons.left,opacity:i}),s.icons.right&&!o.icons.right&&(t.icons.right={...s.icons.right,opacity:i}),s.icons.center&&!o.icons.center&&(t.icons.center={...s.icons.center,opacity:i})}}),Xw.add("textChange",{id:"textChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>{const s=e?.content?.textLines?.join("\n"),o=t?.content?.textLines?.join("\n");return Boolean(s&&o&&(s!==o||eE(t,e)))},updateAnimation:function(e,t,s,o){const i=Kw[this.easingFn](e),n=o.y+(i-1)*o.height,r=o.y+i*o.height,a=eE(o,s),l={id:o.id+"-text-slide-in",x:o.x,y:n,width:o.width,height:o.height,style:{...o.style},skipCellGridLines:!0,content:o.content?{...o.content}:void 0,clipRect:o.clipRect||{...o,x:Math.max(0,o.x-(o.content?.width||0)),width:o.width+2*(o.content?.width||0)},icons:a?Qw(o.icons,o):Jw(o.icons)},c={id:s.id+"-text-slide-out",x:o.x,y:r,width:o.width,height:o.height,style:{...s.style},skipCellGridLines:!0,content:s.content?{...s.content}:void 0,clipRect:s.clipRect||{...o,x:Math.max(0,o.x-(s.content?.width||0)),width:o.width+2*(s.content?.width||0)},icons:a?Qw(s.icons,o):Jw(s.icons)};if(o.content&&s.content&&l.content&&c.content){const e=o.content.y+(i-1)*o.height,t=o.content.y+i*o.height;l.content.y=e,c.content.y=t}return c.style.fillColor=l.style.fillColor=void 0,t.content=void 0,t.icons=a?{}:t.icons,{newBoxes:[l,c]}}}),Xw.add("borderFadeIn",{id:"borderFadeIn",easingFn:"easeInCubic",hasAnimation:(e,t)=>Boolean(!e?.border?.bottom&&t?.border?.bottom||!e?.border?.top&&t?.border?.top||!e?.border?.left&&t?.border?.left||!e?.border?.right&&t?.border?.right),updateAnimation:function(e,t,s,o){const i=Kw[this.easingFn](e);t.border?.top&&o.border?.top&&!s.border?.top&&(t.border.top.opacity=i),t.border?.bottom&&o.border?.bottom&&!s.border?.bottom&&(t.border.bottom.opacity=i),t.border?.left&&o.border?.left&&!s.border?.left&&(t.border.left.opacity=i),t.border?.right&&o.border?.right&&!s.border?.right&&(t.border.right.opacity=i)}}),Xw.add("borderFadeOut",{id:"borderFadeOut",easingFn:"easeOutCubic",hasAnimation:(e,t)=>Boolean(e?.border?.bottom&&!t?.border?.bottom||e?.border?.top&&!t?.border?.top||e?.border?.left&&!t?.border?.left||e?.border?.right&&!t?.border?.right),updateAnimation:function(e,t,s,o){const i=1-Kw[this.easingFn](e);t.border||(t.border={}),s.border?.top&&!o.border?.top&&(t.border.top={...s.border.top,opacity:i}),s.border?.bottom&&!o.border?.bottom&&(t.border.bottom={...s.border.bottom,opacity:i}),s.border?.left&&!o.border?.left&&(t.border.left={...s.border.left,opacity:i}),s.border?.right&&!o.border?.right&&(t.border.right={...s.border.right,opacity:i})}}),Xw.add("borderColorChange",{id:"borderColorChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>{const s=e?.border,o=t?.border;return!(!s||!o)&&Boolean(s.bottom?.color!==o.bottom?.color||s.top?.color!==o.top?.color||s.left?.color!==o.left?.color||s.right?.color!==o.right?.color)},updateAnimation:function(e,t,s,o){const i=i=>{const n=s?.border?.[i],r=o?.border?.[i],a=t.border?.[i];if(n&&r&&a){const t=No([{value:0,color:n.color||"#000000"},{value:1,color:r.color||"#000000"}]);a.color=t(Kw[this.easingFn](e))}};i("top"),i("bottom"),i("left"),i("right")}}),Xw.add("iconChange",{id:"iconChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>!eE(t,e)&&Boolean(e?.icons?.center?.svg?.name!==t?.icons?.center?.svg?.name||e?.icons?.left?.svg?.name!==t?.icons?.left?.svg?.name||e?.icons?.right?.svg?.name!==t?.icons?.right?.svg?.name),updateAnimation:function(e,t,s,o){const i=Kw[this.easingFn](e),n=o.y+(i-1)*o.height,r=o.y+i*o.height,a=[],l=e=>{const i=s.icons?.[e],l=o.icons?.[e],c={id:`${o.id}-icon-${e}-slide-in`,style:{verticalAlign:o.style.verticalAlign},x:o.x,y:n,width:o.width,height:o.height,skipCellGridLines:!0,icons:{[e]:{...l,clipRect:o}}},h={id:`${o.id}-icon-${e}-slide-out`,style:{verticalAlign:s.style.verticalAlign},x:o.x,y:r,width:o.width,height:o.height,skipCellGridLines:!0,icons:{[e]:{...i,clipRect:o}}};t.icons[e]=Jw(o.icons)[e],a.push(c,h)};return l("left"),l("right"),l("center"),{newBoxes:a}}});const Kw={linear:e=>e,easeInCubic:e=>e*e*e,easeOutCubic:e=>(e-=1)*e*e+1,easeInOutCubic:e=>(e/=.5)<1?.5*e*e*e:.5*((e-=2)*e*e+2),easeOutQuart:e=>-((e-=1)*e*e*e-1)};function Jw(e){return{left:e.left?{...e.left,svg:void 0}:void 0,right:e.right?{...e.right,svg:void 0}:void 0,center:e.center?{...e.center,svg:void 0}:void 0}}function Qw(e,t){return{left:e.left?{...e.left,clipRect:t}:void 0,right:e.right?{...e.right,clipRect:t}:void 0,center:e.center?{...e.center,clipRect:t}:void 0}}function eE(e,t){const s=(e,t)=>t&&e?!!(e.horizontalAlign!==t.horizontalAlign||e.size!==t.size||e.margin!==t.margin||e.svg&&!t.svg||!e.svg&&t.svg):!!(e&&!t||!e&&t);return s(e?.icons.left,t?.icons.left)||s(e?.icons.right,t?.icons.right)||s(e?.icons.center,t?.icons.center)}class tE extends t.Component{static template="o-spreadsheet-GaugeChartComponent";static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=t.useRef("chartContainer");animationStore;get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}setup(){this.env.model.getters.isDashboard()&&(this.animationStore=rh(Sh));let e,s=null;t.useEffect((()=>(this.env.isDashboard()&&void 0===e&&"gauge"!==this.animationStore?.animationPlayed[this.animationChartId]||this.env.isDashboard()&&void 0!==e&&!St(this.runtime,e)?(s=this.drawGaugeWithAnimation(),this.animationStore?.disableAnimationForChart(this.animationChartId,"gauge")):dI(this.canvasEl,this.runtime),e=this.runtime,()=>s?.stop())),(()=>{const e=this.canvasEl.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]}))}drawGaugeWithAnimation(){dI(this.canvasEl,{...this.runtime,animationValue:0});const e=this.runtime.gaugeValue?.value||0,t=this.runtime.maxValue.value,s=Math.sign(e)*Math.min(Math.abs(e),Math.abs(t));if(0===s)return null;const o=this.runtime.minValue.value,i=new sE(o,s,1e3,(e=>dI(this.canvasEl,{...this.runtime,animationValue:e})));return i.start(),i}get canvasEl(){return this.canvas.el}get animationChartId(){return this.props.isFullScreen?this.props.chartId+"-fullscreen":this.props.chartId}}class sE{startValue;endValue;duration;callback;startTime=void 0;animationFrameId=null;constructor(e,t,s,o){this.startValue=e,this.endValue=t,this.duration=s,this.callback=o}start(){this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}stop(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}animate(e){this.startTime||(this.startTime=e);const t=e-this.startTime,s=Math.min(t/this.duration,1),o=this.startValue+(this.endValue-this.startValue)*Kw.easeOutQuart(s);this.callback(o),s<1?this.animationFrameId=requestAnimationFrame(this.animate.bind(this)):this.stop()}}class oE extends wy{dataSets;labelRange;background;legendPosition;aggregated;dataSetsHaveTitle;dataSetDesign;axesDesign;type="combo";showValues;hideDataMarkers;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=DC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ca(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 PC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,LC,kC)}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,VC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:sI(this.background||M),fontColor:sI(MC(this.background)),dataSets:e,labelRange:t,verticalAxis:UC(s)}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=RC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new oE(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=xC(this.sheetId,e,this.dataSets),s=TC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new oE(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new oE(t,e,this.getters)}}class iE extends wy{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=DC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ca(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 PC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,LC,kC)}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=xC(this.sheetId,e,this.dataSets),s=TC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new iE(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new iE(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}=RC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new iE(i,this.sheetId,this.getters)}}function nE(e){return e.dataRange&&!ea.test(e.dataRange)?"InvalidGaugeDataRange":"Success"}function rE(e,t){return t((t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):"Success"),(t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):"Success"))}function aE(e,t){if(""===e)switch(t){case"rangeMin":return"EmptyGaugeRangeMin";case"rangeMax":return"EmptyGaugeRangeMax"}return"Success"}function lE(e,t){if(e.startsWith("="))return"Success";if(isNaN(e))switch(t){case"rangeMin":return"GaugeRangeMinNaN";case"rangeMax":return"GaugeRangeMaxNaN";case"lowerInflectionPointValue":return"GaugeLowerInflectionPointNaN";case"upperInflectionPointValue":return"GaugeUpperInflectionPointNaN"}return"Success"}class cE extends wy{dataRange;sectionRule;background;type="gauge";constructor(e,t,s){super(e,t,s),this.dataRange=Ca(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,nE,e.chainValidations(rE(aE,e.batchValidations),rE(lE,e.batchValidations)),e.chainValidations((s=lE,(0,e.batchValidations)((e=>e.sectionRule?s(e.sectionRule.lowerInflectionPoint.value,"lowerInflectionPointValue"):"Success"),(e=>e.sectionRule?s(e.sectionRule.upperInflectionPoint.value,"upperInflectionPointValue"):"Success")))));var s}static transformDefinition(e,t,s){let o;if(t.dataRange){const i=CC(e,t.dataRange,s);i!==Mi.InvalidReference&&(o=i)}return{...t,dataRange:o}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||{text:""},type:"gauge",dataRange:e.range?e.range[0].dataRange:void 0,sectionRule:{colors:{lowerColor:"#EA6175",middleColor:"#FFD86D",upperColor:"#43C5B1"},rangeMin:"0",rangeMax:"100",lowerInflectionPoint:{type:"percentage",value:"15",operator:"<="},upperInflectionPoint:{type:"percentage",value:"40",operator:"<="}},humanize:e.humanize}}duplicateInDuplicatedSheet(e){const t=TC(this.sheetId,e,this.dataRange),s=gE(this.sectionRule,(t=>this.getters.copyFormulaStringForSheet(this.sheetId,e,t,"moveReference"))),o=this.getDefinitionWithSpecificRanges(t,s,e);return new cE(o,e,this.getters)}copyInSheetId(e){const t=gE(this.sectionRule,(t=>this.getters.copyFormulaStringForSheet(this.sheetId,e,t,"keepSameReference"))),s=this.getDefinitionWithSpecificRanges(this.dataRange,t,e);return new cE(s,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.dataRange,this.sectionRule)}getDefinitionWithSpecificRanges(e,t,s){return{background:this.background,sectionRule:t,title:this.title,type:"gauge",dataRange:e?this.getters.getRangeString(e,s||this.sheetId):void 0,humanize:this.humanize}}getDefinitionForExcel(){}getContextCreation(){return{...this,range:this.dataRange?[{dataRange:this.getters.getRangeString(this.dataRange,this.sheetId)}]:void 0}}updateRanges(e,t,s){const o=AC(this.dataRange,e),i=gE(this.sectionRule,(o=>SC(this.sheetId,o,{applyChange:e,sheetId:t,sheetName:s}))),n=this.getDefinitionWithSpecificRanges(o,i);return new cE(n,this.sheetId,this.getters)}}function hE(e,t){const s=t.getLocale(),o=e.sectionRule.colors;let i,n,a;const l=e.dataRange;if(void 0!==l){const e=t.getEvaluatedCell({sheetId:l.sheetId,col:l.zone.left,row:l.zone.top});e.type===r.number&&(i=e.value,n=e.formattedValue,a=e.format)}let c=uE(e.sheetId,e.sectionRule.rangeMin,t),h=uE(e.sheetId,e.sectionRule.rangeMax,t);if(void 0===c||void 0===h)return function(e,t){return{background:t.getStyleOfSingleCellChart(e.background,e.dataRange).background,title:e.title??{text:""},minValue:{value:0,label:""},maxValue:{value:100,label:""},gaugeValue:{value:0,label:Mi.GenericError},inflectionValues:[],colors:[]}}(e,t);h<c&&([c,h]=[h,c]);const d=e.sectionRule.lowerInflectionPoint,u=e.sectionRule.upperInflectionPoint,g=dE(e.sheetId,e.sectionRule.lowerInflectionPoint,c,h,t),p=dE(e.sheetId,e.sectionRule.upperInflectionPoint,c,h,t),m=[],f=[];return void 0!==g&&(m.push({value:g,label:sr(g,a,s,e.humanize),operator:d.operator}),f.push(o.lowerColor)),void 0!==p&&p!==g&&(m.push({value:p,label:sr(p,a,s,e.humanize),operator:u.operator}),f.push(o.middleColor)),void 0!==p&&void 0!==g&&g>p&&(m.reverse(),f.reverse()),f.push(o.upperColor),{background:t.getStyleOfSingleCellChart(e.background,l).background,title:{...e.title,text:e.title.text?t.dynamicTranslate(e.title.text):""},minValue:{value:c,label:sr(c,a,s,e.humanize)},maxValue:{value:h,label:sr(h,a,s,e.humanize)},gaugeValue:void 0!==i&&n?{value:i,label:e.humanize?wr({value:i,format:a},s):n}:void 0,inflectionValues:m,colors:f}}function dE(e,t,s,o,i){const n=uE(e,t.value,i);if(void 0===n)return;return Ke("number"===t.type?n:s+(o-s)*n/100,s,o)}function uE(e,t,s){const o=s.evaluateFormula(e,t);return Yl(o)?void 0:Xi(Zl(o),s.getLocale())}function gE(e,t){return{...e,rangeMin:t(e.rangeMin),rangeMax:t(e.rangeMax),lowerInflectionPoint:{...e.lowerInflectionPoint,value:t(e.lowerInflectionPoint.value)},upperInflectionPoint:{...e.upperInflectionPoint,value:t(e.upperInflectionPoint.value)}}}class pE extends wy{dataSets;labelRange;background;legendPosition;type="geo";dataSetsHaveTitle;dataSetDesign;colorScale;missingValueColor;region;constructor(e,t,s){super(e,t,s),this.dataSets=DC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ca(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 PC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,LC,kC)}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=xC(this.sheetId,e,this.dataSets),s=TC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new pE(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new pE(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}=RC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new pE(i,this.sheetId,this.getters)}}class mE extends wy{dataSets;labelRange;background;legendPosition;labelsAsText;stacked;aggregated;type="line";dataSetsHaveTitle;cumulative;dataSetDesign;axesDesign;fillArea;showValues;hideDataMarkers;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=DC(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ca(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.cumulative=e.cumulative,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.fillArea=e.fillArea,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers,this.zoomable=e.zoomable}static validateChartDefinition(e,t){return e.checkValidations(t,LC,kC)}static transformDefinition(e,t,s){return PC(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:"line",labelRange:e.auxiliaryRange||void 0,stacked:e.stacked??!1,aggregated:e.aggregated??!1,cumulative:e.cumulative??!1,axesDesign:e.axesDesign,fillArea:e.fillArea,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,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:"line",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,stacked:this.stacked,aggregated:this.aggregated,cumulative:this.cumulative,axesDesign:this.axesDesign,fillArea:this.fillArea,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,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}=RC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new mE(i,this.sheetId,this.getters)}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,VC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:sI(this.background||M),fontColor:sI(MC(this.background)),dataSets:e,labelRange:t,verticalAxis:UC(s)}}duplicateInDuplicatedSheet(e){const t=xC(this.sheetId,e,this.dataSets),s=TC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new mE(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new mE(t,e,this.getters)}}function fE(e,t){const s=e.getDefinition(),o=AI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"line",data:{labels:o.labels,datasets:QC(s,o)},options:{...bI,layout:XI(0,o),scales:cw(s,o),plugins:{title:xw(s,t),legend:QI(s),tooltip:Fw(s,o),chartShowValuesPlugin:Iw(s,o)}}},background:e.background||M}}class vE extends wy{dataSets;labelRange;background;legendPosition;type="pie";aggregated;dataSetsHaveTitle;isDoughnut;showValues;pieHolePercentage;constructor(e,t,s){super(e,t,s),this.dataSets=DC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ca(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.isDoughnut=e.isDoughnut,this.showValues=e.showValues,this.pieHolePercentage=e.pieHolePercentage}static transformDefinition(e,t,s){return PC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,LC,kC)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"pie",labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,isDoughnut:e.isDoughnut,pieHolePercentage:e.pieHolePercentage,showValues:e.showValues,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{...this,range:this.dataSets.map((e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,s){return{type:"pie",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,aggregated:this.aggregated,isDoughnut:this.isDoughnut,showValues:this.showValues,pieHolePercentage:this.pieHolePercentage,humanize:this.humanize}}duplicateInDuplicatedSheet(e){const t=xC(this.sheetId,e,this.dataSets),s=TC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new vE(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new vE(t,e,this.getters)}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,VC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:sI(this.background||M),fontColor:sI(MC(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=RC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new vE(i,this.sheetId,this.getters)}}function bE(e,t){const s=e.getDefinition(),o=DI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:e.isDoughnut?"doughnut":"pie",data:{labels:o.labels,datasets:ty(s,o)},options:{...bI,cutout:e.isDoughnut&&void 0!==s.pieHolePercentage?s.pieHolePercentage+"%":void 0,layout:XI(0,o),plugins:{title:xw(s,t),legend:ew(s,o),tooltip:Ow(s,o),chartShowValuesPlugin:Iw(s,o)}}},background:e.background||M}}class SE extends wy{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=DC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ca(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 PC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,LC,kC)}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=xC(this.sheetId,e,this.dataSets),s=TC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new SE(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new SE(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,VC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),o=this.getDefinition(),i=TI(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:sI(this.background||M),fontColor:sI(MC(this.background)),dataSets:t,labelRange:s,verticalAxis:UC(o),maxValue:r}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=RC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new SE(i,this.sheetId,this.getters)}}class CE extends wy{dataSets;labelRange;background;legendPosition;stacked;aggregated;type="radar";dataSetsHaveTitle;dataSetDesign;fillArea;showValues;hideDataMarkers;constructor(e,t,s){super(e,t,s),this.dataSets=DC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ca(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 PC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,LC,kC)}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=xC(this.sheetId,e,this.dataSets),s=TC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new CE(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new CE(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,VC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:sI(this.background||M),fontColor:sI(MC(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=RC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new CE(i,this.sheetId,this.getters)}}class yE extends wy{dataSets;labelRange;background;legendPosition;labelsAsText;aggregated;type="scatter";dataSetsHaveTitle;dataSetDesign;axesDesign;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=DC(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ca(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,LC,kC)}static transformDefinition(e,t,s){return PC(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}=RC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new yE(i,this.sheetId,this.getters)}getDefinitionForExcel(){const e=this.dataSets.map((e=>FC(this.getters,e))).filter((e=>""!==e.range)),t=OC(this.getters,this.labelRange,VC(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:sI(this.background||M),fontColor:sI(MC(this.background)),dataSets:e,labelRange:t,verticalAxis:UC(s)}}duplicateInDuplicatedSheet(e){const t=xC(this.sheetId,e,this.dataSets),s=TC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new yE(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new yE(t,e,this.getters)}}class IE extends wy{dataSets;labelRange;background;legendPosition;type="sunburst";dataSetsHaveTitle;showValues;showLabels;valuesDesign;groupColors;pieHolePercentage;constructor(e,t,s){super(e,t,s),this.dataSets=DC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ca(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 PC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,LC,kC)}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=xC(this.sheetId,e,this.dataSets),s=TC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new IE(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new IE(t,e,this.getters)}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=RC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new IE(i,this.sheetId,this.getters)}}class wE extends wy{static defaults={background:M,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=DC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ca(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 PC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,LC,kC)}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=xC(this.sheetId,e,this.dataSets),s=TC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new wE(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new wE(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}=RC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new wE(i,this.sheetId,this.getters)}}class EE extends wy{dataSets;labelRange;background;verticalAxisPosition;legendPosition;aggregated;type="waterfall";dataSetsHaveTitle;showSubTotals;firstValueAsSubtotal;showConnectorLines;positiveValuesColor;negativeValuesColor;subTotalValuesColor;dataSetDesign;axesDesign;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=DC(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ca(s,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showSubTotals=e.showSubTotals,this.showConnectorLines=e.showConnectorLines,this.positiveValuesColor=e.positiveValuesColor,this.negativeValuesColor=e.negativeValuesColor,this.subTotalValuesColor=e.subTotalValuesColor,this.firstValueAsSubtotal=e.firstValueAsSubtotal,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.zoomable=e.zoomable}static transformDefinition(e,t,s){return PC(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,LC,kC)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"waterfall",verticalAxisPosition:"left",labelRange:e.auxiliaryRange||void 0,showSubTotals:e.showSubTotals??!1,showConnectorLines:e.showConnectorLines??!0,firstValueAsSubtotal:e.firstValueAsSubtotal??!1,axesDesign:e.axesDesign,showValues:e.showValues,zoomable:e.zoomable??!1,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=xC(this.sheetId,e,this.dataSets),s=TC(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new EE(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new EE(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:"waterfall",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,showSubTotals:this.showSubTotals,showConnectorLines:this.showConnectorLines,positiveValuesColor:this.positiveValuesColor,negativeValuesColor:this.negativeValuesColor,subTotalValuesColor:this.subTotalValuesColor,firstValueAsSubtotal:this.firstValueAsSubtotal,axesDesign:this.axesDesign,showValues:this.showValues,zoomable:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=RC(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new EE(i,this.sheetId,this.getters)}}function RE(e,t){const s=e.getDefinition(),o=xI(s,e.dataSets,e.labelRange,t),{labels:i,datasets:n}=JC(s,o);return{chartJsConfig:{type:"bar",data:{labels:i,datasets:n},options:{...bI,layout:XI(0,o),scales:dw(s,o),plugins:{title:xw(s,t),legend:ow(s),tooltip:Pw(s,o),chartShowValuesPlugin:Rw(s,o),waterfallLinesPlugin:{showConnectorLines:s.showConnectorLines}}}},background:e.background||M}}const xE=new n;xE.add("bar",{match:e=>"bar"===e,createChart:(e,t,s)=>new Gw(e,t,s),getChartRuntime:Ww,validateChartDefinition:Gw.validateChartDefinition,transformDefinition:Gw.transformDefinition,getChartDefinitionFromContextCreation:Gw.getDefinitionFromContextCreation,sequence:10}),xE.add("combo",{match:e=>"combo"===e,createChart:(e,t,s)=>new oE(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=xI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:sy(s,o)},options:{...bI,layout:XI(0,o),scales:lw(s,o),plugins:{title:xw(s,t),legend:sw(s),tooltip:_w(s,o),chartShowValuesPlugin:Iw(s,o)}}},background:e.background||M}},validateChartDefinition:oE.validateChartDefinition,transformDefinition:oE.transformDefinition,getChartDefinitionFromContextCreation:oE.getDefinitionFromContextCreation,sequence:15}),xE.add("line",{match:e=>"line"===e,createChart:(e,t,s)=>new mE(e,t,s),getChartRuntime:fE,validateChartDefinition:mE.validateChartDefinition,transformDefinition:mE.transformDefinition,getChartDefinitionFromContextCreation:mE.getDefinitionFromContextCreation,sequence:20}),xE.add("pie",{match:e=>"pie"===e,createChart:(e,t,s)=>new vE(e,t,s),getChartRuntime:bE,validateChartDefinition:vE.validateChartDefinition,transformDefinition:vE.transformDefinition,getChartDefinitionFromContextCreation:vE.getDefinitionFromContextCreation,sequence:30}),xE.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,s)=>new _y(e,t,s),getChartRuntime:Oy,validateChartDefinition:_y.validateChartDefinition,transformDefinition:_y.transformDefinition,getChartDefinitionFromContextCreation:_y.getDefinitionFromContextCreation,sequence:40}),xE.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,s)=>new cE(e,t,s),getChartRuntime:hE,validateChartDefinition:cE.validateChartDefinition,transformDefinition:cE.transformDefinition,getChartDefinitionFromContextCreation:cE.getDefinitionFromContextCreation,sequence:50}),xE.add("scatter",{match:e=>"scatter"===e,createChart:(e,t,s)=>new yE(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=AI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"line",data:{labels:o.labels,datasets:ey(s,o)},options:{...bI,layout:XI(0,o),scales:hw(s,o),plugins:{title:xw(s,t),legend:tw(s),tooltip:Fw(s,o),chartShowValuesPlugin:Iw(s,o)}}},background:e.background||M}},validateChartDefinition:yE.validateChartDefinition,transformDefinition:yE.transformDefinition,getChartDefinitionFromContextCreation:yE.getDefinitionFromContextCreation,sequence:60}),xE.add("waterfall",{match:e=>"waterfall"===e,createChart:(e,t,s)=>new EE(e,t,s),getChartRuntime:RE,validateChartDefinition:EE.validateChartDefinition,transformDefinition:EE.transformDefinition,getChartDefinitionFromContextCreation:EE.getDefinitionFromContextCreation,sequence:70}),xE.add("pyramid",{match:e=>"pyramid"===e,createChart:(e,t,s)=>new SE(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=TI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:KC(s,o)},options:{...bI,indexAxis:"y",layout:XI(0,o),scales:uw(s,o),plugins:{title:xw(s,t),legend:JI(s),tooltip:Mw(s,o),chartShowValuesPlugin:Ew(s,o)}}},background:e.background||M}},validateChartDefinition:SE.validateChartDefinition,transformDefinition:SE.transformDefinition,getChartDefinitionFromContextCreation:SE.getDefinitionFromContextCreation,sequence:80,dataSeriesLimit:2}),xE.add("radar",{match:e=>"radar"===e,createChart:(e,t,s)=>new CE(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=_I(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"radar",data:{labels:o.labels,datasets:oy(s,o)},options:{...bI,layout:XI(0,o),scales:gw(s,o),plugins:{title:xw(s,t),legend:iw(s),tooltip:Nw(s,o),chartShowValuesPlugin:Iw(s,o)}}},background:e.background||M}},validateChartDefinition:CE.validateChartDefinition,transformDefinition:CE.transformDefinition,getChartDefinitionFromContextCreation:CE.getDefinitionFromContextCreation,sequence:80}),xE.add("geo",{match:e=>"geo"===e,createChart:(e,t,s)=>new pE(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=FI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"choropleth",data:{datasets:iy(s,o)},options:{...bI,layout:XI(0,o),scales:pw(s,o),plugins:{title:xw(s,t),tooltip:Lw(s,o),legend:{display:!1}}}},background:e.background||M}},validateChartDefinition:pE.validateChartDefinition,transformDefinition:pE.transformDefinition,getChartDefinitionFromContextCreation:pE.getDefinitionFromContextCreation,sequence:90,dataSeriesLimit:1}),xE.add("funnel",{match:e=>"funnel"===e,createChart:(e,t,s)=>new iE(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=OI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"funnel",data:{labels:o.labels,datasets:ny(s,o)},options:{...bI,indexAxis:"y",layout:XI(0,o),scales:mw(0,o),plugins:{title:xw(s,t),legend:{display:!1},tooltip:kw(s,o),chartShowValuesPlugin:Iw(s,o)}}},background:e.background||M}},validateChartDefinition:iE.validateChartDefinition,transformDefinition:iE.transformDefinition,getChartDefinitionFromContextCreation:iE.getDefinitionFromContextCreation,sequence:100,dataSeriesLimit:1}),xE.add("sunburst",{match:e=>"sunburst"===e,createChart:(e,t,s)=>new IE(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=PI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"doughnut",data:{datasets:ay(s,o)},options:{cutout:void 0===e.pieHolePercentage?"25%":`${e.pieHolePercentage}%`,...bI,layout:XI(0,o),plugins:{title:xw(s,t),legend:nw(s),tooltip:Vw(s,o),sunburstLabelsPlugin:ww(s,o),sunburstHoverPlugin:{enabled:!0}}}},background:e.background||M}},validateChartDefinition:IE.validateChartDefinition,transformDefinition:IE.transformDefinition,getChartDefinitionFromContextCreation:IE.getDefinitionFromContextCreation,sequence:30}),xE.add("treemap",{match:e=>"treemap"===e,createChart:(e,t,s)=>new wE(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=PI(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"treemap",data:{labels:o.labels,datasets:dy(s,o)},options:{...bI,layout:XI(0,o),plugins:{title:xw(s,t),legend:{display:!1},tooltip:Uw(s,o)}}},background:e.background||M}},validateChartDefinition:wE.validateChartDefinition,transformDefinition:wE.transformDefinition,getChartDefinitionFromContextCreation:wE.getDefinitionFromContextCreation,sequence:100});const TE=new n;TE.add("line",Yw),TE.add("bar",Yw),TE.add("combo",Yw),TE.add("pie",Iy),TE.add("gauge",tE),TE.add("scatter",Yw),TE.add("scorecard",ky),TE.add("waterfall",Yw),TE.add("pyramid",Iy),TE.add("radar",Iy),TE.add("geo",Iy),TE.add("funnel",Iy),TE.add("sunburst",Iy),TE.add("treemap",Iy);const AE={line:Go("Line"),column:Go("Column"),bar:Go("Bar"),area:Go("Area"),pie:Go("Pie"),hierarchical:Go("Hierarchical"),misc:Go("Miscellaneous")},DE=new n;function _E(e){const t=xE.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(s,o,i){const n=t.find((e=>e.match(o.type)));if(!n)throw new Error(`No builder for this chart: ${o.type}`);return n.createChart(o,i,e)}}function FE(e){const t=xE.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(s){const o=t.find((e=>e.match(s.type)));if(!o)throw new Error("No runtime builder for this chart.");const i=o.getChartRuntime(s,e),n=s.getDefinition();if("chartJsConfig"in i&&/line|combo|bar|scatter|waterfall/.test(n.type)){const e=i.chartJsConfig;i.masterChartConfig=function(e){return{...e,data:{...e.data,datasets:e.data.datasets.filter((e=>!$C(e.xAxisID))).map((e=>({...e,pointRadius:0,showLine:!0})))},options:{...e.options,hover:{mode:null},plugins:{...e.options.plugins,title:{display:!1},legend:{display:!1},tooltip:{enabled:!1},chartShowValuesPlugin:void 0},layout:{padding:{...e.options.layout?.padding,top:5,bottom:10}},scales:{y:{...e.options.scales?.y,display:!1},y1:{...e.options.scales?.y1,display:!1},x:{...e.options.scales?.x,title:void 0,ticks:{...e.options.scales?.x?.ticks,callback:function(t){return WC(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}(e)}return i}}function OE(e,t){const s=xE.getAll().find((e=>e.match(t.type)));if(!s)throw new Error("Unknown chart type.");return s.validateChartDefinition(e,t)}function PE(e,t,s){const o=xE.getAll().find((e=>e.match(t.type)));if(!o)throw new Error("Unknown chart type.");return o.transformDefinition(e,t,s)}DE.add("line",{matcher:e=>"line"===e.type&&!e.stacked&&!e.fillArea,displayName:Go("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:Go("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:Go("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:Go("Stacked Area"),chartType:"line",chartSubtype:"stacked_area",subtypeDefinition:{stacked:!0,fillArea:!0},category:"area",preview:"o-spreadsheet-ChartPreview.STACKED_AREA_CHART"}).add("scatter",{displayName:Go("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:Go("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:Go("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:Go("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:Go("Stacked Bar"),chartType:"bar",chartSubtype:"stacked_bar",subtypeDefinition:{horizontal:!0,stacked:!0},category:"bar",preview:"o-spreadsheet-ChartPreview.STACKED_BAR_CHART"}).add("combo",{displayName:Go("Combo"),chartSubtype:"combo",chartType:"combo",category:"line",preview:"o-spreadsheet-ChartPreview.COMBO_CHART"}).add("pie",{matcher:e=>"pie"===e.type&&!e.isDoughnut,displayName:Go("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:Go("Doughnut"),chartSubtype:"doughnut",chartType:"pie",subtypeDefinition:{isDoughnut:!0},category:"pie",preview:"o-spreadsheet-ChartPreview.DOUGHNUT_CHART"}).add("gauge",{displayName:Go("Gauge"),chartSubtype:"gauge",chartType:"gauge",category:"misc",preview:"o-spreadsheet-ChartPreview.GAUGE_CHART"}).add("scorecard",{displayName:Go("Scorecard"),chartSubtype:"scorecard",chartType:"scorecard",category:"misc",preview:"o-spreadsheet-ChartPreview.SCORECARD_CHART"}).add("waterfall",{displayName:Go("Waterfall"),chartSubtype:"waterfall",chartType:"waterfall",category:"misc",preview:"o-spreadsheet-ChartPreview.WATERFALL_CHART"}).add("pyramid",{displayName:Go("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:Go("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:Go("Filled Radar"),chartType:"radar",chartSubtype:"filled_radar",subtypeDefinition:{fillArea:!0},category:"misc",preview:"o-spreadsheet-ChartPreview.FILLED_RADAR_CHART"}).add("geo",{displayName:Go("Geo Chart"),chartSubtype:"geo",chartType:"geo",category:"misc",preview:"o-spreadsheet-ChartPreview.GEO_CHART"}).add("funnel",{displayName:Go("Funnel"),chartSubtype:"funnel",chartType:"funnel",category:"misc",preview:"o-spreadsheet-ChartPreview.FUNNEL_CHART"}).add("sunburst",{matcher:e=>"sunburst"===e.type,displayName:Go("Sunburst"),chartSubtype:"sunburst",chartType:"sunburst",category:"hierarchical",preview:"o-spreadsheet-ChartPreview.SUNBURST_CHART"}).add("treemap",{matcher:e=>"treemap"===e.type,displayName:Go("Tree Map"),chartType:"treemap",chartSubtype:"treemap",category:"hierarchical",preview:"o-spreadsheet-ChartPreview.TREE_MAP_CHART"});var ME=Object.freeze({__proto__:null,AbstractChart:wy,BarChart:Gw,CHART_AXIS_CHOICES:BC,CHART_COMMON_OPTIONS:bI,GaugeChart:cE,LineChart:mE,MOVING_AVERAGE_TREND_LINE_XAXIS_ID:wC,PieChart:vE,SPREADSHEET_TO_EXCEL_TRENDLINE_TYPE_MAPPING:EC,ScorecardChart:_y,TREND_LINE_XAXIS_ID:IC,WaterfallChart:EE,adaptChartRange:AC,chartFactory:_E,chartFontColor:MC,chartMutedFontColor:NC,chartRuntimeFactory:FE,chartToImageFile:CI,chartToImageUrl:SI,checkDataset:LC,checkLabelRange:kC,createBarChartRuntime:Ww,createDataSets:DC,createGaugeChartRuntime:hE,createLineChartRuntime:fE,createPieChartRuntime:bE,createScorecardChartRuntime:Oy,createWaterfallChartRuntime:RE,drawScoreChart:Fy,duplicateDataSetsInDuplicatedSheet:xC,duplicateLabelRangeInDuplicatedSheet:TC,formatChartDatasetValue:HC,formatTickValue:zC,getChartPositionAtCenterOfViewport:function(e,t){const{x:s,y:o}=e.getMainViewportCoordinates(),{scrollX:i,scrollY:n}=e.getActiveSheetScrollInfo(),{width:r,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:s+i+Math.max(0,(r-t.width)/2),y:o+n+Math.max(0,(a-t.height)/2)}},getDefinedAxis:UC,getPieColors:GC,isTrendLineAxis:$C,shouldRemoveFirstLabel:VC,toExcelDataset:FC,toExcelLabelRange:OC,transformChartDefinitionWithDataSetsWithZone:PC,transformDefinition:PE,truncateLabel:WC,updateChartRangesWithDataSets:RC,validateChartDefinition:OE});function NE(e,t){const{scrollX:s,scrollY:o}=e.getActiveSheetScrollInfo(),i=e.getSheetViewDimension(),n=s+Math.max(0,(i.width-t.width)/2),r=o+Math.max(0,(i.height-t.height)/2);return e.getPositionAnchorOffset({x:n,y:r})}function LE(e,t){const s=qe(t),o=e.getSheetViewDimension(),i=o.width,n=o.height;if(s.width>i){const e=i/s.width;s.width=i,s.height=s.height*e}if(s.height>n){const e=n/s.height;s.height=n,s.width=s.width*e}return s}class kE{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}}const VE=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart","comboChart","radarChart"];function UE(e,t,s){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:s}}function HE(e){return String(e).replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"")}function zE(e){return new kE(e.map((([e,t])=>`${e}="${HE(t)}"`)).join(" "))}function BE(e,t="text/xml"){const s=(new DOMParser).parseFromString(e.toString(),t),o=s.querySelector("parsererror");if(o){const t=o.innerHTML,s=parseInt(t.split(":")[0],10),i=e.toString().trim().split("\n"),n=i.slice(Math.max(s-3,0),Math.min(s+2,i.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${n}`)}return s}function GE(e){if(e)return{style:e.style,color:{rgb:e.color}}}function WE(e,t){return qE`
2
- <Override ContentType="${t}" PartName="${e}" />
3
- `}function $E(e){return new kE(e.join("\n"))}function qE(e,...t){const s=[e[0]];for(let o=0;o<t.length;o++){const i=t[o]instanceof kE?t[o]:HE(t[o]);s.push(i+e[o+1])}return new kE(mt(s))}function ZE(e){return e.replace(/NAMESPACE.*NAMESPACE(.*)/,"$1")}function jE(e){return e.replaceAll(/([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,"NAMESPACE$1NAMESPACE$2")}function YE(e,t,o){if(!o.model.getters.getChartIdFromFigureId(e))return[];return s([{id:"edit",name:Go("Edit"),execute:()=>{o.model.dispatch("SELECT_FIGURE",{figureId:e}),o.openSidePanel("ChartPanel")},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall},XE(e,o),KE(e,o),JE(e,o),QE(e,o),eR(e,t,o)]).filter((e=>!o.model.getters.isReadonly()||e.isReadonlyAllowed))}function XE(e,t,s){return{id:"copy",name:Go("Copy"),description:"Ctrl+C",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e}),t.model.dispatch("COPY");const o=await t.model.getters.getClipboardTextAndImageContent();await t.clipboard.write(o),s&&t.notifyUser({sticky:!1,type:"success",text:s})},icon:"o-spreadsheet-Icon.CLIPBOARD"}}function KE(e,t){return{id:"cut",name:Go("Cut"),description:"Ctrl+X",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e}),t.model.dispatch("CUT"),await t.clipboard.write(await t.model.getters.getClipboardTextAndImageContent())},icon:"o-spreadsheet-Icon.CUT"}}function JE(e,t){return{id:"copy_as_image",name:Go("Copy as image"),icon:"o-spreadsheet-Icon.COPY_AS_IMAGE",execute:async()=>{const s=t.model.getters.getFigureSheetId(e),o=t.model.getters.getFigure(s,e),i=t.model.getters.getChartIdFromFigureId(e);if(!i)return;const n=t.model.getters.getChartType(i),r=t.model.getters.getChartRuntime(i),a=`<img src="${HE(SI(r,o,n))}" />`,l=await CI(r,o,n);t.clipboard.write({"text/html":a,"image/png":l}),t.notifyUser({sticky:!1,type:"success",text:Go("Chart copied to clipboard")})},isReadonlyAllowed:!0}}function QE(e,t){return{id:"download",name:Go("Download"),icon:"o-spreadsheet-Icon.DOWNLOAD",execute:async()=>{const s=t.model.getters.getFigureSheetId(e),o=t.model.getters.getFigure(s,e),i=t.model.getters.getChartIdFromFigureId(e);if(!i)return;const n=t.model.getters.getChartType(i);Jy(SI(t.model.getters.getChartRuntime(i),o,n),"chart")},isReadonlyAllowed:!0}}function eR(e,t,s){return{id:"delete",name:Go("Delete"),execute:()=>{s.model.dispatch("DELETE_FIGURE",{sheetId:s.model.getters.getActiveSheetId(),figureId:e}),t()},icon:"o-spreadsheet-Icon.TRASH"}}const tR={type:"bar",title:{},stacked:!1,dataSetsHaveTitle:!1,dataSets:[],legendPosition:"top",humanize:!0};function sR(e,t){if(t.title)return t.title;if("carouselDataView"===t.type)return Go("Data");const s=e.getChartDefinition(t.chartId);return(DE.getAll().find((e=>e.matcher?.(s)))||DE.get(s.type)).displayName}class oR extends ph{mutators=["toggleFullScreenFigure"];fullScreenFigure=void 0;toggleFullScreenFigure(e){this.fullScreenFigure?.id===e?this.fullScreenFigure=void 0:this.makeFullScreen(e)}makeFullScreen(e){const t=this.getters.getActiveSheetId(),s=this.getters.getFigure(t,e);s&&(this.fullScreenFigure={...s,x:0,y:0,width:0,height:0})}}function iR({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function nR(e){const t=rR(e);return e?(e.fillColor&&(t.background=e.fillColor),t):t}function rR(e){const t={};if(!e)return t;if(e.bold&&(t["font-weight"]="bold"),e.italic&&(t["font-style"]="italic"),e.fontSize&&(t["font-size"]=`${e.fontSize}px`),e.strikethrough||e.underline){let s=e.strikethrough?"line-through":"";s=e.underline?s+" underline":s,t["text-decoration"]=s}return e.textColor&&(t.color=e.textColor),t}function aR(e){let t="";for(const s in e)e[s]&&(t+=`${s}:${e[s]}; `);return t}class lR extends t.Component{static template="o-spreadsheet-Menu";static props={menuItems:Array,onClose:Function,onClickMenu:{type:Function,optional:!0},onMouseEnter:{type:Function,optional:!0},onMouseOver:{type:Function,optional:!0},onMouseLeave:{type:Function,optional:!0},width:{type:Number,optional:!0},isActive:{type:Function,optional:!0},onScroll:{type:Function,optional:!0}};static components={};static defaultProps={};hoveredMenu=void 0;setup(){t.onWillUnmount((()=>{this.hoveredMenu?.onStopHover?.(this.env)}))}get menuItemsAndSeparators(){const e=[];for(let t=0;t<this.props.menuItems.length;t++){const s=this.props.menuItems[t];s.isVisible(this.env)&&e.push(s),s.separator&&t!==this.props.menuItems.length-1&&"separator"!==e[e.length-1]&&e.push("separator")}return"separator"===e[e.length-1]&&e.pop(),1===e.length&&"separator"===e[0]?[]:e}get childrenHaveIcon(){return this.props.menuItems.some((e=>!!this.getIconName(e)))}getIconName(e){return e.icon(this.env)?e.icon(this.env):e.isActive?.(this.env)?"o-spreadsheet-Icon.CHECK":""}getColor(e){return aR({color:e.textColor})}getIconColor(e){return aR({color:e.iconColor})}getName(e){return e.name(this.env)}isRoot(e){return!e.execute}isEnabled(e){return!!e.isEnabled(this.env)&&(!this.env.model.getters.isReadonly()||e.isReadonlyAllowed)}get menuStyle(){return this.props.width?aR({width:this.props.width+"px"}):""}onMouseEnter(e,t){this.hoveredMenu=e,e.onStartHover?.(this.env),this.props.onMouseEnter?.(e,t)}onMouseLeave(e,t){this.hoveredMenu=void 0,e.onStopHover?.(this.env),this.props.onMouseLeave?.(e,t)}onClickMenu(e,t){this.isEnabled(e)&&this.props.onClickMenu?.(e,t)}}function cR(e){return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}function hR(e){if(e)return{x:e.left,y:e.top,width:e.right-e.left,height:e.bottom-e.top}}function dR(){const e=t.useState({x:0,y:0,width:0,height:0});let s=null;function o(){if(s||(s=document.querySelector(".o-spreadsheet")),s){const{top:t,left:o,width:i,height:n}=s.getBoundingClientRect();e.x=o,e.y=t,e.width=i,e.height=n}}return t.onMounted(o),t.onPatched(o),e}class uR extends t.Component{static template="o-spreadsheet-Popover";static props={anchorRect:Object,containerRect:{type:Object,optional:!0},positioning:{type:String,optional:!0},maxWidth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},verticalOffset:{type:Number,optional:!0},onMouseWheel:{type:Function,optional:!0},onPopoverHidden:{type:Function,optional:!0},onPopoverMoved:{type:Function,optional:!0},zIndex:{type:Number,optional:!0},class:{type:String,optional:!0},slots:Object};static defaultProps={positioning:"bottom-left",verticalOffset:0,onMouseWheel:()=>{},onPopoverMoved:()=>{},onPopoverHidden:()=>{}};popoverRef=t.useRef("popover");popoverContentRef=t.useRef("popoverContent");currentPosition=void 0;currentDisplayValue=void 0;spreadsheetRect=dR();containerRect;setup(){this.containerRect=function(){const e=t.useState({x:0,y:0,width:0,height:0}),s=t.useComponent(),o=dR();function i(){const t=s.env,i="getPopoverContainerRect"in t&&t.getPopoverContainerRect?t.getPopoverContainerRect():o;e.x=i.x,e.y=i.y,e.width=i.width,e.height=i.height}return i(),t.onMounted(i),t.onPatched(i),e}();const e=new ResizeObserver(this.computePopoverPosition.bind(this));t.onMounted((()=>{e.observe(this.popoverContentRef.el)})),t.onWillUnmount((()=>{e.disconnect()})),t.useEffect(this.computePopoverPosition.bind(this))}computePopoverPosition(){if(!this.containerRect)throw new Error("Popover container is not defined");const e=this.popoverRef.el,t=this.popoverContentRef.el,s=(o=this.props.anchorRect,i=this.containerRect,hR(Rs(cR(o),cR(i))));var o,i;const n=s?"block":"none";if("none"!==this.currentDisplayValue&&"none"===n&&this.props.onPopoverHidden?.(),e.style.display=n,this.currentDisplayValue=n,!s)return;const r={width:this.props.maxWidth,height:this.props.maxHeight};let a={width:t.getBoundingClientRect().width,height:t.getBoundingClientRect().height};const l=this.spreadsheetRect,c="bottom-left"===this.props.positioning?new pR(s,this.containerRect,r,l,this.currentPosition):new mR(s,this.containerRect,r,l,this.currentPosition);e.style["max-height"]=c.getMaxHeight(a.height)+"px",e.style["max-width"]=c.getMaxWidth(a.width)+"px",a={width:e.getBoundingClientRect().width,height:e.getBoundingClientRect().height};const h=c.getCss(a,this.props.verticalOffset);for(const t of Object.keys(h))e.style[t]=h[t];const d=c.getCurrentPosition(a);this.currentPosition&&d!==this.currentPosition&&this.props.onPopoverMoved?.(),this.currentPosition=d}}class gR{anchorRect;containerRect;propsMaxSize;spreadsheetOffset;lastPosition;constructor(e,t,s,o,i){this.anchorRect=e,this.containerRect=t,this.propsMaxSize=s,this.spreadsheetOffset=o,this.lastPosition=i}shouldRenderAtBottom(e){if("top-left"===this.lastPosition||"top-right"===this.lastPosition){return!(e<=this.availableHeightUp||this.availableHeightUp>=this.availableHeightDown)}return e<=this.availableHeightDown||this.availableHeightDown>=this.availableHeightUp}shouldRenderAtRight(e){if("bottom-left"===this.lastPosition||"top-left"===this.lastPosition){return!(e<=this.availableWidthLeft||this.availableWidthLeft>=this.availableWidthRight)}return e<=this.availableWidthRight||this.availableWidthRight>=this.availableWidthLeft}getMaxHeight(e){const t=this.shouldRenderAtBottom(e)?this.availableHeightDown:this.availableHeightUp;return this.propsMaxSize.height?Math.min(t,this.propsMaxSize.height):t}getMaxWidth(e){const t=this.shouldRenderAtRight(e)?this.availableWidthRight:this.availableWidthLeft;return this.propsMaxSize.width?Math.min(t,this.propsMaxSize.width):t}getCss(e,t){const s=this.getMaxHeight(e.height),o=this.getMaxWidth(e.width),i=Math.min(s,e.height),n=Math.min(o,e.width),r=this.shouldRenderAtBottom(e.height),a=this.shouldRenderAtRight(e.width);return t=r?t:-t,{top:this.getTopCoordinate(i,r)-this.spreadsheetOffset.y-t+"px",left:this.getLeftCoordinate(n,a)-this.spreadsheetOffset.x+"px"}}getCurrentPosition(e){const t=this.shouldRenderAtBottom(e.height),s=this.shouldRenderAtRight(e.width);return t&&s?"bottom-right":t&&!s?"bottom-left":!t&&s?"top-right":"top-left"}}class pR extends gR{get availableHeightUp(){return this.anchorRect.y-this.containerRect.y}get availableHeightDown(){return this.containerRect.height-this.availableHeightUp-this.anchorRect.height}get availableWidthRight(){return this.containerRect.x+this.containerRect.width-this.anchorRect.x}get availableWidthLeft(){return this.anchorRect.x+this.anchorRect.width-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y+this.anchorRect.height:this.anchorRect.y-e}getLeftCoordinate(e,t){return t?this.anchorRect.x:this.anchorRect.x+this.anchorRect.width-e}}class mR extends gR{get availableHeightUp(){return this.anchorRect.y+this.anchorRect.height-this.containerRect.y}get availableHeightDown(){return this.containerRect.y+this.containerRect.height-this.anchorRect.y}get availableWidthRight(){return this.containerRect.width-this.anchorRect.width-this.availableWidthLeft}get availableWidthLeft(){return this.anchorRect.x-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y:this.anchorRect.y+this.anchorRect.height-e}getLeftCoordinate(e,t){return t?this.anchorRect.x+this.anchorRect.width:this.anchorRect.x-e}}class fR extends t.Component{static template="o-spreadsheet-Menu-Popover";static props={anchorRect:Object,popoverPositioning:{type:String,optional:!0},menuItems:Array,depth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},onClose:Function,onMenuClicked:{type:Function,optional:!0},menuId:{type:String,optional:!0},onMouseOver:{type:Function,optional:!0},width:{type:Number,optional:!0}};static components={MenuPopover:fR,Menu:lR,Popover:uR};static defaultProps={depth:1,popoverPositioning:"top-right"};subMenu=t.useState({isOpen:!1,anchorRect:null,scrollOffset:0,menuItems:[],isHoveringChild:!1});menuRef=t.useRef("menu");hoveredMenu=void 0;openingTimeOut=function(){let e;function s(){void 0!==e&&(clearTimeout(e),e=void 0)}return t.onWillUnmount(s),{clear:s,schedule:function(t,o){s(),e=setTimeout(t,o)}}}();setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.useExternalListener(window,"contextmenu",this.onExternalClick,{capture:!0}),t.onWillUpdateProps((e=>{e.menuItems!==this.props.menuItems&&this.closeSubMenu()})),t.onWillUnmount((()=>{this.hoveredMenu?.onStopHover?.(this.env)}))}get menuProps(){return{menuItems:this.props.menuItems,onClose:this.close.bind(this),onClickMenu:this.onClickMenu.bind(this),onMouseOver:this.onMouseOver.bind(this),onMouseLeave:this.onMouseLeave.bind(this),width:this.props.width||250,isActive:this.isActive.bind(this),onScroll:this.onScroll.bind(this)}}get subMenuAnchorRect(){const e=Object.assign({},this.subMenu.anchorRect);return e.y-=this.subMenu.scrollOffset||0,e}get popoverProps(){const e=1===this.props.depth;return{anchorRect:{x:this.props.anchorRect.x,y:this.props.anchorRect.y,width:e?this.props.anchorRect.width:this.props.width||250,height:e?this.props.anchorRect.height:26},positioning:this.props.popoverPositioning,verticalOffset:e?0:6,onPopoverHidden:()=>this.closeSubMenu(),onPopoverMoved:()=>this.closeSubMenu(),maxHeight:this.props.maxHeight}}get childrenHaveIcon(){return this.props.menuItems.some((e=>!!this.getIconName(e)))}getIconName(e){return e.icon(this.env)?e.icon(this.env):e.isActive?.(this.env)?"o-spreadsheet-Icon.CHECK":""}getColor(e){return aR({color:e.textColor})}getIconColor(e){return aR({color:e.iconColor})}async activateMenu(e,t){const s=await(e.execute?.(this.env,t));this.close(),this.props.onMenuClicked?.({detail:s})}close(){this.closeSubMenu(),this.props.onClose()}onExternalClick(e){this.menuRef.el&&Array.from(document.querySelectorAll(".o-spreadsheet .o-menu")).some((t=>Hy(t,e)))||(e.closedMenuId=this.props.menuId,this.close())}getName(e){return e.name(this.env)}isRoot(e){return!e.execute}isEnabled(e){return!!e.isEnabled(this.env)&&(!this.env.model.getters.isReadonly()||e.isReadonlyAllowed)}isActive(e){return!!this.subMenu?.isHoveringChild&&this.isParentMenu(this.subMenu,e)}onScroll(e){this.subMenu.scrollOffset=e.target.scrollTop}openSubMenu(e,t){if(!t)return;const s=t.getBoundingClientRect().top;this.subMenu.anchorRect={x:By(this.menuRef).x,y:s-(this.subMenu.scrollOffset||0),width:this.props.width||250,height:26},this.subMenu.menuItems=e.children(this.env),this.subMenu.isOpen=!0,this.subMenu.parentMenu=e}isParentMenu(e,t){return e.parentMenu?.id===t.id}closeSubMenu(){this.subMenu.isHoveringChild||(this.subMenu.isOpen=!1,this.subMenu.parentMenu=void 0)}onClickMenu(e,t){this.isRoot(e)?this.openSubMenu(e,t.currentTarget):this.activateMenu(e,Ky(t))}onMouseOver(e,t){if(this.isEnabled(e)){if(this.isParentMenu(this.subMenu,e))return void this.openingTimeOut.clear();const s=t.currentTarget;this.isRoot(e)&&this.openingTimeOut.schedule((()=>{this.openSubMenu(e,s)}),250)}}onMouseOverMainMenu(){this.props.onMouseOver?.(),this.subMenu.isHoveringChild=!1}onMouseOverChildMenu(){this.subMenu.isHoveringChild=!0,this.openingTimeOut.clear()}onMouseLeave(e){this.openingTimeOut.schedule(this.closeSubMenu.bind(this),250)}get menuStyle(){return this.props.width?aR({width:this.props.width+"px"}):""}}class vR extends t.Component{static template="o-spreadsheet-ChartDashboardMenu";static components={MenuPopover:fR};static props={chartId:String,hasFullScreenButton:{type:Boolean,optional:!0}};static defaultProps={hasFullScreenButton:!0};fullScreenFigureStore;menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});setup(){super.setup(),this.fullScreenFigureStore=rh(oR)}getMenuItems(){return[this.fullScreenMenuItem].filter(ut)}get backgroundColor(){return"background-color: "+(this.env.model.getters.getChartDefinition(this.props.chartId).background||M)}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.anchorRect={x:e.clientX,y:e.clientY,width:0,height:0};const t=this.env.model.getters.getFigureIdFromChartId(this.props.chartId);this.menuState.menuItems=YE(t,(()=>{}),this.env)}get fullScreenMenuItem(){if(!this.props.hasFullScreenButton)return;const e=this.env.model.getters.getChartDefinition(this.props.chartId),t=this.env.model.getters.getFigureIdFromChartId(this.props.chartId);if("scorecard"===e.type)return;const s=t===this.fullScreenFigureStore.fullScreenFigure?.id;return{id:"fullScreenChart",label:Go(s?"Exit Full Screen":"Full Screen"),class:"text-muted fa "+(s?"fa-compress":"fa-expand"),onClick:()=>{this.fullScreenFigureStore.toggleFullScreenFigure(t)}}}}class bR extends t.Component{static template="o-spreadsheet-CarouselFigure";static props={figureUI:Object,onFigureDeleted:Function,editFigureStyle:{type:Function,optional:!0},isFullScreen:{type:Boolean,optional:!0}};static components={ChartDashboardMenu:vR,MenuPopover:fR};carouselTabsRef=t.useRef("carouselTabs");carouselTabsDropdownRef=t.useRef("carouselTabsDropdown");menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});hiddenItems=[];animationStore;fullScreenFigureStore;setup(){this.animationStore=rh(Sh),this.fullScreenFigureStore=rh(oR),t.useEffect((()=>{"carouselDataView"===this.selectedCarouselItem?.type?this.props.editFigureStyle?.({"pointer-events":"none"}):this.props.editFigureStyle?.({"pointer-events":"auto"}),this.updateTabsVisibility()}))}get carousel(){return this.env.model.getters.getCarousel(this.props.figureUI.id)}get selectedCarouselItem(){return this.env.model.getters.getSelectedCarouselItem(this.props.figureUI.id)}get chartComponent(){const e=this.selectedCarouselItem;if("chart"!==e?.type)throw new Error("Selected item is not a chart");const t=this.env.model.getters.getChartType(e.chartId),s=TE.get(t);if(!s)throw new Error(`Component is not defined for type ${t}`);return s}onCarouselDoubleClick(){this.env.model.dispatch("SELECT_FIGURE",{figureId:this.props.figureUI.id}),this.env.openSidePanel("CarouselPanel",{figureId:this.props.figureUI.id})}isItemSelected(e){return St(this.selectedCarouselItem,e)}getItemTitle(e){return sR(this.env.model.getters,e)}onCarouselTabClick(e){if(this.env.model.dispatch("UPDATE_CAROUSEL_ACTIVE_ITEM",{figureId:this.props.figureUI.id,sheetId:this.env.model.getters.getActiveSheetId(),item:e}),"chart"===e.type){const t=e.chartId+(this.props.isFullScreen?"-fullscreen":"");this.animationStore?.enableAnimationForChart(t)}}get headerStyle(){const e={};if("chart"===this.selectedCarouselItem?.type){const t=this.env.model.getters.getChartRuntime(this.selectedCarouselItem.chartId);e["background-color"]=t.background}else e["background-color"]="#ffffff";return aR(e)}get title(){return this.carousel.title?.text??""}get titleStyle(){return aR(rR(function(e){return{bold:e.bold,italic:e.italic,fontSize:e.fontSize,textColor:e.color,align:e.align}}({...He,...this.carousel.title})))}updateTabsVisibility(){const e=this.carouselTabsRef.el,t=this.carouselTabsDropdownRef.el;if(!e||!t)return;this.hiddenItems=[];const s=Gy(e),o=Array.from(e.children);for(const e of o)e.style.display="block";const i=o.map((e=>Gy(e).width));let n=0;for(let e=0;e<o.length;e++){const t=n+i[e]>s.width;n+=i[e],t&&(o[e].style.display="none",this.hiddenItems.push(this.carousel.items[e]))}t.style.display=this.hiddenItems.length?"block":"none"}get menuId(){return"carousel-tabs-menu-"}toggleMenu(e){if(e.closedMenuId===this.menuId)return void(this.menuState.isOpen=!1);const t=By(this.carouselTabsDropdownRef),o=this.hiddenItems.map((e=>({name:this.getItemTitle(e),execute:()=>this.onCarouselTabClick(e),isActive:()=>this.isItemSelected(e),isReadonlyAllowed:!0})));this.menuState.isOpen=!0,this.menuState.anchorRect=t,this.menuState.menuItems=s(o)}toggleFullScreen(){"chart"===this.selectedCarouselItem?.type&&this.fullScreenFigureStore.toggleFullScreenFigure(this.props.figureUI.id)}get fullScreenButtonTitle(){return this.props.isFullScreen?Go("Exit Full Screen"):Go("Full Screen")}get visibleCarouselItems(){return this.carousel.items.filter((e=>"carouselDataView"!==e.type||!this.props.isFullScreen))}}class SR extends t.Component{static template="o-spreadsheet-ChartFigure";static props={figureUI:Object,onFigureDeleted:Function,editFigureStyle:{type:Function,optional:!0},isFullScreen:{type:Boolean,optional:!0}};static components={ChartDashboardMenu:vR};onDoubleClick(){this.env.model.dispatch("SELECT_FIGURE",{figureId:this.props.figureUI.id}),this.env.openSidePanel("ChartPanel")}get chartType(){return this.env.model.getters.getChartType(this.chartId)}get chartId(){const e=this.env.model.getters.getChartIdFromFigureId(this.props.figureUI.id);if(!e)throw new Error(`No chart found for figure ID: ${this.props.figureUI.id}`);return e}get chartComponent(){const e=this.chartType,t=TE.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}class CR extends t.Component{static template="o-spreadsheet-ImageFigure";static props={figureUI:Object,onFigureDeleted:Function,editFigureStyle:{type:Function,optional:!0}};static components={};get figureId(){return this.props.figureUI.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}}const yR=new n;yR.add("chart",{Component:SR,SidePanelComponent:"ChartPanel",menuBuilder:YE}),yR.add("image",{Component:CR,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t,o){return s([XE(e,o,Go("Image copied to clipboard")),KE(e,o),{id:"reset_size",name:Go("Reset size"),execute:async()=>{const t=o.model.getters.getActiveSheetId(),s=o.model.getters.getFigure(t,e);if(!s)return;const i=o.model.getters.getImagePath(e),n=o.model.getters.getImageSize(e)??await(o.imageProvider?.getImageOriginalSize(i));if(!o.model.getters.getImageSize(e)){o.model.getters.getImage(e).size=n}const{col:r,row:a}=s,{height:l,width:c}=LE(o.model.getters,n);o.model.dispatch("UPDATE_FIGURE",{sheetId:t,figureId:e,height:l,width:c,col:r,row:a})},icon:"o-spreadsheet-Icon.REFRESH"},{id:"download",name:Go("Download"),execute:async()=>{o.model.dispatch("SELECT_FIGURE",{figureId:e});Jy(o.model.getters.getImagePath(e),"image")},icon:"o-spreadsheet-Icon.DOWNLOAD"},eR(e,t,o)])}}),yR.add("carousel",{Component:bR,menuBuilder:function(e,t,o){const i=t=>"chart"===t.model.getters.getSelectedCarouselItem(e)?.type;return s([{id:"edit_carousel",name:Go("Edit carousel"),execute:()=>{o.model.dispatch("SELECT_FIGURE",{figureId:e}),o.openSidePanel("CarouselPanel",{figureId:e})},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall},{...XE(e,o,Go("Carousel copied to clipboard")),name:Go("Copy carousel")},{...KE(e,o),name:Go("Cut carousel")},{...eR(e,t,o),name:Go("Delete carousel"),separator:!0},{id:"edit_chart",name:Go("Edit chart"),execute:()=>{o.model.dispatch("SELECT_FIGURE",{figureId:e}),o.openSidePanel("ChartPanel",{})},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall,isVisible:i},{...JE(e,o),isVisible:i,name:Go("Copy chart as image")},{...QE(e,o),isVisible:i,name:Go("Download chart")},{id:"popout_chart",name:Go("Pop out chart"),icon:"o-spreadsheet-Icon.EXTERNAL",execute:()=>{const t=o.model.getters.getSelectedCarouselItem(e);t&&"chart"===t.type&&o.model.dispatch("POPOUT_CHART_FROM_CAROUSEL",{carouselId:e,chartId:t.chartId,sheetId:o.model.getters.getActiveSheetId()})},isVisible:i},{id:"delete_carousel_item",name:t=>{const s=t.model.getters.getSelectedCarouselItem(e);return Go("chart"===s?.type?"Delete chart":"Delete data view")},execute:()=>{const t=o.model.getters.getSelectedCarouselItem(e);if(!t)return;const s=o.model.getters.getCarousel(e),i=s.items.filter((e=>!St(e,t)));o.model.dispatch("UPDATE_CAROUSEL",{figureId:e,sheetId:o.model.getters.getActiveSheetId(),definition:{...s,items:i}})},icon:"o-spreadsheet-Icon.TRASH",isVisible:t=>t.model.getters.getCarousel(e).items.length>=1}]).filter((e=>!o.model.getters.isReadonly()||e.isReadonlyAllowed))}});class IR extends t.Component{static template="o-spreadsheet-FigureComponent";static props={figureUI:Object,style:{type:String,optional:!0},class:{type:String,optional:!0},onFigureDeleted:{type:Function,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}};static components={MenuPopover:fR};static defaultProps={onFigureDeleted:()=>{},onMouseDown:()=>{},onClickAnchor:()=>{}};menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});figureRef=t.useRef("figure");figureWrapperRef=t.useRef("figureWrapper");menuButtonRef=t.useRef("menuButton");borderWidth;get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figureUI.id}get figureRegistry(){return yR}getBorderWidth(){return this.env.isDashboard()?0:this.isSelected?2:this.borderWidth}getBorderStyle(e){return`border-${e}-width: ${this.getBorderWidth()}px;`}get wrapperStyle(){const{x:e,y:t,width:s,height:o}=this.props.figureUI;return aR({left:`${e}px`,top:`${t}px`,width:`${s}px`,height:`${o}px`})}getResizerPosition(e){const t={};return e.includes("top")?t.top="-3px":e.includes("bottom")?t.bottom="-3px":t.bottom="calc(50% - 3px)",e.includes("left")?t.left="-3px":e.includes("right")?t.right="-3px":t.right="calc(50% - 3px)",aR(t)}setup(){const e=yR.get(this.props.figureUI.tag).borderWidth;this.borderWidth=void 0!==e?e:1,t.useEffect(((e,t,s)=>{e===t&&s?.focus({preventScroll:!0})}),(()=>[this.env.model.getters.getSelectedFigureId(),this.props.figureUI.id,this.figureRef.el])),t.onWillUnmount((()=>{this.props.onFigureDeleted()}))}clickAnchor(e,t,s){this.props.onClickAnchor(e,t,s)}onMouseDown(e){this.env.isMobile()||this.props.onMouseDown(e)}onClick(e){this.env.isMobile()&&this.props.onMouseDown(e)}onKeyDown(e){const t=jy(e);switch(t){case"Delete":case"Backspace":this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),figureId:this.props.figureUI.id}),this.props.onFigureDeleted(),e.preventDefault(),e.stopPropagation();break;case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":const{col:s,row:o,offset:i}=this.postionInBoundary(this.props.figureUI,e.key);this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),figureId:this.props.figureUI.id,offset:i,col:s,row:o}),e.preventDefault(),e.stopPropagation();break;case"Ctrl+A":e.preventDefault(),e.stopPropagation();break;case"Ctrl+Y":case"Ctrl+Z":"Ctrl+Y"===t?this.env.model.dispatch("REQUEST_REDO"):"Ctrl+Z"===t&&this.env.model.dispatch("REQUEST_UNDO"),e.preventDefault(),e.stopPropagation()}}postionInBoundary(e,t){const s=this.env.model.getters.getActiveSheetId();let{col:o,row:i,offset:n}=e;switch(n={...n},t){case"ArrowUp":0===n.y?(i--,n.y=this.env.model.getters.getRowSize(s,i)-1):n.y--;break;case"ArrowLeft":0===n.x?(o--,n.x=this.env.model.getters.getColSize(s,o)-1):n.x--;break;case"ArrowDown":n.y===this.env.model.getters.getRowSize(s,i)?(i++,n.y=0):n.y++;break;case"ArrowRight":n.x===this.env.model.getters.getColSize(s,i)?(o++,n.x=0):n.x++}return{col:o,row:i,offset:n}}onContextMenu(e){this.env.isDashboard()||this.openContextMenu({x:e.clientX,y:e.clientY,width:0,height:0})}showMenu(){this.openContextMenu(By(this.menuButtonRef))}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.anchorRect=e,this.menuState.menuItems=yR.get(this.props.figureUI.tag).menuBuilder(this.props.figureUI.id,this.props.onFigureDeleted,this.env)}editWrapperStyle(e){if(this.figureWrapperRef.el)for(const t in e)this.figureWrapperRef.el.style.setProperty(t,e[t]||null)}}class wR extends ph{mutators=["clear","hover"];col;row;handle(e){if("ACTIVATE_SHEET"===e.type)this.clear()}hover(e){if(e.col===this.col&&e.row===this.row)return"noStateChange";this.col=e.col,this.row=e.row}clear(){if(void 0===this.col&&void 0===this.row)return"noStateChange";this.col=void 0,this.row=void 0}}const ER=new n;class RR extends ph{mutators=["open","close"];persistentPopover;hoveredCell=this.get(wR);handle(e){if("ACTIVATE_SHEET"===e.type)this.close()}open({col:e,row:t},s){const o=this.getters.getActiveSheetId();ER.contains(s)&&(this.persistentPopover={col:e,row:t,sheetId:o,type:s})}close(){if(!this.persistentPopover)return"noStateChange";this.persistentPopover=void 0}get persistentCellPopover(){return this.persistentPopover&&{isOpen:!0,...this.persistentPopover}||{isOpen:!1}}get isOpen(){return void 0!==this.persistentPopover}get cellPopover(){const e=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=ER.get(this.persistentPopover.type).onOpen?.(e,this.getters);return t?.isOpen?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}const{col:t,row:s}=this.hoveredCell;if(void 0===t||void 0===s||!this.getters.isVisibleInViewport({sheetId:e,col:t,row:s}))return{isOpen:!1};const o=this.getters.getMainCellPosition({sheetId:e,col:t,row:s}),i=ER.getAll().map((e=>e.onHover?.(o,this.getters))).find((e=>e?.isOpen));return i?.isOpen?{...i,anchorRect:this.computePopoverAnchorRect(o)}:{isOpen:!1}}computePopoverAnchorRect({col:e,row:t}){const s=this.getters.getActiveSheetId(),o=this.getters.getMerge({sheetId:s,col:e,row:t});return o?this.getters.getVisibleRect(o):this.getters.getVisibleRect(Us({col:e,row:t}))}}class xR extends t.Component{static maxSize={maxHeight:80};static template="o-spreadsheet-ErrorToolTip";static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};get dataValidationErrorMessage(){return this.env.model.getters.getInvalidDataValidationMessage(this.props.cellPosition)}get evaluationError(){const e=this.env.model.getters.getEvaluatedCell(this.props.cellPosition);if(e.message)return e}get errorOriginPositionString(){if(this.env.model.getters.isDashboard())return"";const e=this.evaluationError,t=e?.errorOriginPosition;if(!t||St(t,this.props.cellPosition))return"";const s=t.sheetId;return this.env.model.getters.getRangeString(this.env.model.getters.getRangeFromZone(s,Us(t)),this.env.model.getters.getActiveSheetId())}selectCell(){const e=this.evaluationError?.errorOriginPosition;if(!e)return;const t=this.env.model.getters.getActiveSheetId();e.sheetId!==t&&this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:e.sheetId}),this.env.model.selection.selectCell(e.col,e.row)}}const TR={onHover:(e,t)=>{const s=t.getEvaluatedCell(e);return s.type===r.error&&s.message||t.getInvalidDataValidationMessage(e)?{isOpen:!0,props:{cellPosition:e},Component:xR,cellCorner:"top-right"}:{isOpen:!1}}};class AR extends t.Component{static template="o-spreadsheet-Collapse";static props={isCollapsed:Boolean,slots:Object};contentRef=t.useRef("content");setup(){t.onMounted((()=>{this.props.isCollapsed&&this.contentRef.el?.classList.add("d-none")})),t.onWillUpdateProps((e=>{e.isCollapsed!==this.props.isCollapsed&&this.startTransition(e.isCollapsed)}))}startTransition(e){const t=this.contentRef.el;if(!t)return;t.classList.remove("d-none"),t.classList.add("overflow-hidden");const s=e?t.scrollHeight:0,o=e?0:t.scrollHeight;t.animate([{maxHeight:s+"px"},{maxHeight:o+"px"}],{duration:350,easing:"ease"}).onfinish=()=>{t.classList.remove("overflow-hidden"),this.props.isCollapsed&&t.classList.add("d-none")}}}class DR extends t.Component{static template="o-spreadsheet-SidePanelCollapsible";static props={slots:Object,title:{type:String,optional:!0},isInitiallyCollapsed:{type:Boolean,optional:!0},class:{type:String,optional:!0}};static components={Collapse:AR};state=t.useState({isCollapsed:this.props.isInitiallyCollapsed});toggle(){this.state.isCollapsed=!this.state.isCollapsed}}class _R extends t.Component{static props={criterion:Object,onCriterionChanged:Function,disableFormulas:{type:Boolean,optional:!0}};setup(){const e=rh(fh);t.onMounted((()=>{e.activeComposer.stopEdition()}))}updateCriterion(e){const t={...this.props.criterion,...e};this.props.onCriterionChanged(t)}}const FR=new n;FR.add("containsText",{type:"containsText",isValueValid:(e,t)=>String(e).toLowerCase().includes(String(t.values[0]).toLowerCase()),getErrorString:e=>Go('The value must be a text that contains "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:rb.CriterionError.notEmptyValue,numberOfValues:()=>1,name:Go("Text contains"),getPreview:e=>Go('Text contains "%s"',e.values[0])}),FR.add("notContainsText",{type:"notContainsText",isValueValid:(e,t)=>!String(e).toLowerCase().includes(String(t.values[0]).toLowerCase()),getErrorString:e=>Go('The value must be a text that does not contain "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:rb.CriterionError.notEmptyValue,numberOfValues:()=>1,name:Go("Text does not contain"),getPreview:e=>Go('Text does not contain "%s"',e.values[0])}),FR.add("isEqualText",{type:"isEqualText",isValueValid:(e,t)=>String(e).toLowerCase()===String(t.values[0]).toLowerCase(),getErrorString:e=>Go('The value must be exactly "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:rb.CriterionError.notEmptyValue,numberOfValues:()=>1,name:Go("Text is exactly"),getPreview:e=>Go('Text is exactly "%s"',e.values[0])});const OR=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/;function PR(e,t){return e.values.map((e=>void 0!==e?yl(String(e),t):Mi.InvalidReference))}function MR(e,t){return Ur(e,w).map((e=>void 0!==e?or(e,{locale:t,format:t.dateFormat}):Mi.InvalidReference))}function NR(e){return void 0!==ui(e,w)}function LR(e){return void 0!==Xi(e,w)}FR.add("isEmail",{type:"isEmail",isValueValid:(e,t)=>"string"==typeof e&&OR.test(e),getErrorString:()=>Go("The value must be a valid email address"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:Go("Text is valid email"),getPreview:()=>Go("Text is valid email")}),FR.add("isLink",{type:"isLink",isValueValid:(e,t)=>void 0!==Jo(e),getErrorString:()=>Go("The value must be a valid link"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:Go("Text is valid link"),getPreview:()=>Go("Text is valid link")}),FR.add("dateIs",{type:"dateIs",isValueValid:(e,t)=>{const s=Ur(t,w)[0],o=ui(e,w);if(void 0===o||void 0===s)return!1;if(["lastWeek","lastMonth","lastYear"].includes(t.dateValue)){return Ti(o,vi(Qo.now()),s)}return i=o,n=s,Math.trunc(i)===Math.trunc(n);var i,n},getErrorString:(e,t)=>{const s=t.getLocale();return"exactDate"===e.dateValue?Go("The value must be the date %s",MR(e,s)[0]):Go("The value must be %s",rb.DateIs[e.dateValue])},isCriterionValueValid:e=>NR(e),criterionValueErrorString:rb.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:Go("Date is"),getPreview:(e,t)=>"exactDate"===e.dateValue?Go("Date is %s",Hr(e.values,t.getLocale())[0]):Go("Date is %s",rb.DateIs[e.dateValue])}),FR.add("dateIsBefore",{type:"dateIsBefore",isValueValid:(e,t)=>{const s=Ur(t,w)[0],o=ui(e,w);return void 0!==o&&void 0!==s&&function(e,t){return Math.trunc(e)<Math.trunc(t)}(o,s)},getErrorString:(e,t)=>{const s=t.getLocale();return"exactDate"===e.dateValue?Go("The value must be a date before %s",MR(e,s)[0]):Go("The value must be a date before %s",rb.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>NR(e),criterionValueErrorString:rb.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:Go("Date is before"),getPreview:(e,t)=>"exactDate"===e.dateValue?Go("Date is before %s",Hr(e.values,t.getLocale())[0]):Go("Date is before %s",rb.DateIsBefore[e.dateValue])}),FR.add("dateIsOnOrBefore",{type:"dateIsOnOrBefore",isValueValid:(e,t)=>{const s=Ur(t,w)[0],o=ui(e,w);return void 0!==o&&void 0!==s&&function(e,t){return Math.trunc(e)<=Math.trunc(t)}(o,s)},getErrorString:(e,t)=>{const s=t.getLocale();return"exactDate"===e.dateValue?Go("The value must be a date on or before %s",MR(e,s)[0]):Go("The value must be a date on or before %s",rb.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>NR(e),criterionValueErrorString:rb.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:Go("Date is on or before"),getPreview:(e,t)=>"exactDate"===e.dateValue?Go("Date is on or before %s",Hr(e.values,t.getLocale())[0]):Go("Date is on or before %s",rb.DateIsBefore[e.dateValue])}),FR.add("dateIsAfter",{type:"dateIsAfter",isValueValid:(e,t)=>{const s=Ur(t,w)[0],o=ui(e,w);return void 0!==o&&void 0!==s&&function(e,t){return Math.trunc(e)>Math.trunc(t)}(o,s)},getErrorString:(e,t)=>{const s=t.getLocale();return"exactDate"===e.dateValue?Go("The value must be a date after %s",MR(e,s)[0]):Go("The value must be a date after %s",rb.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>NR(e),criterionValueErrorString:rb.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:Go("Date is after"),getPreview:(e,t)=>"exactDate"===e.dateValue?Go("Date is after %s",Hr(e.values,t.getLocale())[0]):Go("Date is after %s",rb.DateIsBefore[e.dateValue])}),FR.add("dateIsOnOrAfter",{type:"dateIsOnOrAfter",isValueValid:(e,t)=>{const s=Ur(t,w)[0],o=ui(e,w);return void 0!==o&&void 0!==s&&function(e,t){return Math.trunc(e)>=Math.trunc(t)}(o,s)},getErrorString:(e,t)=>{const s=t.getLocale();return"exactDate"===e.dateValue?Go("The value must be a date on or after %s",MR(e,s)[0]):Go("The value must be a date on or after %s",rb.DateIsBefore[e.dateValue])},isCriterionValueValid:e=>NR(e),criterionValueErrorString:rb.CriterionError.dateValue,numberOfValues:e=>"exactDate"===e.dateValue?1:0,name:Go("Date is on or after"),getPreview:(e,t)=>"exactDate"===e.dateValue?Go("Date is on or after %s",Hr(e.values,t.getLocale())[0]):Go("Date is on or after %s",rb.DateIsBefore[e.dateValue])}),FR.add("dateIsBetween",{type:"dateIsBetween",isValueValid:(e,t)=>{const s=Ur(t,w),o=ui(e,w);return void 0!==o&&void 0!==s[0]&&void 0!==s[1]&&Ti(o,s[0],s[1])},getErrorString:(e,t)=>{const s=MR(e,t.getLocale());return Go("The value must be a date between %s and %s",s[0],s[1])},isCriterionValueValid:e=>NR(e),criterionValueErrorString:rb.CriterionError.dateValue,numberOfValues:()=>2,name:Go("Date is between"),getPreview:(e,t)=>{const s=Hr(e.values,t.getLocale());return Go("Date is between %s and %s",s[0],s[1])}}),FR.add("dateIsNotBetween",{type:"dateIsNotBetween",isValueValid:(e,t)=>{const s=Ur(t,w),o=ui(e,w);return void 0!==o&&void 0!==s[0]&&void 0!==s[1]&&!Ti(o,s[0],s[1])},getErrorString:(e,t)=>{const s=MR(e,t.getLocale());return Go("The value must be a date not between %s and %s",s[0],s[1])},isCriterionValueValid:e=>NR(e),criterionValueErrorString:rb.CriterionError.dateValue,numberOfValues:()=>2,name:Go("Date is not between"),getPreview:(e,t)=>{const s=Hr(e.values,t.getLocale());return Go("Date is not between %s and %s",s[0],s[1])}}),FR.add("dateIsValid",{type:"dateIsValid",isValueValid:(e,t)=>void 0!==ui(e,w),getErrorString:()=>Go("The value must be a valid date"),isCriterionValueValid:e=>NR(e),criterionValueErrorString:"",numberOfValues:()=>0,name:Go("Is valid date"),getPreview:()=>Go("Date is valid")}),FR.add("isEqual",{type:"isEqual",isValueValid:(e,t)=>e===t.values[0],getErrorString:(e,t)=>{const s=PR(e,t.getLocale());return Go("The value must be equal to %s",s[0])},isCriterionValueValid:e=>LR(e),criterionValueErrorString:rb.CriterionError.numberValue,numberOfValues:()=>1,name:Go("Is equal to"),getPreview:e=>Go("Value is equal to %s",e.values[0])}),FR.add("isNotEqual",{type:"isNotEqual",isValueValid:(e,t)=>e!==t.values[0],getErrorString:(e,t)=>{const s=PR(e,t.getLocale());return Go("The value must not be equal to %s",s[0])},isCriterionValueValid:e=>LR(e),criterionValueErrorString:rb.CriterionError.numberValue,numberOfValues:()=>1,name:Go("Is not equal to"),getPreview:e=>Go("Value is not equal to %s",e.values[0])}),FR.add("isGreaterThan",{type:"isGreaterThan",isValueValid:(e,t)=>{if("number"!=typeof e)return!1;const s=t.values[0];return"number"==typeof s&&e>s},getErrorString:(e,t)=>{const s=PR(e,t.getLocale());return Go("The value must be greater than %s",s[0])},isCriterionValueValid:e=>LR(e),criterionValueErrorString:rb.CriterionError.numberValue,numberOfValues:()=>1,name:Go("Is greater than"),getPreview:e=>Go("Value is greater than %s",e.values[0])}),FR.add("isGreaterOrEqualTo",{type:"isGreaterOrEqualTo",isValueValid:(e,t)=>{if("number"!=typeof e)return!1;const s=t.values[0];return"number"==typeof s&&e>=s},getErrorString:(e,t)=>{const s=PR(e,t.getLocale());return Go("The value must be greater or equal to %s",s[0])},isCriterionValueValid:e=>LR(e),criterionValueErrorString:rb.CriterionError.numberValue,numberOfValues:()=>1,name:Go("Is greater or equal to"),getPreview:e=>Go("Value is greater or equal to %s",e.values[0])}),FR.add("isLessThan",{type:"isLessThan",isValueValid:(e,t)=>{if("number"!=typeof e)return!1;const s=t.values[0];return"number"==typeof s&&e<s},getErrorString:(e,t)=>{const s=PR(e,t.getLocale());return Go("The value must be less than %s",s[0])},isCriterionValueValid:e=>LR(e),criterionValueErrorString:rb.CriterionError.numberValue,numberOfValues:()=>1,name:Go("Is less than"),getPreview:e=>Go("Value is less than %s",e.values[0])}),FR.add("isLessOrEqualTo",{type:"isLessOrEqualTo",isValueValid:(e,t)=>{if("number"!=typeof e)return!1;const s=t.values[0];return"number"==typeof s&&e<=s},getErrorString:(e,t)=>{const s=PR(e,t.getLocale());return Go("The value must be less or equal to %s",s[0])},isCriterionValueValid:e=>LR(e),criterionValueErrorString:rb.CriterionError.numberValue,numberOfValues:()=>1,name:Go("Is less or equal to"),getPreview:e=>Go("Value is less or equal to %s",e.values[0])}),FR.add("isBetween",{type:"isBetween",isValueValid:(e,t)=>"number"==typeof e&&("number"==typeof t.values[0]&&"number"==typeof t.values[1]&&Nt(e,t.values[0],t.values[1])),getErrorString:(e,t)=>{const s=PR(e,t.getLocale());return Go("The value must be between %s and %s",s[0],s[1])},isCriterionValueValid:e=>LR(e),criterionValueErrorString:rb.CriterionError.numberValue,numberOfValues:()=>2,name:Go("Is between"),getPreview:e=>Go("Value is between %s and %s",e.values[0],e.values[1])}),FR.add("isNotBetween",{type:"isNotBetween",isValueValid:(e,t)=>"number"==typeof e&&("number"==typeof t.values[0]&&"number"==typeof t.values[1]&&!Nt(e,t.values[0],t.values[1])),getErrorString:(e,t)=>{const s=PR(e,t.getLocale());return Go("The value must not be between %s and %s",s[0],s[1])},isCriterionValueValid:e=>LR(e),criterionValueErrorString:rb.CriterionError.numberValue,numberOfValues:()=>2,name:Go("Is not between"),getPreview:e=>Go("Value is not between %s and %s",e.values[0],e.values[1])}),FR.add("isBoolean",{type:"isBoolean",isValueValid:(e,t)=>""===e||"boolean"==typeof e,getErrorString:()=>Go("The value must be a boolean"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:Go("Checkbox"),getPreview:()=>Go("Checkbox")}),FR.add("isValueInList",{type:"isValueInList",isValueValid:(e,t)=>null!==e&&t.values.map((e=>String(e).toLowerCase())).includes(e.toString().toLowerCase()),getErrorString:e=>Go("The value must be one of: %s",e.values.join(", ")),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>{},allowedValues:"onlyLiterals",name:Go("Value in list"),getPreview:e=>Go("Value one of: %s",e.values.join(", "))}),FR.add("isValueInRange",{type:"isValueInList",isValueValid:(e,t,s,o)=>{if(!e)return!1;return s.getDataValidationRangeValues(o,t).map((e=>e.value.toLowerCase())).includes(e.toString().toLowerCase())},getErrorString:e=>Go("The value must be a value in the range %s",String(e.values[0])),isCriterionValueValid:e=>ea.test(e),criterionValueErrorString:rb.CriterionError.validRange,numberOfValues:()=>1,allowedValues:"onlyLiterals",name:Go("Value in range"),getPreview:e=>Go("Value in range %s",e.values[0])}),FR.add("customFormula",{type:"customFormula",isValueValid:(e,t)=>{const s=t.values[0];return("number"==typeof s||"boolean"==typeof s)&&!!s},getErrorString:()=>Go("The value does not match the custom formula data validation rule"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>1,allowedValues:"onlyFormulas",name:Go("Custom formula"),getPreview:e=>Go("Custom formula %s",e.values[0])}),FR.add("beginsWithText",{type:"beginsWithText",isValueValid:(e,t)=>String(e).toLowerCase().startsWith(String(t.values[0]).toLowerCase()),getErrorString:e=>Go('The value must be a text that begins with "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:rb.CriterionError.notEmptyValue,numberOfValues:()=>1,name:Go("Text begins with"),getPreview:e=>Go('Text begins with "%s"',e.values[0])}),FR.add("endsWithText",{type:"endsWithText",isValueValid:(e,t)=>String(e).toLowerCase().endsWith(String(t.values[0]).toLowerCase()),getErrorString:e=>Go('The value must be a text that ends with "%s"',String(e.values[0])),isCriterionValueValid:e=>!!e,criterionValueErrorString:rb.CriterionError.notEmptyValue,numberOfValues:()=>1,name:Go("Text ends with"),getPreview:e=>Go('Text ends with "%s"',e.values[0])}),FR.add("isEmpty",{type:"isEmpty",isValueValid:(e,t)=>""===(e??"").toString().trim(),getErrorString:()=>Go("The value must be empty"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:Go("Is empty"),getPreview:()=>Go("Is empty")}),FR.add("isNotEmpty",{type:"isNotEmpty",isValueValid:(e,t)=>""!==(e??"").toString().trim(),getErrorString:()=>Go("The value must not be empty"),isCriterionValueValid:()=>!0,criterionValueErrorString:"",numberOfValues:()=>0,name:Go("Is not empty"),getPreview:()=>Go("Is not empty")});class kR{mutators=["setFocusableElement","focus"];focusableElement=void 0;setFocusableElement(e){return this.focusableElement=e,"noStateChange"}focus(){if(this.focusableElement===document.activeElement)return"noStateChange";this.focusableElement?.focus()}}const VR={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function UR(e,t){const s=VR[e.key];e.shiftKey?t.resizeAnchorZone(s,Xy(e)?"end":1):t.moveAnchorCell(s,Xy(e)?"end":1)}class HR extends t.Component{static template="o-spreadsheet-TextValueProvider";static props={proposals:Array,selectedIndex:{type:Number,optional:!0},onValueSelected:Function,onValueHovered:Function};autoCompleteListRef=t.useRef("autoCompleteList");setup(){t.useEffect((()=>{const e=this.props.selectedIndex;if(void 0===e)return;const t=this.autoCompleteListRef.el?.children[e];t?.scrollIntoView?.({block:"nearest"})}),(()=>[this.props.selectedIndex,this.autoCompleteListRef.el]))}getCss(e){return aR({color:e.color||"#000000",background:e.backgroundColor})}}class zR{el;constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){const s=window.getSelection(),{start:o,end:i}=this.getCurrentSelection();if(o===e&&i===t)return;if(0===s.rangeCount){const e=document.createRange();s.addRange(e)}const n=s.getRangeAt(0);let r;if(this.el.contains(n.startContainer)?r=n:(r=document.createRange(),s.removeAllRanges(),s.addRange(r)),e===t&&0===e)r.setStart(this.el,0),r.setEnd(this.el,0);else{const s=this.getText().length;(e<0||t>s)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${s}`),e<0&&(e=0),t>s&&(t=s),e>s&&(e=s));const o=this.findChildAtCharacterIndex(e),i=this.findChildAtCharacterIndex(t);e<=t?(r.setStart(o.node,o.offset),r.setEnd(i.node,i.offset)):(r.setStart(i.node,i.offset),r.setEnd(o.node,o.offset))}}findChildAtCharacterIndex(e){const t=Wy(this.el);let s,o,i=e,n=!0;do{s=t.next(),s.done||s.value.hasChildNodes()||(s.value.textContent&&s.value.textContent.length<i?i-=s.value.textContent.length:s.value.textContent&&s.value.textContent.length>=i&&t.return(s.value),o=s.value),s.done||"P"!==s.value.nodeName||(n?n=!1:i--)}while(!s.done&&i);return s.value?{node:s.value,offset:i}:{node:o,offset:i}}setText(e){if(0===e.length)return void this.removeAll();const t=Array.from(this.el.childNodes),s=e.length;for(let o=0;o<s;o++){const s=e[o],i=t[o];let n,r=!1;i&&"P"===i.nodeName?n=i:(r=!0,n=document.createElement("p"));const a=s.length,l=Array.from(n.childNodes);for(let e=0;e<a;e++){const t=s[e],o=l[e];if(o&&"tagName"in o&&"SPAN"===o.tagName&&BR(t,o))continue;if(!t.value&&!t.classes?.length){o&&n.removeChild(o);continue}const i=document.createElement("span");i.innerText=t.value,i.style.color=t.color||"",i.addEventListener("mousemove",(()=>{t.onHover?.(Gy(i))})),i.addEventListener("mouseleave",(()=>{t.onStopHover?.()})),i.classList.add(...t.classes||[]),o?n.replaceChild(i,o):n.appendChild(i)}if(l.length>a)for(let e=a;e<l.length;e++)n.removeChild(l[e]);n.hasChildNodes()||n.appendChild(document.createElement("span")),r&&(i?this.el.replaceChild(n,i):this.el.appendChild(n))}if(t.length>s)for(let e=s;e<t.length;e++)this.el.removeChild(t[e])}scrollSelectionIntoView(){const e=document.getSelection()?.focusNode;if(!e||!this.el.contains(e))return;const t=e instanceof HTMLElement?e:e.parentElement;t?.scrollIntoView?.({block:"nearest"})}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){return $y(this.el)}getText(){let e="",t=!0,s=!1;const o=Wy(this.el);for(let i=o.next();!i.done;i=o.next())"P"===i.value.nodeName||"DIV"===i.value.nodeName&&i.value!==this.el?(t?t=!1:e+=Ne,s=["<br>","<span><br></span>"].includes(i.value.innerHTML)):i.value.hasChildNodes()||("BR"!==i.value.nodeName||s||(e+=Ne),e+=i.value.textContent);return e}}function BR(e,t){const s=(e.color?ro(e.color):"")===(t.style?.color?ro(t.style.color):""),o=St(e.classes,[...t.classList]),i=t.innerText===e.value;return s&&o&&i}class GR extends t.Component{static template="o-spreadsheet-FunctionDescriptionProvider";static props={functionDescription:Object,argsToFocus:Array};static components={Collapse:AR};state=t.useState({isCollapsed:!0});toggle(){this.state.isCollapsed=!this.state.isCollapsed}getContext(){return this.props}get formulaArgSeparator(){return this.env.model.getters.getLocale().formulaArgSeparator+" "}}class WR extends t.Component{static template="o-spreadsheet-SpeechBubble";static props={content:String,anchorRect:Object};static components={};spreadsheetRect=dR();bubbleRef=t.useRef("bubble");setup(){t.useEffect((()=>{const e=this.bubbleRef.el;if(!e)return;const t=this.props.anchorRect,s=Gy(e),o=t.x+t.width/2-s.width/2-this.spreadsheetRect.x,i=t.y-s.height-7-this.spreadsheetRect.y;e.style.left=`${o}px`,e.style.top=`${i}px`}))}}const $R=JS.content,qR=300;class ZR extends t.Component{static template="o-spreadsheet-Composer";static props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},inputStyle:{type:String,optional:!0},rect:{type:Object,optional:!0},delimitation:{type:Object,optional:!0},onComposerCellFocused:{type:Function,optional:!0},onComposerContentFocused:Function,isDefaultFocus:{type:Boolean,optional:!0},onInputContextMenu:{type:Function,optional:!0},composerStore:Object,placeholder:{type:String,optional:!0},inputMode:{type:String,optional:!0},showAssistant:{type:Boolean,optional:!0}};static components={TextValueProvider:HR,FunctionDescriptionProvider:GR,SpeechBubble:WR};static defaultProps={inputStyle:"",isDefaultFocus:!1,inputMode:"text",showAssistant:!0};DOMFocusableElementStore;composerRef=t.useRef("o_composer");contentHelper=new zR(this.composerRef.el);composerState=t.useState({positionStart:0,positionEnd:0,hoveredRect:void 0});functionDescriptionState=t.useState({showDescription:!1,functionDescription:{},argsToFocus:[]});assistant=t.useState({forcedClosed:!1});compositionActive=!1;spreadsheetRect=dR();lastHoveredTokenIndex=void 0;debouncedHover=pt(((e,t)=>{const s=this.contentHelper.getCurrentSelection();if(s.start!==s.end)return;const o=this.props.composerStore.hoveredTokens;this.props.composerStore.hoverToken(e),St(o,this.props.composerStore.hoveredTokens)||(this.composerState.hoveredRect=t)}),120);get assistantStyleProperties(){const e=this.composerRef.el.getBoundingClientRect(),t={},s=Math.min(this.props.rect?.width||1/0,qR);t["min-width"]=`${s}px`;const o=this.props.composerStore.autoCompleteProposals,i=o?.some((e=>e.description));if((this.functionDescriptionState.showDescription||i)&&(t.width="300px"),this.props.delimitation&&this.props.rect){const{x:e,y:s,height:o}=this.props.rect,i=this.props.delimitation.height-(s+o);if(t["max-height"]=`${i}px`,s>i){const e=s;t["max-height"]=e-9+"px",t.transform=`translate(0, calc(-100% - ${o+3}px))`}e+qR>this.props.delimitation.width&&(t.right="0px")}else t["max-height"]=this.spreadsheetRect.height-e.bottom-1+"px",e.left+qR+re+9>this.spreadsheetRect.width&&(t.right="9px");return t}get assistantStyle(){const e=this.assistantStyleProperties;return aR({"max-height":e["max-height"],width:e.width,"min-width":e["min-width"]})}get assistantContainerStyle(){const e=this.assistantStyleProperties;return aR({top:e.top,right:e.right,transform:e.transform})}shouldProcessInputEvents=!1;tokens=[];keyMapping={Enter:e=>this.processEnterKey(e,"down"),"Shift+Enter":e=>this.processEnterKey(e,"up"),"Alt+Enter":this.processNewLineEvent,"Ctrl+Enter":this.processNewLineEvent,Escape:this.processEscapeKey,F2:e=>this.toggleEditionMode(e),F4:e=>this.processF4Key(e),Tab:e=>this.processTabKey(e,"right"),"Shift+Tab":e=>this.processTabKey(e,"left")};keyCodeMapping={NumpadDecimal:this.processNumpadDecimal};setup(){this.DOMFocusableElementStore=rh(kR),t.onMounted((()=>{const e=this.composerRef.el;this.props.isDefaultFocus&&this.DOMFocusableElementStore.setFocusableElement(e),this.contentHelper.updateEl(e)})),t.onWillUnmount((()=>{this.debouncedHover.stopDebounce()})),t.useEffect((()=>{this.processContent(),document.activeElement!==this.contentHelper.el||"inactive"!==this.props.composerStore.editionMode||this.props.isDefaultFocus||this.DOMFocusableElementStore.focus()})),t.useEffect((()=>{this.processTokenAtCursor()}),(()=>["inactive"!==this.props.composerStore.editionMode])),t.useEffect((()=>{this.contentHelper.scrollSelectionIntoView()}),(()=>[this.props.composerStore.composerSelection.start,this.props.composerStore.composerSelection.end]))}processArrowKeys(e){const t=this.props.composerStore.tokenAtCursor;if((this.props.composerStore.isSelectingRange||"inactive"===this.props.composerStore.editionMode)&&(!["ArrowUp","ArrowDown"].includes(e.key)||!this.props.composerStore.isAutoCompleteDisplayed||"REFERENCE"===t?.type))return this.functionDescriptionState.showDescription=!1,this.props.composerStore.hideHelp(),e.preventDefault(),e.stopPropagation(),void UR(e,this.env.model.selection);const s=this.props.composerStore.currentContent;"cellFocus"!==this.props.focus||this.props.composerStore.isAutoCompleteDisplayed||Gt(s)?(e.stopPropagation(),this.handleArrowKeysForAutocomplete(e)):this.props.composerStore.stopEdition()}handleArrowKeysForAutocomplete(e){["ArrowUp","ArrowDown"].includes(e.key)&&this.props.composerStore.isAutoCompleteDisplayed&&(e.preventDefault(),this.props.composerStore.moveAutoCompleteSelection("ArrowDown"===e.key?"next":"previous"))}processTabKey(e,t){e.preventDefault(),e.stopPropagation(),this.assistant.forcedClosed||this.props.composerStore.autoCompleteOrStop(t)}processEnterKey(e,t){e.preventDefault(),e.stopPropagation(),this.assistant.forcedClosed||this.props.composerStore.autoCompleteOrStop(t)}processNewLineEvent(e){e.preventDefault(),e.stopPropagation();const t=this.contentHelper.getText(),s=this.contentHelper.getCurrentSelection(),o=Math.min(s.start,s.end),i=Math.max(s.start,s.end);this.props.composerStore.stopComposerRangeSelection(),this.props.composerStore.setCurrentContent(t.slice(0,o)+Ne+t.slice(i),{start:o+1,end:o+1}),this.processContent()}processEscapeKey(e){this.props.composerStore.cancelEdition(),e.stopPropagation(),e.preventDefault()}processF4Key(e){e.stopPropagation(),this.props.composerStore.cycleReferences(),this.processContent()}toggleEditionMode(e){e.stopPropagation(),this.props.composerStore.toggleEditionMode(),this.processContent()}processNumpadDecimal(e){e.stopPropagation(),e.preventDefault();const t=this.env.model.getters.getLocale(),s=this.contentHelper.getCurrentSelection(),o=this.props.composerStore.currentContent,i=o.slice(0,s.start)+t.decimalSeparator+o.slice(s.end);this.props.composerStore.setCurrentContent(i,{start:s.start+1,end:s.start+1}),this.processContent()}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){if("inactive"===this.props.composerStore.editionMode)return;if(e.key.startsWith("Arrow"))return void this.processArrowKeys(e);const t=this.keyMapping[jy(e)]||this.keyCodeMapping[jy(e,"code")];t?t.call(this,e):e.stopPropagation()}onPaste(e){"inactive"!==this.props.composerStore.editionMode?e.stopPropagation():e.preventDefault()}onInput(e){if(!this.shouldProcessInputEvents)return;let t;if(e.stopPropagation(),t="inactive"===this.props.composerStore.editionMode?e.data||"":this.contentHelper.getText(),"inactive"===this.props.focus)return this.props.onComposerCellFocused?.(t);const s=this.contentHelper.getCurrentSelection();this.props.composerStore.stopComposerRangeSelection(),this.props.composerStore.setCurrentContent(t,s),this.processTokenAtCursor()}onKeyup(e){if(this.contentHelper.el===document.activeElement){if(this.props.composerStore.isAutoCompleteDisplayed&&["ArrowUp","ArrowDown"].includes(e.key))return;if(this.props.composerStore.isSelectingRange&&e.key?.startsWith("Arrow"))return;const{start:t,end:s}=this.props.composerStore.composerSelection,{start:o,end:i}=this.contentHelper.getCurrentSelection();o===t&&i===s||this.props.composerStore.changeComposerCursorSelection(o,i),this.processTokenAtCursor()}}onBlur(e){if("inactive"===this.props.composerStore.editionMode)return;const t=e.relatedTarget;t&&t instanceof HTMLElement?t.attributes.getNamedItem("composerFocusableElement")?this.contentHelper.el.focus():t.classList.contains("o-composer")||this.props.composerStore.stopEdition():this.props.composerStore.stopEdition()}onMousedown(e){e.button>0||this.env.isMobile()&&!eI()||(this.debouncedHover.stopDebounce(),this.contentHelper.removeSelection())}onMouseup(){if(this.env.model.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection();e.start!==e.end&&this.props.composerStore.hoverToken(void 0)}onClick(){if(this.env.model.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection();this.props.composerStore.stopComposerRangeSelection(),this.props.onComposerContentFocused(),this.props.composerStore.changeComposerCursorSelection(e.start,e.end),this.processTokenAtCursor()}onDblClick(){if(this.env.model.getters.isReadonly())return;const e=this.props.composerStore.currentContent;if(Gt(e)){const t=this.props.composerStore.currentTokens,s=this.contentHelper.getCurrentSelection();if(s.start===s.end)return;const o=e.substring(s.start,s.end),i=t.filter((e=>e.value.includes(o)&&e.start<=s.start&&e.end>=s.end))[0];if(!i)return;"REFERENCE"===i.type&&this.props.composerStore.changeComposerCursorSelection(i.start,i.end)}}onContextMenu(e){"inactive"===this.props.composerStore.editionMode&&this.props.onInputContextMenu?.(e)}closeAssistant(){this.props.composerStore.canBeToggled&&(this.assistant.forcedClosed=!0)}openAssistant(){this.props.composerStore.canBeToggled&&(this.assistant.forcedClosed=!1)}onWheel(e){this.composerRef.el&&this.composerRef.el.scrollHeight>this.composerRef.el.clientHeight&&e.stopPropagation()}processContent(){if(this.compositionActive)return;this.shouldProcessInputEvents=!1,"inactive"!==this.props.focus&&document.activeElement!==this.contentHelper.el&&this.contentHelper.el.focus();const e=this.getContentLines();if(this.contentHelper.setText(e),0!==e.length&&0!==e.length[0]&&"inactive"!==this.props.focus){const{start:e,end:t}=this.props.composerStore.composerSelection;this.contentHelper.selectRange(e,t)}this.shouldProcessInputEvents=!0}getContentLines(){const e=this.props.composerStore.currentContent,t=Gt(e);return""===e?[]:t&&"inactive"!==this.props.focus?this.splitHtmlContentIntoLines(this.getHtmlContentFromTokens()):this.splitHtmlContentIntoLines([{value:e,classes:[]}])}getHtmlContentFromTokens(){const e=this.props.composerStore.currentTokens,t=[],{end:s,start:o}=this.props.composerStore.composerSelection;for(let i=0;i<e.length;i++){const n=e[i];let r=n.color||ze;n.isBlurred&&(r=So(r,.5));const a=[];"REFERENCE"===n.type&&this.props.composerStore.tokenAtCursor===n&&"selecting"===this.props.composerStore.editionMode&&a.push("text-decoration-underline"),s===o&&n.isParenthesisLinkedToCursor&&a.push("highlight-parenthesis-flag"),n.isInHoverContext&&a.push("highlight-flag"),this.props.composerStore.showSelectionIndicator&&s===o&&s===n.end&&a.push("selector-flag"),t.push({value:n.value,color:r,classes:a,onHover:e=>this.onTokenHover(i,e),onStopHover:()=>this.onTokenHover(void 0)})}return t}onTokenHover(e,t){this.lastHoveredTokenIndex!==e&&(this.lastHoveredTokenIndex=e,this.debouncedHover(e,t))}splitHtmlContentIntoLines(e){const t=[];let s=[];for(const o of e)if(o.value.includes(Ne)){const e=o.value.split(Ne),i=e.pop();for(const i of e)s.push({color:o.color,value:i}),t.push(s),s=[];s.push({...o,value:i})}else s.push(o);s.length&&t.push(s);const o=[];for(const e of t)e.every(this.isContentEmpty)?o.push([e[0]]):o.push(e.filter((e=>!this.isContentEmpty(e))));return o}isContentEmpty(e){return!(e.value||e.classes?.length)}processTokenAtCursor(){const e=this.props.composerStore;this.functionDescriptionState.showDescription=!1;const t=this.props.composerStore.tokenAtCursor;if(Gt(e.currentContent)&&t&&"SYMBOL"!==t.type){const e=t.functionContext,s=e?.parent.toUpperCase();if(e&&s&&s in $R&&"UNKNOWN"!==t.type){const o=$R[s],i=e.argPosition,n=e.args.length;this.functionDescriptionState.functionDescription=o;const r=this.props.composerStore.currentTokens.some((e=>"RIGHT_PAREN"===e.type&&e.parenthesesCode===t.parenthesesCode));this.functionDescriptionState.argsToFocus=this.getArgsToFocus(r,o,n,i),this.functionDescriptionState.showDescription=!0}}}getArgsToFocus(e,t,s,o){const{nbrArgRepeating:i,minArgRequired:n,nbrArgOptional:r,maxArgPossible:a}=t;if(e){const e=jh(t,Math.max(Math.min(a,s),n))(o);return void 0!==e?[e]:[]}const l=Math.max(s,n),c=i?n+Math.ceil((l-n)/i)*i+r:a,h=[];for(let e=l;e<=c;e++){const s=jh(t,e)(o);void 0!==s&&h.push(s)}return[...new Set(h)]}autoComplete(e){!e||this.assistant.forcedClosed&&this.props.composerStore.canBeToggled||(this.props.composerStore.insertAutoCompleteValue(e),this.processTokenAtCursor())}get displaySpeechBubble(){return!("inactive"===this.props.focus||!this.composerState.hoveredRect||!this.props.composerStore.hoveredContentEvaluation)}}class jR{lastId=0;add(e){this.lastId++;const t=this.lastId;return new Promise(((s,o)=>{e.then((e=>{this.lastId===t&&s(e)})).catch((e=>{this.lastId===t&&o(e)}))}))}}function YR(e,t,s){const{x:o,y:i,width:n,height:r}=s;if(n<0||r<0)return;const a=t.color||A,{ctx:l}=e;l.save(),t.noBorder||(t.dashed&&l.setLineDash([5,3]),l.strokeStyle=a,t.thinLine?(l.lineWidth=1,l.strokeRect(o,i,n,r)):(l.lineWidth=2,l.strokeRect(o+.5,i+.5,n,r))),t.noFill||(l.fillStyle=So(ro(a),t.fillAlpha??.12),l.fillRect(o,i,n,r)),l.restore()}class XR extends ph{mutators=["register","unRegister"];providers=[];constructor(e){super(e),this.onDispose((()=>{this.providers=[]}))}get renderingLayers(){return["Highlights"]}get highlights(){const e=this.getters.getActiveSheetId();return this.providers.flatMap((e=>e.highlights)).filter((t=>t.range.sheetId===e)).map((e=>{const{numberOfRows:t,numberOfCols:s}=Fs(e.range.zone),o=t*s==1?this.getters.expandZone(e.range.sheetId,e.range.zone):e.range.unboundedZone;return{...e,range:this.model.getters.getRangeFromZone(e.range.sheetId,o)}}))}register(e){this.providers.push(e)}unRegister(e){this.providers=this.providers.filter((t=>t!==e))}drawLayer(e,t){if("Highlights"===t)for(const t of this.highlights){YR(e,t,this.getters.getVisibleRect(t.range.zone))}}}class KR{mutators=["notifyUser","raiseError","askConfirmation","updateNotificationCallbacks"];notifyUser=e=>window.alert(e.text);askConfirmation=(e,t,s)=>{window.confirm(e)?t():s?.()};raiseError=(e,t)=>{window.alert(e),t?.()};updateNotificationCallbacks(e){this.notifyUser=e.notifyUser||this.notifyUser,this.raiseError=e.raiseError||this.raiseError,this.askConfirmation=e.askConfirmation||this.askConfirmation}}class JR extends ph{mutators=["useProvider","moveSelection","hide","selectIndex"];selectedIndex=void 0;provider;get selectedProposal(){if(void 0!==this.selectedIndex&&void 0!==this.provider)return this.provider.proposals[this.selectedIndex]}useProvider(e){this.provider=e,this.selectedIndex=e.autoSelectFirstProposal?0:void 0}hide(){this.provider=void 0,this.selectedIndex=void 0}selectIndex(e){this.selectedIndex=e}moveSelection(e){this.provider&&(void 0!==this.selectedIndex?"previous"===e?(this.selectedIndex--,this.selectedIndex<0&&(this.selectedIndex=this.provider.proposals.length-1)):this.selectedIndex=(this.selectedIndex+1)%this.provider.proposals.length:this.selectedIndex=0)}}class QR extends ph{mutators=["startEdition","setCurrentContent","stopEdition","stopComposerRangeSelection","cancelEdition","cycleReferences","hideHelp","autoCompleteOrStop","insertAutoCompleteValue","moveAutoCompleteSelection","selectAutoCompleteIndex","toggleEditionMode","changeComposerCursorSelection","replaceComposerCursorSelection","hoverToken"];col=0;row=0;editionMode="inactive";sheetId="";_currentContent="";currentTokens=[];selectionStart=0;selectionEnd=0;initialContent="";colorIndexByRange={};autoComplete=new JR(this.get);hoveredTokens=[];hoveredContentEvaluation="";autoCompleteKeepLast=new jR;notificationStore=this.get(KR);highlightStore=this.get(XR);constructor(e){super(e),this.highlightStore.register(this),this.onDispose((()=>{this.highlightStore.unRegister(this)}))}handleEvent(e){this.hideHelp();const t=this.getters.getActiveSheetId();let s;if(s=e.options.unbounded?this.getters.getUnboundedZone(t,e.anchor.zone):e.anchor.zone,"newAnchor"===e.mode)"selecting"===this.editionMode&&this.insertSelectedRange(s);else"selecting"===this.editionMode?this.replaceSelectedRange(s):this.updateComposerRange(e.previousAnchor.zone,s)}changeComposerCursorSelection(e,t){this.isSelectionValid(this._currentContent.length,e,t)&&(this.selectionStart=e,this.selectionEnd=t,this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor(),this.updateAutoCompleteProvider())}stopComposerRangeSelection(){this.isSelectingRange&&(this.editionMode="editing")}startEdition(e,t){if(t){const s=e||this.getComposerContent(this.getters.getActivePosition());if(!this.isSelectionValid(s.length,t.start,t.end))return}const{col:s,row:o}=this.getters.getActivePosition();this.model.dispatch("SELECT_FIGURE",{figureId:null}),this.model.dispatch("SCROLL_TO_CELL",{col:s,row:o}),"inactive"!==this.editionMode&&e?this.setContent(e,t):this._startEdition(e,t),this.updateTokenColor(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor(),this.updateAutoCompleteProvider()}cancelEdition(){this.resetContent(),this.cancelEditionAndActivateSheet()}setCurrentContent(e,t){t&&!this.isSelectionValid(e.length,t.start,t.end)||(this.setContent(e,t,!0),this.updateTokenColor(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor())}replaceComposerCursorSelection(e){this.replaceSelection(e)}handle(e){switch(e.type){case"SELECT_FIGURE":e.figureId&&(this.resetContent(),this.cancelEditionAndActivateSheet());break;case"START_CHANGE_HIGHLIGHT":const{left:t,top:s}=e.zone;this.isSelectingRange&&(this.editionMode="editing"),this.model.selection.resetAnchor(this,{cell:{col:t,row:s},zone:e.zone})}}get currentContent(){return"inactive"===this.editionMode?this.getComposerContent(this.getters.getActivePosition()):this._currentContent}get composerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}get isSelectingRange(){return"selecting"===this.editionMode}get showSelectionIndicator(){return this.isSelectingRange&&this.canStartComposerRangeSelection()}get tokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find((s=>s.start<=e&&s.end>=t))}get autoCompleteProposals(){return this.autoComplete.provider?.proposals||[]}get autoCompleteSelectedIndex(){return this.autoComplete.selectedIndex}get isAutoCompleteDisplayed(){return!!this.autoComplete.provider}get canBeToggled(){return this.autoComplete.provider?.canBeToggled??!0}cycleReferences(){const e=this.getters.getLocale(),t=Av(this.composerSelection,this._currentContent,e);void 0!==t&&this.setCurrentContent(t.content,t.selection)}toggleEditionMode(){if("inactive"===this.editionMode)return;const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd),s=[...this.currentTokens].reverse().find((s=>s.end>=e&&t>=s.start&&"REFERENCE"===s.type));if("editing"===this.editionMode&&s){const e=this.getters.getActiveSheetId(),{sheetName:t,xc:o}=na(s.value),i=this.getters.getSheetIdByName(t);i&&i!==e&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:i}),this.selectionStart=this.selectionEnd=s.end;const n=this.getters.getRangeFromSheetXC(this.sheetId,o).zone;this.captureSelection(n),this.editionMode="selecting"}else this.editionMode="editing"}hoverToken(e){this.currentTokens.forEach((e=>e.isInHoverContext=void 0));const t=[...this.currentTokens];if(void 0===e||["ARG_SEPARATOR","SPACE"].includes(t[e].type))return this.hoveredContentEvaluation="",void(this.hoveredTokens=[]);const s=this.getNumberOfMissingParenthesis(t);s>0&&t.push(...Array(s).fill({value:")",type:"RIGHT_PAREN"}));let o=t;if(0!==e){const s=this.getRelatedTokens(t,e),i=t.filter((e=>!s.includes(e)&&"SPACE"!==e.type));o=1===i.length&&i[0]===t[0]?t:s}o.forEach((e=>e.isInHoverContext=!0));let i=o.map((e=>e.value)).join("");Gt(i)||(i=`=${i}`);const n=Sl(i,this.getters.getLocale()),r=this.getters.evaluateFormulaResult(this.sheetId,n);this.hoveredTokens=o,this.hoveredContentEvaluation=this.evaluationResultToDisplayString(r)}getRelatedTokens(e,t){try{const s=bv(e);let o;for(const e of Cv(s))if(t>=e.tokenStartIndex&&t<=e.tokenEndIndex)o=e;else if(t<e.tokenStartIndex)break;return o?e.slice(o.tokenStartIndex,o.tokenEndIndex+1):e}catch(t){if(t instanceof Li)return e;throw t}}evaluationResultToDisplayString(e){const t=this.getters.getLocale();if(R(e)){const s=","===t.decimalSeparator?"/":",";return`{${vn(e).map((e=>e.map((e=>this.cellValueToDisplayString(e))).join(s))).join(";")}}`}return this.cellValueToDisplayString(e)}cellValueToDisplayString(e){const t=e.value;switch(typeof t){case"number":return or(t,{locale:this.getters.getLocale(),format:e.format});case"string":return qi(t)?t:`"${t}"`;case"boolean":return t?"TRUE":"FALSE"}return"0"}captureSelection(e,t,s){this.model.selection.capture(this,{cell:{col:t??e.left,row:s??e.right},zone:e},{handleEvent:this.handleEvent.bind(this),release:()=>{this._stopEdition()}})}isSelectionValid(e,t,s){return t>=0&&t<=e&&s>=0&&s<=e}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=Us({col:this.col,row:this.row});this.model.selection.resetAnchor(this,{cell:{col:this.col,row:this.row},zone:e})}this.editionMode="selecting"}_startEdition(e,t){const s=this.getters.getActiveCell(),o=this.getters.getLocale();e&&s.format?.includes("%")&&_i(e,o)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const{col:i,row:n,sheetId:r}=this.getters.getActivePosition();this.col=i,this.sheetId=r,this.row=n,this.editionMode="editing",this.initialContent=this.getComposerContent({sheetId:r,col:i,row:n}),this.setContent(e||this.initialContent,t),this.colorIndexByRange={};const a=Us({col:this.col,row:this.row});this.captureSelection(a,i,n)}_stopEdition(){if("inactive"!==this.editionMode){this.cancelEditionAndActivateSheet();let e=this.getCurrentCanonicalContent();if(!(this.initialContent!==e))return;if(e&&Gt(e)){const t=this.getNumberOfMissingParenthesis(this.currentTokens);t>0&&(e+=mt(new Array(t).fill(")")))}this.confirmEdition(e)}}getCurrentCanonicalContent(){return Sl(this._currentContent,this.getters.getLocale())}cancelEditionAndActivateSheet(){if("inactive"===this.editionMode)return;this._cancelEdition();this.getters.getActiveSheetId()!==this.sheetId&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}_cancelEdition(){"inactive"!==this.editionMode&&(this.editionMode="inactive",this.model.selection.release(this),this.colorIndexByRange={},this.hoveredTokens=[],this.hoveredContentEvaluation="")}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,s){const o=this._currentContent!==e;if(this._currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,o||"inactive"!==this.editionMode){const t=this.getters.getLocale();this.currentTokens=Gt(e)?wv(e,t):[];this.currentTokens.filter((e=>"SPACE"!==e.type)).length>1e3&&s&&this.notificationStore.raiseError(Go("This formula has over 1000 parts. It can't be processed properly, consider splitting it into multiple cells"))}this.canStartComposerRangeSelection()&&this.startComposerRangeSelection(),this.updateAutoCompleteProvider()}getAutoCompleteProviders(){return Xh.getAll()}insertSelectedRange(e){const t=Math.min(this.selectionStart,this.selectionEnd),s=this.getZoneReference(e);this.canStartComposerRangeSelection()?this.insertText(s,t):this.insertText(","+s,t)}replaceSelectedRange(e){const t=this.getZoneReference(e),s=this.tokenAtCursor,o="REFERENCE"===s?.type?s.start:this.selectionStart;this.replaceText(t,o,this.selectionEnd)}updateComposerRange(e,t){const s=this.getters.getActiveSheetId(),o=this.tokenAtCursor,i=(o?[o,...this.currentTokens]:this.currentTokens).filter((e=>"REFERENCE"===e.type)).find((t=>{const{xc:o,sheetName:i}=na(t.value),n=i||this.getters.getSheetName(this.sheetId);if(!ua(this.getters.getSheetName(s),n))return!1;const r=this.getters.getRangeFromSheetXC(s,o);return xs(this.getters.expandZone(s,r.zone),e)}));if(!i)return;const n=this.getters.getRangeFromSheetXC(s,i.value);this.selectionStart=i.start,this.selectionEnd=this.selectionStart+i.value.length;const r=this.getters.getRangeFromZone(s,t),a=this.getRangeReference(r,n.parts);this.replaceSelection(a)}getZoneReference(e){const t=this.sheetId,s=this.getters.getActiveSheetId(),o=this.getters.getRangeFromZone(s,e);return this.getters.getSelectionRangeString(o,t)}getRangeReference(e,t){const s={...e,parts:[...t]};return this.getters.getSelectionRangeString(s,this.sheetId)}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),s=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,s)}replaceText(e,t,s){this._currentContent=this._currentContent.slice(0,t)+this._currentContent.slice(s,this._currentContent.length),this.insertText(e,t)}insertText(e,t){const s=this._currentContent.slice(0,t)+e+this._currentContent.slice(t),o=t+e.length;this.setCurrentContent(s,{start:o,end:o})}updateTokenColor(){this.updateRangeColor();for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].color=this.getTokenColor(this.currentTokens[e])}getTokenColor(e){if("REFERENCE"===e.type){const{xc:t,sheetName:s}=na(e.value);return this.rangeColor(t,s)||ze}if("SYMBOL"===e.type){const t=e.value.toUpperCase();if("TRUE"===t||"FALSE"===t)return Ge.NUMBER;if(t in JS.content)return Ge.FUNCTION}return["LEFT_PAREN","RIGHT_PAREN"].includes(e.type)&&""===e.parenthesesCode?Ge.ORPHAN_RIGHT_PAREN:Ge[e.type]||ze}rangeColor(e,t){const s=t?this.model.getters.getSheetIdByName(t):this.sheetId,o=this.highlights.find((t=>{if(t.range.sheetId!==s)return!1;let o=this.model.getters.getRangeFromSheetXC(s,e).zone;return o=1===Gs(o)?this.model.getters.expandZone(s,o):o,xs(o,t.range.zone)}));return o&&o.color?o.color:void 0}computeFormulaCursorContext(){for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].isBlurred=!1;if(this.selectionStart!==this.selectionEnd)return;const e=this.getParenthesesCodeAfterCursor(),t=[...this.currentTokens].reverse().find((t=>e.startsWith(t.parenthesesCode)&&"SYMBOL"===t.type));if(t)for(let e=0;e<this.currentTokens.length;e++)(this.currentTokens[e].parenthesesCode||"").startsWith(t.parenthesesCode||"")||(this.currentTokens[e].isBlurred=!0)}getParenthesesCodeAfterCursor(){const e=this.tokenAtCursor?.parenthesesCode||"";return"RIGHT_PAREN"===this.tokenAtCursor?.type?e.slice(0,-1)||"":e}computeParenthesisRelatedToCursor(){for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].isParenthesisLinkedToCursor=!1;const e=this.tokenAtCursor;if(e&&""!==e.parenthesesCode&&["LEFT_PAREN","RIGHT_PAREN"].includes(e.type))for(let t=0;t<this.currentTokens.length;t++){const s=this.currentTokens[t];["LEFT_PAREN","RIGHT_PAREN"].includes(s.type)&&s.parenthesesCode===e.parenthesesCode&&s!==e&&(this.currentTokens[t].isParenthesisLinkedToCursor=!0,this.tokenAtCursor.isParenthesisLinkedToCursor=!0)}}updateRangeColor(){if(!Gt(this._currentContent)||"inactive"===this.editionMode)return;const e=this.sheetId,t=this.getReferencedRanges().map((t=>this.getters.getRangeString(t,e))),s={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(s[e]=this.colorIndexByRange[e]);const o=new Set(Object.values(s));let i=0;const n=()=>{for(;o.has(i);)i++;return o.add(i),i};for(const e of t){const t=e in s?s[e]:n();s[e]=t}this.colorIndexByRange=s}get highlights(){if(!Gt(this.currentContent)||"inactive"===this.editionMode)return[];const e=this.sheetId,t=e=>{const t=this.colorIndexByRange[e];return oo[t%oo.length]};return this.getReferencedRanges().map((s=>{const o=this.getters.getRangeString(s,e),{numberOfRows:i,numberOfCols:n}=Fs(s.zone),r=i*n==1?this.getters.expandZone(s.sheetId,s.zone):s.unboundedZone;return{range:this.model.getters.getRangeFromZone(s.sheetId,r),color:t(o),interactive:!0}}))}getReferencedRanges(){const e=this.sheetId;return this.currentTokens.filter((e=>"REFERENCE"===e.type)).map((t=>this.getters.getRangeFromSheetXC(e,t.value))).filter((e=>!e.invalidSheetName&&!e.invalidXc))}async updateAutoCompleteProvider(){this.autoComplete.hide();const e=await this.autoCompleteKeepLast.add(this.findAutocompleteProvider());e&&(this.autoComplete.useProvider(e),this.model.trigger("update"))}async findAutocompleteProvider(){const e=this.currentContent,t=Gt(e)?this.tokenAtCursor:{type:"STRING",value:e};if("inactive"===this.editionMode||!t||["TRUE","FALSE"].includes(t.value.toUpperCase())||!this.canStartComposerRangeSelection()&&!["SYMBOL","STRING","UNKNOWN"].includes(t.type))return;const s={composer:this,getters:this.getters},o=this.getAutoCompleteProviders().sort(((e,t)=>(e.sequence??1/0)-(t.sequence??1/0))).map((o=>({...o,getProposals:o.getProposals.bind(s,t,e),selectProposal:o.selectProposal.bind(s,t)})));for(const e of o){let s=await e.getProposals();const o=s?.find((e=>e.text===t.value)),i=t.value.replace(/[ ,\(\)]/g,"");if(this._currentContent===this.initialContent&&e.displayAllOnInitialContent&&s?.length)return{proposals:s,selectProposal:e.selectProposal,autoSelectFirstProposal:e.autoSelectFirstProposal??!1,canBeToggled:e.canBeToggled};if(o&&this._currentContent!==this.initialContent)return;if(i&&s&&!["ARG_SEPARATOR","LEFT_PAREN","OPERATOR"].includes(t.type)){const e=Fa(i,s,(e=>e.fuzzySearchKey||e.text));o&&!e.length||(s=e)}if(e.maxDisplayedProposals&&(s=s?.slice(0,e.maxDisplayedProposals)),s?.length)return{proposals:s,selectProposal:e.selectProposal,autoSelectFirstProposal:e.autoSelectFirstProposal??!1,canBeToggled:e.canBeToggled}}}hideHelp(){this.autoComplete.hide()}autoCompleteOrStop(e){if("inactive"!==this.editionMode){const t=this.autoComplete;if(t.provider&&void 0!==t.selectedIndex){const e=t.provider.proposals[t.selectedIndex]?.text;if(e)return void this.autoComplete.provider?.selectProposal(e)}this.stopEdition(e)}}insertAutoCompleteValue(e){this.autoComplete.provider?.selectProposal(e)}selectAutoCompleteIndex(e){this.autoComplete.selectIndex(Ke(0,e,10))}moveAutoCompleteSelection(e){this.autoComplete.moveSelection(e)}canStartComposerRangeSelection(){if(Gt(this._currentContent)){const e=this.tokenAtCursor;if(!e)return!1;const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let s=t,o=e;for(;!["ARG_SEPARATOR","LEFT_PAREN","OPERATOR"].includes(o.type)||el.includes(o.value);){if("SPACE"!==o.type||s<1)return!1;s--,o=this.currentTokens[s]}for(s=t+1,o=this.currentTokens[s];o&&!["ARG_SEPARATOR","RIGHT_PAREN","OPERATOR"].includes(o.type);){if("SPACE"!==o.type)return!1;s++,o=this.currentTokens[s]}return!0}return!1}getNumberOfMissingParenthesis(e){return e.filter((e=>"LEFT_PAREN"===e.type)).length-e.filter((e=>"RIGHT_PAREN"===e.type)).length}}class ex extends QR{args;constructor(e,t){super(e),this.args=t,this._currentContent=this.getComposerContent()}getAutoCompleteProviders(){const e=super.getAutoCompleteProviders(),t=this.args().contextualAutocomplete;return t&&e.push(t),e}getZoneReference(e){const t=super.getZoneReference(e);return this.args().defaultStatic?xv(t,"colrow"):t}getComposerContent(){let e=this._currentContent;if("inactive"===this.editionMode){const t=this.args().defaultRangeSheetId;e=av(this.args().content).map((e=>{if("REFERENCE"===e.type){const s=this.getters.getRangeFromSheetXC(t,e.value);return this.getters.getRangeString(s,this.getters.getActiveSheetId())}return e.value})).join("")}return yl(e,this.getters.getLocale())}stopEdition(){this._stopEdition()}confirmEdition(e){this.args().onConfirm(e)}getTokenColor(e){if("SYMBOL"===e.type){const t=this.args().getContextualColoredSymbolToken?.(e);if(t)return t}return super.getTokenColor(e)}}class tx extends t.Component{static template="o-spreadsheet-StandaloneComposer";static props={composerContent:{type:String,optional:!0},defaultRangeSheetId:{type:String,optional:!0},defaultStatic:{type:Boolean,optional:!0},onConfirm:Function,contextualAutocomplete:{type:Object,optional:!0},placeholder:{type:String,optional:!0},title:{type:String,optional:!0},class:{type:String,optional:!0},invalid:{type:Boolean,optional:!0},getContextualColoredSymbolToken:{type:Function,optional:!0}};static components={Composer:ZR};static defaultProps={composerContent:"",defaultStatic:!1};composerFocusStore;standaloneComposerStore;composerInterface;spreadsheetRect=dR();setup(){this.composerFocusStore=rh(fh);const e=ah(ex,(()=>({onConfirm:this.props.onConfirm,content:this.props.composerContent,defaultStatic:this.props.defaultStatic??!1,contextualAutocomplete:this.props.contextualAutocomplete,defaultRangeSheetId:this.props.defaultRangeSheetId,getContextualColoredSymbolToken:this.props.getContextualColoredSymbolToken})));this.standaloneComposerStore=e,this.composerInterface={id:"standaloneComposer",get editionMode(){return e.editionMode},startEdition:this.standaloneComposerStore.startEdition,setCurrentContent:this.standaloneComposerStore.setCurrentContent,stopEdition:this.standaloneComposerStore.stopEdition}}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get composerStyle(){return this.props.invalid?aR({padding:"1px 0px 0px 0px"}):aR({padding:"1px 0px"})}get containerClass(){return["inactive"===this.focus?"":"active",this.props.invalid?"o-invalid":"",this.props.class||""].join(" ")}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}}class sx extends t.Component{static template="o-spreadsheet-CriterionInput";static props={value:{type:String,optional:!0},criterionType:String,onValueChanged:Function,onKeyDown:{type:Function,optional:!0},focused:{type:Boolean,optional:!0},onBlur:{type:Function,optional:!0},onFocus:{type:Function,optional:!0},disableFormulas:{type:Boolean,optional:!0}};static defaultProps={value:"",onKeyDown:()=>{},focused:!1,onBlur:()=>{}};static components={StandaloneComposer:tx};inputRef=t.useRef("input");setup(){t.useEffect((()=>{this.props.focused&&this.inputRef.el.focus()}),(()=>[this.props.focused,this.inputRef.el]))}state=t.useState({shouldDisplayError:!!this.props.value});get placeholder(){return"onlyFormulas"===this.allowedValues?Go("Formula"):"onlyLiterals"===this.allowedValues?Go("Value"):Go("Value or formula")}get allowedValues(){const e=FR.get(this.props.criterionType);if("onlyFormulas"===e.allowedValues&&this.props.disableFormulas)throw new Error(`Cannot disable formulas for criterion type ${this.props.criterionType} that accept only formulas`);return(this.props.disableFormulas?"onlyLiterals":e.allowedValues)??"any"}onInputValueChanged(e){this.state.shouldDisplayError=!0,this.props.onValueChanged(e.target.value)}onChangeComposerValue(e){this.state.shouldDisplayError=!0,this.props.onValueChanged(e)}getDataValidationRuleInputComposerProps(){return{onConfirm:e=>this.onChangeComposerValue(e),composerContent:this.props.value,placeholder:this.placeholder,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId(),invalid:this.state.shouldDisplayError&&!!this.errorMessage,defaultStatic:!0}}get errorMessage(){if(this.state.shouldDisplayError)return this.env.model.getters.getDataValidationInvalidCriterionValueMessage(this.props.criterionType,Cl(this.props.value,this.env.model.getters.getLocale()))}}const ox={today:Go("today"),yesterday:Go("yesterday"),tomorrow:Go("tomorrow"),lastWeek:Go("in the past week"),lastMonth:Go("in the past month"),lastYear:Go("in the past year"),exactDate:Go("exact date")};class ix extends _R{static template="o-spreadsheet-DataValidationDateCriterion";static components={CriterionInput:sx};setup(){super.setup();const e=e=>{void 0===e.criterion.dateValue&&this.updateCriterion({dateValue:"exactDate"})};t.onWillUpdateProps(e),t.onWillStart((()=>e(this.props)))}onValueChanged(e){this.updateCriterion({values:[e]})}onDateValueChanged(e){const t=e.target.value;this.updateCriterion({dateValue:t})}get dateValues(){return Object.keys(ox).map((e=>({value:e,title:ox[e]})))}}class nx extends _R{static template="o-spreadsheet-DoubleInputCriterionForm";static components={CriterionInput:sx};onFirstValueChanged(e){const t=this.props.criterion.values;this.updateCriterion({values:[e,t[1]||""]})}onSecondValueChanged(e){const t=this.props.criterion.values;this.updateCriterion({values:[t[0]||"",e]})}}class rx extends _R{static template="o-spreadsheet-SingleInputCriterionForm";static components={CriterionInput:sx};onValueChanged(e){const t=qe(this.props.criterion);t.values[0]=e,this.updateCriterion(t)}}function ax(e,t){const s=()=>{window.removeEventListener("pointerup",o,{capture:!0}),window.removeEventListener("dragstart",i),window.removeEventListener("pointermove",e),window.removeEventListener("wheel",e)},o=e=>{t(e),s()};function i(e){e.preventDefault()}return window.addEventListener("pointerup",o,{capture:!0}),window.addEventListener("dragstart",i),window.addEventListener("pointermove",e),window.addEventListener("wheel",e,{passive:!1}),s}const lx=216;class cx extends t.Component{static template="o-spreadsheet-ColorPicker";static props={onColorPicked:Function,currentColor:{type:String,optional:!0},maxHeight:{type:Number,optional:!0},anchorRect:Object,disableNoColor:{type:Boolean,optional:!0}};static defaultProps={currentColor:""};static components={Popover:uR};COLORS=te;state=t.useState({showGradient:!1,currentHslaColor:ao(this.props.currentColor)?{...vo(this.props.currentColor),a:1}:{h:0,s:100,l:100,a:1},customHexColor:ao(this.props.currentColor)?ro(this.props.currentColor):""});get colorPickerStyle(){return void 0!==this.props.maxHeight&&this.props.maxHeight<=0?aR({display:"none"}):""}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"bottom-left",verticalOffset:0}}get gradientHueStyle(){return aR({background:`hsl(${this.state.currentHslaColor?.h||0} 100% 50%)`})}get sliderStyle(){const e=this.state.currentHslaColor?.h||0;return aR({"margin-left":`${Ke(Math.round(e/360*lx),1,lx)-9}px`})}get pointerStyle(){const{s:e,l:t}=this.state.currentHslaColor||{s:0,l:0};return aR({left:`${-8+Math.round(lx*Ke(e/100,0,1))}px`,top:`${-8+Math.round(186*Ke(1-2*t/(200-e),0,1))}px`,background:fo(this.state.currentHslaColor)})}get colorPreviewStyle(){return aR({"background-color":fo(this.state.currentHslaColor)})}get checkmarkColor(){return MC(this.props.currentColor)}get isHexColorInputValid(){return!this.state.customHexColor||ao(this.state.customHexColor)}setCustomGradient({x:e,y:t}){const s=Ke(e,0,lx),o=Ke(t,0,186),i=s/lx,n=100*i,r=100*(1-o/186)*(1-.5*i);this.updateColor({s:n,l:r})}setCustomHue(e){const t=Math.round(Ke(360*e/lx,0,359));this.updateColor({h:t})}updateColor(e){this.state.currentHslaColor={...this.state.currentHslaColor,...e},this.state.customHexColor=fo(this.state.currentHslaColor)}onColorClick(e){e&&this.props.onColorPicked(ro(e))}resetColor(){this.props.onColorPicked("")}toggleColorPicker(){this.state.showGradient=!this.state.showGradient}dragGradientPointer(e){const t={x:e.offsetX,y:e.offsetY};this.setCustomGradient(t);const s=e.clientX,o=e.clientY;ax((e=>{const i=e.clientX,n=e.clientY,r={x:t.x+(i-s),y:t.y+(n-o)};this.setCustomGradient(r)}),(()=>{}))}dragHuePointer(e){const t=e.offsetX,s=e.clientX;this.setCustomHue(t);ax((e=>{const o=e.clientX,i=t+(o-s);this.setCustomHue(i)}),(()=>{}))}setHexColor(e){const t=e.target.value.replace("##","#").slice(0,7);this.state.customHexColor=t,ao(t)&&(this.state.currentHslaColor={...vo(t),a:1})}addCustomColor(e){(function(e){try{return fo(e),!0}catch(e){return!1}})(this.state.currentHslaColor)&&ao(this.state.customHexColor)&&this.props.onColorPicked(ro(this.state.customHexColor))}isSameColor(e,t){return function(e,t,s=0){if(!ao(e)||!ao(t))return!1;const o=go(e),i=go(t);return o.a===i.a&&Math.sqrt(((o.r-i.r)/255)**2+((o.g-i.g)/255)**2+((o.b-i.b)/255)**2)<=s}(e,t)}}class hx extends t.Component{static template="o_spreadsheet.Section";static props={class:{type:String,optional:!0},title:{type:String,optional:!0},slots:Object}}class dx extends t.Component{static template="o-spreadsheet.RoundColorPicker";static components={Section:hx,ColorPicker:cx};static props={currentColor:{type:String,optional:!0},title:{type:String,optional:!0},onColorPicked:Function,disableNoColor:{type:Boolean,optional:!0}};colorPickerButtonRef=t.useRef("colorPickerButton");state;setup(){this.state=t.useState({pickerOpened:!1}),t.useExternalListener(window,"click",this.closePicker)}closePicker(){this.state.pickerOpened=!1}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.props.onColorPicked(e),this.state.pickerOpened=!1}get colorPickerAnchorRect(){return Gy(this.colorPickerButtonRef.el)}get buttonStyle(){return aR({background:this.props.currentColor})}}function ux(){let e;const s=document.body.style.cursor;let o=[];const i=()=>{e=void 0,document.body.style.cursor=s,o.forEach((e=>e())),o=[]};t.onWillUnmount((()=>{i()}));const n=t.useState({itemsStyle:{},draggedItemId:void 0,start:(t,r)=>{n.cancel=()=>{n.draggedItemId=void 0,n.itemsStyle={},document.body.style.cursor=s,r.onCancel?.(),i()};document.body.style.cursor="move",n.draggedItemId=r.draggedItemId;const a="horizontal"===t?new fx(r.scrollableContainerEl):new mx(r.scrollableContainerEl);e=new gx({...r,container:a,onChange:()=>{document.body.style.cursor="move",e&&(Object.assign(n.itemsStyle,e.getItemStyles()),r.onChange?.())},onDragEnd:(e,t)=>{n.draggedItemId=void 0,n.itemsStyle={},document.body.style.cursor=s,r.onDragEnd?.(e,t),i()},onCancel:n.cancel});const l=ax(e.onMouseMove.bind(e),e.onMouseUp.bind(e));o.push(l);const c=e.onScroll.bind(e);r.scrollableContainerEl.addEventListener("scroll",c),o.push((()=>r.scrollableContainerEl.removeEventListener("scroll",c))),o.push(e.destroy.bind(e))},cancel:()=>{}});return n}class gx{draggedItemId;items;container;initialMousePosition;currentMousePosition;initialScroll;minPosition;maxPosition;edgeScrollIntervalId;onChange;onCancel;onDragEnd;deadZone;constructor(e){this.items=e.items.map((e=>({...e,positionAtStart:e.position}))),this.draggedItemId=e.draggedItemId,this.container=e.container,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onDragEnd=e.onDragEnd,this.initialMousePosition=e.initialMousePosition,this.currentMousePosition=e.initialMousePosition,this.initialScroll=this.container.scroll,this.minPosition=this.items[0].position,this.maxPosition=this.items[this.items.length-1].position+this.items[this.items.length-1].size}getItemStyles(){const e={};for(const t of this.items)e[t.id]=this.getItemStyle(t.id);return e}getItemStyle(e){const t=this.container.cssPositionProperty,s={position:"relative"};return s[t]=(this.getItemsPositions()[e]||0)+"px",s.transition=`${t} 0.5s`,s["pointer-events"]="none",this.draggedItemId===e&&(s.transition=`${t} 0s`,s["z-index"]="1000"),aR(s)}onScroll(){this.moveDraggedItemToPosition(this.currentMousePosition+this.scrollOffset)}onMouseMove(e){if(e.button>1)return void this.onCancel();const t=this.container.getMousePosition(e);this.currentMousePosition=t,t<this.container.start||t>this.container.end?this.startEdgeScroll(t<this.container.start?-1:1):(this.stopEdgeScroll(),this.moveDraggedItemToPosition(t+this.scrollOffset))}moveDraggedItemToPosition(e){const t=this.getHoveredItemIndex(e,this.items),s=this.items.findIndex((e=>e.id===this.draggedItemId)),o=this.items[s];if(this.deadZone&&this.isInZone(e,this.deadZone))return void this.onChange(this.getItemsPositions());if(this.isInZone(e,{start:o.position,end:o.position+o.size})&&(this.deadZone=void 0),s===t)return void this.onChange(this.getItemsPositions());const i=Math.min(s,t),n=Math.max(s,t),r=Math.sign(t-s);let a=0;for(let e=i;e<=n;e++)e!==s&&(this.items[e].position-=r*o.size,a+=this.items[e].size);o.position+=r*a,this.items.sort(((e,t)=>e.position-t.position)),this.deadZone=r>0?{start:e,end:o.position}:{start:o.position+o.size,end:e},this.onChange(this.getItemsPositions())}onMouseUp(e){0!==e.button&&this.onCancel(),e.stopPropagation(),e.preventDefault();const t=this.items.findIndex((e=>e.id===this.draggedItemId));return this.onDragEnd(this.draggedItemId,t),this.stopEdgeScroll(),!1}startEdgeScroll(e){this.edgeScrollIntervalId||(this.edgeScrollIntervalId=window.setInterval((()=>{const t=3*e;this.container.scroll+=t}),5))}stopEdgeScroll(){window.clearInterval(this.edgeScrollIntervalId),this.edgeScrollIntervalId=void 0}getHoveredItemIndex(e,t){return e<=this.minPosition?0:e>=this.maxPosition?t.length-1:t.findIndex((t=>t.position+t.size>=e))}getItemsPositions(){const e={};for(const t of this.items){if(t.id!==this.draggedItemId){e[t.id]=t.position-t.positionAtStart;continue}let s=this.currentMousePosition-this.initialMousePosition+this.scrollOffset;s=Math.max(this.minPosition-t.positionAtStart,s),s=Math.min(this.maxPosition-t.positionAtStart-t.size,s),e[t.id]=s}return e}isInZone(e,t){return e>=t.start&&e<=t.end}get scrollOffset(){return this.container.scroll-this.initialScroll}destroy(){this.stopEdgeScroll()}}class px{el;constructor(e){this.el=e}get containerRect(){return this.el.getBoundingClientRect()}}class mx extends px{get start(){return this.containerRect.top}get end(){return this.containerRect.bottom}get cssPositionProperty(){return"top"}get scroll(){return this.el.scrollTop}set scroll(e){this.el.scrollTop=e}getMousePosition(e){return e.clientY}}class fx extends px{get start(){return this.containerRect.left}get end(){return this.containerRect.right}get cssPositionProperty(){return"left"}get scroll(){return this.el.scrollLeft}set scroll(e){this.el.scrollLeft=e}getMousePosition(e){return e.clientX}}class vx{mutators=["focus","unfocus"];focusedElement=null;focus(e){this.focusedElement=e}unfocus(e){this.focusedElement&&this.focusedElement===e&&(this.focusedElement=null)}}class bx extends ph{initialRanges;inputHasSingleRange;colors;disabledRanges;mutators=["resetWithRanges","focusById","unfocus","addEmptyRange","removeRange","changeRange","reset","confirm","updateColors","updateDisabledRanges"];ranges=[];focusedRangeIndex=null;inputSheetId;focusStore=this.get(vx);highlightStore=this.get(XR);constructor(e,t=[],s=!1,o=[],i=[]){if(super(e),this.initialRanges=t,this.inputHasSingleRange=s,this.colors=o,this.disabledRanges=i,s&&t.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");this.inputSheetId=this.getters.getActiveSheetId(),this.resetWithRanges(t),this.highlightStore.register(this),this.onDispose((()=>{this.unfocus(),this.highlightStore.unRegister(this)}))}handleEvent(e){if(null===this.focusedRangeIndex)return;const t=this.inputSheetId,s=this.getters.getActiveSheetId(),o=e.options.unbounded?this.getters.getUnboundedZone(s,e.anchor.zone):e.anchor.zone,i=this.getters.getRangeFromZone(s,o);if("newAnchor"===e.mode&&!this.inputHasSingleRange&&""!==this.ranges[this.focusedRangeIndex].xc.trim()){const e=this.getters.getSelectionRangeString(i,t);this.insertNewRange(this.ranges.length,[e]),this.focusLast()}else{let e=i.parts;const s=this.ranges[this.focusedRangeIndex].xc.trim();s&&(e=this.getters.getRangeFromSheetXC(t,s).parts);const o={...i,parts:e},n=this.getters.getSelectionRangeString(o,t);this.setRange(this.focusedRangeIndex,[n])}}handle(e){switch(e.type){case"ACTIVATE_SHEET":if(e.sheetIdFrom!==e.sheetIdTo){const{col:t,row:s}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),o=this.getters.expandZone(e.sheetIdTo,Us({col:t,row:s}));this.model.selection.resetAnchor(this,{cell:{col:t,row:s},zone:o})}break;case"START_CHANGE_HIGHLIGHT":const t=this.getters.getActiveSheetId(),s=this.getters.expandZone(t,e.zone),o=this.ranges.findIndex((e=>{const{xc:o,sheetName:i}=na(e.xc),n=i||this.getters.getSheetName(this.inputSheetId);if(this.getters.getSheetName(t)!==n)return!1;const r=this.getters.getRangeFromSheetXC(t,o);return xs(this.getters.expandZone(t,r.zone),s)}));if(-1!==o){this.focus(o);const{left:e,top:t}=s;this.model.selection.resetAnchor(this,{cell:{col:e,row:t},zone:s})}}}changeRange(e,t){if(this.inputHasSingleRange&&t.split(",").length>1)return;const s=this.getIndex(e);if(null!==s&&this.focusedRangeIndex!==s&&this.focus(s),null!==s){const e=t.replace(/^,+/,"").split(",").map((e=>e.trim()));this.setRange(s,e),this.captureSelection()}}addEmptyRange(){this.inputHasSingleRange&&1===this.ranges.length||(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}removeRange(e){if(1===this.ranges.length)return;const t=this.getIndex(e);null!==t&&this.removeRangeByIndex(t)}updateColors(e){this.colors=e;const t=new Oo(this.ranges.length,this.colors);this.ranges=this.ranges.map((e=>({...e,color:t.next()})))}updateDisabledRanges(e){this.disabledRanges=e}confirm(){for(const e of this.selectionInputs)""===e.xc&&this.removeRange(e.id);const e=this.getters.getActiveSheetId();this.inputSheetId!==e&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:this.inputSheetId}),this.selectionInputValues.join()!==this.initialRanges.join()&&this.resetWithRanges(this.selectionInputValues),this.initialRanges=this.selectionInputValues,this.unfocus()}reset(){this.resetWithRanges(this.initialRanges),this.confirm()}get selectionInputValues(){return this.cleanInputs(this.ranges.map((e=>e.xc?e.xc:"")))}get selectionInputs(){return this.ranges.map(((e,t)=>Object.assign({},e,{color:this.hasMainFocus&&null!==this.focusedRangeIndex&&this.getters.isRangeValid(e.xc)?e.color:null,isFocused:this.hasMainFocus&&this.focusedRangeIndex===t,isValidRange:""===e.xc||this.getters.isRangeValid(e.xc),disabled:this.disabledRanges?.[t]})))}get isResettable(){return this.initialRanges.join()!==this.ranges.map((e=>e.xc)).join()}get isConfirmable(){return this.selectionInputs.every((e=>e.isValidRange))}get hasFocus(){return this.selectionInputs.some((e=>e.isFocused))}get hasMainFocus(){const e=this.focusStore.focusedElement;return!!e&&e===this}get highlights(){return this.hasMainFocus?this.ranges.map((e=>this.inputToHighlights(e))).flat():[]}focusById(e){this.focus(this.getIndex(e))}focus(e){this.focusStore.focus(this),this.focusedRangeIndex=e,this.captureSelection()}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null,this.focusStore.unfocus(this),this.model.selection.release(this)}captureSelection(){if(null===this.focusedRangeIndex)return;const e=this.ranges[this.focusedRangeIndex],t=this.getters.getActiveSheetId(),s=this.getters.getRangeFromSheetXC(t,e?.xc||"A1").zone;this.model.selection.capture(this,{cell:{col:s.left,row:s.top},zone:s},{handleEvent:this.handleEvent.bind(this),release:this.unfocus.bind(this)})}resetWithRanges(e){e.length&&e.every((e=>this.getters.isRangeValid(e)))&&(this.initialRanges=e),this.ranges=[],this.insertNewRange(0,e),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){const s=Math.max(0,...this.ranges.map((e=>Number(e.id)))),o=new Oo(this.ranges.length,this.colors);for(let t=0;t<e;t++)o.next();this.ranges.splice(e,0,...t.map(((e,t)=>({xc:e,id:s+t+1,color:o.next()}))))}setRange(e,t){const[,...s]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,s),s.length&&this.focus(e+s.length)}removeRangeByIndex(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const s=this.cleanInputs([e]).filter((e=>this.getters.isRangeValid(e))).filter((e=>this.shouldBeHighlighted(this.inputSheetId,e)));return s.map((e=>{const{sheetName:s}=na(e),o=s&&this.getters.getSheetIdByName(s)||this.inputSheetId;return{range:this.getters.getRangeFromSheetXC(o,e),color:t,interactive:!0}}))}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:s}=na(t),o=this.getters.getSheetIdByName(s),i=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(o===i||void 0===o&&i===e)}getIndex(e){const t=this.ranges.findIndex((t=>t.id===e));return t>=0?t:null}}class Sx extends t.Component{static template="o-spreadsheet-SelectionInput";static props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},required:{type:Boolean,optional:!0},isInvalid:{type:Boolean,optional:!0},class:{type:String,optional:!0},onSelectionChanged:{type:Function,optional:!0},onSelectionConfirmed:{type:Function,optional:!0},onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},colors:{type:Array,optional:!0,default:[]},disabledRanges:{type:Array,optional:!0,default:[]},disabledRangeTitle:{type:String,optional:!0}};state=t.useState({isMissing:!1,mode:"select-range"});dragAndDrop=ux();focusedInput=t.useRef("focusedInput");selectionRef=t.useRef("o-selection");store;get ranges(){return this.store.selectionInputs}get canAddRange(){return!this.props.hasSingleRange}get isInvalid(){return this.props.isInvalid||this.state.isMissing}get isConfirmable(){return this.store.isConfirmable}get isResettable(){return this.store.isResettable}get hasDisabledRanges(){return this.store.disabledRanges.some(Boolean)}setup(){t.useEffect((()=>this.focusedInput.el?.focus()),(()=>[this.focusedInput.el])),this.store=ah(bx,this.props.ranges,this.props.hasSingleRange||!1,this.props.colors,this.props.disabledRanges),t.onWillUpdateProps((e=>{e.ranges.join()!==this.store.selectionInputValues.join()&&this.triggerChange(),e.ranges.join()!==this.props.ranges.join()&&e.ranges.join()!==this.store.selectionInputValues.join()&&this.store.resetWithRanges(e.ranges),e.colors?.join()!==this.props.colors?.join()&&e.colors?.join()!==this.store.colors.join()&&this.store.updateColors(e.colors||[]),St(e.disabledRanges,this.props.disabledRanges)||St(e.disabledRanges,this.store.disabledRanges)||this.store.updateDisabledRanges(e.disabledRanges||[])}))}startDragAndDrop(e,t){if(0!==t.button||"SELECT"===t.target.tagName)return;const s=this.getRangeElementsRects(),o=this.ranges.map((e=>e.id)),i=o.map(((e,t)=>({id:e.toString(),size:s[t].height,position:s[t].y})));this.dragAndDrop.start("vertical",{draggedItemId:e.toString(),initialMousePosition:t.clientY,items:i,scrollableContainerEl:this.selectionRef.el,onDragEnd:(t,s)=>{const i=o.findIndex((t=>t===e));if(i===s)return;const n=Je(0,o.length);n.splice(i,1),n.splice(s,0,i),this.props.onSelectionReordered?.(n),this.props.onSelectionConfirmed?.(),this.store.confirm()}})}getRangeElementsRects(){return Array.from(this.selectionRef.el.children).map((e=>e.getBoundingClientRect()))}getColor(e){return e.color?aR({color:e.color}):""}triggerChange(){const e=this.store.selectionInputValues;this.props.onSelectionChanged?.(e)}onKeydown(e){if("F2"===e.key)e.preventDefault(),e.stopPropagation(),this.state.mode="select-range"===this.state.mode?"text-edit":"select-range";else if(e.key.startsWith("Arrow"))e.stopPropagation(),"select-range"===this.state.mode&&(e.preventDefault(),UR(e,this.env.model.selection));else if("Enter"===e.key){e.target.blur(),this.isConfirmable&&this.confirm()}}extractRanges(e){return this.props.hasSingleRange?e.split(",")[0]:e}focus(e){this.state.isMissing=!1,this.state.mode="select-range",this.store.focusById(e)}addEmptyInput(){this.store.addEmptyRange()}removeInput(e){const t=this.store.selectionInputs.findIndex((t=>t.id===e));this.ranges.find((t=>t.id===e))?.xc&&(this.props.onSelectionRemoved?.(t),this.props.onSelectionConfirmed?.()),this.store.removeRange(e)}onInputChanged(e,t){const s=t.target,o=this.extractRanges(s.value);this.store.changeRange(e,o),this.triggerChange()}reset(){this.store.reset(),this.triggerChange()}confirm(){this.store.confirm();const e=this.store.selectionInputs.some((e=>this.env.model.getters.isRangeValid(e.xc)));this.props.required&&!e&&(this.state.isMissing=!0),this.props.onSelectionChanged?.(this.store.selectionInputValues),this.props.onSelectionConfirmed?.()}}const Cx={list:10,text:20,date:30,number:40,misc:50},yx=new n;function Ix(e,t){const o=yx.getAll().filter((e=>t.has(e.type))).sort(((e,t)=>e.category===t.category?e.sequence-t.sequence:Cx[e.category]-Cx[t.category]));return s(o.map(((t,s)=>({name:FR.get(t.type).name,id:t.type,separator:t.category!==o[s+1]?.category,execute:()=>e(t.type)}))))}yx.add("containsText",{type:"containsText",component:rx,category:"text",sequence:10}),yx.add("notContainsText",{type:"notContainsText",component:rx,category:"text",sequence:20}),yx.add("beginsWithText",{type:"beginsWithText",component:rx,category:"text",sequence:25}),yx.add("endsWithText",{type:"endsWithText",component:rx,category:"text",sequence:26}),yx.add("isEqualText",{type:"isEqualText",component:rx,category:"text",sequence:30}),yx.add("isEmail",{type:"isEmail",component:void 0,category:"text",sequence:40}),yx.add("isLink",{type:"isLink",component:void 0,category:"text",sequence:50}),yx.add("dateIs",{type:"dateIs",component:ix,category:"date",sequence:20}),yx.add("dateIsBefore",{type:"dateIsBefore",component:ix,category:"date",sequence:30}),yx.add("dateIsOnOrBefore",{type:"dateIsOnOrBefore",component:ix,category:"date",sequence:40}),yx.add("dateIsAfter",{type:"dateIsAfter",component:ix,category:"date",sequence:50}),yx.add("dateIsOnOrAfter",{type:"dateIsOnOrAfter",component:ix,category:"date",sequence:60}),yx.add("dateIsBetween",{type:"dateIsBetween",component:nx,category:"date",sequence:70}),yx.add("dateIsNotBetween",{type:"dateIsNotBetween",component:nx,category:"date",sequence:80}),yx.add("dateIsValid",{type:"dateIsValid",component:void 0,category:"date",sequence:10}),yx.add("isEqual",{type:"isEqual",component:rx,category:"number",sequence:10}),yx.add("isNotEqual",{type:"isNotEqual",component:rx,category:"number",sequence:20}),yx.add("isGreaterThan",{type:"isGreaterThan",component:rx,category:"number",sequence:50}),yx.add("isGreaterOrEqualTo",{type:"isGreaterOrEqualTo",component:rx,category:"number",sequence:60}),yx.add("isLessThan",{type:"isLessThan",component:rx,category:"number",sequence:30}),yx.add("isLessOrEqualTo",{type:"isLessOrEqualTo",component:rx,category:"number",sequence:40}),yx.add("isBetween",{type:"isBetween",component:nx,category:"number",sequence:70}),yx.add("isNotBetween",{type:"isNotBetween",component:nx,category:"number",sequence:80}),yx.add("isBoolean",{type:"isBoolean",component:void 0,category:"misc",sequence:10}),yx.add("isValueInList",{type:"isValueInList",component:class extends _R{static template="o-spreadsheet-ListCriterionForm";static components={CriterionInput:sx,RoundColorPicker:dx};state=t.useState({numberOfValues:Math.max(this.props.criterion.values.length,2)});setup(){super.setup();const e=e=>{void 0===e.criterion.displayStyle&&this.updateCriterion({displayStyle:"chip"})};t.onWillUpdateProps(e),t.onWillStart((()=>e(this.props)))}onValueChanged(e,t){const s=[...this.displayedValues];s[t]=e,this.updateCriterion({values:s})}onColorChanged(e,t){const s={...this.props.criterion.colors};s[t]=e||void 0,this.updateCriterion({colors:s})}onAddAnotherValue(){this.state.numberOfValues++}removeItem(e){const t=[...this.displayedValues];t.splice(e,1),this.state.numberOfValues--,this.updateCriterion({values:t})}onChangedDisplayStyle(e){const t=e.target.value;this.updateCriterion({displayStyle:t})}onKeyDown(e,t){"Enter"!==e.key&&"Tab"!==e.key||t!==this.state.numberOfValues-1?"Enter"===e.key&&(this.state.focusedValueIndex=t+1):(this.onAddAnotherValue(),this.state.focusedValueIndex=t+1,e.preventDefault())}onBlurInput(){this.state.focusedValueIndex=void 0}get displayedValues(){const e=[];for(let t=0;t<this.state.numberOfValues;t++)e.push(this.props.criterion.values[t]||"");return e}},category:"list",sequence:10}),yx.add("isValueInRange",{type:"isValueInRange",component:class extends _R{static template="o-spreadsheet-ValueInRangeCriterionForm";static components={RoundColorPicker:dx,SelectionInput:Sx};setup(){super.setup();const e=e=>{void 0===e.criterion.displayStyle&&this.updateCriterion({displayStyle:"chip"})};t.onWillUpdateProps(e),t.onWillStart((()=>e(this.props)))}onRangeChanged(e){this.updateCriterion({values:[e]})}onChangedDisplayStyle(e){const t=e.target.value;this.updateCriterion({displayStyle:t})}onColorChanged(e,t){const s={...this.props.criterion.colors};s[t]=e||void 0,this.updateCriterion({colors:s})}get values(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getDataValidationRangeValues(e,this.props.criterion);return new Set(t)}},category:"list",sequence:20}),yx.add("customFormula",{type:"customFormula",component:rx,category:"misc",sequence:20}),yx.add("isEmpty",{type:"isEmpty",component:void 0,category:"misc",sequence:5}),yx.add("isNotEmpty",{type:"isNotEmpty",component:void 0,category:"misc",sequence:6});class wx extends t.Component{static template="o-spreadsheet-SelectMenu";static props={menuItems:Array,selectedValue:String,class:{type:String,optional:!0}};static components={MenuPopover:fR};menuId=(new Xa).uuidv4();selectRef=t.useRef("select");state=t.useState({isMenuOpen:!1});onClick(e){e.closedMenuId!==this.menuId&&(this.state.isMenuOpen=!this.state.isMenuOpen)}onMenuClosed(){this.state.isMenuOpen=!1}get menuAnchorRect(){return By(this.selectRef)}}class Ex extends t.Component{static template="o-spreadsheet-FilterMenuCriterion";static props={filterPosition:Object,onCriterionChanged:Function,criterionOperators:Array};static components={SelectMenu:wx};state;setup(){t.onWillUpdateProps((e=>{St(e.filterPosition,this.props.filterPosition)||(this.state.criterion=this.getFilterCriterionValue(e.filterPosition))})),this.state=t.useState({criterion:this.getFilterCriterionValue(this.props.filterPosition)})}getFilterCriterionValue(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getFilterCriterionValue({sheetId:t,...e});return"criterion"===s?.filterType?qe(s):{filterType:"criterion",type:"none",values:[]}}get criterionMenuItems(){return[i({name:Go("None"),id:"none",separator:!0,execute:()=>this.onCriterionTypeChange("none")}),...Ix((e=>this.onCriterionTypeChange(e)),new Set(this.props.criterionOperators))]}get selectedCriterionName(){return"none"===this.state.criterion.type?Go("None"):FR.get(this.state.criterion.type).name}get criterionComponent(){return"none"===this.state.criterion.type?void 0:yx.get(this.state.criterion.type).component}onCriterionChanged(e){this.state.criterion.values=e.values,this.state.criterion.dateValue=e.dateValue,this.props.onCriterionChanged(this.state.criterion)}onCriterionTypeChange(e){this.state.criterion.type=e,this.props.onCriterionChanged(this.state.criterion)}}class Rx extends t.Component{static template="o-spreadsheet.Checkbox";static props={label:{type:String,optional:!0},value:{type:Boolean,optional:!0},className:{type:String,optional:!0},name:{type:String,optional:!0},title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},onChange:Function};static defaultProps={value:!1};onChange(e){const t=e.target.checked;this.props.onChange(t)}}class xx extends t.Component{static template="o-spreadsheet-FilterMenuValueItem";static components={Checkbox:Rx};static props={value:String,isChecked:Boolean,isSelected:Boolean,onMouseMove:Function,onClick:Function,scrolledTo:{type:String,optional:!0}};itemRef=t.useRef("menuValueItem");setup(){t.onWillPatch((()=>{this.props.scrolledTo&&this.scrollListToSelectedValue()}))}scrollListToSelectedValue(){this.itemRef.el&&this.itemRef.el.scrollIntoView?.({block:"bottom"===this.props.scrolledTo?"end":"start"})}}class Tx extends t.Component{static template="o-spreadsheet-FilterMenuValueList";static props={filterPosition:Object,onUpdateHiddenValues:Function};static components={FilterMenuValueItem:xx};state=t.useState({values:[],displayedValues:[],textFilter:"",selectedValue:void 0,numberOfDisplayedValues:50,hasMoreValues:!1});searchBar=t.useRef("filterMenuSearchBar");setup(){t.onWillUpdateProps((e=>{St(e.filterPosition,this.props.filterPosition)||(this.state.values=this.getFilterHiddenValues(e.filterPosition),this.computeDisplayedValues())})),this.state.values=this.getFilterHiddenValues(this.props.filterPosition),this.computeDisplayedValues()}getFilterHiddenValues(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getFilter({sheetId:t,...e});if(!s)return[];const o=this.env.model.getters.getFilterValue({sheetId:t,...e});let i=(s.filteredRange?Ms(s.filteredRange.zone):[]).map((e=>({position:e,cellValue:this.env.model.getters.getEvaluatedCell({sheetId:t,...e}).formattedValue})));"criterion"!==o?.filterType&&(i=i.filter((e=>!this.env.model.getters.isRowHidden(t,e.position.row))));const n=i.map((e=>e.cellValue)),r="values"===o?.filterType?o.hiddenValues:[],a=new Set(r.map($a)),l=new Set,c=[],h=e=>{const t=$a(e);l.has(t)||(c.push({string:e||"",checked:"criterion"!==o?.filterType&&!a.has(t),normalizedValue:t}),l.add(t))};return n.forEach(h),r.forEach(h),c.sort(((e,t)=>e.normalizedValue.localeCompare(t.normalizedValue,void 0,{numeric:!0,sensitivity:"base"})))}checkValue(e){this.state.selectedValue=e.string,e.checked=!e.checked,this.searchBar.el?.focus(),this.updateHiddenValues()}onMouseMove(e){this.state.selectedValue=e.string}selectAll(){this.state.displayedValues.forEach((e=>e.checked=!0)),this.props.onUpdateHiddenValues([])}clearAll(){this.state.displayedValues.forEach((e=>e.checked=!1));const e=this.state.values.map((e=>e.string));this.props.onUpdateHiddenValues(e)}updateHiddenValues(){const e=this.state.values.filter((e=>!e.checked)).map((e=>e.string));this.props.onUpdateHiddenValues(e)}updateSearch(e){const t=e.target;this.state.textFilter=t.value,this.state.selectedValue=void 0,this.computeDisplayedValues()}computeDisplayedValues(){const e=this.state.textFilter?Fa(this.state.textFilter,this.state.values,(e=>e.string)):this.state.values;this.state.displayedValues=e.slice(0,this.state.numberOfDisplayedValues),this.state.hasMoreValues=e.length>this.state.numberOfDisplayedValues}loadMoreValues(){this.state.numberOfDisplayedValues+=100,this.computeDisplayedValues()}onKeyDown(e){const t=this.state.displayedValues;if(0===t.length)return;let s;if(void 0!==this.state.selectedValue){const e=t.findIndex((e=>e.string===this.state.selectedValue));s=-1===e?void 0:e}switch(e.key){case"ArrowDown":s=void 0===s?0:Math.min(s+1,t.length-1),e.preventDefault(),e.stopPropagation();break;case"ArrowUp":s=void 0===s?t.length-1:Math.max(s-1,0),e.preventDefault(),e.stopPropagation();break;case"Enter":void 0!==s&&this.checkValue(t[s]),e.stopPropagation(),e.preventDefault()}this.state.selectedValue=void 0!==s?t[s].string:void 0,"ArrowUp"!==e.key&&"ArrowDown"!==e.key||this.scrollListToSelectedValue(e.key)}clearScrolledToValue(){this.state.values.forEach((e=>e.scrolledTo=void 0))}scrollListToSelectedValue(e){this.clearScrolledToValue();const t=this.state.values.find((e=>e.string===this.state.selectedValue));t&&(t.scrolledTo="ArrowUp"===e?"top":"bottom")}}class Ax extends t.Component{static template="o-spreadsheet-FilterMenu";static props={filterPosition:Object,onClosed:{type:Function,optional:!0}};static components={FilterMenuValueList:Tx,SidePanelCollapsible:DR,FilterMenuCriterion:Ex};criterionCategory="text";updatedCriterionValue;setup(){t.onWillUpdateProps((e=>{St(e.filterPosition,this.props.filterPosition)||(this.updatedCriterionValue=void 0,this.criterionCategory=this.getCriterionCategory(e.filterPosition))})),this.criterionCategory=this.getCriterionCategory(this.props.filterPosition)}get isSortable(){if(!this.table)return!1;const e=this.env.model.getters.getCoreTableMatchingTopLeft(this.table.range.sheetId,this.table.range.zone);return!this.env.model.getters.isReadonly()&&"dynamic"!==e?.type}get table(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition;return this.env.model.getters.getTable({sheetId:e,...t})}get filterValueType(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition,s=this.env.model.getters.getFilterValue({sheetId:e,...t});return s?.filterType}getCriterionCategory(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getFilter({sheetId:t,...e});if(!s||!s.filteredRange)return"text";const o={text:0,number:0,date:0},i=s.filteredRange.zone;for(let s=i.top;s<=i.bottom&&!(s>100);s++){const i=this.env.model.getters.getEvaluatedCell({sheetId:t,row:s,col:e.col});i.type===r.text||i.type===r.boolean?o.text++:i.type===r.number&&(i.format&&ur(i.format)?o.date++:o.number++)}const n=Math.max(o.text,o.number,o.date);return Object.keys(o).find((e=>o[e]===n))||"text"}onUpdateHiddenValues(e){this.updatedCriterionValue={filterType:"values",hiddenValues:e}}onCriterionChanged(e){this.updatedCriterionValue=e}confirm(){if(!this.updatedCriterionValue)return void this.props.onClosed?.();const e=this.props.filterPosition;this.env.model.dispatch("UPDATE_FILTER",{...e,sheetId:this.env.model.getters.getActiveSheetId(),value:this.updatedCriterionValue}),this.props.onClosed?.()}get criterionOperators(){return"date"===this.criterionCategory?jt:"number"===this.criterionCategory?Zt:qt}cancel(){this.props.onClosed?.()}sortFilterZone(e){const t=this.props.filterPosition,s=this.table,o=s?.range.zone;if(!t||!o||o.top===o.bottom)return;const i=this.env.model.getters.getActiveSheetId(),n={...o,top:o.top+1},r={col:t.col,row:n.top};Hm(this.env,i,r,n,e,{emptyCellAsZero:!0,sortHeaders:!0}),this.props.onClosed?.()}}const Dx={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:Ax,cellCorner:"bottom-left"})};class _x extends t.Component{static template="o-spreadsheet-LinkDisplay";static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};cellPopovers;setup(){this.cellPopovers=rh(RR)}get cell(){const{col:e,row:t}=this.props.cellPosition,s=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getEvaluatedCell({sheetId:s,col:e,row:t})}get link(){if(this.cell.link)return this.cell.link;const{col:e,row:t}=this.props.cellPosition;throw new Error(`LinkDisplay Component can only be used with link cells. ${as(e,t)} is not a link.`)}getUrlRepresentation(e){return Xo(e,this.env.model.getters)}openLink(e){Ko(this.link,this.env,Ky(e))}edit(){const{col:e,row:t}=this.props.cellPosition;this.env.model.selection.selectCell(e,t),this.cellPopovers.open({col:e,row:t},"LinkEditor")}unlink(){const e=this.env.model.getters.getActiveSheetId(),{col:t,row:s}=this.props.cellPosition,o=this.env.model.getters.getCellComputedStyle({sheetId:e,col:t,row:s}),i=o?.textColor===L?void 0:o?.textColor;this.env.model.dispatch("UPDATE_CELL",{col:t,row:s,sheetId:e,content:this.link.label,style:{...o,textColor:i,underline:void 0}})}}const Fx={onHover:(e,t)=>{const s=t.getEvaluatedCell(e);return!t.isDashboard()&&s.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:_x,props:{cellPosition:e},cellCorner:"bottom-left"}:{isOpen:!1}}},Ox={name:Go("Link sheet"),children:[e=>e.model.getters.getSheetIds().map((t=>e.model.getters.getSheet(t))).map((e=>({id:e.id,name:e.name,execute:()=>rt(e.name,ht(e.id))})))]},Px={name:Go("Delete"),isVisible:e=>e.model.getters.getVisibleSheetIds().length>1,execute:e=>e.askConfirmation(Go("Are you sure you want to delete this sheet?"),(()=>{e.model.dispatch("DELETE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName()})})),icon:"o-spreadsheet-Icon.TRASH"},Mx={name:Go("Duplicate"),execute:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSheetName(t),o=e.model.uuidGenerator.smallUuid(),i=e.model.getters.getDuplicateSheetName(s);e.model.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:o,sheetNameTo:i}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},icon:"o-spreadsheet-Icon.COPY"},Nx=e=>({name:Go("Rename"),execute:e.renameSheetCallback,icon:"o-spreadsheet-Icon.RENAME_SHEET"}),Lx=e=>({name:Go("Change color"),execute:e.openSheetColorPickerCallback,icon:"o-spreadsheet-Icon.PAINT_FORMAT"}),kx={name:Go("Move right"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getVisibleSheetIds();return s.indexOf(t)!==s.length-1},execute:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:1}),icon:"o-spreadsheet-Icon.MOVE_SHEET_RIGHT"},Vx={name:Go("Move left"),isVisible:e=>{const t=e.model.getters.getActiveSheetId();return e.model.getters.getVisibleSheetIds()[0]!==t},execute:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:-1}),icon:"o-spreadsheet-Icon.MOVE_SHEET_LEFT"},Ux={name:Go("Hide sheet"),isVisible:e=>1!==e.model.getters.getVisibleSheetIds().length,execute:e=>e.model.dispatch("HIDE_SHEET",{sheetId:e.model.getters.getActiveSheetId()}),icon:"o-spreadsheet-Icon.HIDE_SHEET"};class Hx extends n{replace(e,t){return void 0===t.id&&(t.id=e),this.content[e]=t,this}addChild(e,t,s){return this._replaceChild(e,t,s,{force:!1})}replaceChild(e,t,s){return this._replaceChild(e,t,s,{force:!0})}_replaceChild(e,t,s,o={force:!0}){"function"!=typeof s&&void 0===s.id&&(s.id=e);const i=t.splice(0,1)[0];let n=this.content[i];if(!n)throw new Error(`Path ${i+":"+t.join(":")} not found`);for(const e of t){const s=n.children;if(!s||"function"==typeof s)throw new Error(`${e} is either not a node or it's dynamically computed`);if(n=s.find((t=>t.id===e)),!n)throw new Error(`Path ${i+":"+t.join(":")} not found`)}n.children||(n.children=[]);const r=n.children;if(!r||"function"==typeof r)throw new Error(`${t} is either not a node or it's dynamically computed`);if("id"in s){const e=r.findIndex((e=>"id"in e&&e.id===s.id));if(e>-1){if(!o.force)throw new Error(`A child with the id "${s.id}" already exists.`);return n.children.splice(e,1,s),this}}return n.children.push(s),this}getMenuItems(){return s(this.getAll())}}const zx=new Hx;zx.add("sheet",{...Ox,sequence:10});class Bx extends t.Component{static template="o-spreadsheet-LinkEditor";static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};static components={MenuPopover:fR};menuItems=zx.getMenuItems();link=t.useState(this.defaultState);menu=t.useState({isOpen:!1});linkEditorMenuButtonRef=t.useRef("linkEditorMenuButton");urlInput=t.useRef("urlInput");setup(){t.onMounted((()=>this.urlInput.el?.focus()))}get defaultState(){const{col:e,row:t}=this.props.cellPosition,s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getEvaluatedCell({sheetId:s,col:e,row:t});return o.link?{url:o.link.url,label:o.formattedValue,isUrlEditable:o.link.isUrlEditable}:{label:o.formattedValue,url:"",isUrlEditable:!0}}get menuButtonRect(){return By(this.linkEditorMenuButtonRef)}onSpecialLink(e){const{detail:t}=e,s=Jo(t);s&&(this.link.url=s.url,this.link.label=s.label,this.link.isUrlEditable=s.isUrlEditable)}getUrlRepresentation(e){return Xo(e,this.env.model.getters)}openMenu(){this.menu.isOpen=!0}removeLink(){this.link.url="",this.link.isUrlEditable=!0}save(){const{col:e,row:t}=this.props.cellPosition,s=this.env.model.getters.getLocale(),o=this.link.label?Sl(this.link.label,s):this.link.url;this.env.model.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:this.env.model.getters.getActiveSheetId(),content:rt(o,this.link.url)}),this.props.onClosed?.()}cancel(){this.props.onClosed?.()}onKeyDown(e){switch(e.key){case"Enter":this.link.url&&this.save(),e.stopPropagation(),e.preventDefault();break;case"Escape":this.cancel(),e.stopPropagation()}}}const Gx={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:Bx,cellCorner:"bottom-left"})};ER.add("ErrorToolTip",TR).add("LinkCell",Fx).add("LinkEditor",Gx).add("FilterMenu",Dx);const Wx={MAX_PIE_CATEGORIES:7,MAX_PIE_CATEGORIES_NO_TITLE:6,MIN_RADAR_CATEGORIES:3,MAX_RADAR_CATEGORIES:12,PERCENTAGE_THRESHOLD:100};function $x(e,t){return Ss(e.getUnboundedZone(e.getActiveSheetId(),t))}function qx(e){if(!e.length)return"empty";const t={number:0,text:0,date:0,percentage:0};let s=0,o="empty";for(const i of e){let e=null;if(i.type===r.number?e=i.format&&ur(i.format)?"date":i.format?.includes("%")?"percentage":"number":i.type===r.text&&(e="text"),e){const i=++t[e];i>s&&(s=i,o=e)}}return o}function Zx(e,t){const s={number:[],text:[],date:[]};for(const o of function(e){const t=new Map;for(const s of e)for(let e=s.left;e<=s.right;e++){const o=t.get(e);o?(o.top=Math.min(o.top,s.top),o.bottom=Math.max(o.bottom,s.bottom)):t.set(e,{left:e,right:e,top:s.top,bottom:s.bottom})}return Array.from(t.values())}(e)){const e=qx(t.getEvaluatedCellsInZone(t.getActiveSheetId(),o));if("empty"!==e){s["percentage"===e?"number":e].push({zone:o,type:e})}}return s}function jx(e,t){const s=e.getEvaluatedCellsInZone(e.getActiveSheetId(),t),o=new Set;let i=0,n=0;for(let e=0;e<s.length;e++){const{value:t}=s[e],r=t?.toString().trim();if(!r)continue;o.add(r),i++;const a=Number(t);isNaN(a)||(n+=100*Math.abs(a))}return{uniqueCount:o.size,totalCount:i,percentageSum:n}}function Yx(e,t){const s=e.getEvaluatedCell({sheetId:e.getActiveSheetId(),col:t.zone.left,row:t.zone.top});return![r.number,r.empty].includes(s.type)}function Xx(e,t,s={}){return{type:e,title:{},dataSets:t,legendPosition:"none",...s}}function Kx(e,t){const s=Zx(e,t),{number:o,text:i,date:n}=s;switch(o.length+i.length+n.length){case 0:return Xx("bar",[{dataRange:$x(t,e[0])}],{dataSetsHaveTitle:!1});case 1:const r=o[0]||i[0]||n[0];return 1===Gs(r.zone)?function(e,t){const s=t.getCell({sheetId:t.getActiveSheetId(),col:e.left,row:e.top});return{type:"scorecard",title:{},keyValue:$x(t,e),background:s?.style?.fillColor,baselineMode:Ee,baselineColorUp:Re,baselineColorDown:xe}}(r.zone,t):function(e,t){const{type:s,zone:o}=e,i=t.getActiveSheetId(),n=Yx(t,e),r=$x(t,o),a=t.getEvaluatedCell({sheetId:i,col:o.left,row:o.top});switch(s){case"percentage":const{percentageSum:e}=jx(t,o);return Xx("pie",[{dataRange:r}],{title:n?{text:String(a.value)}:{},dataSetsHaveTitle:n,isDoughnut:e<Wx.PERCENTAGE_THRESHOLD});case"text":const s=t.getEvaluatedCellsInZone(i,o).reduce(((e,t)=>t.value===a.value?e+1:e),0),l=null!==a.value&&1===s;return Xx("pie",[{dataRange:r}],{title:l?{text:String(a.value)}:{},labelRange:r,dataSetsHaveTitle:l,isDoughnut:!1,aggregated:!0,legendPosition:"top"});case"date":return Xx("line",[{dataRange:r}],{labelRange:r,dataSetsHaveTitle:n,cumulative:!1,labelsAsText:!1})}return Xx("bar",[{dataRange:r}],{dataSetsHaveTitle:n})}(r,t);case 2:return function(e,t){const{number:s,text:o,date:i}=e;if(2===s.length)return Xx("scatter",[{dataRange:$x(t,s[1].zone)}],{labelRange:$x(t,s[0].zone),dataSetsHaveTitle:Yx(t,s[1]),labelsAsText:!1});if(1===i.length&&1===s.length)return Xx("line",[{dataRange:$x(t,s[0].zone)}],{labelRange:$x(t,i[0].zone),dataSetsHaveTitle:Yx(t,s[0]),aggregated:!1,cumulative:!1,labelsAsText:!1});if(1===o.length&&1===s.length){const[e]=o,[i]=s,{uniqueCount:n,totalCount:r}=jx(t,e.zone),a=Yx(t,i),l=a?Wx.MAX_PIE_CATEGORIES:Wx.MAX_PIE_CATEGORIES_NO_TITLE,c=$x(t,e.zone),h=$x(t,i.zone);if(n<=l){const{percentageSum:e}=jx(t,i.zone);return Xx("pie",[{dataRange:h}],{labelRange:c,dataSetsHaveTitle:a,isDoughnut:"percentage"===i.type&&e<Wx.PERCENTAGE_THRESHOLD,aggregated:!0,legendPosition:"top"})}return n!==r?Xx("treemap",[{dataRange:c}],{labelRange:h,dataSetsHaveTitle:a}):Xx("bar",[{dataRange:h}],{labelRange:c,dataSetsHaveTitle:a})}const n=o[0]||i[0]||s[0],r=s[0]||o[0]||i[0];return Xx("line",[{dataRange:$x(t,r.zone)}],{labelRange:$x(t,n.zone),dataSetsHaveTitle:Yx(t,r),cumulative:!1,labelsAsText:!0})}(s,t);default:return function(e,t){const{number:s,text:o,date:i}=e,n=s.some((e=>Yx(t,e)));if(o.length>=2&&1===s.length){const e=o.sort(((e,s)=>jx(t,e.zone).uniqueCount-jx(t,s.zone).uniqueCount)).map((({zone:e})=>({dataRange:$x(t,e)})));return Xx(o.length>=3?"sunburst":"treemap",e,{labelRange:$x(t,s[0].zone),dataSetsHaveTitle:n})}const r=ls(s.map((e=>e.zone))).map((e=>({dataRange:$x(t,e)})));if(1===i.length&&s.length>1)return Xx("line",r,{labelRange:$x(t,i[0].zone),dataSetsHaveTitle:n,cumulative:!1,labelsAsText:!1,legendPosition:"top"});if(1===o.length&&s.length>=2){const[e]=o,i=t.getEvaluatedCell({sheetId:t.getActiveSheetId(),row:e.zone.top,col:e.zone.left}),{uniqueCount:a,totalCount:l}=jx(t,e.zone),c=(n&&i.value?a-1:a)*s.length+(n?s.length:0),h=s.reduce(((e,s)=>e+jx(t,s.zone).totalCount),0);if(a===l&&a>=Wx.MIN_RADAR_CATEGORIES&&a<=Wx.MAX_RADAR_CATEGORIES&&c===h)return Xx("radar",r,{title:n&&i.value?{text:String(i.value)}:{},labelRange:$x(t,e.zone),dataSetsHaveTitle:n,legendPosition:"top"})}const a=o[0]||i[0]||s[0];return Xx("bar",r,{labelRange:r.length?$x(t,a.zone):"",dataSetsHaveTitle:n,aggregated:!0,legendPosition:"top"})}(s,t)}}const Jx={light:Go("Light"),medium:Go("Medium"),dark:Go("Dark"),custom:Go("Custom")},Qx={hasFilters:!1,totalRow:!1,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,bandedRows:!0,bandedColumns:!1,automaticAutofill:!0,styleId:"TableStyleMedium2"};function eT(e,t){return{coloredText:yo(t,.3),light:Co(t,.8),medium:Co(t,.6),dark:yo(t,.3),mediumBorder:Co(t,.45),highlight:t,name:e}}const tT={black:{name:Go("Black"),coloredText:"#000000",light:"#D9D9D9",medium:"#A6A6A6",dark:"#404040",mediumBorder:"#000000",highlight:"#000000"},lightBlue:eT(Go("Light blue"),"#346B90"),red:eT(Go("Red"),"#C53628"),lightGreen:eT(Go("Light green"),"#748747"),purple:eT(Go("Purple"),"#6C4E65"),gray:{name:Go("Gray"),coloredText:"#666666",light:"#EEEEEE",medium:"#DDDDDD",dark:"#767676",mediumBorder:"#D0D0D0",highlight:"#A9A9A9"},orange:eT(Go("Orange"),"#C37034")},sT={black:tT.black,orangeBlue:{...tT.lightBlue,highlight:tT.orange.highlight},purpleGreen:{...tT.lightGreen,highlight:tT.purple.highlight},redBlue:{...tT.lightBlue,highlight:tT.red.highlight}},oT=e=>({category:"light",templateName:"lightColoredText",primaryColor:e.highlight,wholeTable:{style:{textColor:e.coloredText},border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"}}},headerRow:{border:{bottom:{color:e.highlight,style:"thin"}}},totalRow:{border:{top:{color:e.highlight,style:"thin"}}},firstRowStripe:{style:{fillColor:e.light}}}),iT=e=>({category:"light",templateName:"lightWithHeader",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"},left:{color:e.highlight,style:"thin"},right:{color:e.highlight,style:"thin"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"},border:{bottom:{color:e.highlight,style:"thin"}}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{border:{bottom:{color:e.highlight,style:"thin"}}},secondRowStripe:{border:{bottom:{color:e.highlight,style:"thin"}}}}),nT=e=>({category:"light",templateName:"lightAllBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.highlight,style:"thin"},bottom:{color:e.highlight,style:"thin"},left:{color:e.highlight,style:"thin"},right:{color:e.highlight,style:"thin"},horizontal:{color:e.highlight,style:"thin"},vertical:{color:e.highlight,style:"thin"}}},headerRow:{border:{bottom:{color:e.highlight,style:"medium"}}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.light}},firstColumnStripe:{style:{fillColor:e.light}}}),rT=e=>({category:"medium",templateName:"mediumBandedBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.mediumBorder,style:"thin"},bottom:{color:e.mediumBorder,style:"thin"},left:{color:e.mediumBorder,style:"thin"},right:{color:e.mediumBorder,style:"thin"},horizontal:{color:e.mediumBorder,style:"thin"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.light}},firstColumnStripe:{style:{fillColor:e.light}}}),aT=e=>({category:"medium",templateName:"mediumWhiteBorders",primaryColor:e.highlight,wholeTable:{border:{horizontal:{color:"#FFFFFF",style:"thin"},vertical:{color:"#FFFFFF",style:"thin"}},style:{fillColor:e.light}},headerRow:{border:{bottom:{color:"#FFFFFF",style:"thick"}},style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{border:{top:{color:"#FFFFFF",style:"thick"}},style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},lastColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),lT=e=>({category:"medium",templateName:"mediumMinimalBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:"#000000",style:"medium"},bottom:{color:"#000000",style:"medium"}}},totalRow:{border:{top:{color:"#000000",style:"medium"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"},border:{bottom:{color:"#000000",style:"medium"}}},firstColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},lastColumn:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:tT.black.light}},firstColumnStripe:{style:{fillColor:tT.black.light}}}),cT=e=>({category:"medium",templateName:"mediumAllBorders",primaryColor:e.highlight,wholeTable:{border:{top:{color:e.mediumBorder,style:"thin"},bottom:{color:e.mediumBorder,style:"thin"},left:{color:e.mediumBorder,style:"thin"},right:{color:e.mediumBorder,style:"thin"},horizontal:{color:e.mediumBorder,style:"thin"},vertical:{color:e.mediumBorder,style:"thin"}},style:{fillColor:e.light}},totalRow:{border:{top:{color:e.highlight,style:"medium"}}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),hT=e=>({category:"dark",templateName:"dark",primaryColor:e.highlight,wholeTable:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},totalRow:{style:{fillColor:e.dark,textColor:"#FFFFFF"},border:{top:{color:"#FFFFFF",style:"thick"}}},headerRow:{style:{fillColor:"#000000"},border:{bottom:{color:"#FFFFFF",style:"thick"}}},firstColumn:{style:{fillColor:e.dark},border:{right:{color:"#FFFFFF",style:"thick"}}},lastColumn:{style:{fillColor:e.dark},border:{left:{color:"#FFFFFF",style:"thick"}}},firstRowStripe:{style:{fillColor:e.dark}},firstColumnStripe:{style:{fillColor:e.dark}}}),dT=e=>({category:"dark",templateName:"darkNoBorders",primaryColor:e.highlight,wholeTable:{style:{fillColor:e.light}},totalRow:{border:{top:{color:"#000000",style:"medium"}}},headerRow:{style:{fillColor:e.highlight,textColor:"#FFFFFF"}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),uT=hT(tT.black);uT.wholeTable.style.fillColor="#737373";const gT=lT(tT.black);function pT(e,t,s){return{...t(s),displayName:`${s.name}, ${e}`}}gT.wholeTable.border={...gT.wholeTable.border,left:{color:"#000000",style:"thin"},right:{color:"#000000",style:"thin"},horizontal:{color:"#000000",style:"thin"},vertical:{color:"#000000",style:"thin"}};const mT={None:{category:"light",templateName:"none",primaryColor:"",displayName:"none"},TableStyleLight1:pT("TableStyleLight1",oT,tT.black),TableStyleLight2:pT("TableStyleLight2",oT,tT.lightBlue),TableStyleLight3:pT("TableStyleLight3",oT,tT.red),TableStyleLight4:pT("TableStyleLight4",oT,tT.lightGreen),TableStyleLight5:pT("TableStyleLight5",oT,tT.purple),TableStyleLight6:pT("TableStyleLight6",oT,tT.gray),TableStyleLight7:pT("TableStyleLight7",oT,tT.orange),TableStyleLight8:pT("TableStyleLight8",iT,tT.black),TableStyleLight9:pT("TableStyleLight9",iT,tT.lightBlue),TableStyleLight10:pT("TableStyleLight10",iT,tT.red),TableStyleLight11:pT("TableStyleLight11",iT,tT.lightGreen),TableStyleLight12:pT("TableStyleLight12",iT,tT.purple),TableStyleLight13:pT("TableStyleLight13",iT,tT.gray),TableStyleLight14:pT("TableStyleLight14",iT,tT.orange),TableStyleLight15:pT("TableStyleLight15",nT,tT.black),TableStyleLight16:pT("TableStyleLight16",nT,tT.lightBlue),TableStyleLight17:pT("TableStyleLight17",nT,tT.red),TableStyleLight18:pT("TableStyleLight18",nT,tT.lightGreen),TableStyleLight19:pT("TableStyleLight19",nT,tT.purple),TableStyleLight20:pT("TableStyleLight20",nT,tT.gray),TableStyleLight21:pT("TableStyleLight21",nT,tT.orange),TableStyleMedium1:pT("TableStyleMedium1",rT,tT.black),TableStyleMedium2:pT("TableStyleMedium2",rT,tT.lightBlue),TableStyleMedium3:pT("TableStyleMedium3",rT,tT.red),TableStyleMedium4:pT("TableStyleMedium4",rT,tT.lightGreen),TableStyleMedium5:pT("TableStyleMedium5",rT,tT.purple),TableStyleMedium6:pT("TableStyleMedium6",rT,tT.gray),TableStyleMedium7:pT("TableStyleMedium7",rT,tT.orange),TableStyleMedium8:pT("TableStyleMedium8",aT,tT.black),TableStyleMedium9:pT("TableStyleMedium9",aT,tT.lightBlue),TableStyleMedium10:pT("TableStyleMedium10",aT,tT.red),TableStyleMedium11:pT("TableStyleMedium11",aT,tT.lightGreen),TableStyleMedium12:pT("TableStyleMedium12",aT,tT.purple),TableStyleMedium13:pT("TableStyleMedium13",aT,tT.gray),TableStyleMedium14:pT("TableStyleMedium14",aT,tT.orange),TableStyleMedium15:{...gT,displayName:"Black, TableStyleMedium15"},TableStyleMedium16:pT("TableStyleMedium16",lT,tT.lightBlue),TableStyleMedium17:pT("TableStyleMedium17",lT,tT.red),TableStyleMedium18:pT("TableStyleMedium18",lT,tT.lightGreen),TableStyleMedium19:pT("TableStyleMedium19",lT,tT.purple),TableStyleMedium20:pT("TableStyleMedium20",lT,tT.gray),TableStyleMedium21:pT("TableStyleMedium21",lT,tT.orange),TableStyleMedium22:pT("TableStyleMedium22",cT,tT.black),TableStyleMedium23:pT("TableStyleMedium23",cT,tT.lightBlue),TableStyleMedium24:pT("TableStyleMedium24",cT,tT.red),TableStyleMedium25:pT("TableStyleMedium25",cT,tT.lightGreen),TableStyleMedium26:pT("TableStyleMedium26",cT,tT.purple),TableStyleMedium27:pT("TableStyleMedium27",cT,tT.gray),TableStyleMedium28:pT("TableStyleMedium28",cT,tT.orange),TableStyleDark1:{...uT,displayName:"Black, TableStyleDark1"},TableStyleDark2:pT("TableStyleDark2",hT,tT.lightBlue),TableStyleDark3:pT("TableStyleDark3",hT,tT.red),TableStyleDark4:pT("TableStyleDark4",hT,tT.lightGreen),TableStyleDark5:pT("TableStyleDark5",hT,tT.purple),TableStyleDark6:pT("TableStyleDark6",hT,tT.gray),TableStyleDark7:pT("TableStyleDark7",hT,tT.orange),TableStyleDark8:pT("TableStyleDark8",dT,sT.black),TableStyleDark9:pT("TableStyleDark9",dT,sT.redBlue),TableStyleDark10:pT("TableStyleDark10",dT,sT.purpleGreen),TableStyleDark11:pT("TableStyleDark11",dT,sT.orangeBlue)},fT={none:()=>({category:"none",templateName:"none",primaryColor:"",name:"none"}),lightColoredText:oT,lightAllBorders:nT,mediumAllBorders:cT,lightWithHeader:iT,mediumBandedBorders:rT,mediumMinimalBorders:lT,darkNoBorders:dT,mediumWhiteBorders:aT,dark:hT};function vT(e,t,s){const o=eT("",s);return{...fT[t](o),category:"custom",displayName:e}}const bT="M256 9 a247 247 0 1 0.1 0 0";function ST(e){return{name:"CARET_DOWN",width:512,height:512,paths:[{fillColor:e.textColor||Z,path:"M120 195 h270 l-135 130"}]}}function CT(e){return{name:"CARET_UP",width:512,height:512,paths:[{fillColor:e.textColor||Z,path:"M120 325 h270 l-135 -130"}]}}const yT="M40 185 h270 l-135 128";function IT(e){return{name:"CHIP",width:512,height:512,paths:[{fillColor:e.textColor||Z,path:yT}]}}function wT(e){return{name:"CHIP",width:512,height:512,paths:[{fillColor:e.textColor||Z,path:"M0,225 A175,175 0 1,0 350,225 A175,175 0 1,0 0,225"},{fillColor:e.fillColor||Z,path:yT}]}}const ET={name:"CHECKBOX_UNCHECKED",width:512,height:512,paths:[{fillColor:W,path:"M45,45 h422 v422 h-422 v-422 m30,30 v362 h362 v-362"}]},RT={name:"CHECKBOX_UNCHECKED",width:512,height:512,paths:[{fillColor:j,path:"M45,45 h422 v422 h-422 v-422 m30,30 v362 h362 v-362"}]},xT={name:"CHECKBOX_CHECKED",width:512,height:512,paths:[{fillColor:j,path:"M45,45 h422 v422 h-422 v-422"},{fillColor:"#FFF",path:"M165,240 l45,45 l135,-135 h60 l-195,195 l-105,-105"}]};function TT(e,t){return{name:"PIVOT_ICON",width:512,height:512,paths:[{path:"M21,21 h469 v469 h-469",fillColor:t?G:"#777"},{path:"M64,64 v384 h384 v-384",fillColor:t?$:"#eee"},{path:e?"M149,235 h213 v43 h-213 M235,149 h43 v213 h-43":"M149,235 h213 v43 h-213",fillColor:t?G:"#777"}]}}function AT(e,t,s){const o=e?"M18.6 3.5H4.29c-.7 0-1.06.85-.56 1.35l6.1 6.1v6.8c0 .26.13.5.34.65l2.64 1.85a.79.79 0 0 0 1.25-.65v-8.64l6.1-6.1a.79.79 0 0 0-.56-1.35":"M 339.667 681 L 510.333 681 L 510.333 595.667 L 339.667 595.667 L 339.667 681 Z M 41 169 L 41 254.333 L 809 254.333 L 809 169 L 41 169 Z M 169 467.667 L 681 467.667 L 681 382.333 L 169 382.333 L 169 467.667 Z",i=e?"M0,0 h24 v24 h-24":"M0,0 h850 v850 h-850",n={iconColor:k,hoverBackgroundColor:k};return s&&!t?n.iconColor="#fff":!s&&t?n.iconColor="#defade":s&&t&&(n.iconColor=k,n.hoverBackgroundColor="#fff"),{name:"DATA_FILTER_ICON",width:e?24:850,height:e?24:850,paths:[s?{path:i,fillColor:n.hoverBackgroundColor}:void 0,{path:o,fillColor:n.iconColor}].filter(ut)}}const DT={arrowGood:{template:"ARROW_UP",svg:{name:"ARROW_UP",width:448,height:512,paths:[{fillColor:"#6AA84F",path:"M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z"}]}},arrowNeutral:{template:"ARROW_RIGHT",svg:{name:"ARROW_RIGHT",width:448,height:512,paths:[{fillColor:"#F0AD4E",path:"M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"}]}},arrowBad:{template:"ARROW_DOWN",svg:{name:"ARROW_DOWN",width:448,height:512,paths:[{fillColor:"#E06666",path:"M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z"}]}},smileyGood:{template:"SMILE",svg:{name:"SMILE",width:496,height:512,paths:[{fillColor:"#6AA84F",path:"M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160 0c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm4 72.6c-20.8 25-51.5 39.4-84 39.4s-63.2-14.3-84-39.4c-8.5-10.2-23.7-11.5-33.8-3.1-10.2 8.5-11.5 23.6-3.1 33.8 30 36 74.1 56.6 120.9 56.6s90.9-20.6 120.9-56.6c8.5-10.2 7.1-25.3-3.1-33.8-10.1-8.4-25.3-7.1-33.8 3.1z"}]}},smileyNeutral:{template:"MEH",svg:{name:"MEH",width:496,height:512,paths:[{fillColor:"#F0AD4E",path:"M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm8 144H160c-13.2 0-24 10.8-24 24s10.8 24 24 24h176c13.2 0 24-10.8 24-24s-10.8-24-24-24z"}]}},smileyBad:{template:"FROWN",svg:{name:"FROWN",width:496,height:512,paths:[{fillColor:"#E06666",path:"M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm-80 128c-40.2 0-78 17.7-103.8 48.6-8.5 10.2-7.1 25.3 3.1 33.8 10.2 8.4 25.3 7.1 33.8-3.1 16.6-19.9 41-31.4 66.9-31.4s50.3 11.4 66.9 31.4c8.1 9.7 23.1 11.9 33.8 3.1 10.2-8.5 11.5-23.6 3.1-33.8C326 321.7 288.2 304 248 304z"}]}},dotGood:{template:"GREEN_DOT",svg:{name:"GREEN_DOT",width:512,height:512,paths:[{fillColor:"#6AA84F",path:bT}]}},dotNeutral:{template:"YELLOW_DOT",svg:{name:"YELLOW_DOT",width:512,height:512,paths:[{fillColor:"#F0AD4E",path:bT}]}},dotBad:{template:"RED_DOT",svg:{name:"RED_DOT",width:512,height:512,paths:[{fillColor:"#E06666",path:bT}]}}},_T={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}},FT={};function OT(e){if(FT[e])return FT[e];const t=new Path2D(e);return FT[e]=t,t}var PT;!function(e){e.DiagonalBorderNotSupported="Diagonal Borders",e.BorderStyleNotSupported="Border style",e.FillStyleNotSupported="Fill Style",e.FontNotSupported="Font",e.HorizontalAlignmentNotSupported="Horizontal Alignment",e.VerticalAlignmentNotSupported="Vertical Alignments",e.MultipleRulesCfNotSupported="Multiple rules conditional formats",e.CfTypeNotSupported="Conditional format type",e.CfFormatBorderNotSupported="Borders in conditional formats",e.CfFormatAlignmentNotSupported="Alignment in conditional formats",e.CfFormatNumFmtNotSupported="Num formats in conditional formats",e.CfIconSetEmptyIconNotSupported="IconSets with empty icons",e.BadlyFormattedHyperlink="Badly formatted hyperlink",e.NumFmtIdNotSupported="Number format",e.TimeDataValidationNotSupported="Time data validation rules",e.TextLengthDataValidationNotSupported="Text length data validation rules",e.WholeNumberDataValidationNotSupported="Whole number data validation rules",e.NotEqualDateDataValidationNotSupported="Not equal date data validation rules"}(PT||(PT={}));class MT{_parsingWarnings=new Set;_conversionWarnings=new Set;addParsingWarning(e){this._parsingWarnings.add(e)}addConversionWarning(e){this._conversionWarnings.add(e)}get warnings(){return[...this._parsingWarnings,...this._conversionWarnings]}generateNotSupportedWarning(e,t,s){let o=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;s&&(o+=`Only ${s.join(", ")} are currently supported.`),this._conversionWarnings.has(o)||this._conversionWarnings.add(o)}}const NT=["thin","medium","thick","dashed","dotted"],LT=["general","left","center","right"],kT=["top","center","bottom"],VT=["Arial"],UT=["solid","none"],HT=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWithText","containsBlanks","notContainsBlanks"],zT={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},BT={dashDot:"thin",dashDotDot:"thin",dashed:"dashed",dotted:"dotted",double:"thin",hair:"thin",medium:"medium",mediumDashDot:"thin",mediumDashDotDot:"thin",mediumDashed:"thin",none:void 0,slantDashDot:"thin",thick:"thick",thin:"thin"},GT={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"},WT={top:"top",center:"middle",bottom:"bottom",justify:"middle",distributed:"middle"},$T={top:"top",middle:"center",bottom:"bottom"},qT={beginsWith:"beginsWithText",endsWith:"endsWithText",containsText:"containsText",notContains:"notContainsText",between:"isBetween",notBetween:"isNotBetween",equal:"isEqual",notEqual:"isNotEqual",greaterThan:"isGreaterThan",greaterThanOrEqual:"isGreaterOrEqualTo",lessThan:"isLessThan",lessThanOrEqual:"isLessOrEqualTo"},ZT={aboveAverage:void 0,expression:"customFormula",cellIs:void 0,colorScale:void 0,dataBar:void 0,iconSet:void 0,top10:void 0,uniqueValues:void 0,duplicateValues:void 0,containsText:"containsText",notContainsText:"notContainsText",beginsWith:"beginsWithText",endsWith:"endsWithText",containsBlanks:"isEmpty",notContainsBlanks:"isNotEmpty",containsErrors:void 0,notContainsErrors:void 0,timePeriod:void 0},jT={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},YT={NoIcons:void 0,"3Arrows":"arrows","3ArrowsGray":"arrows","3Symbols":"smiley","3Symbols2":"smiley","3Signs":"dots","3Flags":"dots","3TrafficLights1":"dots","3TrafficLights2":"dots","4Arrows":"arrows","4ArrowsGray":"arrows","4RedToBlack":"dots","4Rating":"smiley","4TrafficLights":"dots","5Arrows":"arrows","5ArrowsGray":"arrows","5Rating":"smiley","5Quarters":"dots","3Stars":"smiley","3Triangles":"arrows","5Boxes":"dots"},XT={none:"none",b:"bottom",t:"top",l:"left",r:"right",tr:"right"},KT={areaChart:void 0,area3DChart:void 0,lineChart:"line",line3DChart:void 0,stockChart:void 0,radarChart:"radar",scatterChart:"scatter",pieChart:"pie",pie3DChart:void 0,doughnutChart:"pie",barChart:"bar",bar3DChart:void 0,ofPieChart:void 0,surfaceChart:void 0,surface3DChart:void 0,bubbleChart:void 0,comboChart:"combo"},JT={exp:"exponential",log:"logarithmic",poly:"polynomial",movingAvg:"trailingMovingAverage"},QT={1:"AVERAGE",2:"COUNT",3:"COUNTA",4:"MAX",5:"MIN",6:"PRODUCT",7:"STDEV",8:"STDEVP",9:"SUM",10:"VAR",11:"VARP",101:"AVERAGE",102:"COUNT",103:"COUNTA",104:"MAX",105:"MIN",106:"PRODUCT",107:"STDEV",108:"STDEVP",109:"SUM",110:"VAR",111:"VARP"},eA={0:"General",1:"0",2:"0.00",3:"#,#00",4:"#,##0.00",9:"0%",10:"0.00%",11:void 0,12:void 0,13:void 0,14:"m/d/yyyy",15:"m/d/yyyy",16:"m/d/yyyy",17:"m/d/yyyy",18:"hh:mm:ss a",19:"hh:mm:ss a",20:"hhhh:mm:ss",21:"hhhh:mm:ss",22:"m/d/yy h:mm",37:void 0,38:void 0,39:void 0,40:void 0,45:"hhhh:mm:ss",46:"hhhh:mm:ss",47:"hhhh:mm:ss",48:void 0,49:"@"},tA={0:1,"0.00":2,"#,#00":3,"#,##0.00":4,"0%":9,"0.00%":10,"0.00E+00":11,"# ?/?":12,"# ??/??":13,"mm-dd-yy":14,"d-mm-yy":15,"mm-yy":16,"mmm-yy":17,"h:mm AM/PM":18,"h:mm:ss AM/PM":19,"h:mm":20,"h:mm:ss":21,"m/d/yy h:mm":22,"#,##0 ;(#,##0)":37,"#,##0 ;[Red](#,##0)":38,"#,##0.00;(#,##0.00)":39,"#,##0.00;[Red](#,##0.00)":40,"mm:ss":45,"[h]:mm:ss":46,"mmss.0":47,"##0.0E+0":48,"@":49,"hh:mm:ss a":19},sA={0:"000000",1:"FFFFFF",2:"FF0000",3:"00FF00",4:"0000FF",5:"FFFF00",6:"FF00FF",7:"00FFFF",8:"000000",9:"FFFFFF",10:"FF0000",11:"00FF00",12:"0000FF",13:"FFFF00",14:"FF00FF",15:"00FFFF",16:"800000",17:"008000",18:"000080",19:"808000",20:"800080",21:"008080",22:"C0C0C0",23:"808080",24:"9999FF",25:"993366",26:"FFFFCC",27:"CCFFFF",28:"660066",29:"FF8080",30:"0066CC",31:"CCCCFF",32:"000080",33:"FF00FF",34:"FFFF00",35:"00FFFF",36:"800080",37:"800000",38:"008080",39:"0000FF",40:"00CCFF",41:"CCFFFF",42:"CCFFCC",43:"FFFF99",44:"99CCFF",45:"FF99CC",46:"CC99FF",47:"FFCC99",48:"3366FF",49:"33CCCC",50:"99CC00",51:"FFCC00",52:"FF9900",53:"FF6600",54:"666699",55:"969696",56:"003366",57:"339966",58:"003300",59:"333300",60:"993300",61:"993366",62:"333399",63:"333333",64:"000000",65:"FFFFFF"},oA={"image/avif":"avif","image/bmp":"bmp","image/gif":"gif","image/vnd.microsoft.icon":"ico","image/jpeg":"jpeg","image/png":"png","image/tiff":"tiff","image/webp":"webp"},iA={avif:"image/avif",bmp:"image/bmp",gif:"image/gif",ico:"image/vnd.microsoft.icon",jpeg:"image/jpeg",png:"image/png",tiff:"image/tiff",webp:"image/webp",jpg:"image/jpeg"},nA={between:"isBetween",notBetween:"isNotBetween",equal:"isEqual",notEqual:"isNotEqual",greaterThan:"isGreaterThan",greaterThanOrEqual:"isGreaterOrEqualTo",lessThan:"isLessThan",lessThanOrEqual:"isLessOrEqualTo"},rA={between:"dateIsBetween",notBetween:"dateIsNotBetween",equal:"dateIs",greaterThan:"dateIsAfter",greaterThanOrEqual:"dateIsOnOrAfter",lessThan:"dateIsBefore",lessThanOrEqual:"dateIsOnOrBefore"};function aA(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=Eh;else{if(!e.indexed)return;t=sA[e.indexed]}var s;return t=6===(s=t).length?"#"+s+"FF":"#"+s.slice(2)+s.slice(0,2),e.tint&&(t=function(e,t){const s=go(e),o=mo(s);t<0&&(o.l=o.l*(1+t));t>0&&(o.l=o.l*(1-t)+(100-100*(1-t)));return uo(po(o))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function lA(e){return 9===e.length&&(e=e.slice(0,7)),parseInt(e.replace("#",""),16)}function cA(e,t){const s=e.split("/"),o=t.split("/");let i="",n=0;for(let e=0;e<s.length-1;e++)s[e]===o[e]?n++:i+="../";return i+=o.slice(n).join("/"),i}function hA(e,t=0){const s={};for(let o=0;o<e.length;o++)e[o]&&(s[o+t]=e[o]);return s}function dA(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,((e,t)=>String.fromCharCode(parseInt(t,16))))}function uA(e,t,s){return"COL"===t?(e.cols[s]||(e.cols[s]={}),e.cols[s]):(e.rows[s]||(e.rows[s]={}),e.rows[s])}const gA=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function pA(e,t,s){const o=eA[e]||t.find((t=>t.id===e))?.format;if("General"!==o){if(o)try{let e=o.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]");if(e=e.replace(/\[\$\]/g,""),e=e.replace(/_.{1}/g,""),e=e.replace(/\*.{1}/g,""),function(e){return gA.test(e)}(e)&&(e=function(e){return e=e.toLowerCase(),e=e.replace(/mmmmm/g,"mmm"),e=e.replace(/am\/pm|a\/m/g,"a"),e=e.replace(/hhhh/g,"hh"),e=e.replace(/\bh\b/g,"hh"),e}(e)),function(e){try{return or(0,{format:e,locale:w}),!0}catch(e){return!1}}(e))return e}catch(e){}s.generateNotSupportedWarning(PT.NumFmtIdNotSupported,o||`nmFmtId ${e}`)}}function mA(e,t){const s=e.borders.map((e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(PT.DiagonalBorderNotSupported)}(e,t);const s={top:fA(e.top,t),bottom:fA(e.bottom,t),left:fA(e.left,t),right:fA(e.right,t)};return Object.keys(s).forEach((e=>void 0===s[e]&&delete s[e])),s}));return hA(s,1)}function fA(e,t){if(!e)return;!function(e,t){NT.includes(e.style)||t.generateNotSupportedWarning(PT.BorderStyleNotSupported,e.style,NT)}(e,t);const s=BT[e.style];return s?{style:s,color:aA(e.color)}:void 0}function vA(e,t){return hA(e.styles.map((s=>bA({fontStyle:e.fonts[s.fontId],fillStyle:e.fills[s.fillId],alignment:s.alignment},t))),1)}function bA(e,t){return function(e,t,s){e&&e.name&&!VT.includes(e.name)&&s.generateNotSupportedWarning(PT.FontNotSupported,e.name,VT);t&&t.patternType&&!UT.includes(t.patternType)&&s.generateNotSupportedWarning(PT.FillStyleNotSupported,t.patternType,UT)}(e?.fontStyle,e?.fillStyle,t),function(e,t){e&&!LT.includes(e)&&t.generateNotSupportedWarning(PT.HorizontalAlignmentNotSupported,e,LT)}(e?.alignment?.horizontal,t),function(e,t){e&&!kT.includes(e)&&t.generateNotSupportedWarning(PT.VerticalAlignmentNotSupported,e,kT)}(e?.alignment?.vertical,t),{bold:e.fontStyle?.bold,italic:e.fontStyle?.italic,strikethrough:e.fontStyle?.strike,underline:e.fontStyle?.underline,verticalAlign:e.alignment?.vertical?WT[e.alignment.vertical]:void 0,align:e.alignment?.horizontal?GT[e.alignment.horizontal]:void 0,fillColor:"solid"===e.fillStyle?.patternType?aA(e.fillStyle?.fgColor):aA(e.fillStyle?.bgColor),textColor:aA(e.fontStyle?.color),fontSize:e.fontStyle?.size,wrapping:e.alignment?.wrapText?"wrap":"overflow"}}function SA(e,t){const s=[];for(const o of e.styles){const i=pA(o.numFmtId,e.numFmts,t);i&&(s[o.numFmtId]=i)}return hA(s,1)}function CA(e,t,s){const o=[];let i=1;for(const n of e){if(0===n.cfRules.length)continue;xA(n,t,s);const e=n.cfRules[0];let r;const a=[];if(void 0!==e.dxfId||"colorScale"===e.type||"iconSet"===e.type||"dataBar"===e.type){switch(e.type){case"aboveAverage":case"containsErrors":case"notContainsErrors":case"duplicateValues":case"top10":case"uniqueValues":case"timePeriod":continue;case"dataBar":const t=yA(i++,n);t&&o.push(t);continue;case"colorScale":const l=IA(i++,n);l&&o.push(l);continue;case"iconSet":const c=wA(i++,n,s);c&&o.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;r=ZT[e.type],a.push(e.text);break;case"expression":if(!e.formula?.length)continue;r=ZT[e.type],a.push(`=${e.formula[0]}`);break;case"containsBlanks":case"notContainsBlanks":r=ZT[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;r=qT[e.operator],a.push(RA(e.formula[0])),2===e.formula.length&&a.push(RA(e.formula[1]))}r&&void 0!==e.dxfId&&o.push({id:(i++).toString(),ranges:n.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:r,values:a,style:bA({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},s)}})}}return o}function yA(e,t){const s=t.cfRules[0].dataBar;if(!s)return;const o=lA(aA(s.color)||"#FFFFFF");return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"DataBarRule",color:o}}}function IA(e,t){const s=t.cfRules[0].colorScale;if(!s||s.cfvos.length!==s.colors.length||s.cfvos.length<2||s.cfvos.length>3)return;const o=[];for(let e=0;e<s.cfvos.length;e++)o.push({color:lA(aA(s.colors[e])||"#FFFFFF"),type:jT[s.cfvos[e].type],value:s.cfvos[e].value});const i=o[0],n=2===o.length?o[1]:o[2],r=3===o.length?o[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:i,midpoint:r,maximum:n}}}function wA(e,t,s){const o=t.cfRules[0].iconSet;if(!o)return;let i=o.cfvos,n=o.cfIcons;if(i.length<3||n&&n.length<3)return;i.length>3&&(i=[i[0],i[Math.floor(i.length/2)],i[i.length-1]]),n&&n.length>3&&(n=[n[0],n[Math.floor(n.length/2)],n[n.length-1]]);const r=[];for(let e=1;e<=2;e++){const t=jT[i[e].type];if("value"===t)return;r.push({value:i[e].value||"",operator:i[e].gte?"ge":"gt",type:t})}let a={lower:n?EA(n[0].iconSet,n[0].iconId):EA(o.iconSet,0),middle:n?EA(n[1].iconSet,n[1].iconId):EA(o.iconSet,1),upper:n?EA(n[2].iconSet,n[2].iconId):EA(o.iconSet,2)};o.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(const e of Object.keys(a))if(!a[e])switch(s.generateNotSupportedWarning(PT.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=_T.dots.good;break;case"middle":a[e]=_T.dots.neutral;break;case"lower":a[e]=_T.dots.bad}return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"IconSetRule",icons:a,upperInflectionPoint:r[1],lowerInflectionPoint:r[0]}}}function EA(e,t){const s=YT[e];return s?0===t?_T[s].bad:1===t?_T[s].neutral:_T[s].good:""}function RA(e){const t=sl(e);return 1===t.length&&"REFERENCE"!==t[0].type?e:"="+e}function xA(e,t,s){if(e.cfRules.length>1&&s.generateNotSupportedWarning(PT.MultipleRulesCfNotSupported),HT.includes(e.cfRules[0].type)||s.generateNotSupportedWarning(PT.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const o=t[e.cfRules[0].dxfId];o.border&&s.generateNotSupportedWarning(PT.CfFormatBorderNotSupported),o.alignment&&s.generateNotSupportedWarning(PT.CfFormatAlignmentNotSupported),o.numFmt&&s.generateNotSupportedWarning(PT.CfFormatNumFmtNotSupported)}}function TA(e){switch(e){case"isNotEmpty":case"notContainsText":return"notContainsBlanks";case"isEmpty":return"containsBlanks";case"containsText":return"containsText";case"beginsWithText":return"beginsWith";case"endsWithText":return"endsWith";case"isGreaterThan":return"greaterThan";case"isGreaterOrEqualTo":return"greaterThanOrEqual";case"isLessThan":return"lessThan";case"isLessOrEqualTo":return"lessThanOrEqual";case"isBetween":return"between";case"isNotBetween":return"notBetween";case"isEqual":return"equal";case"isNotEqual":return"notEqual";case"customFormula":return""}}function AA(e){return Math.round(Ph*e*100)/100}function DA(e){return Math.round(Mh*e*100)/100}function _A(e,t,s,o,i){const n=s?e.styles[s]:{},r=o?e.formats[o]:void 0,a={font:{size:n?.fontSize||fe,color:{rgb:n?.textColor?n.textColor:"000000"},family:2,name:"Arial"},fill:n?.fillColor?{fgColor:{rgb:n.fillColor}}:{reservedAttribute:"none"},numFmt:r?{format:r,id:0}:void 0,border:i||0,alignment:{horizontal:n.align,vertical:n.verticalAlign?$T[n.verticalAlign]:void 0,wrapText:!("wrap"!==n.wrapping&&!t?.includes(Ne))||void 0}};return a.font.strike=!!n?.strikethrough||void 0,a.font.underline=!!n?.underline||void 0,a.font.bold=!!n?.bold||void 0,a.font.italic=!!n?.italic||void 0,a}function FA(e,t){const s=function(e,t){if(!e)return 0;let s=tA[e.format];s||(s=MA(e,t)+Uh);return s}(t.numFmt,e.numFmts),o={fontId:MA(t.font,e.fonts),fillId:MA(t.fill,e.fills),borderId:t.border,numFmtId:s,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal,wrapText:t.alignment.wrapText}};return MA(o,e.styles)}function OA(e,t,s){const o=e.find((e=>e.path===t));let i;return o?(i=`rId${(o.rels.length+1).toString()}`,o.rels.push({...s,id:i})):(i="rId1",e.push({path:t,rels:[{...s,id:i}]})),i}const PA=new WeakMap;function MA(e,t){let s=PA.get(t);if(!s){s=new Map;for(let e=0;e<t.length;e++){const o=qr(t[e]);s.set(o,e)}PA.set(t,s)}const o=qr(e);if(s.has(o))return s.get(o);const i=t.length;return t.push(e),s.set(o,i),i}function NA(e,t){const s=t.chartIds.findIndex((t=>t===e));return-1===s?(t.chartIds.push(e),t.chartIds.length):s+1}const LA=[];function kA(e){const t=LA.findIndex((t=>t===e));return-1===t?(LA.push(e),LA.length):t+1}function VA(e){return Math.round(914400*e/96)}function UA(e,t,s){let o,i,n=e;if(({xc:n,sheetName:o}=na(e)),o){const e=s.sheets.findIndex((e=>ua(e.name,o)));if(e<0)throw new Error("Unable to find a sheet with the name "+o);i=e}else i=Number(t);const r=ps(n);return void 0===r.right&&(r.right=s.sheets[i].colNumber),void 0===r.bottom&&(r.bottom=s.sheets[i].rowNumber),(r.right-r.left+1)*(r.bottom-r.top+1)}function HA(e){return Math.round(96*e/914400)}function zA(e,t){let s=0;for(let o=0;o<e;o++){const e=t.cols.find((e=>o>=e.min&&o<=e.max));e?.width?s+=e.width:t.sheetFormat?.defaultColWidth?s+=t.sheetFormat.defaultColWidth:s+=Nh}return s/Mh}function BA(e,t){let s=0;for(let o=0;o<e;o++){const e=t.rows.find((e=>e.index-1===o));e?.height?s+=e.height:t.sheetFormat?.defaultRowHeight?s+=t.sheetFormat.defaultRowHeight:s+=Lh}return s/Ph}function GA(e){let t=1;return e.figures.map((s=>function(e,t,s){let o,i,n,r,a;if(1===e.anchors.length)({col:o,row:i,offset:n}=ZA(e.anchors[0])),a=HA(e.figureSize.cx),r=HA(e.figureSize.cy);else{({col:o,row:i,offset:n}=ZA(e.anchors[0]));const{x:t,y:l}=jA(e.anchors[0],s),{x:c,y:h}=jA(e.anchors[1],s);a=c-t,r=h-l}const l={id:t,col:o,row:i,offset:n};if("dataSets"in(c=e.data)&&c.dataSets.length>0)return{...l,width:a,height:r,tag:"chart",data:WA(e.data)};if(function(e){return"imageSrc"in e}(e.data))return{...l,width:HA(e.data.size.cx),height:HA(e.data.size.cy),tag:"image",data:{path:e.data.imageSrc,mimetype:e.data.mimetype}};var c;return}(s,(t++).toString(),e))).filter(ut)}function WA(e){const t=e.dataSets.some((e=>"reference"in(e.label??{}))),s=e.labelRange?$A(e.labelRange,t):void 0,o=e.dataSets.map((e=>{let s;return e.label&&"text"in e.label&&(s=e.label.text),{dataRange:$A(e.range,t),label:s,backgroundColor:e.backgroundColor,trend:qA(e.trend)}}));"pie"===e.type&&o.reverse();const i={range:o,dataSetsHaveTitle:t,auxiliaryRange:s,title:e.title??{text:""},background:aA({rgb:e.backgroundColor})||"#FFFFFF",legendPosition:e.legendPosition,stacked:e.stacked||!1,aggregated:!1,cumulative:e.cumulative||!1,labelsAsText:!1,horizontal:e.horizontal,isDoughnut:e.isDoughnut,pieHolePercentage:e.pieHolePercentage};try{return xE.get(e.type).getChartDefinitionFromContextCreation(i)}catch(e){return}}function $A(e,t){const{sheetName:s,xc:o}=na(e);let i=ps(o);if(t&&void 0!==i.bottom&&void 0!==i.right){const e=i.bottom-i.top+1,t=i.right-i.left+1;1===e?i={...i,left:i.left-1}:1===t&&(i={...i,top:i.top-1})}return ra(s,Ss(i))}function qA(e){if(e&&e.type)return{type:"linear"===e.type?"polynomial":JT[e.type],order:"linear"===e.type?1:e.order,color:e.color,window:e.window||De,display:!0}}function ZA(e){const t={x:HA(e.colOffset)-ye,y:HA(e.rowOffset)-ye};return{col:e.col,row:e.row,offset:t}}function jA(e,t){return{x:zA(e.col,t)+HA(e.colOffset),y:BA(e.row,t)+HA(e.rowOffset)}}function YA(e,t){const s=[];let o=1;for(const i of e)if(i)switch(i.type){case"time":t.generateNotSupportedWarning(PT.TimeDataValidationNotSupported);break;case"textLength":t.generateNotSupportedWarning(PT.TextLengthDataValidationNotSupported);break;case"whole":t.generateNotSupportedWarning(PT.WholeNumberDataValidationNotSupported);break;case"decimal":const e=XA(o++,i);s.push(e);break;case"list":const n=KA(o++,i);s.push(n);break;case"date":if("notEqual"===i.operator){t.generateNotSupportedWarning(PT.NotEqualDateDataValidationNotSupported);break}const r=JA(o++,i);s.push(r);break;case"custom":const a=QA(o++,i);s.push(a)}return s}function XA(e,t){const s=[t.formula1.toString()];return t.formula2&&s.push(t.formula2.toString()),{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:nA[t.operator],values:s}}}function KA(e,t){const s=t.formula1.toString(),o=ea.test(s);return{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:o?"isValueInRange":"isValueInList",values:o?[s]:s.replaceAll('"',"").split(","),displayStyle:"arrow"}}}function JA(e,t){let s;const o=[t.formula1.toString()];return t.formula2?(o.push(t.formula2.toString()),s={type:rA[t.operator],values:Hr(o,w)}):s={type:rA[t.operator],values:Hr(o,w),dateValue:"exactDate"},{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:s}}function QA(e,t){return{id:e.toString(),ranges:t.sqref,isBlocking:"warning"!==t.errorStyle,criterion:{type:"customFormula",values:[`=${t.formula1.toString()}`]}}}const eD=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),tD=new RegExp(/SUBTOTAL\(([0-9]*),/g),sD=new RegExp(jr.source,"ig");function oD(e,t){const s=function(e){const t={};for(const s of e.rows)for(const e of s.cells)e.formula&&void 0!==e.formula.sharedIndex&&e.formula.content&&(t[e.formula.sharedIndex]={refCellXc:e.xc,formula:e.formula.content});return t}(e);for(const o of e.rows.map((e=>e.cells)).flat())o?.formula&&(o.formula.content=void 0===o.formula.sharedIndex||o.formula.content?"="+o.formula.content:"="+nD(o.xc,s[o.formula.sharedIndex]),o.formula.content=iD(o.formula.content,t))}function iD(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(tD,((e,t)=>{const s=QT[t];return s?s+"(":e}))).replace(eD,((e,s,o,i)=>{s=Number(s)-1,i=i.replace(/\$/g,"");const n=t.externalBooks[s].sheetNames.findIndex((e=>ua(e,o)));if(-1===n)return e;const r=t.externalBooks[s].datasets.find((e=>e.sheetId===n))?.data;if(!r)return e;const a=r&&r[i];return(Number(a)?a:`"${a}"`)||e}))}function nD(e,t){const s=rs(t.refCellXc);let o,i=t.formula.slice();do{if(o=sD.exec(i),o){const t=rs(o[0].replace("$","")),n=rs(e),r={colFixed:o[0].startsWith("$"),rowFixed:o[0].includes("$",1)},a={col:n.col-s.col,row:n.row-s.row},l={col:r.colFixed?t.col:t.col+a.col,row:r.rowFixed?t.row:t.row+a.row};i=i.slice(0,o.index)+as(l.col,l.row,r)+i.slice(o.index+o[0].length)}}while(o);return i}function rD(e,t){return e.sheets.map((s=>{oD(s,e);const o=function(e){const t=[0,0];for(const s of e.rows)t[0]=Math.max(t[0],kt(s.cells.map((e=>rs(e.xc).col)))),t[1]=Math.max(t[1],s.index);for(const s of e.figures)t[0]=Math.max(t[0],s.anchors[s.anchors.length-1]?.col??0),t[1]=Math.max(t[1],s.anchors[s.anchors.length-1]?.row??0);return t[0]=Math.max(t[0]+5,kh),t[1]=Math.max(t[1]+5,Vh),t}(s),i=s.sheetViews[0],n=dD(s,"ROW",o[1]),r=dD(s,"COL",o[0]);return{id:s.sheetName,areGridLinesVisible:!i||i.showGridLines,name:s.sheetName,colNumber:o[0],rowNumber:o[1],...cD(s,e,o,t),merges:s.merges,cols:aD(s,o[0],r),rows:lD(s,o[1],n),conditionalFormats:CA(s.cfs,e.dxfs,t),dataValidationRules:YA(s.dataValidations,t),figures:GA(s),isVisible:s.isVisible,panes:i?{xSplit:i.pane.xSplit,ySplit:i.pane.ySplit}:{xSplit:0,ySplit:0},tables:[],headerGroups:{COL:r,ROW:n},color:aA(s.sheetProperties?.tabColor)}}))}function aD(e,t,s){const o={};for(let n=1;n<t+1;n++){const t=e.cols.find((e=>e.min<=n&&n<=e.max));let r;r=t&&t.width?t.width:e.sheetFormat?.defaultColWidth?e.sheetFormat.defaultColWidth:Nh;const a=n-1,l=s.some((e=>e.isFolded&&e.start<=a&&a<=e.end));o[a]={size:(i=r,i?Math.round(i/Mh*100)/100:i),isHidden:!l&&t?.hidden}}var i;return o}function lD(e,t,s){const o={};for(let n=1;n<t+1;n++){const t=e.rows.find((e=>e.index===n));let r;r=t&&t.height?t.height:e.sheetFormat?.defaultRowHeight?e.sheetFormat.defaultRowHeight:Lh;const a=n-1,l=s.some((e=>e.isFolded&&e.start<=a&&a<=e.end));o[a]={size:(i=r,i?Math.round(i/Ph*100)/100:i),isHidden:!l&&t?.hidden}}var i;return o}function cD(e,t,s,o){const i={},n={},r={},a={},l=t.sharedStrings.map(At);const c=e.hyperlinks.reduce(((e,t)=>(e[t.xc]=t,e)),{});for(const s of e.rows)for(const e of s.cells)i[e.xc]=hD(e,c,l,o),e.styleIndex&&(n[e.xc]=e.styleIndex+1,r[e.xc]=t.styles[e.styleIndex].numFmtId+1,a[e.xc]=t.styles[e.styleIndex].borderId+1);for(const o of e.rows.filter((e=>e.styleIndex)))for(let e=1;e<=s[0];e++){const s=as(e-1,o.index-1);n[s]??=o.styleIndex+1,a[s]??=t.styles[o.styleIndex].borderId+1,r[s]??=t.styles[o.styleIndex].numFmtId+1}for(const o of e.cols.filter((e=>e.styleIndex)))for(let e=o.min;e<=Math.min(o.max,s[0]);e++)for(let i=1;i<=s[1];i++){const s=as(e-1,i-1);n[s]??=o.styleIndex+1,a[s]??=t.styles[o.styleIndex].borderId+1,r[s]??=t.styles[o.styleIndex].numFmtId+1}return{cells:i,styles:n,formats:r,borders:a}}function hD(e,t,s,o){let i;switch(e.type){case"sharedString":i=s[parseInt(e.value,10)];break;case"boolean":i=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":i=e.value}return i&&t[e.xc]&&(i=function(e,t,s){const o=e.display||t;e.relTarget||e.location||s.generateNotSupportedWarning(PT.BadlyFormattedHyperlink);const i=e.relTarget?e.relTarget:ht(na(e.location).sheetName);return rt(o,i)}(t[e.xc],i,o)),e.formula&&(i=e.formula.content),i}function dD(e,t,s){const o=e?.sheetProperties?.outlinePr,i=[];let n=0;for(let r=0;r<s;r++){const s=gD(e,t,r),a=s?.outlineLevel||0;if(a>n){const s=uD(e,t,r,("ROW"===t?o?.summaryBelow:o?.summaryRight)??!0);s&&i.push(s)}n=a}return i}function uD(e,t,s,o){const i=gD(e,t,s),n=i?.outlineLevel;if(!n||!n)return;let r=n,a=s,l=i;for(;l&&r>=n;)a++,l=gD(e,t,a),r=l?.outlineLevel||0;const c=s,h=a-1,d=gD(e,t,o?h+1:c-1);return{start:c-1,end:h-1,isFolded:d?.collapsed||!1}}function gD(e,t,s){return"COL"===t?e.cols.find((e=>e.min<=s&&s<=e.max)):e.rows.find((e=>e.index===s))}function pD(e,t){for(const s of t.sheets){const t=e.sheets.find((e=>e.name===s.sheetName));if(t){t.tables||(t.tables=[]);for(const e of s.tables)t.tables.push({range:e.ref,config:mD(e)});for(const e of s.pivotTables)t.tables.push({range:e.location.ref,config:fD(e)})}}!function(e,t){let s=null;for(const o of e){const i=t.find((e=>ua(e.sheetName,o.name))).tables;if(i&&0!==i.length){s||(s=vD(e));for(const t of i)for(const i in s){const n=e.find((e=>e.id===i));for(const e in s[i]){for(let r=s[i][e].length-3;r>=0;r-=2){const a=s[i][e][r];if(!a.endsWith(t.name))continue;const l=s[i][e][r+1],c=bD(o.id===n.id?"":o.name+"!",l,t,e);s[i][e][r+2]=a.slice(0,a.indexOf(t.name))+c+s[i][e][r+2],s[i][e].splice(r,2)}}}}}if(!s)return;for(const t in s){const o=e.find((e=>e.id===t));for(const e in s[t]){const i=s[t][e];if(1===i.length){o.cells[e]=i[0];continue}let n="";for(let e=0;e<i.length;e+=2)n+=i[e]+"["+i[e+1]+"]";n+=i[i.length-1],o.cells[e]=n}}}(e.sheets,t.sheets)}function mD(e){const t=e.style?.name||"";return{hasFilters:void 0!==e.autoFilter,numberOfHeaders:e.headerRowCount,totalRow:e.totalsRowCount>0,firstColumn:e.style?.showFirstColumn||!1,lastColumn:e.style?.showLastColumn||!1,bandedRows:e.style?.showRowStripes||!1,bandedColumns:e.style?.showColumnStripes||!1,styleId:mT[t]?t:Qx.styleId}}function fD(e){return{hasFilters:!1,numberOfHeaders:e.location.firstDataRow,totalRow:e.rowGrandTotals,firstColumn:!0,lastColumn:e.style?.showLastColumn||!1,bandedRows:e.style?.showRowStripes||!1,bandedColumns:e.style?.showColStripes||!1,styleId:Qx.styleId}}function vD(e){const t={};for(const s of e)for(const e in s.cells){const o=s.cells[e];if(!o||!o.startsWith("="))continue;const i=o.indexOf("[");if(-1===i)continue;const n=[];let r=o.slice(0,i),a="",l=1,c=0,h=i;for(let e=i+1;e<o.length;e++)"["!==o[e]?"]"===o[e]&&(l--,0===l&&(a=o.slice(h+1,e),n.push(r),n.push(a),c=e+1)):(0===l&&(r=o.slice(c,e),h=e),l++);n.length&&(t[s.id]||(t[s.id]={}),n.push(o.slice(c)),t[s.id][e]=[...n])}return t}function bD(e,t,s,o){const i=t.split(",").map((e=>e.trim())),n=ms(s.ref),r=[],a=[],l=[];for(const e of i)if(SD(e).startsWith("#")){const t=SD(e);switch(l.push(t),t){case"#All":a.push(n.top,n.bottom);break;case"#Data":const e=s.headerRowCount?n.top+s.headerRowCount:n.top,t=s.totalsRowCount?n.bottom-s.totalsRowCount:n.bottom;a.push(e,t);break;case"#This Row":a.push(rs(o).row);break;case"#Headers":if(!s.headerRowCount)return Mi.InvalidReference;a.push(n.top);break;case"#Totals":if(!s.totalsRowCount)return Mi.InvalidReference;a.push(n.bottom)}}else{const t=e.split(":").map((e=>e.trim())).map(SD);if(r.length)return Mi.InvalidReference;const o=s.cols.findIndex((e=>e.name===t[0]));if(-1===o)return Mi.InvalidReference;if(r.push(o+n.left),t[1]){const e=s.cols.findIndex((e=>e.name===t[1]));if(-1===e)return Mi.InvalidReference;r.push(e+n.left)}}if(!function(e){if(e.length<2)return!0;if(e.length>2)return!1;if(e.includes("#Data")&&e.includes("#Totals"))return!0;if(e.includes("#Headers")&&e.includes("#Data"))return!0;return!1}(l))return Mi.InvalidReference;if(0===a.length){const e=s.headerRowCount?n.top+s.headerRowCount:n.top,t=s.totalsRowCount?n.bottom-s.totalsRowCount:n.bottom;a.push(e,t)}0===r.length&&r.push(n.left,n.right);return e+Ss({top:Math.min(...a),left:Math.min(...r),bottom:Math.max(...a),right:Math.max(...r)})}function SD(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,e.length-1):e}class CD{value;constructor(e){this.value=e}asString(){return dA(String(this.value))}asBool(){return"true"===this.value||"false"!==this.value&&Boolean(Number(this.value))}asNum(){return Number(this.value)}}class yD{rootFile;xlsxFileStructure;warningManager;relationships;currentFile=void 0;constructor(e,t,s){this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=s,this.relationships={},e.rels&&this.extractRelationships(e.rels).map((e=>{this.relationships[e.id]=e}))}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:"Relationship"},(e=>({id:this.extractAttr(e,"Id",{required:!0}).asString(),target:this.extractAttr(e,"Target",{required:!0}).asString(),type:this.extractAttr(e,"Type",{required:!0}).asString()})))}getListOfXMLFiles(){return Object.entries(this.xlsxFileStructure).filter((([e])=>"images"!==e)).map((([e,t])=>t)).flat().filter(ut)}mapOnElements(e,t){const s=[],o=this.currentFile;let i;if(e.children){const t=this.querySelector(e.parent,e.query)?.children;i=t||[]}else i=this.querySelectorAll(e.parent,e.query);if(i)for(const e of i)try{s.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=o,s}catchErrorOnElement(e,t){const s=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([s,e.message].join("\n"))}extractAttr(e,t,s){const o=e.attributes[t];o||this.handleMissingValue(e,`attribute "${t}"`,s);const i=o?.value?o.value:s?.default;return void 0===i?void 0:new CD(i)}extractTextContent(e,t){if(void 0!==t?.default&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const s="preserve"===e?.attributes["xml:space"]?.value;let o=e?.textContent;return e&&null!==o||this.handleMissingValue(e,"text content",t),o&&(o=s?o:o.trim()),o?dA(o):t?.default}extractChildAttr(e,t,s,o){let i;i="number"==typeof t?e.children[t]:this.querySelector(e,t),i||this.handleMissingValue(e,"number"==typeof t?`child at index ${t}`:`child <${t}>`,o);const n=i?this.extractAttr(i,s,o)?.asString():o?.default;return void 0!==n?new CD(n):void 0}extractChildTextContent(e,t,s){if(void 0!==s?.default&&"string"!=typeof s.default)throw new Error("extractTextContent default value should be a string");const o=this.querySelector(e,t);return o||this.handleMissingValue(e,`child <${t}>`,s),o?this.extractTextContent(o,s):s?.default}handleMissingValue(e,t,s){if(s?.required){if(void 0===s?.default)throw new Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`);this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${s.default}`)}}extractColor(e,t,s){if(!e)return s?{rgb:s}:void 0;const o=this.extractAttr(e,"theme")?.asString();let i;if(void 0!==o){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");i=this.getThemeColor(o,t.clrScheme)}else i=this.extractAttr(e,"rgb")?.asString(),i="FF000000"===i?void 0:i;return{rgb:i||s,auto:this.extractAttr(e,"auto")?.asBool(),indexed:this.extractAttr(e,"indexed")?.asNum(),tint:this.extractAttr(e,"tint")?.asNum()}}getTargetXmlFile(e){if(!e)throw new Error("Undefined target file");const t=this.processRelationshipTargetName(e.target),s=this.getListOfXMLFiles().find((e=>e.file.fileName.endsWith(t)));if(!s||!s.file)throw new Error("Cannot find target file");return s}getTargetImageFile(e){if(!e)throw new Error("Undefined target file");const t=this.processRelationshipTargetName(e.target),s=this.xlsxFileStructure.images.find((e=>e.fileName.endsWith(t)));if(!s)throw new Error("Cannot find target file");return s}querySelector(e,t){const s=jE(t);return e.querySelector(s)}querySelectorAll(e,t){const s=jE(t);return e.querySelectorAll(s)}getThemeColor(e,t){switch(e){case"0":return"FFFFFF";case"1":return"000000";case"2":return t[3].value;case"3":return t[2].value;default:return t[e].value}}processRelationshipTargetName(e){return e.replace(/\.+\//,"")}}class ID extends yD{getTheme(){return{clrScheme:this.mapOnElements({query:"a:clrScheme",parent:this.rootFile.file.xml,children:!0},(e=>({name:e.tagName,value:this.extractChildAttr(e,0,"val",{required:!0,default:Eh}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:Eh}).asString()})))}}getSharedStrings(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"si"},(e=>this.mapOnElements({parent:e,query:"t"},(e=>this.extractTextContent(e)||"")).join("")))}}class wD extends yD{theme;constructor(e,t,s,o){super(e,t,s),this.theme=o}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},(e=>({sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),pivot:this.extractAttr(e,"pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)})));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:"extLst x14:conditionalFormatting"},(e=>({sqref:this.extractChildTextContent(e,"xm:sqref",{required:!0}).split(" "),pivot:this.extractAttr(e,"xm:pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)})))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:"cfRule, x14:cfRule"},(e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),priority:this.extractAttr(e,"priority",{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:this.extractAttr(e,"dxfId")?.asNum(),stopIfTrue:this.extractAttr(e,"stopIfTrue")?.asBool(),aboveAverage:this.extractAttr(e,"aboveAverage")?.asBool(),percent:this.extractAttr(e,"percent")?.asBool(),bottom:this.extractAttr(e,"bottom")?.asBool(),operator:this.extractAttr(e,"operator")?.asString(),text:this.extractAttr(e,"text")?.asString(),timePeriod:this.extractAttr(e,"timePeriod")?.asString(),rank:this.extractAttr(e,"rank")?.asNum(),stdDev:this.extractAttr(e,"stdDev")?.asNum(),equalAverage:this.extractAttr(e,"equalAverage")?.asBool(),dataBar:this.extractCfDataBar(e,t)})))}extractCfFormula(e){return this.mapOnElements({parent:e,query:"formula"},(e=>this.extractTextContent(e,{required:!0})))}extractCfColorScale(e,t){const s=this.querySelector(e,"colorScale");if(s)return{colors:this.mapOnElements({parent:s,query:"color"},(e=>this.extractColor(e,t,"ffffff"))),cfvos:this.extractCFVos(s)}}extractCfDataBar(e,t){const s=this.querySelector(e,"dataBar");if(s)return{color:this.extractColor(s.querySelector("color"),t,"EFF7FF"),cfvos:this.extractCFVos(s)}}extractCfIconSet(e){const t=this.querySelector(e,"iconSet, x14:iconSet");if(t)return{iconSet:this.extractAttr(t,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(t,"showValue",{default:!0}).asBool(),percent:this.extractAttr(t,"percent",{default:!0}).asBool(),reverse:this.extractAttr(t,"reverse")?.asBool(),custom:this.extractAttr(t,"custom")?.asBool(),cfvos:this.extractCFVos(t),cfIcons:this.extractCfIcons(t)}}extractCfIcons(e){const t=this.mapOnElements({parent:e,query:"cfIcon, x14:cfIcon"},(e=>({iconSet:this.extractAttr(e,"iconSet",{required:!0}).asString(),iconId:this.extractAttr(e,"iconId",{required:!0}).asNum()})));return 0===t.length?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:"cfvo, x14:cfvo"},(e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),gte:this.extractAttr(e,"gte",{default:!0})?.asBool(),value:e.attributes.val?this.extractAttr(e,"val")?.asString():this.extractChildTextContent(e,"f, xm:f")})))}}class ED extends yD{theme;constructor(e,t,s,o){super(e,t,s),this.theme=o}extractDataValidations(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > dataValidations > dataValidation"},(e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),operator:this.extractAttr(e,"operator",{default:"between"})?.asString(),sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),errorStyle:this.extractAttr(e,"errorStyle")?.asString(),formula1:this.extractDataValidationFormula(e,1)[0],formula2:this.extractDataValidationFormula(e,2)[0],showErrorMessage:this.extractAttr(e,"showErrorMessage")?.asBool(),errorTitle:this.extractAttr(e,"errorTitle")?.asString(),error:this.extractAttr(e,"error")?.asString(),showInputMessage:this.extractAttr(e,"showInputMessage")?.asBool(),promptTitle:this.extractAttr(e,"promptTitle")?.asString(),prompt:this.extractAttr(e,"prompt")?.asString(),allowBlank:this.extractAttr(e,"allowBlank")?.asBool()})))}extractDataValidationFormula(e,t){return this.mapOnElements({parent:e,query:`formula${t}`},(e=>this.extractTextContent(e,{required:!0})))}}class RD extends yD{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!KT[t])throw new Error(`Unsupported chart type ${t}`);if("combo"===KT[t])return this.extractComboChart(e);const s=this.mapOnElements({parent:e,query:"c:chart > c:title a:t"},(e=>e.textContent||"")).join(""),o=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString(),i=this.extractChildAttr(e,"c:barDir","val",{default:"col"}).asString(),n=this.extractChildAttr(e,"c:holeSize","val",{default:"0"}).asNum();return{title:{text:s},type:KT[t],dataSets:this.extractChartDatasets(this.querySelectorAll(e,`c:${t}`),t),labelRange:this.extractLabelRange(t,e),backgroundColor:this.extractChildAttr(e,"c:chartSpace > c:spPr a:srgbClr","val",{default:"ffffff"}).asString(),legendPosition:XT[this.extractChildAttr(e,"c:legendPos","val",{default:"none"}).asString()],stacked:"stacked"===o,fontColor:"000000",horizontal:"bar"===i,isDoughnut:n>0,pieHolePercentage:n}}))[0]}extractLabelRange(e,t){return"scatterChart"===e?this.extractChildTextContent(t,"c:ser c:strRef c:f")||this.extractChildTextContent(t,"c:ser c:numRef c:f"):this.extractChildTextContent(t,"c:ser c:cat c:f")}extractComboChart(e){const t=this.mapOnElements({parent:e,query:"c:title a:t"},(e=>e.textContent||"")).join(""),s=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:{text:t},type:"combo",dataSets:[...this.extractChartDatasets(this.querySelectorAll(e,"c:barChart"),"comboChart"),...this.extractChartDatasets(this.querySelectorAll(e,"c:lineChart"),"comboChart")],labelRange:this.extractChildTextContent(e,"c:ser c:cat c:f"),backgroundColor:this.extractChildAttr(e,"c:chartSpace > c:spPr a:srgbClr","val",{default:"ffffff"}).asString(),legendPosition:XT[this.extractChildAttr(e,"c:legendPos","val",{default:"none"}).asString()],stacked:"stacked"===s,fontColor:"000000"}}extractChartDatasets(e,t){return Array.from(e).map((e=>"scatterChart"===t?this.extractScatterChartDatasets(e):this.mapOnElements({parent:e,query:"c:ser"},(e=>{let t={};const s=this.extractChildTextContent(e,"c:tx c:f");if(s)t={reference:s};else{const s=this.extractChildTextContent(e,"c:tx c:v");s&&(t={text:s})}const o=this.querySelectorAll(e,"c:spPr a:solidFill"),i=o.length?this.querySelector(o[0],"a:srgbClr"):void 0,n=i?i.getAttribute("val"):void 0;return{label:t,range:this.extractChildTextContent(e,"c:val c:f",{required:!0}),backgroundColor:n&&ao(n)?`${ro(n)}`:void 0,trend:this.extractChartTrendline(e)}})))).flat()}extractChartTrendline(e){const t=this.querySelector(e,"c:trendline");if(!t)return;const s=this.extractChildAttr(t,"c:trendlineType","val"),o=this.extractChildAttr(t,"a:solidFill a:srgbClr","val");return{type:s?s.asString():void 0,order:this.extractChildAttr(t,"c:order","val")?.asNum(),window:this.extractChildAttr(t,"c:period","val")?.asNum(),color:o&&ao(o.asString())?`${ro(o.asString())}`:void 0}}extractScatterChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},(e=>{let t={};const s=this.querySelectorAll(e,"c:spPr a:solidFill a:srgbClr"),o=s.length?s[0].getAttribute("val"):void 0,i=this.extractChildTextContent(e,"c:tx c:f");if(i)t={reference:i};else{const s=this.extractChildTextContent(e,"c:tx c:v");s&&(t={text:s})}return{label:t,range:this.extractChildTextContent(e,"c:yVal c:f",{required:!0}),trend:this.extractChartTrendline(e),backgroundColor:o&&ao(o)?`${ro(o)}`:void 0}}))}getChartType(e){const t=this.querySelector(e,"c:plotArea");if(!t)throw new Error("Missing plot area in the chart definition.");let s;for(const e of t.children){const t=ZE(e.tagName);VE.some((e=>e===t))&&(s?s!==t&&(s="comboChart"):s=t)}if(s)return s;throw new Error("Unknown chart type")}}const xD="oneCellAnchor",TD="twoCellAnchor";class AD extends yD{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{const t=ZE(e.tagName),s=this.extractFigureAnchorsByType(e,t),o=this.querySelector(e,"c:chart"),i=this.querySelector(e,"a:blip");if(!o&&!i)throw new Error("Only chart and image figures are currently supported.");return{anchors:s,data:o?this.extractChart(o):this.extractImage(e),figureSize:t===xD?this.extractFigureSizeFromSizeTag(e,"xdr:ext"):void 0}}))}extractFigureAnchorsByType(e,t){switch(t){case xD:return[this.extractFigureAnchor("xdr:from",e)];case TD:return[this.extractFigureAnchor("xdr:from",e),this.extractFigureAnchor("xdr:to",e)];default:throw new Error(`${t} is not supported for xlsx drawings. `)}}extractFigureSizeFromSizeTag(e,t){const s=this.querySelector(e,t);if(!s)throw new Error(`Missing size element '${t}'`);return{cx:this.extractAttr(s,"cx",{required:!0}).asNum(),cy:this.extractAttr(s,"cy",{required:!0}).asNum()}}extractFigureAnchor(e,t){const s=this.querySelector(t,e);if(!s)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(s,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(s,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(s,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(s,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),s=this.getTargetXmlFile(this.relationships[t]),o=new RD(s,this.xlsxFileStructure,this.warningManager).extractChart();if(!o)throw new Error("Unable to extract chart definition");return o}extractImage(e){const t=this.querySelector(e,"a:blip"),s=this.extractAttr(t,"r:embed",{required:!0}).asString(),o=this.getTargetImageFile(this.relationships[s]);if(!o)throw new Error("Unable to extract image");const i=o.fileName.split(".").at(-1),n=ZE(e.tagName),r=n===TD?this.querySelector(e,"a:xfrm"):e,a=n===TD?"a:ext":"xdr:ext",l=this.extractFigureSizeFromSizeTag(r,a);return{imageSrc:o.imageSrc,mimetype:i?iA[i]:void 0,size:l}}}class DD extends yD{getPivotTable(){return this.mapOnElements({query:":root",parent:this.rootFile.file.xml},(e=>({name:this.extractAttr(e,"name",{required:!0}).asString(),rowGrandTotals:this.extractAttr(e,"rowGrandTotals",{default:!0}).asBool(),location:this.extractPivotLocation(e),style:this.extractPivotStyleInfo(e)})))[0]}extractPivotLocation(e){return this.mapOnElements({query:"location",parent:e},(e=>({ref:this.extractAttr(e,"ref",{required:!0}).asString(),firstHeaderRow:this.extractAttr(e,"firstHeaderRow",{required:!0}).asNum(),firstDataRow:this.extractAttr(e,"firstDataRow",{required:!0}).asNum(),firstDataCol:this.extractAttr(e,"firstDataCol",{required:!0}).asNum()})))[0]}extractPivotStyleInfo(e){return this.mapOnElements({query:"pivotTableStyleInfo",parent:e},(e=>({name:this.extractAttr(e,"name",{required:!0}).asString(),showRowHeaders:this.extractAttr(e,"showRowHeaders",{required:!0}).asBool(),showColHeaders:this.extractAttr(e,"showColHeaders",{required:!0}).asBool(),showRowStripes:this.extractAttr(e,"showRowStripes",{required:!0}).asBool(),showColStripes:this.extractAttr(e,"showColStripes",{required:!0}).asBool(),showLastColumn:this.extractAttr(e,"showLastColumn")?.asBool()})))[0]}}class _D extends yD{getTable(){return this.mapOnElements({query:"table",parent:this.rootFile.file.xml},(e=>({displayName:this.extractAttr(e,"displayName",{required:!0}).asString(),name:this.extractAttr(e,"name")?.asString(),id:this.extractAttr(e,"id",{required:!0}).asString(),ref:this.extractAttr(e,"ref",{required:!0}).asString(),headerRowCount:this.extractAttr(e,"headerRowCount",{default:1}).asNum(),totalsRowCount:this.extractAttr(e,"totalsRowCount",{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)})))[0]}extractTableCols(e){return this.mapOnElements({query:"tableColumn",parent:e},(e=>({id:this.extractAttr(e,"id",{required:!0}).asString(),name:this.extractAttr(e,"name",{required:!0}).asString(),colFormula:this.extractChildTextContent(e,"calculatedColumnFormula")})))}extractTableStyleInfo(e){return this.mapOnElements({query:"tableStyleInfo",parent:e},(e=>({name:this.extractAttr(e,"name")?.asString(),showFirstColumn:this.extractAttr(e,"showFirstColumn")?.asBool(),showLastColumn:this.extractAttr(e,"showLastColumn")?.asBool(),showRowStripes:this.extractAttr(e,"showRowStripes")?.asBool(),showColumnStripes:this.extractAttr(e,"showColumnStripes")?.asBool()})))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:"autoFilter",parent:e},(e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,"ref",{required:!0}).asString()})))[0]}extractFilterColumns(e){return this.mapOnElements({query:"tableColumn",parent:e},(t=>({colId:this.extractAttr(e,"colId",{required:!0}).asNum(),hiddenButton:this.extractAttr(e,"hiddenButton",{default:!1}).asBool(),filters:this.extractSimpleFilter(t)})))}extractSimpleFilter(e){return this.mapOnElements({query:"filter",parent:e},(e=>({val:this.extractAttr(e,"val",{required:!0}).asString()})))}}class FD extends yD{theme;constructor(e,t,s,o){super(e,t,s),this.theme=o}getSheet(){return this.mapOnElements({query:"worksheet",parent:this.rootFile.file.xml},(e=>{const t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),sheetProperties:this.extractSheetProperties(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),dataValidations:this.extractDataValidations(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:this.extractTables(e),pivotTables:this.extractPivotTables(),isVisible:"visible"===t.state}}))[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:"sheetView"},(e=>{const t=this.querySelector(e,"pane");return{tabSelected:this.extractAttr(e,"tabSelected",{default:!1}).asBool(),showFormulas:this.extractAttr(e,"showFormulas",{default:!1}).asBool(),showGridLines:this.extractAttr(e,"showGridLines",{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,"showRowColHeaders",{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,"xSplit",{default:0}).asNum():0,ySplit:t?this.extractAttr(t,"ySplit",{default:0}).asNum():0}}}))}extractSheetName(){const e=cA(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id;for(const e of this.querySelectorAll(this.xlsxFileStructure.workbook.file.xml,"sheet"))if(e.attributes["r:id"].value===t)return e.attributes.name.value;throw new Error("Missing sheet name")}getSheetWorkbookInfo(){const e=cA(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id,s=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:"sheet"},(e=>({relationshipId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetId:this.extractAttr(e,"sheetId",{required:!0}).asString(),sheetName:this.extractAttr(e,"name",{required:!0}).asString(),state:this.extractAttr(e,"state",{default:"visible"}).asString()}))).find((e=>e.relationshipId===t));if(!s)throw new Error("Cannot find corresponding workbook sheet");return s}extractConditionalFormats(){return new wD(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractDataValidations(){return new ED(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractDataValidations()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},(e=>{const t=this.extractAttr(e,"r:id",{required:!0})?.asString(),s=this.getTargetXmlFile(this.relationships[t]);return new AD(s,this.xlsxFileStructure,this.warningManager).extractFigures()}))[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},(e=>{const t=this.extractAttr(e,"r:id",{required:!0})?.asString(),s=this.getTargetXmlFile(this.relationships[t]);return new _D(s,this.xlsxFileStructure,this.warningManager).getTable()}))}extractPivotTables(){try{return Object.values(this.relationships).filter((e=>e.type.endsWith("pivotTable"))).map((e=>{const t=this.getTargetXmlFile(e);return new DD(t,this.xlsxFileStructure,this.warningManager).getPivotTable()}))}catch(e){return this.catchErrorOnElement(e),[]}}extractMerges(e){return this.mapOnElements({parent:e,query:"mergeCell"},(e=>this.extractAttr(e,"ref",{required:!0}).asString()))}extractSheetFormat(e){const t=this.querySelector(e,"sheetFormatPr");if(t)return{defaultColWidth:this.extractAttr(t,"defaultColWidth",{default:Nh.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:Lh.toString()}).asNum()}}extractSheetProperties(e){const t=this.querySelector(e,"sheetPr");if(t)return{outlinePr:this.extractSheetOutlineProperties(t),tabColor:this.extractColor(this.querySelector(t,"tabColor"),this.theme)}}extractSheetOutlineProperties(e){const t=this.querySelector(e,"outlinePr");if(t)return{summaryBelow:this.extractAttr(t,"summaryBelow",{default:!0}).asBool(),summaryRight:this.extractAttr(t,"summaryRight",{default:!0}).asBool()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},(e=>({width:this.extractAttr(e,"width")?.asNum(),customWidth:this.extractAttr(e,"customWidth")?.asBool(),bestFit:this.extractAttr(e,"bestFit")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),min:this.extractAttr(e,"min",{required:!0})?.asNum(),max:this.extractAttr(e,"max",{required:!0})?.asNum(),styleIndex:this.extractAttr(e,"style")?.asNum(),outlineLevel:this.extractAttr(e,"outlineLevel")?.asNum(),collapsed:this.extractAttr(e,"collapsed")?.asBool()})))}extractRows(e){const t=new Set;return this.mapOnElements({parent:e,query:"sheetData row"},(e=>({index:this.extractAttr(e,"r",{required:!0})?.asNum(),cells:this.extractCells(e,t),height:this.extractAttr(e,"ht")?.asNum(),customHeight:this.extractAttr(e,"customHeight")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),styleIndex:this.extractAttr(e,"s")?.asNum(),outlineLevel:this.extractAttr(e,"outlineLevel")?.asNum(),collapsed:this.extractAttr(e,"collapsed")?.asBool()})))}extractCells(e,t){return this.mapOnElements({parent:e,query:"c"},(e=>{const s=this.extractAttr(e,"r",{required:!0})?.asString(),o=this.extractCellFormula(e);if(o?.ref&&void 0===o.sharedIndex){const e=ms(o.ref);for(const{col:o,row:i}of Ms(e)){const e=as(o,i);e!==s&&t.add(e)}}const i=t.has(s);return{xc:s,styleIndex:this.extractAttr(e,"s")?.asNum(),type:zT[this.extractAttr(e,"t",{default:"n"})?.asString()],value:i?void 0:this.extractChildTextContent(e,"v")??void 0,formula:i?void 0:o}}))}extractCellFormula(e){const t=this.querySelector(e,"f");if(!t)return;const s=this.extractTextContent(t),o=this.extractAttr(t,"si")?.asNum(),i=this.extractAttr(t,"ref")?.asString();return void 0!==s&&""!==s.trim()||void 0!==o?{content:s,sharedIndex:o,ref:i}:void 0}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},(e=>{const t=this.extractAttr(e,"r:id")?.asString();return{xc:this.extractAttr(e,"ref",{required:!0})?.asString(),location:this.extractAttr(e,"location")?.asString(),display:this.extractAttr(e,"display")?.asString(),relTarget:t?this.relationships[t].target:void 0}}))}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),s={};for(const e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),o=this.extractTextContent(e,{required:!0});s[t]=o}const o=[];for(let e=0;e<Object.keys(s).length;e++)s[e]?o.push(s[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),o.push(""));return o}}class OD extends yD{theme;constructor(e,t,s){super(e.styles,e,t),this.theme=s}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},(e=>this.extractNumFormats(e)))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},(e=>this.extractFont(e)))}extractFont(e){const t=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),s=this.extractChildAttr(e,"sz","val",{default:fe.toString()}).asNum(),o=this.extractColor(this.querySelector(e,"color"),this.theme),i=this.querySelector(e,"i")||void 0,n=i&&"0"!==i.attributes.val?.value,r=this.querySelector(e,"b")||void 0,a=r&&"0"!==r.attributes.val?.value,l=this.querySelector(e,"strike")||void 0,c=l&&"0"!==l.attributes.val?.value,h=this.querySelector(e,"u")||void 0;return{name:t,size:s,color:o,italic:n,bold:a,underline:h&&"none"!==h.attributes.val?.value,strike:c}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},(e=>this.extractFill(e)))}extractFill(e){const t=e.children[0];return"patternFill"===t.tagName?{patternType:t.attributes.patternType?.value,bgColor:this.extractColor(this.querySelector(t,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(t,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(t,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},(e=>this.extractBorder(e)))}extractBorder(e){const t={left:this.extractSingleBorder(e,"left",this.theme),right:this.extractSingleBorder(e,"right",this.theme),top:this.extractSingleBorder(e,"top",this.theme),bottom:this.extractSingleBorder(e,"bottom",this.theme),diagonal:this.extractSingleBorder(e,"diagonal",this.theme)};return t.diagonal&&(t.diagonalUp=this.extractAttr(e,"diagonalUp")?.asBool(),t.diagonalDown=this.extractAttr(e,"diagonalDown")?.asBool()),t}extractSingleBorder(e,t,s){const o=this.querySelector(e,t);if(o&&o.attributes.style)return{style:this.extractAttr(o,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(o.children[0],s,"000000")}}extractAlignment(e){return{horizontal:this.extractAttr(e,"horizontal",{default:"general"}).asString(),vertical:this.extractAttr(e,"vertical",{default:"bottom"}).asString(),textRotation:this.extractAttr(e,"textRotation")?.asNum(),wrapText:this.extractAttr(e,"wrapText")?.asBool(),indent:this.extractAttr(e,"indent")?.asNum(),relativeIndent:this.extractAttr(e,"relativeIndent")?.asNum(),justifyLastLine:this.extractAttr(e,"justifyLastLine")?.asBool(),shrinkToFit:this.extractAttr(e,"shrinkToFit")?.asBool(),readingOrder:this.extractAttr(e,"readingOrder")?.asNum()}}getDxfs(){return this.mapOnElements({query:"dxf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"font"),s=this.querySelector(e,"fill"),o=this.querySelector(e,"border"),i=this.querySelector(e,"numFmt"),n=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:s?this.extractFill(s):void 0,numFmt:i?this.extractNumFormats(i):void 0,alignment:n?this.extractAlignment(n):void 0,border:o?this.extractBorder(o):void 0}}))}getStyles(){return this.mapOnElements({query:"cellXfs xf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"alignment");return{fontId:this.extractAttr(e,"fontId",{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,"fillId",{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,"borderId",{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,"numFmtId",{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}}))}}class PD extends yD{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"externalBook"},(e=>({rId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:"sheetName"},(e=>this.extractAttr(e,"val",{required:!0}).asString())),datasets:this.extractExternalSheetData(e)})))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:"sheetData"},(e=>{const t=this.mapOnElements({parent:e,query:"cell"},(e=>({xc:this.extractAttr(e,"r",{required:!0}).asString(),value:this.extractChildTextContent(e,"v",{required:!0})}))),s={};for(const e of t)s[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:s}}))}}function MD(e,t){const s=function(e,t){const s=t[Gh],o=s.querySelectorAll(`Override[ContentType="${e}"]`),i=[];for(const e of o){const t=e?.attributes.PartName.value;i.push(t.substring(1))}return i}(e,t);return function(e,t){const s=[];for(const o of e){const e=ND(o,t);s.push({file:{fileName:o,xml:t[o]},rels:e?{fileName:e,xml:t[e]}:void 0})}return s}(s,t)}function ND(e,t){if(e===Gh)return"_rels/.rels";let s="";const o=e.split("/");for(let e=0;e<o.length-1;e++)s+=o[e]+"/";return s+="_rels/",s+=o[o.length-1]+".rels",t[s]||(s=void 0),s}class LD{warningManager;xmls;images;constructor(e){this.warningManager=new MT,this.xmls={},this.images=[];for(const t of Object.keys(e))if(t.endsWith(".xml")||t.endsWith(".rels")){const s=e[t].replaceAll(/(<\/?)([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,"$1NAMESPACE$2NAMESPACE$3");this.xmls[t]=BE(new kE(s))}else t.includes("media/image")&&this.images.push({fileName:t,imageSrc:e[t].imageSrc})}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new ID(e.theme,e,this.warningManager).getTheme():void 0,s=e.sharedStrings?new ID(e.sharedStrings,e,this.warningManager).getSharedStrings():[],o=e.sheets.sort(((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0}))).map((s=>new FD(s,e,this.warningManager,t).getSheet())),i=e.externalLinks.map((t=>new PD(t,e,this.warningManager).getExternalBook())),n=new OD(e,this.warningManager,t);return{fonts:n.getFonts(),fills:n.getFills(),borders:n.getBorders(),dxfs:n.getDxfs(),numFmts:n.getNumFormats(),styles:n.getStyles(),sheets:o,sharedStrings:s,externalBooks:i,chartIds:[],imageIds:[]}}buildXlsxFileStructure(){const e={sheets:MD(Dh.sheet,this.xmls),workbook:MD(Dh.workbook,this.xmls)[0]||MD(Dh.macroEnabledWorkbook,this.xmls)[0]||MD(Dh.templateWorkbook,this.xmls)[0]||MD(Dh.macroEnabledTemplateWorkbook,this.xmls)[0]||MD(Dh.excelAddInWorkbook,this.xmls)[0],styles:MD(Dh.styles,this.xmls)[0],sharedStrings:MD(Dh.sharedStrings,this.xmls)[0],theme:MD(Dh.themes,this.xmls)[0],charts:MD(Dh.chart,this.xmls),figures:MD(Dh.drawing,this.xmls),tables:MD(Dh.table,this.xmls),pivots:MD(Dh.pivot,this.xmls),externalLinks:MD(Dh.externalLink,this.xmls),images:this.images};if(!e.workbook.rels)throw Error(Go("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:"18.4.2",sheets:rD(e,this.warningManager),styles:vA(e,this.warningManager),formats:SA(e,this.warningManager),borders:mA(e,this.warningManager),revisionId:Ce};return pD(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=wt(e.styles[t])})),t}}function kD(e){const t=av(e),s=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&jr.test(e.value)){const t=e.value.trim();return s.includes(t)||s.push(t),`${Oe}${s.indexOf(t)}${Oe}`}return e.value}))),dependencies:s}}const VD={am_ET:7,ar_001:6,ar_SY:6,az_AZ:1,eu_ES:1,be_BY:1,bn_IN:1,bs_BA:1,bg_BG:1,ca_ES:1,zh_CN:7,zh_HK:7,zh_TW:7,hr_HR:1,cs_CZ:1,da_DK:1,nl_BE:1,nl_NL:1,en_AU:7,en_CA:7,en_GB:1,en_IN:7,en_NZ:7,et_EE:1,fi_FI:1,fr_BE:1,fr_CA:7,fr_CH:1,fr_FR:1,gl_ES:1,ka_GE:1,de_DE:1,de_CH:1,el_GR:1,gu_IN:7,he_IL:7,hi_IN:7,hu_HU:1,id_ID:7,it_IT:1,ja_JP:7,kab_DZ:6,km_KH:7,ko_KP:1,ko_KR:7,lo_LA:7,lv_LV:1,lt_LT:1,lb_LU:1,mk_MK:1,ml_IN:1,mn_MN:7,ms_MY:1,nb_NO:1,fa_IR:6,pl_PL:1,pt_AO:1,pt_BR:7,pt_PT:1,ro_RO:1,ru_RU:1,sr_RS:7,"sr@latin":7,sk_SK:1,sl_SI:1,es_AR:7,es_BO:1,es_CL:1,es_CO:7,es_CR:1,es_DO:1,es_EC:1,es_GT:7,es_MX:7,es_PA:7,es_PE:7,es_PY:7,es_UY:1,es_VE:7,sw:1,sv_SE:1,th_TH:7,tl_PH:1,tr_TR:1,uk_UA:1,vi_VN:1,sq_AL:1,te_IN:7,en_US:7,my_MM:7,es_ES:1,es_419:1},UD=new n;function HD(e){for(const t of e.sheets||[]){const e=[];for(const s of t.filterTables||[]){const t=ms(s.range),o=e.findIndex((e=>As(e,t)));-1!==o?e[o]=t:e.push(t)}t.filterTables=e.map((e=>({range:Ss(e)})))}return e}function zD(){return BD().at(-1)}function BD(){return UD.getKeys().sort(qD)}UD.add("0.1",{migrate:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)}).add("0.2",{migrate(e){if(e.sheets&&e.sheets.length)for(const t of e.sheets)t.id=t.id||t.name;return e}}).add("0.3",{migrate(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find((t=>t.name===e.activeSheet));e.activeSheet=t.id}return e}}).add("0.4",{migrate(e){for(const t of e.sheets||[])t.figures=t.figures||[];return e}}).add("0.5",{migrate(e){for(const t of e.sheets||[])for(const e in t.cells||[]){const s=t.cells[e];s.content&&s.content.startsWith("=")&&(s.formula=kD(s.content))}return e}}).add("0.6",{migrate(e){for(const t of e.sheets||[])for(const e in t.figures||[]){const{dataSets:s,...o}=t.figures[e].data,i=[];for(const e of s)if(e.labelCell){const t=ms(e.dataRange),s=e.labelCell+":"+as(t.right,t.bottom);i.push(s)}else i.push(e.dataRange);o.dataSetsHaveTitle=Boolean(s[0].labelCell),o.dataSets=i,t.figures[e].data=o}return e}}).add("0.7",{migrate(e){const t=[];for(const s of e.sheets||[]){if(!s.name)continue;const e=s.name,o=Bt(Xe(e,"_"),t,{compute:(e,t)=>`${e}${t}`});s.name=o,t.push(o);const i=t=>{if(void 0===t)return t;let s=t.replace(e,o),i=t;for(;i!==s;)i=s,s=i.replace(e,o);return i};for(const e in s.cells){const t=s.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(i))}for(const e of s.figures||[])if("chart"===e.tag){const t=e.data.dataSets.map(i),s=i(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:s}}for(const e of s.conditionalFormats||[]){e.ranges=e.ranges.map(i);for(const t of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===e.rule[t]?.type&&(e.rule[t].value=i(e.rule[t].value))}}return e}}).add("0.8",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=M,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stacked=!1;return e}}).add("0.9",{migrate(e){for(const t of e.sheets||[])for(const e in t.cells||[]){const s=t.cells[e];if(s.formula){let{text:e,dependencies:t}=s.formula;for(const[s,o]of Object.entries(t)){const t=`\\${Oe}${s}\\${Oe}`;e=e.replace(new RegExp(t,"g"),o)}s.content=e,delete s.formula}}return e}}).add("0.10",{migrate(e){const t={};for(const s of e.sheets||[])for(const e in s.cells||[]){const o=s.cells[e];o.format&&(o.format=Gr(o.format,t))}return e.formats=t,e}}).add("15.4",{migrate(e){for(const t of e.sheets||[])t.isVisible=!0;return e}}).add("15.4.1",{migrate:e=>HD(e)}).add("16.3",{migrate(e){for(const t in e.borders){const s=e.borders[t];for(const e in s)Array.isArray(s[e])&&(s[e]={style:s[e][0],color:s[e][1]})}return e}}).add("16.4",{migrate:e=>(e.settings||(e.settings={}),e.settings.locale||(e.settings.locale=w),e)}).add("16.4.1",{migrate:e=>HD(e)}).add("17.2",{migrate(e){for(const t of e.sheets||[])t.tables=t.tables||t.filterTables||[],delete t.filterTables;return e}}).add("17.3",{migrate:e=>(e.pivots||(e.pivots={}),e.pivotNextId||(e.pivotNextId=Dc(e.pivots)+1),e)}).add("17.4",{migrate(e){for(const t of e.sheets||[])for(const e in t.figures||[]){const s=t.figures[e];"title"in s.data&&"string"==typeof s.data.title&&(s.data.title={text:s.data.title});const o=s.data.type;if(!["line","bar","pie","scatter","waterfall","combo"].includes(o))continue;const{dataSets:i,...n}=t.figures[e].data,r=i.map((e=>({dataRange:e})));n.dataSets=r,t.figures[e].data=n}return e}}).add("18.0",{migrate:e=>e}).add("18.0.1",{migrate(e){for(const t of Object.values(e.pivots||{}))t.measures=t.measures.map((e=>({id:e.name,fieldName:e.name,aggregator:e.aggregator}))),t.columns=t.columns.map((e=>({fieldName:e.name,order:e.order,granularity:e.granularity}))),t.rows=t.rows.map((e=>({fieldName:e.name,order:e.order,granularity:e.granularity})));return e}}).add("18.0.2",{migrate(e){const t=e.settings?.locale;if(t){const e=t.code;t.weekStart=VD[e]||1}return e}}).add("18.0.3",{migrate(e){for(const t of e.sheets||[]){t.styles={},t.formats={},t.borders={};for(const e in t.cells)t.styles[e]=t.cells[e].style,t.formats[e]=t.cells[e].format,t.borders[e]=t.cells[e].border,delete t.cells[e].style,delete t.cells[e].format,delete t.cells[e].border}return e}}).add("18.0.4",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[]){if("chart"!==e.tag||"gauge"!==e.data.type)continue;const t=e.data;t?.sectionRule?.lowerInflectionPoint&&(t.sectionRule.lowerInflectionPoint.operator="<="),t?.sectionRule?.upperInflectionPoint&&(t.sectionRule.upperInflectionPoint.operator="<=")}return e}}).add("18.1",{migrate(e){for(const t of e.sheets||[])for(const e of t.tables||[])e.config||(e.config={...Qx,hasFilters:!0});return e}}).add("18.1.1",{migrate(e){for(const t of e.sheets||[])for(const e in t.cells){const s=t.cells[e];s&&(t.cells[e]=s.content)}return e}}).add("18.2",{migrate:e=>e}).add("18.3",{migrate(e){if(!e.pivots)return e;for(const t of Object.values(e.pivots)){if(!t.sortedColumn)continue;t.measures.map((e=>e.id)).includes(t.sortedColumn.measure)||delete t.sortedColumn}return e}}).add("18.3.1",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[]){const t=e;e.offset={x:t.x||0,y:t.y||0},e.col=0,e.row=0,delete e.x,delete e.y}return e}}).add("18.4.1",{migrate(e){const t={textContains:"containsText",textNotContains:"notContainsText",textIs:"isEqualText",textIsEmail:"isEmail",textIsLink:"isLink"},s={BeginsWith:"beginsWithText",Between:"isBetween",ContainsText:"containsText",EndsWith:"endsWithText",Equal:"isEqual",GreaterThan:"isGreaterThan",GreaterThanOrEqual:"isGreaterOrEqualTo",IsEmpty:"isEmpty",IsNotEmpty:"isNotEmpty",LessThan:"isLessThan",LessThanOrEqual:"isLessOrEqualTo",NotBetween:"isNotBetween",NotContains:"notContainsText",NotEqual:"isNotEqual"};for(const t of e.sheets||[])for(const e of t.conditionalFormats||[])"CellIsRule"===e.rule.type&&(e.rule.operator=s[e.rule.operator]);for(const s of e.sheets||[])for(const e of s.dataValidationRules||[])e.criterion.type in t&&(e.criterion.type=t[e.criterion.type]);return e}}).add("18.4.2",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[]){if("chart"!==e.tag||"scorecard"!==e.data.type)continue;const t=e.data;t.baselineDescr&&(t.baselineDescr={text:t.baselineDescr})}return e}}).add("18.4.3",{migrate(e){if(!e.pivots)return e;for(const t in e.pivots){const s=e.pivots[t];if(s.sortedColumn){const e=s.measures.find((e=>e.fieldName===s.sortedColumn?.measure));e&&(s.sortedColumn.measure=e.id)}}return e}}).add("18.5.1",{migrate(e){for(const t of e.sheets||[])for(const e of t.figures||[])"chart"===e.tag&&(e.data.chartId=e.id);return e}});const GD="Sheet1";function WD(e,t){if(!e)return XD();console.debug("### Loading data ###");const s=performance.now();if(e["[Content_Types].xml"]){const s=new LD(e);if(e=s.convertXlsx(),t)for(const e of s.warningManager.warnings.sort())console.warn(e)}return"version"in e&&(function(e){return"number"==typeof e.version}(e)&&(e.version=$D[e.version]),e.version!==zD()&&(console.debug("Migrating data from version",e.version),e=function(e){const t=performance.now(),s=BD();for(let t=s.findIndex((t=>t===e.version))+1;t<s.length;t++){const o=s[t];e=UD.get(o).migrate(e)}return console.debug("Data migrated in",performance.now()-t,"ms"),e}(e))),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,s=new Xa;for(const o of e.sheets||[])for(const e of o.figures||[])t.has(e.id)&&(e.id+=s.smallUuid()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){const t=Object.assign(XD(),e,{version:zD()});t.sheets=t.sheets?t.sheets.map(((e,t)=>Object.assign(YD(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===t.sheets.length&&t.sheets.push(YD(GD,"Sheet1"));bl(t.settings.locale)||(t.settings.locale=w);return t}(e),e}(e),console.debug("Data loaded in",performance.now()-s,"ms"),console.debug("###"),e}const $D={25:"18.2",24:"18.1.1",23:"18.1",22:"18.0.4",21:"18.0.3",20:"18.0.2",19:"18.0.1",18:"18.0",17:"17.4",16:"17.3",15:"17.2",14:"16.4",13:"16.3",12:"15.4",11:"0.10",10:"0.9",9:"0.8",8:"0.7",7:"0.6",6:"0.5",5:"0.4",4:"0.3",3:"0.2",2:"0.1",1:"0"};function qD(e,t){const s=e.split(".").map(Number),o=t.split(".").map(Number);for(let e=0;e<Math.max(s.length,o.length);e++){const t=s[e]||0,i=o[e]||0;if(t>i)return 1;if(t<i)return-1}return 0}function ZD(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const s=[],o=[],i=e=>{if("CREATE_SHEET"===e.type)s.push(e.sheetId);else if("sheetId"in e&&!s.includes(e.sheetId))return{...e,sheetId:GD};return e};for(const e of t)"REMOTE_REVISION"===e.type?o.push({...e,commands:e.commands.map(i)}):o.push(e);return o}(e,t),t=jD(t,"SORT_CELLS"),t=function(e,t){const s=[],o={};for(const t of e.sheets||[])t.figures?.forEach((t=>{"chart"===t.tag&&(e.version&&qD(String(e.version),"18.5.1")<=0?o[t.data.chartId]=t.data:o[t.id]=t.data)}));for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const s of e.commands){let e=s;switch(s.type){case"CREATE_CHART":o[s.chartId]=s.definition;break;case"UPDATE_CHART":if(!o[s.chartId]){console.log(`Fix chart definition: chart with id ${s.chartId} not found.`);continue}const t={...o[s.chartId],...s.definition};e={...s,definition:t},o[s.chartId]=t}t.push(e)}s.push({...e,commands:t})}else s.push(e);return s}(e,t=jD(t,"SET_DECIMAL")),t=function(e,t){const s={};for(const t of e.sheets||[])t.figures?.forEach((e=>{s[e.id]=e.offset}));for(const e of t)if("REMOTE_REVISION"===e.type)for(const t of e.commands)switch(t.type){case"UPDATE_FIGURE":t.offset&&(void 0===t.offset.x&&(t.offset.x=s[t.figureId]||0),void 0===t.offset.y&&(t.offset.y=s[t.figureId]||0),s[t.figureId]=s);break;case"CREATE_IMAGE":case"CREATE_CHART":case"CREATE_FIGURE":s[t.figureId]=t.offset}return t}(e,t),t=function(e,t){const s={};for(const t of e.sheets||[])s[t.id]=t.name;const o=[];for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const o of e.commands){switch(o.type){case"DUPLICATE_SHEET":o.sheetNameTo=o.sheetNameTo??da(s[o.sheetId],Object.values(s));break;case"CREATE_SHEET":s[o.sheetId]=o.name||ha(Object.values(s));break;case"RENAME_SHEET":s[o.sheetId]=o.newName||ha(Object.values(s))}t.push(o)}o.push({...e,commands:t})}else o.push(e);return t}(e,t),t}function jD(e,t){const s=[];for(const o of e)"REMOTE_REVISION"===o.type?s.push({...o,commands:o.commands.filter((e=>e.type!==t))}):s.push(o);return s}function YD(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},styles:{},formats:{},borders:{},cols:{},rows:{},merges:[],conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],isVisible:!0}}function XD(e="Sheet1"){return{version:zD(),sheets:[YD(GD,e)],styles:{},formats:{},borders:{},revisionId:Ce,uniqueFigureIds:!0,settings:{locale:w},pivots:{},pivotNextId:1,customTableStyles:{}}}function KD(e,t){return{...YD(e,t),charts:[],images:[],cellValues:{}}}const JD={wrongPasteSelection:Go("This operation is not allowed with multiple selections."),willRemoveExistingMerge:nb.Errors.WillRemoveExistingMerge,wrongFigurePasteOption:Go("Cannot do a special paste of a figure."),frozenPaneOverlap:Go("This operation is not allowed due to an overlapping frozen pane.")};function QD(e,t){t.isSuccessful||(t.reasons.includes("WrongPasteSelection")?e.raiseError(JD.wrongPasteSelection):t.reasons.includes("WillRemoveExistingMerge")?e.raiseError(JD.willRemoveExistingMerge):t.reasons.includes("WrongFigurePasteOption")?e.raiseError(JD.wrongFigurePasteOption):t.reasons.includes("FrozenPaneOverlap")&&e.raiseError(JD.frozenPaneOverlap))}function e_(e,t,s){const o=e.model.dispatch("PASTE",{target:t,pasteOption:s});QD(e,o)}async function t_(e,t,s,o){let i;try{const n=s;if(s.imageBlob){try{const t=await(e.imageProvider?.uploadFile(s.imageBlob));n.imageData=t}catch(t){const s=Go("An error occurred while uploading the image. %s",t.message);console.error(t),e.raiseError(s)}delete s.imageBlob}i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,clipboardContent:s,pasteOption:o})}catch(n){const r=s.data;r?.version!==zD()?e.raiseError(Go("An unexpected error occurred while pasting content. This is probably due to a spreadsheet version mismatch.")):(e.raiseError(Go("An unexpected error occurred while pasting content. Additional information can be found in the browser console.")),console.error(n)),i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,clipboardContent:{text:s.text},pasteOption:o})}QD(e,i)}function s_(e,t,s=Qx){let o=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,o);1!==o.length||i||1!==Gs(o[0])||(e.model.selection.selectTableAroundSelection(),o=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,o));const n=o.map((s=>e.model.getters.getRangeDataFromZone(t,s))),r=e.model.dispatch("CREATE_TABLE",{ranges:n,sheetId:t,config:s,tableType:i?"dynamic":"static"});return r.isCancelledBecause("TableOverlap")?e.raiseError(ab.Errors.TableOverlap):r.isCancelledBecause("NonContinuousTargets")&&e.raiseError(ab.Errors.NonContinuousTargets),r}function o_(e,t){e.model.dispatch("SET_FORMATTING_WITH_PIVOT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function i_(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const n_=async e=>r_(e,"asValue");async function r_(e,t){const s=await e.clipboard.read();switch(s.status){case"ok":const o=e.model.getters.getClipboardId(),i=Ks(s.content),n=i.data?.clipboardId,r=e.model.getters.getSelectedZones();o!==n?await t_(e,r,i,t):e_(e,r,t),e.model.getters.isCutOperation()&&"asValue"!==t&&await e.clipboard.write({[a.PlainText]:""});break;case"notImplemented":e.raiseError(Go("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(Go("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const a_=(e,t)=>{if("COL"===e&&t.model.getters.getActiveRows().size>0||"ROW"===e&&t.model.getters.getActiveCols().size>0)return!1;const s=t.model.getters.getActiveSheetId(),o=t.model.getters.getElementsFromSelection(e),i=t.model.getters.checkElementsIncludeAllVisibleHeaders(s,e,o),n=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(s,e,o);return!i&&!n},l_=e=>{const t=e.model.getters.getActiveRows();let s,o;if(t.size)s=Vt([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.top,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"before",base:s,quantity:o,dimension:"ROW"})},c_=e=>{const t=e.model.getters.getActiveCols();let s,o;if(t.size)s=Vt([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.left,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"before",dimension:"COL",base:s,quantity:o})},h_=e=>{const t=e.model.getters.getActiveCols();let s,o;if(t.size)s=kt([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.right,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"after",dimension:"COL",base:s,quantity:o})};const d_=async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),s=e.model.uuidGenerator.smallUuid(),o=await async function(e){try{return await e.imageProvider.requestImage()}catch{return void e.raiseError(Go("An unexpected error occurred during the image transfer"))}}(e);if(!o)return;const i=LE(e.model.getters,o.size),{col:n,row:r,offset:a}=NE(e.model.getters,i);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:s,col:n,row:r,offset:a,size:i,definition:o})}},u_=e=>{const{col:t,row:s}=e.model.getters.getActivePosition();e.getStore(RR).open({col:t,row:s},"LinkEditor")},g_=e=>{const t=e.model.getters.getFirstTableInSelection();return t?.config.hasFilters||!1},p_=e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZones();return 1===e.model.getters.getTablesOverlappingZones(t,s).length},m_=e=>$s(e.model.getters.getSelectedZones()),f_=e=>1===e.model.getters.getSelectedZones().length,v_=(e,t)=>{if(!f_(e))return!1;const s="COL"===t?e.model.getters.getActiveCols():e.model.getters.getActiveRows(),o="COL"===t?e.model.getters.getActiveRows():e.model.getters.getActiveCols(),i=e.model.getters.getActiveSheetId(),n=xs(e.model.getters.getSelectedZone(),e.model.getters.getSheetZone(i));return Dt(s)&&(0===o.size||n)},b_={name:e=>g_(e)?Go("Remove selected filters"):Go("Add filters"),isEnabled:e=>m_(e),execute:e=>g_(e)?(e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getFirstTableInSelection();s&&e.model.dispatch("UPDATE_TABLE",{sheetId:t,zone:s.range.zone,config:{hasFilters:!1}})})(e):(e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getFirstTableInSelection();s?e.model.dispatch("UPDATE_TABLE",{sheetId:t,zone:s.range.zone,config:{hasFilters:!0}}):s_(e,t,{...Qx,hasFilters:!0,bandedRows:!1,styleId:"TableStyleLight11"})})(e),icon:"o-spreadsheet-Icon.FILTER_ICON_ACTIVE"};function S_(e,t,s){const o=e.model.getters.getActiveSheetId(),i="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(i,{sheetId:o,quantity:s}).isCancelledBecause("MergeOverlap")&&e.raiseError(sb)}class C_{map={};constructor(e=[]){for(const[t,s]of e)this.set(t,s)}set({sheetId:e,col:t,row:s},o){const i=this.map;i[e]||(i[e]={}),i[e][t]||(i[e][t]={}),i[e][t][s]=o}setMany(e){for(const[t,s]of e)this.set(t,s)}get({sheetId:e,col:t,row:s}){return this.map[e]?.[t]?.[s]}getSheet(e){return this.map[e]}clearSheet(e){delete this.map[e]}has({sheetId:e,col:t,row:s}){return void 0!==this.map[e]?.[t]?.[s]}delete({sheetId:e,col:t,row:s}){delete this.map[e]?.[t]?.[s]}keys(){const e=this.map,t=[];for(const s in e)for(const o in e[s])for(const i in e[s][o])t.push({sheetId:s,col:parseInt(o),row:parseInt(i)});return t}keysForSheet(e){const t=this.map[e];if(!t)return[];const s=[];for(const o in t)for(const i in t[o])s.push({sheetId:e,col:parseInt(o),row:parseInt(i)});return s}*entries(){const e=this.map;for(const t of this.keys()){const{sheetId:s,col:o,row:i}=t;yield[t,e[s][o][i]]}}}class y_ extends ph{mutators=["enable","disable"];isInvalidated=!1;fingerprintColors={[I_]:"#D9D9D9"};isEnabled=!1;colors=new C_;handle(e){switch(f(e)&&this.isEnabled&&(this.isInvalidated=!0),e.type){case"UNDO":case"REDO":case"ACTIVATE_SHEET":this.isEnabled&&(this.isInvalidated=!0)}}finalize(){this.isInvalidated&&(this.isInvalidated=!1,this.computeFingerprints())}enable(){this.isEnabled=!0,this.computeFingerprints()}disable(){this.isEnabled=!1,this.colors=new C_}computeFingerprints(){this.colors=new C_;const e=new C_,t=new Set,s=this.getters.getActiveSheetId(),o=this.getters.getCells(s);for(const s in o){const i=this.computeFingerprint(o[s]);if(!i)continue;t.add(i);const n=this.getters.getCellPosition(s);e.set(n,i)}this.assignColors(t);for(const[t,s]of e.entries()){const e=this.fingerprintColors[s];this.colors.set(t,e),this.colorSpreadZone(t,e)}}colorSpreadZone(e,t){const s=this.getters.getSpreadZone(e);if(!s)return;const o=e.sheetId;for(let e=s.top;e<=s.bottom;e++)for(let i=s.left;i<=s.right;i++){const s={sheetId:o,col:i,row:e};this.colors.set(s,t)}}assignColors(e){const t=new Po(e.size);Object.keys(this.fingerprintColors).forEach((()=>t.next()));for(const s of e)this.fingerprintColors[s]||(this.fingerprintColors[s]=So(t.next(),.8))}computeFingerprint(e){const t=this.getters.getCellPosition(e.id);return e.isFormula?this.computeFormulaFingerprint(t,e):this.getLiteralFingerprint(t)}computeFormulaFingerprint(e,t){const s=t.compiledFormula.dependencies,o=e.col,i=e.row,n=this.getters.getSheetIds().indexOf(e.sheetId),r={dx:0,dy:0,dSheet:0};for(const e of s){const t=e.zone,[s,a]=e.parts,l=this.getters.getSheetIds().indexOf(e.sheetId);r.dSheet=l-n;const c=va(e)&&!e.unboundedZone.hasHeader,h=fa(e)&&!e.unboundedZone.hasHeader,d=c||s?.colFixed?0:o,u=h||s?.rowFixed?0:i,g=!a&&s?.colFixed||a?.colFixed,p=!a&&s.rowFixed||a?.rowFixed,m=void 0===e.unboundedZone.right||g?0:o,f=void 0===e.unboundedZone.bottom||p?0:i,v=Ls({top:t.top-u,left:t.left-d,right:t.right-m,bottom:t.bottom-f});for(let e=v.top;e<=v.bottom;e++)for(let t=v.left;t<=v.right;t++)r.dx+=t,r.dy+=e}const a=t.compiledFormula.normalizedFormula;return l=r,Object.entries(l).sort((([e],[t])=>e.localeCompare(t))).map((([e,t])=>t)).join(",")+a;var l}getLiteralFingerprint(e){switch(this.getters.getEvaluatedCell(e).type){case r.number:case r.boolean:return I_;case r.text:case r.empty:case r.error:return}}}const I_="DATA_FINGERPRINT",w_={name:e=>{const t=e.model.getters.getElementsFromSelection("COL"),s=t[0],o=t[t.length-1];return 1===t.length?Go("Hide column %s",Xt(s).toString()):o-s+1===t.length?Go("Hide columns %s - %s",Xt(s).toString(),Xt(o).toString()):Go("Hide columns")},execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getElementsFromSelection("COL");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"COL",s)},icon:"o-spreadsheet-Icon.HIDE_COL"},E_={name:Go("Unhide columns"),execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))},icon:"o-spreadsheet-Icon.UNHIDE_COL"},R_={name:Go("Unhide all columns"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"COL",elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0,icon:"o-spreadsheet-Icon.UNHIDE_COL"},x_={name:e=>{const t=e.model.getters.getElementsFromSelection("ROW"),s=t[0],o=t[t.length-1];return 1===t.length?Go("Hide row %s",(s+1).toString()):o-s+1===t.length?Go("Hide rows %s - %s",(s+1).toString(),(o+1).toString()):Go("Hide rows")},execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getElementsFromSelection("ROW");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"ROW",s)},icon:"o-spreadsheet-Icon.HIDE_ROW"},T_={name:Go("Unhide rows"),execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))},icon:"o-spreadsheet-Icon.UNHIDE_ROW"},A_={name:Go("Unhide all rows"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"ROW",elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0,icon:"o-spreadsheet-Icon.UNHIDE_ROW"},D_={name:Go("Unfreeze"),isVisible:e=>{const{xSplit:t,ySplit:s}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+s>0},execute:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),icon:"o-spreadsheet-Icon.UNFREEZE"},__={name:Go("Freeze"),icon:"o-spreadsheet-Icon.FREEZE"},F_={name:Go("No rows"),execute:e=>e.model.dispatch("UNFREEZE_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit},O_={name:Go("1 row"),execute:e=>S_(e,"ROW",1),isReadonlyAllowed:!0},P_={name:Go("2 rows"),execute:e=>S_(e,"ROW",2),isReadonlyAllowed:!0},M_={name:Go("Up to current row"),execute:e=>{const{bottom:t}=e.model.getters.getSelectedZone();S_(e,"ROW",t+1)},isReadonlyAllowed:!0},N_={name:Go("No columns"),execute:e=>e.model.dispatch("UNFREEZE_COLUMNS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit},L_={name:Go("1 column"),execute:e=>S_(e,"COL",1),isReadonlyAllowed:!0},k_={name:Go("2 columns"),execute:e=>S_(e,"COL",2),isReadonlyAllowed:!0},V_={name:Go("Up to current column"),execute:e=>{const{right:t}=e.model.getters.getSelectedZone();S_(e,"COL",t+1)},isReadonlyAllowed:!0},U_={name:Go("Gridlines"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},isActive:e=>{const t=e.model.getters.getActiveSheetId();return e.model.getters.getGridLinesVisibility(t)}},H_={name:Go("Irregularity map"),execute:e=>{const t=e.getStore(y_);t.isEnabled?t.disable():t.enable()},isReadonlyAllowed:!0,icon:"o-spreadsheet-Icon.IRREGULARITY_MAP"},z_={name:Go("Formulas"),isActive:e=>e.model.getters.shouldShowFormulas(),execute:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0},B_={name:e=>{const t=e.model.getters.getSelectedZone();return t.left===t.right?Go("Group column %s",Xt(t.left)):Go("Group columns %s - %s",Xt(t.left),Xt(t.right))},execute:e=>q_(e,"COL"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZone(),o=e.model.getters.getHeaderGroupsInZone(t,"COL",s);return f_(e)&&!o.some((e=>e.start===s.left&&e.end===s.right))},icon:"o-spreadsheet-Icon.GROUP_COLUMNS"},G_={name:e=>{const t=e.model.getters.getSelectedZone();return t.top===t.bottom?Go("Group row %s",String(t.top+1)):Go("Group rows %s - %s",String(t.top+1),String(t.bottom+1))},execute:e=>q_(e,"ROW"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZone(),o=e.model.getters.getHeaderGroupsInZone(t,"ROW",s);return f_(e)&&!o.some((e=>e.start===s.top&&e.end===s.bottom))},icon:"o-spreadsheet-Icon.GROUP_ROWS"},W_={name:e=>{const t=e.model.getters.getSelectedZone();return t.left===t.right?Go("Ungroup column %s",Xt(t.left)):Go("Ungroup columns %s - %s",Xt(t.left),Xt(t.right))},execute:e=>Z_(e,"COL"),icon:"o-spreadsheet-Icon.UNGROUP_COLUMNS"},$_={name:e=>{const t=e.model.getters.getSelectedZone();return t.top===t.bottom?Go("Ungroup row %s",String(t.top+1)):Go("Ungroup rows %s - %s",String(t.top+1),String(t.bottom+1))},execute:e=>Z_(e,"ROW"),icon:"o-spreadsheet-Icon.UNGROUP_ROWS"};function q_(e,t){const s=e.model.getters.getSelectedZone(),o=e.model.getters.getActiveSheetId();e.model.dispatch("GROUP_HEADERS",{sheetId:o,dimension:t,start:"COL"===t?s.left:s.top,end:"COL"===t?s.right:s.bottom})}function Z_(e,t){const s=e.model.getters.getSelectedZone(),o=e.model.getters.getActiveSheetId();e.model.dispatch("UNGROUP_HEADERS",{sheetId:o,dimension:t,start:"COL"===t?s.left:s.top,end:"COL"===t?s.right:s.bottom})}function j_(e,t){const s=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return 1===o.length&&e.model.getters.getHeaderGroupsInZone(s,t,o[0]).length>0}const Y_=["wholeTable","firstColumnStripe","secondColumnStripe","firstRowStripe","secondRowStripe","firstColumn","lastColumn","headerRow","totalRow"];function X_(e){const t=e.range;return{row:t.zone.top,col:t.zone.left,sheetId:t.sheetId}}function K_(e,t,s,o){const i=t.zone;if(i.left!==i.right)throw new Error("Can only define a filter on a single column");const n={...i,top:i.top+s.numberOfHeaders},r=o(t.sheetId,n);return{id:e,rangeWithHeaders:t,col:i.left,filteredRange:n.top>n.bottom?void 0:r}}function J_(e){return"static"===e.type||"forceStatic"===e.type}function Q_(e,t,s,o){return{borders:eF(e,t,s,o),styles:sF(e,t,s,o)}}function eF(e,t,s,o){const i=mn(s,o,(()=>({})));for(const n of Y_){const r=t[n]?.border;if(!r)continue;const a=iF(n,e,s,o);for(const t of a)for(let a=t.left;a<=t.right;a++)for(let l=t.top;l<=t.bottom;l++){const c="wholeTable"===n&&l<=e.numberOfHeaders-1;l===t.top&&r?.top?tF(i,"top",r.top,a,l,s,o):l!==t.top&&!c&&r?.horizontal&&tF(i,"top",r.horizontal,a,l,s,o),l===t.bottom&&r?.bottom&&tF(i,"bottom",r.bottom,a,l,s,o),a===t.left&&r?.left&&tF(i,"left",r.left,a,l,s,o),a===t.right&&r?.right?tF(i,"right",r.right,a,l,s,o):a!==t.right&&!c&&r?.vertical&&tF(i,"right",r.vertical,a,l,s,o)}}return i}function tF(e,t,s,o,i,n,r){switch(t){case"top":return e[o][i].top=s,void(0!==i&&(e[o][i-1].bottom=s));case"bottom":return e[o][i].bottom=s,void(i!==r-1&&(e[o][i+1].top=s));case"left":return e[o][i].left=s,void(0!==o&&(e[o-1][i].right=s));case"right":return e[o][i].right=s,void(o!==n-1&&(e[o+1][i].left=s))}}function sF(e,t,s,o){const i=mn(s,o,(()=>({})));for(const n of Y_){const r=t[n],a=oF(n);if(!r&&!a)continue;const l=iF(n,e,s,o);for(const e of l)for(let t=e.left;t<=e.right;t++)for(let s=e.top;s<=e.bottom;s++)i[t][s]||(i[t][s]={}),i[t][s]={...i[t][s],...r?.style},a&&(i[t][s].bold=!0)}return i}function oF(e){return"firstColumn"===e||"lastColumn"===e||"headerRow"===e||"totalRow"===e}function iF(e,t,s,o){const i=[],n=Math.min(t.numberOfHeaders,o),r=t.totalRow?1:0,a=s-1,l=o-1;switch(e){case"wholeTable":i.push({top:0,left:0,bottom:l,right:a});break;case"firstColumn":if(!t.firstColumn)break;i.push({top:0,left:0,bottom:l,right:0});break;case"lastColumn":if(!t.lastColumn)break;i.push({top:0,left:a,bottom:l,right:a});break;case"headerRow":if(!t.numberOfHeaders)break;i.push({top:0,left:0,bottom:n-1,right:a});break;case"totalRow":if(!t.totalRow)break;i.push({top:l,left:0,bottom:l,right:a});break;case"firstRowStripe":if(!t.bandedRows)break;for(let e=n;e<o-r;e+=2)i.push({top:e,left:0,bottom:e,right:a});break;case"secondRowStripe":if(!t.bandedRows)break;for(let e=n+1;e<o-r;e+=2)i.push({top:e,left:0,bottom:e,right:a});break;case"firstColumnStripe":if(!t.bandedColumns)break;for(let e=0;e<s;e+=2)i.push({top:n,left:e,bottom:l-r,right:e});break;case"secondColumnStripe":if(!t.bandedColumns)break;for(let e=1;e<s;e+=2)i.push({top:n,left:e,bottom:l-r,right:e})}return i}function nF(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause("WrongCutSelection")&&e.raiseError(Go("This operation is not allowed with multiple selections."))}const rF={MergeIsDestructive:Go("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:Go("You can't merge cells inside of an existing filter.")};const aF={name:Go("Undo"),description:"Ctrl+Z",execute:e=>e.model.dispatch("REQUEST_UNDO"),isEnabled:e=>e.model.getters.canUndo(),icon:"o-spreadsheet-Icon.UNDO"},lF={name:Go("Redo"),description:"Ctrl+Y",execute:e=>e.model.dispatch("REQUEST_REDO"),isEnabled:e=>e.model.getters.canRedo(),icon:"o-spreadsheet-Icon.REDO"},cF={name:Go("Copy"),description:"Ctrl+C",isReadonlyAllowed:!0,execute:async e=>{e.model.dispatch("COPY"),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},icon:"o-spreadsheet-Icon.CLIPBOARD"},hF={name:Go("Cut"),description:"Ctrl+X",execute:async e=>{nF(e),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},icon:"o-spreadsheet-Icon.CUT"},dF={name:Go("Paste"),description:"Ctrl+V",execute:async e=>r_(e),icon:"o-spreadsheet-Icon.PASTE"},uF={name:Go("Paste special"),isVisible:e=>!e.model.getters.isCutOperation(),icon:"o-spreadsheet-Icon.PASTE"},gF={name:Go("Paste as value"),description:"Ctrl+Shift+V",execute:n_},pF={name:Go("Paste format only"),execute:e=>r_(e,"onlyFormat")},mF={name:Go("Find and replace"),description:"Ctrl+H",isReadonlyAllowed:!0,execute:e=>{e.openSidePanel("FindAndReplace",{})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.SEARCH"},fF={name:Go("Delete values"),execute:e=>e.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},vF={name:e=>{if(e.model.getters.getSelectedZones().length>1)return Go("Delete rows");let t,s;const o=e.model.getters.getActiveRows();if(0!==o.size)t=Vt([...o]),s=kt([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?Go("Delete row %s",(t+1).toString()):Go("Delete rows %s - %s",(t+1).toString(),(s+1).toString())},execute:e=>{const t=[...e.model.getters.getActiveRows()];if(!t.length){const s=e.model.getters.getSelectedZones()[0];for(let e=s.top;e<=s.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:"ROW",elements:t})},isVisible:e=>a_("ROW",e)},bF={...vF,isVisible:f_},SF={name:e=>{if(e.model.getters.getSelectedZones().length>1)return Go("Clear rows");let t,s;const o=e.model.getters.getActiveRows();if(0!==o.size)t=Vt([...o]),s=kt([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?Go("Clear row %s",(t+1).toString()):Go("Clear rows %s - %s",(t+1).toString(),(s+1).toString())},execute:e=>{const t=e.model.getters.getActiveSheetId(),s=[...e.model.getters.getActiveRows()].map((s=>e.model.getters.getRowsZone(t,s,s)));e.model.dispatch("DELETE_CONTENT",{target:s,sheetId:e.model.getters.getActiveSheetId()})}},CF={name:e=>{if(e.model.getters.getSelectedZones().length>1)return Go("Delete columns");let t,s;const o=e.model.getters.getActiveCols();if(0!==o.size)t=Vt([...o]),s=kt([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?Go("Delete column %s",Xt(t)):Go("Delete columns %s - %s",Xt(t),Xt(s))},execute:e=>{const t=[...e.model.getters.getActiveCols()];if(!t.length){const s=e.model.getters.getSelectedZones()[0];for(let e=s.left;e<=s.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:"COL",elements:t})},isVisible:e=>a_("COL",e)},yF={...CF,isVisible:f_},IF={name:e=>{if(e.model.getters.getSelectedZones().length>1)return Go("Clear columns");let t,s;const o=e.model.getters.getActiveCols();if(0!==o.size)t=Vt([...o]),s=kt([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?Go("Clear column %s",Xt(t)):Go("Clear columns %s - %s",Xt(t),Xt(s))},execute:e=>{const t=e.model.getters.getActiveSheetId(),s=[...e.model.getters.getActiveCols()].map((s=>e.model.getters.getColsZone(t,s,s)));e.model.dispatch("DELETE_CONTENT",{target:s,sheetId:e.model.getters.getActiveSheetId()})}},wF={name:Go("Delete cells"),isVisible:f_},EF={name:Go("Delete cell and shift up"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});QD(e,s)}},RF={name:Go("Delete cell and shift left"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});QD(e,s)}},xF={name:Go("Merge cells"),isEnabled:e=>!DF(e),isActive:e=>_F(e),execute:e=>function(e){if(DF(e))return;const t=e.model.getters.getSelectedZones(),s=e.model.getters.getActiveSheetId();if(_F(e)){const o=t.flatMap((t=>e.model.getters.getMergesInZone(s,t)));e.model.dispatch("REMOVE_MERGE",{sheetId:s,target:o})}else!function(e,t,s){const o=e.model.dispatch("ADD_MERGE",{sheetId:t,target:s});o.isCancelledBecause("MergeInTable")?e.raiseError(rF.MergeInFilter):o.isCancelledBecause("MergeIsDestructive")&&e.askConfirmation(rF.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:s,force:!0})}))}(e,s,t)}(e),icon:"o-spreadsheet-Icon.MERGE_CELL"},TF={name:()=>Go("Edit table"),execute:e=>e.openSidePanel("TableSidePanel",{}),icon:"o-spreadsheet-Icon.EDIT_TABLE"},AF={name:()=>Go("Delete table"),execute:e=>{const t=e.model.getters.getActivePosition(),s=e.model.getters.getTable(t);s&&e.model.dispatch("REMOVE_TABLE",{sheetId:t.sheetId,target:[s.range.zone]})},icon:"o-spreadsheet-Icon.DELETE_TABLE"};function DF(e){const t=e.model.getters.getSelectedZones(),{sheetId:s}=e.model.getters.getActivePosition(),{xSplit:o,ySplit:i}=e.model.getters.getPaneDivisions(s);return t.every((e=>1===Gs(e)))||Ws(t,o,i)||function(e){for(let t=0;t<e.length-1;t++)for(let s=t+1;s<e.length;s++)if(As(e[t],e[s]))return!0;return!1}(t)}function _F(e){if(DF(e))return!1;const t=e.model.getters.getActiveSheetId();return e.model.getters.getSelectedZones().some((s=>e.model.getters.getMergesInZone(t,s).length>0))}const FF={name:e=>{const t=cO(e);return 1===t?Go("Insert row"):Go("Insert %s rows",t.toString())},isVisible:e=>v_(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW"},OF={name:e=>{const t=cO(e);return 1===t?Go("Insert row above"):Go("Insert %s rows above",t.toString())},execute:l_,isVisible:e=>v_(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},PF={...OF,name:e=>{const t=cO(e);return 1===t?Go("Row above"):Go("%s Rows above",t.toString())}},MF={...OF,name:e=>{const t=cO(e);return 1===t?Go("Insert row"):Go("Insert %s rows",t.toString())},isVisible:f_,icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},NF={execute:e=>{const t=e.model.getters.getActiveRows();let s,o;if(t.size)s=kt([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.bottom,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"after",base:s,quantity:o,dimension:"ROW"})},name:e=>{const t=cO(e);return 1===t?Go("Insert row below"):Go("Insert %s rows below",t.toString())},isVisible:e=>v_(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_AFTER"},LF={...NF,name:e=>{const t=cO(e);return 1===t?Go("Row below"):Go("%s Rows below",t.toString())}},kF={name:e=>{const t=hO(e);return 1===t?Go("Insert column"):Go("Insert %s columns",t.toString())},isVisible:e=>v_(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL"},VF={name:e=>{const t=hO(e);return 1===t?Go("Insert column left"):Go("Insert %s columns left",t.toString())},execute:c_,isVisible:e=>v_(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},UF={...VF,name:e=>{const t=hO(e);return 1===t?Go("Column left"):Go("%s Columns left",t.toString())}},HF={...VF,name:e=>{const t=hO(e);return 1===t?Go("Insert column"):Go("Insert %s columns",t.toString())},isVisible:f_,icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},zF={name:e=>{const t=hO(e);return 1===t?Go("Insert column right"):Go("Insert %s columns right",t.toString())},execute:h_,isVisible:e=>v_(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_AFTER"},BF={...zF,name:e=>{const t=hO(e);return 1===t?Go("Column right"):Go("%s Columns right",t.toString())},execute:h_},GF={name:Go("Insert cells"),isVisible:e=>f_(e)&&0===e.model.getters.getActiveCols().size&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_CELL"},WF={name:Go("Insert cells and shift down"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});QD(e,s)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN"},$F={name:Go("Insert cells and shift right"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});QD(e,s)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT"},qF={name:Go("Chart"),execute:e=>{const t=e.model.getters,s=e.model.uuidGenerator.smallUuid(),o=t.getActiveSheetId();let i=t.getSelectedZones();1===i.length&&1===Gs(i[0])&&(e.model.selection.selectTableAroundSelection(),i=t.getSelectedZones());const n={width:536,height:335},{col:r,row:a,offset:l}=NE(t,n);e.model.dispatch("CREATE_CHART",{sheetId:o,figureId:s,chartId:e.model.uuidGenerator.smallUuid(),col:r,row:a,offset:l,size:n,definition:Kx(i,e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{figureId:s}),e.openSidePanel("ChartPanel"))},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.INSERT_CHART"},ZF={name:Go("Carousel"),execute:e=>{const t=e.model.getters,s=e.model.uuidGenerator.smallUuid(),o=t.getActiveSheetId(),i={width:536,height:335},{col:n,row:r,offset:a}=NE(t,i);e.model.dispatch("CREATE_CAROUSEL",{sheetId:o,figureId:s,col:n,row:r,offset:a,size:i,definition:{items:[]}}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{figureId:s}),e.openSidePanel("CarouselPanel",{figureId:s}))},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.CAROUSEL"},jF={name:Go("Pivot table"),execute:e=>{const t=e.model.uuidGenerator.smallUuid(),s=e.model.uuidGenerator.smallUuid();e.model.dispatch("INSERT_NEW_PIVOT",{pivotId:t,newSheetId:s}).isSuccessful&&e.openSidePanel("PivotSidePanel",{pivotId:t})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.PIVOT"},YF={name:Go("Image"),description:"Ctrl+O",execute:d_,isVisible:e=>void 0!==e.imageProvider,isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.INSERT_IMAGE"},XF={name:()=>Go("Table"),execute:e=>{const t=e.model.getters.getActiveSheetId();s_(e,t).isSuccessful&&e.openSidePanel("TableSidePanel",{})},isVisible:e=>m_(e)&&!e.model.getters.getFirstTableInSelection(),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.PAINT_TABLE"},KF={name:Go("Function"),icon:"o-spreadsheet-Icon.FORMULA"},JF={name:Go("SUM"),execute:e=>e.startCellEdition("=SUM(")},QF={name:Go("AVERAGE"),execute:e=>e.startCellEdition("=AVERAGE(")},eO={name:Go("COUNT"),execute:e=>e.startCellEdition("=COUNT(")},tO={name:Go("MAX"),execute:e=>e.startCellEdition("=MAX(")},sO={name:Go("MIN"),execute:e=>e.startCellEdition("=MIN(")},oO={name:Go("All"),children:[function(){return lO(JS.getKeys().filter((e=>!JS.get(e).hidden)))}]};const iO={name:Go("Link"),execute:u_,icon:"o-spreadsheet-Icon.INSERT_LINK"},nO={name:Go("Checkbox"),execute:e=>{const t=e.model.getters.getSelectedZones(),s=e.model.getters.getActiveSheetId(),o=t.map((t=>e.model.getters.getRangeDataFromZone(s,t)));e.model.dispatch("ADD_DATA_VALIDATION_RULE",{ranges:o,sheetId:s,rule:{id:e.model.uuidGenerator.smallUuid(),criterion:{type:"isBoolean",values:[]}}})},icon:"o-spreadsheet-Icon.INSERT_CHECKBOX"},rO={name:Go("Dropdown list"),execute:e=>{const t=e.model.getters.getSelectedZones(),s=e.model.getters.getActiveSheetId(),o=t.map((t=>e.model.getters.getRangeDataFromZone(s,t))),i=e.model.uuidGenerator.smallUuid();e.model.dispatch("ADD_DATA_VALIDATION_RULE",{ranges:o,sheetId:s,rule:{id:i,criterion:{type:"isValueInList",values:[],displayStyle:"chip"}}});const n=e.model.getters.getDataValidationRule(s,i);n&&e.openSidePanel("DataValidationEditor",{rule:Dl(n,e.model.getters.getLocale()),onExit:()=>{e.replaceSidePanel("DataValidation","DataValidationEditor")}})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.INSERT_DROPDOWN"},aO={name:Go("Insert sheet"),execute:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSheetIds().indexOf(t)+1,o=e.model.uuidGenerator.smallUuid();e.model.dispatch("CREATE_SHEET",{sheetId:o,position:s,name:e.model.getters.getNextSheetName()}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},icon:"o-spreadsheet-Icon.INSERT_SHEET"};function lO(e){return e.sort().map(((e,t)=>({name:e,sequence:10*t,execute:t=>t.startCellEdition(`=${e}(`)})))}function cO(e){const t=e.model.getters.getActiveRows();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function hO(e){const t=e.model.getters.getActiveCols();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.right-t.left+1}}const dO="(previous)",uO="(next)";function gO(e,t){const s=e.definition.rows.map((e=>e.nameWithGranularity)),o=t.filter((e=>s.includes(e.field))),i=e.definition.columns.map((e=>e.nameWithGranularity));return{colDomain:t.filter((e=>i.includes(e.field))),rowDomain:o}}function pO(e,t,s){return"column"===t?gO(e,s).colDomain:gO(e,s).rowDomain}function mO(e,t){return void 0!==fO(e,t)}function fO(e,t,s){let o=t;for(const t of e){const e=o.find((e=>e.value===t.value));if(!e)return;if(e.field===s)return o;o=e.children}return o}function vO(e,t,s){const o=(e=qe(e)).find((e=>e.field===t));return o?(o.value=s,e):e}function bO(e,t){return t.some((t=>t.field===e))}function SO(e,t){if(e.definition.rows.map((e=>e.nameWithGranularity)).includes(t))return"row";if(e.definition.columns.map((e=>e.nameWithGranularity)).includes(t))return"column";throw new Error(`Field ${t} not found in pivot`)}function CO(e){return e?e.map(yO).join(", "):""}function yO(e){return e?`${e.field}=${e.value}`:""}function IO(e,t){const s=e.findIndex((e=>e.field===t));if(-1===s)return"";const o=e.slice(0,s),i=e.at(-1);return CO(i.field===t?o:[...o,i])}function wO(e,t){const s=e.findIndex((e=>e.field===t));return-1===s?"":CO([...e.slice(0,s),...e.slice(s+1)])}function EO(e,t,s){const o=[...e],i=[...t];o.sort(((e,t)=>s([...i,e],[...i,t])));for(const t of e){const e=EO(t.children,[...i,t],s);t.children=e}return o}function RO(e,t){return e.length>t.length&&t.every(((t,s)=>St(t,e[s])))}class xO{measures;columns;rows;sortedColumn;collapsedDomains;customFields;constructor(e,t){this.columns=e.columns.map((e=>this.createPivotDimension(t,e))),this.rows=e.rows.map((e=>this.createPivotDimension(t,e))),this.measures=e.measures.map((e=>this.createMeasure(t,e))),this.sortedColumn=e.sortedColumn,this.collapsedDomains=e.collapsedDomains,this.customFields=e.customFields}getDimension(e){const t=this.columns.find((t=>t.nameWithGranularity===e))||this.rows.find((t=>t.nameWithGranularity===e));if(!t)throw new Li(Go("Dimension %s does not exist",e));return t}getMeasure(e){const t=this.measures.find((t=>t.id===e));if(!t)throw new Li(Go("Field %s is not a measure",e));return t}get invalidAggregatorsForCustomField(){return[]}createMeasure(e,t){const s=t.fieldName,o="__count"===s?{name:"__count",string:Go("Count"),type:"integer",aggregator:"sum"}:e[s],i=t.aggregator;let n=!(!o&&!t.computedBy);for(const t of[...this.rows,...this.columns]){const s=e[t.fieldName];if(s?.isCustomField&&this.invalidAggregatorsForCustomField.includes(i)){n=!1;break}}return{id:t.id,get displayName(){return t.userDefinedName??o?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:s,aggregator:i,type:"__count"===s?"integer":o?.type??"integer",isValid:n,isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}createPivotDimension(e,t){const s=e[t.fieldName],o=s?.type??"integer",i=s&&Pc(s)?t.granularity:void 0;return{displayName:s?.string??t.fieldName,nameWithGranularity:t.fieldName+(i?`:${i}`:""),fieldName:t.fieldName,granularity:i,type:s?.isCustomField?"custom":o,order:t.order,isValid:!!s,isCustomField:!!s?.isCustomField,customGroups:s?.customGroups,parentField:s?.parentField}}}class TO extends xO{range;constructor(e,t,s){if(super(e,t),e.dataSet){const{sheetId:t,zone:o}=e.dataSet;this.range=s.getRangeFromZone(t,o)}}}class AO{columns;rows;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;isSorted=!1;constructor(e,t,s,o,i={COL:[],ROW:[]}){this.measures=s,this.fieldsType=o,i.COL.length&&(e=this.removeCollapsedColumns(e,s,i.COL)),this.columns=e.map((e=>{let t=1;return e.map((e=>(e={...e,offset:t},t+=e.width,e)))})),this.rows=t.filter((e=>!this.isParentCollapsed(i.ROW,e))),this.maxIndent=Math.max(...this.rows.map((e=>e.indent))),this.rowTree=ft((()=>this.buildRowsTree())),this.colTree=ft((()=>this.buildColumnsTree()))}removeCollapsedColumns(e,t,s){const o=(s,o)=>{const i=this.getDomain(s),n=e[o],r=n.findIndex((e=>RO(this.getDomain(e),i))),a=n.findLastIndex((e=>RO(this.getDomain(e),i))),l=o===e.length-1,c=t.map((e=>({fields:l?[...s.fields,"measure"]:[],values:l?[...s.values,e]:[],width:1,offset:0,collapsedHeader:!l})));n.splice(r,a-r+1,...c)};return e.map(((i,n)=>{for(const r of i){if(n>=e.length-2)return i;const a=this.getDomain(r);if(s.some((e=>St(a,e)))){r.width=t.length;for(let t=n+1;t<e.length;t++)o(r,t)}}return i}))}isParentCollapsed(e,t){const s=this.getDomain(t);return e.some((e=>RO(s,e)))}getNumberOfDataColumns(){return this.columns.at(-1)?.length||0}getSkippedRows(e){const t=new Set;if(!e.displayColumnHeaders)for(let e=0;e<this.columns.length-1;e++)t.add(e);return e.displayMeasuresRow||t.add(this.columns.length-1),t}getPivotCells(e={displayColumnHeaders:!0,displayTotals:!0,displayMeasuresRow:!0}){const t=JSON.stringify(e);if(!this.pivotCells[t]){const{displayTotals:s}=e,o=this.rows.length,i=this.getNumberOfDataColumns();let n=this.columns.length+o,r=1+i;s||1===o||(n-=1),s||i===this.measures.length||(r-=this.measures.length);const a=[],l=this.getSkippedRows(e);for(let e=0;e<r;e++){a.push([]);for(let t=0;t<n;t++)l.has(t)||a[e].push(this.getPivotCell(e,t,s))}this.pivotCells[t]=a}return this.pivotCells[t]}getRowTree(){return this.rowTree()}getColTree(){return this.colTree()}isTotalRow(e){return this.rows[e].indent!==this.maxIndent}getPivotCell(e,t,s=!0){const o=this.columns.length;if(e>0&&t===o-1){const s=this.getColHeaderDomain(e,t);if(!s)return DO;const o=s.at(-1)?.value?.toString()||"";return{type:"MEASURE_HEADER",domain:s.slice(0,-1),measure:o}}if(t<=o-1){const s=this.getColHeaderDomain(e,t);return s?{type:"HEADER",domain:s,dimension:"COL"}:DO}if(0===e){const e=t-o;return{type:"HEADER",domain:this.getDomain(this.rows[e]),dimension:"ROW"}}{const i=t-o;if(!s&&this.isTotalRow(i))return DO;return{type:"VALUE",domain:[...this.getDomain(this.rows[i]),...this.getColDomain(e)],measure:this.getColMeasure(e)}}}getColHeaderDomain(e,t){if(0===e)return;const s=this.columns[t].find((t=>t.offset===e));return s&&!s.collapsedHeader?this.getDomain(s):void 0}getDomain(e){return e.fields.map(((t,s)=>{if("measure"===t)return{type:"char",field:t,value:kc({displayName:"measure",type:"char"},e.values[s])};{const{fieldName:o,granularity:i}=Oc(t),n=this.fieldsType[o]||"char";return{type:n,field:t,value:kc({displayName:o,type:n,granularity:i},e.values[s])}}}))}getColDomain(e){const t=this.getColHeaderDomain(e,this.columns.length-1);return t?t.slice(0,-1):[]}getColMeasure(e){const t=this.getColHeaderDomain(e,this.columns.length-1),s=t?.at(-1)?.value;if(null==s)throw new Error("Measure is missing");return s.toString()}buildRowsTree(){const e=[];let t=0;const s={};s[0]=e;for(const o of this.rows){if(0===o.fields.length||0===o.values.length)return e;const i=o.fields.length-1,n=o.fields[i],{fieldName:r,granularity:a}=Oc(n),l=kc({displayName:r,type:this.fieldsType[r]??"char",granularity:a},o.values[i]);if(i>t){t=i,s[t]=[];const e=s[t-1].at(-1);e&&(e.children=s[t])}t=i;const c={value:l,field:o.fields[i],children:[],type:this.fieldsType[r]||"char",width:0};s[t].push(c)}return e}buildColumnsTree(){const e=[],t=this.columns.at(-2)||[],s={};s[0]=e;for(const e of t)for(let t=0;t<e.fields.length;t++){const o=e.fields[t],{fieldName:i,granularity:n}=Oc(o),r=kc({displayName:i,type:this.fieldsType[i]??"char",granularity:n},e.values[t]),a={value:r,field:e.fields[t],children:[],width:e.width,type:this.fieldsType[i]||"char"};s[t]?.at(-1)?.value!==r&&(s[t+1]=[],a.children=s[t+1],s[t].push(a))}return e}export(){return{cols:this.columns,rows:this.rows,measures:this.measures,fieldsType:this.fieldsType}}sort(e,t,s){if(this.isSorted)return;const o=(e,t)=>{const o=s(e,t).value;return"number"==typeof o?o:-1/0},i=t.domain,n=EO(this.rowTree(),[],((s,n)=>{const r=o(e,[...s,...i]),a=o(e,[...n,...i]);return"asc"===t.order?r-a:a-r}));this.rowTree=ft(n),this.rows=[...this.rowTreeToRows(n),this.rows[this.rows.length-1]],this.isSorted=!0}rowTreeToRows(e,t){return e.flatMap((e=>{const s={indent:t?t.indent+1:1,fields:[...t?.fields||[],e.field],values:[...t?.values||[],e.value]};return[s,...this.rowTreeToRows(e.children,s)]}))}get numberOfCells(){return this.rows.length*this.getNumberOfDataColumns()}}const DO={type:"EMPTY"};function _O(e,t,s){const o=t.measures.filter((e=>!e.isHidden)).map((e=>e.id)),i=OO(e,t.columns,0);PO(i,o.length);const n=function(e,t){const s=t.columns.map((e=>e.nameWithGranularity)),o=s.length,i=t.measures.filter((e=>!e.isHidden)),n=i.length,r=new Array(o).fill(0).map((()=>[]));function a(e,t,i){const n=r[t];for(const r of e){const e=i.concat([r.value]),l={fields:s.slice(0,t+1),values:e,width:r.width,offset:0};n.push(l),t<=o-1&&a(r.children,t+1,e)}}a(e,0,[]);const l=s.length>0,c=[];l&&r[r.length-1].forEach((e=>{i.forEach((t=>{const s={fields:[...e.fields,"measure"],values:[...e.values,t.id],width:1,offset:0};c.push(s)}))}));i.forEach((e=>{const t={fields:["measure"],values:[e.id],width:1,offset:0};c.push(t)})),r.push(c),1===r.length&&r.unshift([]);return r[r.length-2].push({fields:[],values:[],width:n,offset:0}),r}(i,t),r=FO(e,0,t.rows,[],[]);r.push({fields:[],values:[],indent:0});const a={};for(const e of t.columns)a[e.fieldName]=e.type;for(const e of t.rows)a[e.fieldName]=e.type;const l="collapsed"===s?t.collapsedDomains:void 0;return new AO(n,r,o,a,l)}function FO(e,t,s,o,i){if(t>=s.length)return[];const n=s[t],r=n.nameWithGranularity,a=MO(e,n),l=NO(a,n),c=[],h=o.concat(r);for(const e of l){const o=i.concat(e);c.push({fields:h,values:o,indent:t+1});const n=a[e];n&&c.push(...FO(n,t+1,s,h,o))}return c}function OO(e,t,s){if(s>=t.length)return[];const o=t[s],i=t[s].nameWithGranularity,n=MO(e,o);return NO(n,t[s]).map((e=>({value:n[e]?.[0]?.[o.nameWithGranularity]?.value??null,field:i,children:OO(n[e]||[],t,s+1),type:o.type,width:0})))}function PO(e,t){for(const s in e){const o=e[s];0===o.children.length?o.width=t:(PO(o.children,t),o.width=o.children.reduce(((e,t)=>e+t.width),0))}}function MO(e,t){return Object.groupBy(e,function(e){const t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}(t))}function NO(e,t){const s=t.order,o=t.customGroups?.find((e=>e.isOtherGroup));return s||o?Object.keys(e).sort(((e,i)=>o&&e===o.name?1:o&&i===o.name?-1:s?function(e,t,s){if("null"===t)return"asc"===e.order?1:-1;if("null"===s)return"asc"===e.order?-1:1;if("integer"===e.type||"datetime"===e.type)return"asc"===e.order?Yi(t,w)-Yi(s,w):Yi(s,w)-Yi(t,w);return"asc"===e.order?t.localeCompare(s):s.localeCompare(t)}(t,e,i):0)):Object.keys(e)}const LO=Symbol("NULL");function kO(e,t,s){const o=e.granularity||"month";if(!(o in VO))throw new Error(`Unknown date granularity: ${o}`);const i="number"==typeof t||"string"==typeof t?t:LO;if(!VO[o].set.has(t)){VO[o].set.add(t);let n=null;if("number"==typeof t||"string"==typeof t){const e=rn(t,s);switch(o){case"year":n=e.getFullYear();break;case"quarter_number":n=Math.floor(e.getMonth()/3)+1;break;case"month_number":n=e.getMonth()+1;break;case"month":case"day":n=Math.floor(Yi(t,s));break;case"iso_week_number":n=e.getIsoWeek();break;case"day_of_month":n=e.getDate();break;case"day_of_week":n=(e.getDay()+7-s.weekStart)%7+1;break;case"hour_number":n=e.getHours();break;case"minute_number":n=e.getMinutes();break;case"second_number":n=e.getSeconds()}}VO[o].values[i]=kc(e,n)}return VO[o].values[i]}const VO={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},month:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};var UO;!function(e){e[e.NONE=0]="NONE",e[e.TABLE=1]="TABLE",e[e.DATA=2]="DATA",e[e.DEFINITION=3]="DEFINITION",e[e.ALL=4]="ALL"}(UO||(UO={}));const HO=new n,zO=["year","quarter_number","month_number","month","iso_week_number","day_of_month","day","day_of_week"];HO.add("SPREADSHEET",{ui:class{type="SPREADSHEET";getters;_definition;coreDefinition;metaData={fields:{},fieldKeys:[]};dataEntries=[];collapsedTable;expandedTable;invalidRangeError;needsReevaluation=!0;constructor(e,t){this.getters=t.getters,this.coreDefinition=t.definition}init(e={}){this._definition&&!e.reload||(this.reload(UO.ALL),this.needsReevaluation=!1)}reload(e){e===UO.ALL&&(this.metaData=this.loadMetaData()),e>=UO.DEFINITION&&(this._definition=this.loadRuntimeDefinition()),e>=UO.DATA&&(this.dataEntries=this.loadData()),e>=UO.TABLE&&(this.collapsedTable=void 0,this.expandedTable=void 0)}onDefinitionChange(e){const t=this.coreDefinition;if(this.coreDefinition=e,this._definition){const s=Math.max(this.computeShouldReload(t,e),UO.NONE);this.reload(s)}}computeShouldReload(e,t){return St(e.dataSet,t.dataSet)?UO.DEFINITION:UO.ALL}get isInvalidRange(){return!!this.invalidRangeError}get invalidRangeMessage(){return this.invalidRangeError?.message}get definition(){if(this._definition||this.init(),!this._definition)throw new Error("Pivot definition should be defined at this point.");return this._definition}isValid(){if(this.invalidRangeError||!this.definition)return!1;for(const e of this.definition.measures)if(!e.isValid)return!1;for(const e of this.definition.columns)if(!e.isValid)return!1;for(const e of this.definition.rows)if(!e.isValid)return!1;return!0}assertIsValid({throwOnError:e}){if(!this.isValid()){if(e)throw this.invalidRangeError?this.invalidRangeError:new Li(Go("At least one measure and/or dimension is not correct."));return{value:Mi.GenericError,message:this.invalidRangeError?.message??Go("At least one measure and/or dimension is not correct.")}}}areDomainArgsFieldsValid(e){let t=e.filter(((e,t)=>t%2==0)).map(tn);return t.length&&"measure"===t.at(-1)&&(t=t.slice(0,-1)),Nc(t,this.definition)}parseArgsToPivotDomain(e){const t=[];for(let s=0;s<e.length-1;s+=2){const o=tn(e[s]),i=this.getTypeOfDimension(o),n="measure"===o?tn(e[s+1]):kc(this.getDimension(o),e[s+1]);t.push({field:o,value:n,type:i})}return t}markAsDirtyForEvaluation(){this.needsReevaluation=!0}getMeasure(e){return this.definition.getMeasure(e)}getPivotMeasureValue(e){return{value:this.getMeasure(e).displayName}}getPivotHeaderValueAndFormat(e){const t=e.at(-1);if(!t)return{value:Go("Total")};const s=this.getDimension(t.field),o=this.filterDataEntriesFromDomain(this.dataEntries,e),i=o[0]?.[s.nameWithGranularity];if("datetime"===s.type){return dc(s.granularity||"month").toValueAndFormat(t.value,this.getters.getLocale())}return i?null===i.value?{value:Go("(Undefined)")}:i:{value:""}}getPivotCellValueAndFormat(e,t){const s=this.filterDataEntriesFromDomain(this.dataEntries,t);if(0===s.length)return{value:""};const o=this.getMeasure(e),i=s.map((e=>e[o.fieldName])).filter(ut),n=i.filter((e=>e.type!==r.empty)),a=o.aggregator,l=Ac[a];if(!l)throw new Error(`Aggregator ${a} does not exist`);try{const e=l([i],this.getters.getLocale());return 0===n.length?{...e,value:""}:e}catch(e){return QS(e,a.toUpperCase())}}getPossibleFieldValues(e){const t=[],s=MO(this.dataEntries,e),o=NO(s,e);for(const i of o)t.push({value:s[i]?.[0]?.[e.nameWithGranularity]?.value??"",label:s[i]?.[0]?.[e.nameWithGranularity]?.formattedValue||""});return t}getCollapsedTableStructure(){if(!this.isValid())throw new Error("Pivot is not valid !");return this.collapsedTable||(this.collapsedTable=_O(this.dataEntries,this.definition,"collapsed")),this.collapsedTable}getExpandedTableStructure(){if(!this.isValid())throw new Error("Pivot is not valid !");return this.expandedTable||(this.expandedTable=_O(this.dataEntries,this.definition,"expanded")),this.expandedTable}getFields(){return this.metaData.fields}get fields(){return this.getFields()}loadMetaData(){if(this.invalidRangeError=void 0,!this.coreDefinition.dataSet)return this.invalidRangeError=new Li(Go("The pivot cannot be created because the dataset is missing.")),{fields:{},fieldKeys:[]};{const{zone:e,sheetId:t}=this.coreDefinition.dataSet,s=this.getters.getRangeFromZone(t,e);try{const e=this.extractFieldsFromRange(s),t=Zc(this.coreDefinition,e.fields);return{...e,fields:{...e.fields,...t}}}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}}loadRuntimeDefinition(){return new TO(this.coreDefinition,this.fields,this.getters)}loadData(){const e=this._definition?.range;return this.isValid()&&e?this.extractDataEntriesFromRange(e):[]}getTypeOfDimension(e){if("measure"===e)return"char";const{fieldName:t}=Oc(e),s=this.fields[t]?.type;if(!s)throw new Error(`Field ${t} does not exist`);return s}filterDataEntriesFromDomain(e,t){return t.reduce(((e,t)=>this.filterDataEntriesFromDomainNode(e,t)),e)}filterDataEntriesFromDomainNode(e,t){const{field:s,value:o,type:i}=t,{nameWithGranularity:n}=this.getDimension(s);return e.filter((e=>{const t=e[n]?.value;return"char"===i?String(t)===String(o):t===o}))}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){const s=this.getters.getEvaluatedCellsInZone(e,t).filter((e=>!(e.type===r.empty||""===e.value)));return 0===s.length?"integer":s.every((e=>e.type===r.number&&e.format&&ur(e.format)))?"datetime":s.every((e=>e.type===r.boolean))?"boolean":s.some((e=>e.type===r.text))?"char":"integer"}assertCellIsValidField(e,t,s){if(s.type===r.error)throw new Li(Go("The pivot cannot be created because cell %s contains an error",as(e,t)));if(s.type===r.empty||""===s.value)throw new Li(Go("The pivot cannot be created because cell %s is empty",as(e,t)));if("__count"===s.value)throw new Li(Go("The pivot cannot be created because cell %s contains a reserved value",as(e,t)))}extractFieldsFromRange(e){const t={},s=[],o=e.sheetId,i=e.zone.top;for(let n=e.zone.left;n<=e.zone.right;n++){const r=this.getters.getEvaluatedCell({sheetId:o,col:n,row:i});this.assertCellIsValidField(n,i,r);const a=r.value?.toString();if(a){const i=this.getTypeFromZone(o,{top:e.zone.top+1,left:n,bottom:e.zone.bottom,right:n}),r=qc(a,t);t[r]={name:r,type:i,string:r,aggregator:"integer"===i?"sum":"count"},s.push(r)}}return{fields:t,fieldKeys:s}}extractDataEntriesFromRange(e){const t=[];for(let s=e.zone.top+1;s<=e.zone.bottom;s++){const o={top:s,bottom:s,left:e.zone.left,right:e.zone.right},i=this.getters.getEvaluatedCellsInZone(e.sheetId,o),n={};for(const e in i){const t=i[e],s=this.fields[this.metaData.fieldKeys[e]];if(!s)throw new Error(`Field ${this.metaData.fieldKeys[e]} does not exist`);""===t.value?n[s.name]={value:null,type:r.empty,formattedValue:""}:n[s.name]=t}for(const e in this.definition.customFields||{}){const t=this.definition.customFields?.[e];if(!t)continue;const s=n[t.parentField],o=this.fields[t.parentField];if(!s||!o){n[e]={value:null,type:r.empty,formattedValue:""};continue}const i=t.groups.find((e=>e.values.some((e=>e===s?.value))))||t.groups.find((e=>e.isOtherGroup));n[e]={...s,value:i?i.name:s.value}}n.__count={value:1,type:r.number,formattedValue:"1"},t.push(n)}const s=this.definition.columns.concat(this.definition.rows).filter((e=>"datetime"===e.type));if(s.length){const e=this.getters.getLocale();for(const o of t)for(const t of s){const s=kO(t,o[t.fieldName]?.value||null,this.getters.getLocale()),i=dc(t.granularity||"month"),{format:n,value:a}=i.toValueAndFormat(s,e);o[t.nameWithGranularity]={value:s,type:o[t.fieldName]?.type||r.empty,format:o[t.fieldName]?.format,formattedValue:or(a,{locale:e,format:n})}}}return t}},definition:TO,externalData:!1,dateGranularities:[...zO],datetimeGranularities:[...zO,"hour_number","minute_number","second_number"],isMeasureCandidate:e=>"boolean"!==e.type,isGroupable:()=>!0,canHaveCustomGroup:e=>"char"===e.type&&!e.isCustomField});const BO={name:Go("See pivot properties"),execute(e){const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotIdFromPosition(t);e.openSidePanel("PivotSidePanel",{pivotId:s})},isVisible:e=>{const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotIdFromPosition(t);return!e.isSmall&&s&&e.model.getters.isExistingPivot(s)||!1},isReadonlyAllowed:!0,icon:"o-spreadsheet-Icon.PIVOT"},GO={name:Go("Ascending"),execute:e=>KO(e,e.model.getters.getActivePosition(),"asc"),isActive:e=>"asc"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},WO={name:Go("Descending"),execute:e=>KO(e,e.model.getters.getActivePosition(),"desc"),isActive:e=>"desc"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},$O={name:Go("No sorting"),execute:e=>KO(e,e.model.getters.getActivePosition(),"none"),isActive:e=>"none"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},qO={name:Go("Convert to individual formulas"),execute(e){const t=e.model.getters.getActivePosition(),s=e.model.getters.getCorrespondingFormulaCell(t),o=e.model.getters.getPivotIdFromPosition(t);if(!s||!o)return;const{sheetId:i,col:n,row:r}=e.model.getters.getCellPosition(s.id),a=e.model.getters.getPivot(o);a.init(),a.isValid()&&e.model.dispatch("SPLIT_PIVOT_FORMULA",{sheetId:i,col:n,row:r,pivotId:o})},isVisible:e=>{const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotIdFromPosition(t);if(!s)return!1;const o=e.model.getters.getPivot(s),i=e.model.getters.getEvaluatedCell(t);return o.isValid()&&e.model.getters.isSpillPivotFormula(t)&&i.type!==r.error},icon:"o-spreadsheet-Icon.PIVOT"},ZO={name:Go("Group pivot dimensions"),execute:e=>{const t=JO(e);if(!t)return;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s),r=qe(e.model.getters.getPivotCoreDefinition(s));if(i.isCustomField){const e=(r.customFields||{})[i.name];if(!e)return;!function(e,t){const s=new Set,o=[];for(const i of t){const t=e.groups.find((e=>e.name===i));t?(o.push(t),t.values.forEach((e=>s.add(e)))):s.add(i)}if(o.some((e=>e.isOtherGroup)))e.groups=e.groups.filter((e=>e.isOtherGroup||!o.includes(e)));else if(0===o.length){const s={name:$c(Go("Group"),e),values:t};e.groups.push(s)}else{const t=o.slice(1);e.groups=e.groups.filter((e=>!t.includes(e))),o[0].values=Array.from(s)}}(e,o)}else!function(e,t,s,o){const i=Xc(e,s,o);jc(t,i);const n={name:$c(Go("Group"),i),values:t};i.groups.push(n),e.customFields||(e.customFields={});e.customFields[i.name]=i,Yc(e,s.name,i.name)}(r,o,i,n.getFields());e.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:r})},isVisible:e=>{const t=JO(e);if(!t)return!1;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s);return o.length>1&&(i.isCustomField||HO.get(n.type).canHaveCustomGroup(i))}},jO={name:Go("Group all remaining dimensions"),execute:e=>{const t=JO(e);if(!t)return;const{pivotId:s,field:o}=t,i=e.model.getters.getPivot(s),n=qe(e.model.getters.getPivotCoreDefinition(s)),r=o.isCustomField?(n.customFields||{})[o.name]:Xc(n,o,i.getFields());r&&(r.groups.push({name:$c(Go("Others"),r),values:[],isOtherGroup:!0}),Yc(n,o.name,r.name),e.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:n}))},isVisible:e=>{const t=JO(e);if(!t)return!1;const{pivotId:s,field:o,values:i}=t;return function(e,t,s,o){const i=e.model.getters.getPivot(t),n=e.model.getters.getPivotCoreDefinition(t),r=o.isCustomField?(n.customFields||{})[o.name]:Object.values(n.customFields||{}).find((e=>e.parentField===o.name)),a=i.definition.getDimension(o.name);if(!a||!r||QO(n,s,o,i.getFields()))return!1;const l=new Set(i.getPossibleFieldValues(a).map((e=>e.value))),c=o.isCustomField?r.groups.map((e=>e.name)):r.groups.flatMap((e=>e.values));for(const e of[...s,...c])l.delete(e);return 0===l.size}(e,s,i,o)}},YO={name:Go("Ungroup pivot dimensions"),execute:e=>{const t=JO(e);if(!t)return;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s),r=qe(e.model.getters.getPivotCoreDefinition(s));!function(e,t,s,o){let i;if(s.isCustomField){if(i=(e.customFields||{})[s.name],!i)return;i.groups=i.groups.filter((e=>!t.includes(e.name)))}else i=Xc(e,s,o),i.groups.some((e=>e.isOtherGroup))&&t.some((e=>!i?.groups.some((t=>t.values.includes(e)))))&&(i.groups=i.groups.filter((e=>!e.isOtherGroup))),jc(t,i);i.groups.every((e=>0===e.values.length&&!e.isOtherGroup))&&(!function(e,t){const s=e.customFields?.[t];if(!s)return;const o=[...e.rows,...e.columns].some((e=>e.fieldName===s.parentField));for(const i of[e.rows,e.columns]){const e=i.findIndex((e=>e.fieldName===t));-1!==e&&(o?i.splice(e,1):i.splice(e,1,{fieldName:s.parentField}))}}(e,i.name),delete e.customFields?.[i.name])}(r,o,i,n.getFields()),e.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:r})},isVisible:e=>{const t=JO(e);if(!t)return!1;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s),r=e.model.getters.getPivotCoreDefinition(s);if(!i.isCustomField){const e=Xc(r,i,n.getFields());if(![...r.rows,...r.columns].some((t=>t.fieldName===e.name)))return!1}return QO(r,o,i,n.getFields())}};function XO(e,t){const s=e.getPivotIdFromPosition(t);if(!s||!e.isExistingPivot(s)||!e.isSpillPivotFormula(t))return!1;if(!e.getPivot(s).isValid())return!1;const o=e.getPivotCellFromPosition(t);return"VALUE"===o.type||"MEASURE_HEADER"===o.type}function KO(e,t,s){const o=e.model.getters.getPivotIdFromPosition(t),i=e.model.getters.getPivotCellFromPosition(t);if("EMPTY"===i.type||"HEADER"===i.type||!o)return;if("none"===s)return void e.model.dispatch("UPDATE_PIVOT",{pivotId:o,pivot:{...e.model.getters.getPivotCoreDefinition(o),sortedColumn:void 0}});const n=gO(e.model.getters.getPivot(o),i.domain).colDomain;e.model.dispatch("UPDATE_PIVOT",{pivotId:o,pivot:{...e.model.getters.getPivotCoreDefinition(o),sortedColumn:{domain:n,order:s,measure:i.measure}}})}function JO(e){let t,s;const o=[];for(const i of e.model.getters.getSelectedZones()){const n=e.model.getters.getActiveSheetId();for(const r of Ns(n,i)){const i=e.model.getters.getPivotIdFromPosition(r);if(t){if(i&&t!==i)return}else t=i;if(!t)continue;const n=e.model.getters.getPivotCellFromPosition(r);if("HEADER"!==n.type||!e.model.getters.isSpillPivotFormula(r))continue;const a=n.domain.at(-1)?.field;if(!s&&a)s=a;else if(s&&a&&s!==a)return;o.push(n)}}if(!t||!s||0===o.length)return;const i=e.model.getters.getPivot(t).getFields()[s];if(!i)return;return{pivotId:t,values:o.map((e=>e.domain.at(-1)?.value)).filter((e=>void 0!==e)),field:i}}function QO(e,t,s,o){if(s.isCustomField){const o=(e.customFields||{})[s.name];return!!o&&o.groups.some((e=>t.includes(e.name)))}return Xc(e,s,o).groups.some((e=>e.isOtherGroup||t.some((t=>e.values.includes(t)))))}const eP=new Hx;eP.add("cut",{...hF,sequence:10}).add("copy",{...cF,sequence:20}).add("paste",{...dF,sequence:30}).add("paste_special",{...uF,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...gF,sequence:10}).addChild("paste_format_only",["paste_special"],{...pF,sequence:20}).add("add_row_before",{...MF,sequence:70}).add("add_column_before",{...HF,sequence:90}).add("insert_cell",{...GF,sequence:100,separator:!0}).addChild("insert_cell_down",["insert_cell"],{...WF,name:Go("Shift down"),sequence:10}).addChild("insert_cell_right",["insert_cell"],{...$F,name:Go("Shift right"),sequence:20}).add("delete_row",{...bF,sequence:110,icon:"o-spreadsheet-Icon.TRASH"}).add("delete_column",{...yF,sequence:120,icon:"o-spreadsheet-Icon.TRASH"}).add("delete_cell",{...wF,sequence:130,separator:!0,icon:"o-spreadsheet-Icon.TRASH"}).addChild("delete_cell_up",["delete_cell"],{...EF,name:Go("Shift up"),sequence:10,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP"}).addChild("delete_cell_left",["delete_cell"],{...RF,name:Go("Shift left"),sequence:20,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT"}).add("edit_table",{...TF,isVisible:p_,isEnabled:e=>!e.isSmall,sequence:140}).add("delete_table",{...AF,isVisible:p_,sequence:145,separator:!0}).add("insert_link",{...iO,name:e=>{const t=e.model.getters.getActiveSheetId(),{col:s,row:o}=e.model.getters.getActivePosition(),i=e.model.getters.getEvaluatedCell({sheetId:t,col:s,row:o});return i&&i.link?Go("Edit link"):Go("Insert link")},sequence:150,separator:!0}).add("pivot_headers_group",{sequence:155,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",...ZO}).add("pivot_group_remaining",{sequence:155,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",...jO}).add("pivot_headers_ungroup",{sequence:155,icon:"o-spreadsheet-Icon.MINUS_IN_BOX",...YO}).add("pivot_sorting",{name:Go("Sort pivot"),sequence:155,icon:"o-spreadsheet-Icon.SORT_RANGE",isVisible:e=>{const t=e.model.getters.getActivePosition();return XO(e.model.getters,t)}}).add("pivot_fix_formulas",{...qO,sequence:160}).add("pivot_properties",{...BO,sequence:170,separator:!0}).addChild("pivot_sorting_asc",["pivot_sorting"],{...GO,sequence:10}).addChild("pivot_sorting_desc",["pivot_sorting"],{...WO,sequence:20}).addChild("pivot_sorting_none",["pivot_sorting"],{...$O,sequence:30});const tP={name:Go("Sort range"),isVisible:f_,icon:"o-spreadsheet-Icon.SORT_RANGE"},sP={name:Go("Ascending (A ⟶ Z)"),execute:e=>{const{anchor:t,zones:s}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();Um(e,o,t.cell,s[0],"asc")},icon:"o-spreadsheet-Icon.SORT_ASCENDING"},oP={name:Go("Data cleanup"),icon:"o-spreadsheet-Icon.DATA_CLEANUP"},iP={name:Go("Remove duplicates"),execute:e=>{1===Gs(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection(),e.openSidePanel("RemoveDuplicates",{})},isEnabled:e=>!e.isSmall},nP={name:Go("Trim whitespace"),execute:e=>{e.model.dispatch("TRIM_WHITESPACE")}},rP={name:Go("Descending (Z ⟶ A)"),execute:e=>{const{anchor:t,zones:s}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();Um(e,o,t.cell,s[0],"desc")},icon:"o-spreadsheet-Icon.SORT_DESCENDING"},aP={...b_},lP={...b_,isActive:e=>g_(e)},cP={name:Go("Split text to columns"),sequence:1,execute:e=>e.openSidePanel("SplitToColumns",{}),isEnabled:e=>!e.isSmall&&e.model.getters.isSingleColSelected(),icon:"o-spreadsheet-Icon.SPLIT_TEXT"},hP={id:"reinsert_dynamic_pivot",name:Go("Re-insert dynamic pivot"),sequence:60,icon:"o-spreadsheet-Icon.INSERT_PIVOT",children:[e=>e.model.getters.getPivotIds().map(((t,s)=>({id:`reinsert_dynamic_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:s,execute:e=>{const s=e.model.getters.getSelectedZone(),o=e.model.getters.getPivot(t).getCollapsedTableStructure().export();e.model.dispatch("INSERT_PIVOT_WITH_TABLE",{pivotId:t,table:o,col:s.left,row:s.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:"dynamic"}),e.model.dispatch("REFRESH_PIVOT",{id:t})},isVisible:e=>e.model.getters.getPivot(t).isValid()})))],isVisible:e=>e.model.getters.getPivotIds().some((t=>e.model.getters.getPivot(t).isValid()))},dP={id:"reinsert_static_pivot",name:Go("Re-insert static pivot"),sequence:70,icon:"o-spreadsheet-Icon.INSERT_PIVOT",children:[e=>e.model.getters.getPivotIds().map(((t,s)=>({id:`reinsert_static_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:s,execute:e=>{const s=e.model.getters.getSelectedZone(),o=e.model.getters.getPivot(t).getExpandedTableStructure();o.numberOfCells>Ve?e.notifyUser({type:"warning",text:cb(o.numberOfCells,e.model.getters.getLocale()),sticky:!0}):(e.model.dispatch("INSERT_PIVOT_WITH_TABLE",{pivotId:t,table:o.export(),col:s.left,row:s.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:"static"}),e.model.dispatch("REFRESH_PIVOT",{id:t}))},isVisible:e=>e.model.getters.getPivot(t).isValid()})))],isVisible:e=>e.model.getters.getPivotIds().some((t=>e.model.getters.getPivot(t).isValid()))};function uP({name:e,format:t,descriptionValue:s}){const o="function"==typeof t?t:()=>t;return{name:e,description:e=>or(s,{format:o(e),locale:e.model.getters.getLocale()}),execute:e=>o_(e,o(e)),isActive:e=>lM(e,o(e)),format:t}}const gP={name:Go("Automatic"),execute:e=>o_(e,""),isActive:e=>function(e){const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotCellFromPosition(t);if("VALUE"===s.type)return!e.model.getters.getEvaluatedCell(t).format;return!e.model.getters.getCell(t)?.format}(e)},pP={name:Go("Plain text"),execute:e=>o_(e,"@"),isActive:e=>lM(e,"@")},mP=uP({name:Go("Number"),descriptionValue:1000.12,format:"#,##0.00"}),fP={name:Go("Format as percent"),execute:e=>o_(e,"0.00%"),icon:"o-spreadsheet-Icon.PERCENT"},vP=uP({name:Go("Percent"),descriptionValue:.1012,format:"0.00%"}),bP=uP({name:Go("Currency"),descriptionValue:1000.12,format:e=>br(e.model.config.defaultCurrency||Ue)}),SP={...uP({name:Go("Currency rounded"),descriptionValue:1e3,format:e=>yr(br(e.model.config.defaultCurrency||Ue))}),isVisible:e=>{const t=br(e.model.config.defaultCurrency||Ue);return t!==yr(t)}},CP=uP({name:Go("Accounting"),descriptionValue:-1000.12,format:e=>Sr(e.model.config.defaultCurrency||Ue)}),yP=Or("2023/09/26 10:43:00 PM",w),IP={name:Go("Custom currency"),isVisible:e=>void 0!==e.loadCurrencies&&!e.isSmall,execute:e=>e.openSidePanel("CustomCurrency",{})},wP=uP({name:Go("Date"),descriptionValue:yP,format:e=>e.model.getters.getLocale().dateFormat}),EP=uP({name:Go("Time"),descriptionValue:yP,format:e=>e.model.getters.getLocale().timeFormat}),RP=uP({name:Go("Date time"),descriptionValue:yP,format:e=>Ol(e.model.getters.getLocale())}),xP=uP({name:Go("Duration"),descriptionValue:"27:51:38",format:"hhhh:mm:ss"}),TP=uP({name:Go("Quarter"),descriptionValue:yP,format:"qq yyyy"}),AP=uP({name:Go("Full quarter"),descriptionValue:yP,format:"qqqq yyyy"}),DP={name:Go("More date formats"),execute:e=>e.openSidePanel("MoreFormats",{})},_P=uP({name:Go("Full date time"),format:"dddd d mmmm yyyy hh:mm:ss a",descriptionValue:yP}),FP=uP({name:Go("ISO Date"),format:"yyyy-mm-dd",descriptionValue:yP}),OP=uP({name:Go("ISO Date time"),format:"yyyy-mm-dd hh:mm:ss",descriptionValue:yP}),PP=uP({name:Go("Full week day and month"),format:"dddd d mmmm yyyy",descriptionValue:yP}),MP=uP({name:Go("Day and full month"),format:"d mmmm yyyy",descriptionValue:yP}),NP=uP({name:Go("Short week day"),format:"ddd d mmm yyyy",descriptionValue:yP}),LP=uP({name:Go("Day and short month"),format:"d mmm yyyy",descriptionValue:yP}),kP=uP({name:Go("Full month"),format:"mmmm yyyy",descriptionValue:yP}),VP=uP({name:Go("Short month"),format:"mmm yyyy",descriptionValue:yP}),UP={name:Go("Increase decimal places"),icon:"o-spreadsheet-Icon.INCREASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:1})},HP={name:Go("Decrease decimal places"),icon:"o-spreadsheet-Icon.DECRASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:-1})},zP={name:Go("Bold"),description:"Ctrl+B",execute:e=>i_(e,{bold:!e.model.getters.getCurrentStyle().bold}),icon:"o-spreadsheet-Icon.BOLD",isActive:e=>!!e.model.getters.getCurrentStyle().bold},BP={name:Go("Italic"),description:"Ctrl+I",execute:e=>i_(e,{italic:!e.model.getters.getCurrentStyle().italic}),icon:"o-spreadsheet-Icon.ITALIC",isActive:e=>!!e.model.getters.getCurrentStyle().italic},GP={name:Go("Underline"),description:"Ctrl+U",execute:e=>i_(e,{underline:!e.model.getters.getCurrentStyle().underline}),icon:"o-spreadsheet-Icon.UNDERLINE",isActive:e=>!!e.model.getters.getCurrentStyle().underline},WP={name:Go("Strikethrough"),execute:e=>i_(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),icon:"o-spreadsheet-Icon.STRIKE",isActive:e=>!!e.model.getters.getCurrentStyle().strikethrough},$P={name:Go("Font size"),children:Le.map((e=>({name:e.toString(),sequence:e,id:`font_size_${e}`,execute:t=>i_(t,{fontSize:e}),isActive:t=>function(e,t){const s=e.model.getters.getCurrentStyle().fontSize||fe;return s===t}(t,e)}))),icon:"o-spreadsheet-Icon.FONT_SIZE"},qP={name:Go("Alignment"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},ZP={name:Go("Horizontal align"),icon:e=>function(e){switch(cM(e)){case"right":return"o-spreadsheet-Icon.ALIGN_RIGHT";case"center":return"o-spreadsheet-Icon.ALIGN_CENTER";default:return"o-spreadsheet-Icon.ALIGN_LEFT"}}(e)},jP={name:Go("Left"),description:"Ctrl+Shift+L",execute:e=>i_(e,{align:"left"}),isActive:e=>"left"===cM(e),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},YP={name:Go("Center"),description:"Ctrl+Shift+E",execute:e=>i_(e,{align:"center"}),isActive:e=>"center"===cM(e),icon:"o-spreadsheet-Icon.ALIGN_CENTER"},XP={name:Go("Right"),description:"Ctrl+Shift+R",execute:e=>i_(e,{align:"right"}),isActive:e=>"right"===cM(e),icon:"o-spreadsheet-Icon.ALIGN_RIGHT"},KP={name:Go("Vertical align"),icon:e=>function(e){switch(hM(e)){case"top":return"o-spreadsheet-Icon.ALIGN_TOP";case"middle":return"o-spreadsheet-Icon.ALIGN_MIDDLE";default:return"o-spreadsheet-Icon.ALIGN_BOTTOM"}}(e)},JP={name:Go("Top"),execute:e=>i_(e,{verticalAlign:"top"}),isActive:e=>"top"===hM(e),icon:"o-spreadsheet-Icon.ALIGN_TOP"},QP={name:Go("Middle"),execute:e=>i_(e,{verticalAlign:"middle"}),isActive:e=>"middle"===hM(e),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},eM={name:Go("Bottom"),execute:e=>i_(e,{verticalAlign:"bottom"}),isActive:e=>"bottom"===hM(e),icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"},tM={name:Go("Wrapping"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},sM={name:Go("Wrapping"),icon:e=>function(e){switch(dM(e)){case"wrap":return"o-spreadsheet-Icon.WRAPPING_WRAP";case"clip":return"o-spreadsheet-Icon.WRAPPING_CLIP";default:return"o-spreadsheet-Icon.WRAPPING_OVERFLOW"}}(e)},oM={name:Go("Overflow"),execute:e=>i_(e,{wrapping:"overflow"}),isActive:e=>"overflow"===dM(e),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},iM={name:Go("Wrap"),execute:e=>i_(e,{wrapping:"wrap"}),isActive:e=>"wrap"===dM(e),icon:"o-spreadsheet-Icon.WRAPPING_WRAP"},nM={name:Go("Clip"),execute:e=>i_(e,{wrapping:"clip"}),isActive:e=>"clip"===dM(e),icon:"o-spreadsheet-Icon.WRAPPING_CLIP"};Go("Text Color"),Go("Fill Color");const rM={name:Go("Conditional formatting"),execute:e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.CONDITIONAL_FORMAT"},aM={name:Go("Clear formatting"),description:"Ctrl+<",execute:e=>e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()}),icon:"o-spreadsheet-Icon.CLEAR_FORMAT"};function lM(e,t){const s=e.model.getters.getActivePosition();return"VALUE"===e.model.getters.getPivotCellFromPosition(s).type?e.model.getters.getEvaluatedCell(s).format===t:e.model.getters.getCell(s)?.format===t}function cM(e){const t=e.model.getters.getCurrentStyle();if(t.align)return t.align;return e.model.getters.getActiveCell().defaultAlign}function hM(e){const t=e.model.getters.getCurrentStyle();return t.verticalAlign?t.verticalAlign:ge}function dM(e){const t=e.model.getters.getCurrentStyle();return t.wrapping?t.wrapping:pe}const uM=new Hx;uM.add("cut",{...hF,sequence:10}).add("copy",{...cF,sequence:20}).add("paste",{...dF,sequence:30}).add("paste_special",{...uF,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...gF,sequence:10}).addChild("paste_format_only",["paste_special"],{...pF,sequence:20}).add("sort_columns",{...tP,name:e=>e.model.getters.getActiveCols().size>1?Go("Sort columns"):Go("Sort column"),sequence:50,separator:!0}).addChild("sort_ascending",["sort_columns"],{...sP,sequence:10}).addChild("sort_descending",["sort_columns"],{...rP,sequence:20}).add("add_column_before",{...VF,sequence:70}).add("add_column_after",{...zF,sequence:80}).add("delete_column",{...CF,sequence:90,icon:"o-spreadsheet-Icon.TRASH"}).add("clear_column",{...IF,sequence:100,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_columns",{...w_,sequence:105,separator:!0}).add("unhide_columns",{...E_,sequence:106,separator:!0}).add("conditional_formatting",{...rM,sequence:110,separator:!0}).add("edit_table",{...TF,isVisible:p_,sequence:120}).add("delete_table",{...AF,isVisible:p_,sequence:125,separator:!0}).add("group_columns",{sequence:150,...B_}).add("ungroup_columns",{sequence:155,...W_,isVisible:e=>j_(e,"COL")});const gM={CannotHideAllRows:Go("Cannot hide all the rows of a sheet."),CannotHideAllColumns:Go("Cannot hide all the columns of a sheet.")};function pM(e,t,s,o,i){const n=e.model.getters.getHeaderGroup(t,s,o,i);if(!n)return;const r=n.isFolded?"UNFOLD_HEADER_GROUP":"FOLD_HEADER_GROUP",a=e.model.dispatch(r,{sheetId:t,dimension:s,start:n.start,end:n.end});if(!a.isSuccessful&&a.isCancelledBecause("NotEnoughElements")){const t="ROW"===s?gM.CannotHideAllRows:gM.CannotHideAllColumns;e.raiseError(t)}}function mM(e,t){return s([{id:"unfold_all",name:Go("ROW"===t?"Expand all row groups":"Expand all column groups"),execute:s=>{s.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:e,dimension:t})}},{id:"fold_all",name:Go("ROW"===t?"Collapse all row groups":"Collapse all column groups"),execute:s=>{s.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:e,dimension:t})}}])}const fM=new Hx;fM.add("group_columns",{sequence:10,...B_,isVisible:()=>!0,isEnabled:B_.isVisible}).add("group_rows",{sequence:20,...G_,isVisible:()=>!0,isEnabled:G_.isVisible});const vM=new Hx;vM.add("ungroup_columns",{sequence:10,...W_,isEnabled:e=>j_(e,"COL")}).add("ungroup_rows",{sequence:20,...$_,isEnabled:e=>j_(e,"ROW")});const bM=new Hx;bM.add("cut",{...hF,sequence:10}).add("copy",{...cF,sequence:20}).add("paste",{...dF,sequence:30}).add("paste_special",{...uF,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...gF,sequence:10}).addChild("paste_format_only",["paste_special"],{...pF,sequence:20}).add("add_row_before",{...OF,sequence:50}).add("add_row_after",{...NF,sequence:60}).add("delete_row",{...vF,sequence:70,icon:"o-spreadsheet-Icon.TRASH"}).add("clear_row",{...SF,sequence:80,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_rows",{...x_,sequence:85,separator:!0}).add("unhide_rows",{...T_,sequence:86,separator:!0}).add("conditional_formatting",{...rM,sequence:90,separator:!0}).add("group_rows",{sequence:100,...G_}).add("ungroup_rows",{sequence:110,...$_,isVisible:e=>j_(e,"ROW")});class SM extends ph{highlightStore=this.get(XR);constructor(e){super(e),this.highlightStore.register(this)}get highlights(){const e=this.model.getters.getActivePosition(),t=this.getters.getEvaluatedCell(e),s=this.model.getters.getArrayFormulaSpreadingOn(e),o=s?this.model.getters.getSpreadZone(s,{ignoreSpillError:!0}):this.model.getters.getSpreadZone(e,{ignoreSpillError:!0});return o?[{range:this.model.getters.getRangeFromZone(e.sheetId,o),dashed:t.value===Mi.SpilledBlocked,color:"#17A2B8",noFill:!0,thinLine:!0}]:[]}}class CM extends ph{mutators=["focusClient","unfocusClient","showClientTag","hideClientTag","jumpToClient"];_showClientTag=!1;clientFocusTimeout={};constructor(e){super(e),this.onDispose((()=>{for(const e in this.clientFocusTimeout)this.unfocusClient(e)}))}get focusedClients(){const e=new Set;return this.model.getters.getConnectedClients().forEach((t=>{(this._showClientTag||void 0!==this.clientFocusTimeout[t.id])&&e.add(t.id)})),e}jumpToClient(e){const t=this.model.getters.getClient(e);this.focusClient(e),t.position&&(this.model.dispatch("ACTIVATE_SHEET",{sheetIdTo:t.position.sheetId,sheetIdFrom:this.getters.getActiveSheetId()}),this.model.dispatch("SCROLL_TO_CELL",{col:t.position.col,row:t.position.row}))}showClientTag(){this._showClientTag=!0}hideClientTag(){this._showClientTag=!1}focusClient(e){this.clientFocusTimeout[e]&&clearTimeout(this.clientFocusTimeout[e]),this.clientFocusTimeout[e]=setTimeout((()=>this.unfocusClient(e)),3e3)}unfocusClient(e){this.clientFocusTimeout[e]&&clearTimeout(this.clientFocusTimeout[e]),this.clientFocusTimeout[e]=void 0}}function yM(e){let s,o,i,n,r=null,a="all";const l=e.model.getters;let c=[];const h=()=>{clearTimeout(r),r=null,c.forEach((e=>e())),c=[]};let d,u;const g=t=>{if(s=t,r)return;const c=l.getActiveSheetId(),h=zy(),{x:u,y:p}=l.getMainViewportCoordinates(),{top:m,left:f,bottom:v,right:b}=l.getActiveMainViewport();let{scrollX:S,scrollY:C}=l.getActiveSheetScrollInfo();const{xSplit:y,ySplit:I}=l.getPaneDivisions(c);let w=!1,E=140;const R=s.clientX-h.left;let x=l.getColIndex(R);if("vertical"!==a){const t=o.clientX-h.left,s=l.getEdgeScrollCol(R,t,i);if(s.canEdgeScroll){w=!0,E=Math.min(E,s.delay);let t=x;switch(s.direction){case"reset":x=t=y;break;case 1:x=b,t=f+1;break;case-1:for(x=f-1;e.model.getters.isColHidden(c,x);)x--;t=x}S=l.getColDimensions(c,t).start-u}}const T=s.clientY-h.top;let A=l.getRowIndex(T);if("horizontal"!==a){const t=o.clientY-h.top,s=l.getEdgeScrollRow(T,t,n);if(s.canEdgeScroll){w=!0,E=Math.min(E,s.delay);let t=A;switch(s.direction){case"reset":A=t=I;break;case 1:A=v,t=m+1;break;case-1:for(A=m-1;e.model.getters.isRowHidden(c,A);)A--;t=A}C=e.model.getters.getRowDimensions(c,t).start-p}}w||(x=IM(x,R,l.getNumberCols(c)-1),A=IM(A,T,l.getNumberRows(c)-1)),d?.(x,A,s),w&&(e.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:S,offsetY:C}),r=setTimeout((()=>{r=null,g(s)}),Math.round(E))),o={clientX:s.clientX,clientY:s.clientY}},p=()=>{u?.(),h()};return t.onWillUnmount((()=>{h()})),t.useEffect((()=>{h()}),(()=>[l.getActiveSheetId()])),{start:(e,t,s,r="all")=>{h();const l=zy();a=r,i=e.clientX-l.left,n=e.clientY-l.top,o={clientX:e.clientX,clientY:e.clientY},d=t,u=s,c.push(ax(g,p))}}}function IM(e,t,s){return-1===e?t<0?0:s:e}class wM extends t.Component{static template="o-spreadsheet-Autofill";static props={position:Object,isVisible:Boolean};state=t.useState({position:{left:0,top:0},handler:!1});dragNDropGrid=yM(this.env);get style(){const{left:e,top:t}=this.props.position;return aR({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?"visible":"hidden"})}get handlerStyle(){const{left:e,top:t}=this.state.handler?this.state.position:this.props.position;return aR({top:`${t}px`,left:`${e}px`})}get styleNextValue(){const{left:e,top:t}=this.state.position;return aR({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){const e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=EM),e}onMouseDown(e){let t,s;this.state.handler=!0;const o=e.clientX-this.props.position.left,i=e.clientY-this.props.position.top;this.dragNDropGrid.start(e,((e,n,r)=>{if(this.state.position={left:r.clientX-o,top:r.clientY-i},t!==e||s!==n){const o=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getNumberCols(o),r=this.env.model.getters.getNumberRows(o);t=-1===e?t:Ke(e,0,i),s=-1===n?s:Ke(n,0,r),void 0!==t&&void 0!==s&&this.env.model.dispatch("AUTOFILL_SELECT",{col:t,row:s})}}),(()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch("AUTOFILL")}))}onDblClick(){this.env.model.dispatch("AUTOFILL_AUTO")}}class EM extends t.Component{static props={content:String};static template=t.xml`
4
- <div t-esc="props.content"/>
5
- `}class RM extends t.Component{static template="o-spreadsheet-ClientTag";static props={active:Boolean,name:String,color:String,col:Number,row:Number};get tagStyle(){const{col:e,row:t,color:s}=this.props,{height:o}=this.env.model.getters.getSheetViewDimensionWithHeaders(),i=this.env.model.getters.isVisibleInViewport({sheetId:this.env.model.getters.getActiveSheetId(),col:e,row:t}),{x:n,y:r}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return aR({bottom:o-r+15+"px",left:n-1+"px",border:`1px solid ${s}`,"background-color":s,visibility:i?"visible":"hidden"})}}const xM=["*","+","&"];function TM(e,t=60){return"="+function(e,t){return function(e){let t="";for(;e;)t+=e.subString,e=e.next;return t}(function(e,t){const s={indentLevel:0,doc:t,next:null};return PM(e,0,s)}(t,e))}(MM(e),t-1)}function AM(e,t){return{type:"nest",indentLevel:e,doc:t}}function DM(e){return{type:"concat",docs:e}}function _M(e){return{type:"chooseBetween",doc1:FM(e),doc2:e}}function FM(e){return"string"==typeof e?e:"chooseBetween"===e.type?FM(e.doc1):"concat"===e.type?DM(e.docs.map(FM)):"nest"===e.type?{type:"nest",indentLevel:e.indentLevel,doc:FM(e.doc)}:"insertLine"===e.type?"":e}const OM=_t((function(e){return"\n"+"\t".repeat(e)}));function PM(e,t,s){if(null===s)return null;const{indentLevel:o,doc:i,next:n}=s;if("string"==typeof i)return{subString:i,next:PM(e,t+i.length,n)};if("concat"===i.type){let s=n;for(let e=i.docs.length-1;e>=0;e--)s={indentLevel:o,doc:i.docs[e],next:s};return PM(e,t,s)}if("nest"===i.type)return PM(e,t,{indentLevel:o+i.indentLevel,doc:i.doc,next:n});if("insertLine"===i.type)return{subString:OM(o),next:PM(e,o,n)};if("chooseBetween"===i.type){const s=PM(e,t,{indentLevel:o,doc:i.doc1,next:n});if(function(e,t){for(;t;){if("\n"===t.subString[0])return!0;if((e-=t.subString.length)<0)return!1;t=t.next}return!0}(e-t,s))return s;return PM(e,t,{indentLevel:o,doc:i.doc2,next:n})}return null}function MM(e){switch(e.type){case"NUMBER":return String(e.value);case"STRING":return`"${e.value}"`;case"BOOLEAN":return e.value?"TRUE":"FALSE";case"REFERENCE":case"SYMBOL":return e.value;case"FUNCALL":return NM(DM(e.args.map(MM).map(((e,t)=>t<1?e:DM([", ",{type:"insertLine"},e])))),e.value);case"UNARY_OPERATION":const t=MM(e.operand),s=(e.postfix?kM(e):VM(e))?NM(t):t;return e.postfix?DM([s,e.value]):DM([e.value,s]);case"BIN_OPERATION":{const t=MM(e.left),s=kM(e)?NM(t):t,o=MM(e.right),i=VM(e)?NM(o):o;return _M(DM([s,`${e.value}`,AM(1,DM([{type:"insertLine"},i]))]))}case"EMPTY":return""}}function NM(e,t=void 0){const s=["(",AM(1,DM([{type:"insertLine"},e])),{type:"insertLine"},")"];return t&&s.unshift(t),_M(DM(s))}function LM(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>LM(e)));return`${e.value}(${t.join(",")})`;case"NUMBER":return e.value.toString();case"REFERENCE":default:return e.value;case"STRING":return`"${e.value}"`;case"BOOLEAN":return e.value?"TRUE":"FALSE";case"UNARY_OPERATION":if(e.postfix){return(kM(e)?`(${LM(e.operand)})`:LM(e.operand))+e.value}const s=VM(e)?`(${LM(e.operand)})`:LM(e.operand);return e.value+s;case"BIN_OPERATION":const o=kM(e)?`(${LM(e.left)})`:LM(e.left),i=VM(e)?`(${LM(e.right)})`:LM(e.right);return o+e.value+i}}function kM(e){const t=e.value,s="left"in e?e.left:e.operand,o=s.value;return"BIN_OPERATION"===s.type&&uv[o]<uv[t]}function VM(e){const t=e.value,s="right"in e?e.right:e.operand,o=uv[s.value],i=uv[t];return"BIN_OPERATION"===s.type&&(o<i||o===i&&!xM.includes(t))}const UM=Go("The cell you are trying to edit has been deleted.");class HM extends QR{canStopEdition(){return"inactive"===this.editionMode||this.checkDataValidation()}stopEdition(e){if(this.canStopEdition())return this._stopEdition(),void(e&&this.model.selection.moveAnchorCell(e,1));const t=this.currentEditedCell,s=as(t.col,t.row),o=this.getters.getValidationRuleForCell(t);if(!o)return;const i=FR.get(o.criterion.type).getErrorString(o.criterion,this.getters,t.sheetId);this.notificationStore.raiseError(Go("The data you entered in %s violates the data validation rule set on the cell:\n%s",s,i)),this.cancelEdition()}handle(e){switch(super.handle(e),e.type){case"SET_FORMATTING":this.cancelEdition();break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"ACTIVATE_SHEET":if(Gt(this._currentContent)||(this._cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){const t=this.getters.getActivePosition(),{col:s,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),i=this.getters.expandZone(e.sheetIdTo,Us({col:s,row:o}));this.model.selection.resetAnchor(this,{cell:{col:s,row:o},zone:i})}break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheetId)||"inactive"===this.editionMode||(this.sheetId=this.getters.getActiveSheetId(),this.resetContent(),this.cancelEditionAndActivateSheet(),this.notificationStore.raiseError(UM))}}get placeholder(){const e=this.getters.getActivePosition(),t=this.model.getters.getArrayFormulaSpreadingOn(e);if(t)return this.getters.getCellText(t,{showFormula:!0})}get currentEditedCell(){return{sheetId:this.sheetId,col:this.col,row:this.row}}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.editionMode)return this.cancelEdition(),void this.notificationStore.raiseError(UM);const{top:t,left:s}=Is({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=s,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.editionMode)return this.cancelEdition(),void this.notificationStore.raiseError(UM);const{top:t,left:s}=Is({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=s,this.row=t}onAddElements(e){const{top:t,left:s}=ys({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=s,this.row=t}confirmEdition(e){if(e){const t=this.getters.getActiveSheetId(),s=this.getters.getEvaluatedCell({sheetId:t,col:this.col,row:this.row});s.link&&!Gt(e)&&(e=rt(e,s.link.url)),this.addHeadersForSpreadingFormula(e),this.model.dispatch("UPDATE_CELL",{...this.currentEditedCell,content:e})}else this.model.dispatch("UPDATE_CELL",{...this.currentEditedCell,content:""});this.model.dispatch("AUTOFILL_TABLE_COLUMN",{...this.currentEditedCell}),this.setContent("")}getComposerContent(e){const t=this.getters.getLocale(),s=this.getters.getCell(e);if(s?.isFormula){return El(this.getPrettifiedFormula(s),t)}if(this.model.getters.getArrayFormulaSpreadingOn(e))return"";const{format:o,value:i,type:n,formattedValue:a}=this.getters.getEvaluatedCell(e);switch(n){case r.empty:return"";case r.text:case r.error:return i;case r.boolean:return a;case r.number:if(o&&ur(o)){if(null!==mi(a,t))return a;return or(i,{locale:t,format:Number.isInteger(i)?t.dateFormat:Ol(t)})}return this.numberComposerContent(i,o,t)}}getPrettifiedFormula(e){if(e.compiledFormula.isBadExpression)return e.content;const t="inactive"===this.editionMode?1/0:80;return TM(bv(e.compiledFormula.tokens),t)}numberComposerContent(e,t,s){return t?.includes("%")?`${dr(100*e,s.decimalSeparator)}%`:dr(e,s.decimalSeparator)}addHeadersForSpreadingFormula(e){if(!Gt(e))return;const t=this.getters.evaluateFormula(this.sheetId,e);if(!R(t))return;const s=this.getters.getNumberRows(this.sheetId),o=this.getters.getNumberCols(this.sheetId),i=this.row+t[0].length-s,n=this.col+t.length-o;n>0&&this.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:this.sheetId,sheetName:this.getters.getSheetName(this.sheetId),dimension:"COL",base:o-1,position:"after",quantity:n+20}),i>0&&this.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:this.sheetId,sheetName:this.getters.getSheetName(this.sheetId),dimension:"ROW",base:s-1,position:"after",quantity:i+50})}checkDataValidation(){const e={sheetId:this.sheetId,col:this.col,row:this.row},t=this.getCurrentCanonicalContent(),s=Gt(t)?this.getters.evaluateFormula(this.sheetId,t):Or(t,this.getters.getLocale());if(Yl(s))return!0;const o=this.getters.getValidationResultForCellValue(Zl(s),e);return!(!o.isValid&&o.rule.isBlocking)}}const zM=3*.4*window.devicePixelRatio||1;class BM extends t.Component{static template="o-spreadsheet-GridComposer";static props={gridDims:Object,onInputContextMenu:Function};static components={Composer:ZR};rect=this.defaultRect;isEditing=!1;isCellReferenceVisible=!1;currentEditedCell={col:0,row:0,sheetId:this.env.model.getters.getActiveSheetId()};composerStore;composerFocusStore;composerInterface;get defaultRect(){return{x:0,y:0,width:0,height:0}}setup(){const e=rh(HM);this.composerStore=e,this.composerFocusStore=rh(fh),this.composerInterface={id:"gridComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"inactive"}),t.onWillUpdateProps((()=>{this.updateComponentPosition(),this.updateCellReferenceVisibility()}))}get shouldDisplayCellReference(){return!this.env.isMobile()&&this.isCellReferenceVisible}get cellReference(){const{col:e,row:t,sheetId:s}=this.composerStore.currentEditedCell;return ra(s!==this.env.model.getters.getActiveSheetId()?this.env.model.getters.getSheetName(s):void 0,as(e,t))}get cellReferenceStyle(){const{x:e,y:t}=this.rect;return aR({left:e-zM+"px",top:t-28+"px"})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get composerProps(){const{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders(),s=this.props.gridDims.height-this.rect.y-2*zM;return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,isDefaultFocus:!0,onComposerContentFocused:()=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"}),onComposerCellFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"cellFocus",content:e}),onInputContextMenu:this.props.onInputContextMenu,composerStore:this.composerStore,inputStyle:`max-height: ${s}px;`,inputMode:"inactive"===this.composerStore.editionMode?"none":void 0}}get containerStyle(){if("inactive"===this.composerStore.editionMode||this.env.isMobile())return"z-index: -1000; opacity: 0;";const e=Gt(this.composerStore.currentContent),t=this.env.model.getters.getActiveCell(),s=this.env.model.getters.getActivePosition(),o=this.env.model.getters.getCellComputedStyle(s),{x:i,y:n,width:r,height:a}=this.rect,l=!e&&o.fillColor||"#ffffff",c=!e&&o.textColor||"#000000",h=!e&&o.fontSize||10,d=!e&&o.bold?"bold":void 0,u=!e&&o.italic?"italic":"normal",g=e?"none":iR(o);let p="left";e||(p=o.align||t.defaultAlign);const m=this.props.gridDims.height-this.rect.y,f=this.props.gridDims.width-this.rect.x,v=Math.min(a+1,m),b=Math.min(r+1,f);return aR({left:i-1+"px",top:`${n}px`,border:`${zM}px solid ${P}`,"min-width":`${b}px`,"min-height":`${v}px`,"max-width":`${f}px`,"max-height":`${m}px`,background:l,color:c,"font-size":`${Ha(h)}px`,"font-weight":d,"font-style":u,"text-decoration":g,"text-align":p})}updateComponentPosition(){const e="inactive"!==this.composerFocusStore.activeComposer.editionMode;e||this.composerFocusStore.activeComposer===this.composerInterface||this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"inactive"});let t=!St(this.currentEditedCell,this.composerStore.currentEditedCell);if(this.isEditing!==e){if(this.isEditing=e,!e)return void(this.rect=this.defaultRect);this.currentEditedCell=this.composerStore.currentEditedCell,t=!0}if(t){const e=this.env.model.getters.getActivePosition(),t=this.env.model.getters.expandZone(e.sheetId,Us(e));this.rect=this.env.model.getters.getVisibleRect(t)}}updateCellReferenceVisibility(){if("inactive"===this.composerStore.editionMode)return void(this.isCellReferenceVisible=!1);if(this.isCellReferenceVisible)return;const e=this.env.model.getters.getActiveSheetId(),t=Us(this.env.model.getters.getSelection().anchor.cell);St(this.env.model.getters.getVisibleRect(t),this.rect)&&e===this.composerStore.currentEditedCell.sheetId||(this.isCellReferenceVisible=!0)}onFocus(){this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"})}}const GM=5;function WM(e,t,s){return s.map((s=>qM(e,t,!1,s))).filter((s=>function(e,t,s){const{x:o,y:i}=e.getMainViewportCoordinates(),n=[];switch(s.axisType){case"top":case"bottom":case"vCenter":if(t.y<i)return!0;n.push({x:t.x,y:s.position}),n.push({x:t.x+t.width,y:s.position});break;case"left":case"right":case"hCenter":if(t.x<o)return!0;n.push({x:s.position,y:t.y}),n.push({x:s.position,y:t.y+t.height})}return n.some(e.isPixelPositionVisible)}(e,t,s)))}function $M(e,t,s,o,i){const n=s.map((s=>qM(e,t,!0,s)));let r;for(const t of o){const s=WM(e,t,i);for(const e of n)for(const o of s){if(a=e.position,l=o.position,!(Math.abs(a-l)<=GM))continue;const s=e.position-o.position;r&&s===r.snapOffset?r.matchedFigIds.push(t.id):(!r||Math.abs(s)<=Math.abs(r.snapOffset))&&(r={matchedFigIds:[t.id],snapOffset:s,snappedAxisType:e.axisType,position:o.position})}}var a,l;return r}function qM(e,t,s,o){let i=0;const{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo(),{x:a,y:l}=e.getMainViewportCoordinates(),c=!s&&t.y<l?t.y+r:t.y,h=!s&&t.x<a?t.x+n:t.x;switch(o){case"top":i=c;break;case"bottom":i=c+t.height-ye;break;case"vCenter":i=c+Math.floor(t.height/2)-ye;break;case"left":i=h;break;case"right":i=h+t.width-ye;break;case"hCenter":i=h+Math.floor(t.width/2)-ye}return{position:i,axisType:o}}class ZM extends t.Component{static template="o-spreadsheet-FiguresContainer";static props={onFigureDeleted:Function};static components={FigureComponent:IR};dnd=t.useState({draggedFigure:void 0,horizontalSnap:void 0,verticalSnap:void 0,cancelDnd:void 0,overlappingCarousel:void 0});setup(){t.onMounted((()=>{this.render()})),t.onWillUpdateProps((()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.dnd.draggedFigure?.id;t&&!this.env.model.getters.getFigure(e,t)&&(this.dnd.cancelDnd&&this.dnd.cancelDnd(),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0,this.dnd.cancelDnd=void 0)}))}getVisibleFigures(){const e=this.env.model.getters.getVisibleFigures();return this.dnd.draggedFigure&&!e.some((e=>e.id===this.dnd.draggedFigure?.id))&&this.dnd.draggedFigure&&e.push(this.dnd.draggedFigure),e}get containers(){const e=this.getVisibleFigures(),t=[];for(const s of["topLeft","topRight","bottomLeft","bottomRight"]){const o=e.filter((e=>this.getFigureContainer(e)===s));o.length>0&&t.push({type:s,figures:o,style:this.getContainerStyle(s),inverseViewportStyle:this.getInverseViewportPositionStyle(s)})}return this.dnd.draggedFigure&&t.push({type:"dnd",figures:[this.getDndFigure()],style:this.getContainerStyle("dnd"),inverseViewportStyle:this.getInverseViewportPositionStyle("dnd")}),t}getContainerStyle(e){return this.rectToCss(this.getContainerRect(e))}rectToCss(e){return aR({left:`${e.x}px`,top:`${e.y}px`,width:`${e.width}px`,height:`${e.height}px`})}getContainerRect(e){const{width:t,height:s}=this.env.model.getters.getSheetViewDimension(),{x:o,y:i}=this.env.model.getters.getMainViewportCoordinates(),n=["bottomRight","topRight"].includes(e)?o:0,r=t-n,a=["bottomRight","bottomLeft"].includes(e)?i:0;return{x:n,y:a,width:r,height:s-a}}getInverseViewportPositionStyle(e){const{scrollX:t,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo(),{x:o,y:i}=this.env.model.getters.getMainViewportCoordinates();let n=0,r=0;return"dnd"===e&&(n=-t,r=-s),["bottomRight","topRight"].includes(e)&&(n=-t-o),["bottomRight","bottomLeft"].includes(e)&&(r=-s-i),aR({left:`${n}px`,top:`${r}px`})}getFigureContainer(e){const{x:t,y:s}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.draggedFigure?.id?"dnd":e.x<t&&e.y<s?"topLeft":e.x<t?"bottomLeft":e.y<s?"topRight":"bottomRight"}toBottomRightViewport(e){const t=this.getFigureContainer(e),s=this.env.model.getters.getActiveSheetScrollInfo(),o={...e};return["bottomLeft","topLeft"].includes(t)&&(o.x+=s.scrollX),["topLeft","topRight"].includes(t)&&(o.y+=s.scrollY),o}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly())return;if(!this.env.model.dispatch("SELECT_FIGURE",{figureId:e.id}).isSuccessful)return;if(this.env.isMobile())return;const s=this.env.model.getters.getActiveSheetId(),o={x:t.clientX,y:t.clientY},i=this.env.model.getters.getActiveSheetScrollInfo(),n=this.toBottomRightViewport(e),r={maxX:this.env.model.getters.getColDimensions(s,this.env.model.getters.getNumberCols(s)-1).end,maxY:this.env.model.getters.getRowDimensions(s,this.env.model.getters.getNumberRows(s)-1).end};let a=!1;this.dnd.cancelDnd=ax((e=>{const t=this.env.model.getters,s={x:e.clientX,y:e.clientY},l=Math.abs(s.x-o.x),c=Math.abs(s.y-o.y);if(!a&&l<5&&c<5)return;a=!0;const h=function({x:e,y:t},{x:s,y:o},i,{maxX:n,maxY:r},{scrollX:a,scrollY:l},{scrollX:c,scrollY:h}){const d=e-s+c-a,u=Ke(i.x+d,0,n-i.width),g=t-o+h-l,p=Ke(i.y+g,0,r-i.height);return{...i,x:u,y:p}}(s,o,n,r,i,t.getActiveSheetScrollInfo()),d=this.getOtherFigures(n.id),u=this.getCarouselOverlappingChart(h,d);if(this.dnd.overlappingCarousel=u,u)this.dnd.draggedFigure=h,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0;else{const e=function(e,t,s){const o=$M(e,t,["hCenter","right","left"],s,["hCenter","right","left"]),i=$M(e,t,["vCenter","bottom","top"],s,["vCenter","bottom","top"]),{y:n,x:r}=e.getMainViewportCoordinates(),{scrollY:a,scrollX:l}=e.getActiveSheetScrollInfo();if(i){t.y-=i.snapOffset;const e=t.y<n,s=t.y<n;e&&!s?t.y+=a:!e&&s&&(t.y-=a)}if(o){t.x-=o.snapOffset;const e=t.x<r,s=t.x<r;e&&!s?t.x+=l:!e&&s&&(t.x-=l)}return{snappedFigure:t,verticalSnapLine:o,horizontalSnapLine:i}}(t,h,d);this.dnd.draggedFigure=e.snappedFigure,this.dnd.horizontalSnap=this.getSnap(e.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(e.verticalSnapLine)}}),(t=>{if(!this.dnd.draggedFigure)return;const{col:o,row:i,offset:n}=this.env.model.getters.getPositionAnchorOffset(this.dnd.draggedFigure);this.dnd.overlappingCarousel?(this.env.model.dispatch("ADD_FIGURE_CHART_TO_CAROUSEL",{sheetId:s,carouselFigureId:this.dnd.overlappingCarousel.id,chartFigureId:e.id}),this.props.onFigureDeleted()):this.env.model.dispatch("UPDATE_FIGURE",{sheetId:s,figureId:e.id,offset:n,col:o,row:i}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0}))}startResize(e,t,s,o){o.stopPropagation();const i={x:o.clientX,y:o.clientY},n=this.env.model.getters.getActiveSheetScrollInfo(),r=yR.get(e.tag).keepRatio||!1,a=yR.get(e.tag).minFigSize||80,l=this.env.model.getters.getActiveSheetId(),c={maxX:this.env.model.getters.getColDimensions(l,this.env.model.getters.getNumberCols(l)-1).end,maxY:this.env.model.getters.getRowDimensions(l,this.env.model.getters.getNumberRows(l)-1).end};this.dnd.cancelDnd=ax((o=>{const l={x:o.clientX,y:o.clientY},h=function(e,t,s,{x:o,y:i},{x:n,y:r},a,l,{scrollX:c,scrollY:h},{scrollX:d,scrollY:u},{maxX:g,maxY:p}){let{x:m,y:f,width:v,height:b}=e;if(a&&0!==t&&0!==s){const e=Math.min(t*(n-o+d-c),v-l),a=Math.min(s*(r-i+u-h),b-l),g=Math.min(e/v,a/b);t<0&&(m+=v*g),s<0&&(f+=b*g),v*=1-g,b*=1-g}else{const e=Math.max(t*(o-n+d-c),l-v),a=Math.max(s*(i-r+u-h),l-b);v+=e,b+=a,t<0&&(m-=e),s<0&&(f-=a)}return m+d<=0?(v=v+m+d,m=-d):m+v>g&&(v=g-m),f+u<=0?(b=b+f+u,f=-u):f+b>p&&(b=p-f),{...e,x:m,y:f,width:v,height:b}}(e,t,s,l,i,r,a,n,this.env.model.getters.getActiveSheetScrollInfo(),c),d=this.getOtherFigures(e.id),u=function(e,t,s,o,i){const n=$M(e,o,[-1===t?"left":"right"],i,["right","left"]);n&&(1===t?o.width-=n.snapOffset:-1===t&&(o.x-=n.snapOffset,o.width+=n.snapOffset));const r=$M(e,o,[-1===s?"top":"bottom"],i,["bottom","top"]);return r&&(1===s?o.height-=r.snapOffset:-1===s&&(o.y-=r.snapOffset,o.height+=r.snapOffset)),o.x=Math.round(o.x),o.y=Math.round(o.y),o.height=Math.round(o.height),o.width=Math.round(o.width),{snappedFigure:o,verticalSnapLine:n,horizontalSnapLine:r}}(this.env.model.getters,t,s,h,d);this.dnd.draggedFigure=u.snappedFigure,this.dnd.horizontalSnap=this.getSnap(u.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(u.verticalSnapLine)}),(o=>{if(!this.dnd.draggedFigure)return;const i=this.env.model.getters.getPositionAnchorOffset(this.dnd.draggedFigure);t&&(i.width=this.dnd.draggedFigure.width),s&&(i.height=this.dnd.draggedFigure.height),this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),figureId:e.id,...i}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0}))}getOtherFigures(e){return this.getVisibleFigures().filter((t=>t.id!==e))}getDndFigure(){const e=this.dnd.draggedFigure;if(!e)throw new Error("Dnd figure not found");return e}getFigureStyle(e){return e.id!==this.dnd.draggedFigure?.id?"":aR({opacity:this.dnd.overlappingCarousel?.id?"0.6":"0.9",cursor:"grabbing"})}getFigureClass(e){return e.id!==this.dnd.overlappingCarousel?.id?"":"o-add-to-carousel"}getSnap(e){if(!e||!this.dnd.draggedFigure)return;const{scrollX:t,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo(),o=e.matchedFigIds.map((e=>this.getVisibleFigures().find((t=>t.id===e)))).filter(ut).map((e=>({x:e.x-t,y:e.y-s,width:e.width,height:e.height}))).filter(ut),i=function(...e){return hR(Es(...e.map(cR)))}({...this.dnd.draggedFigure,x:this.dnd.draggedFigure.x-t,y:this.dnd.draggedFigure.y-s},...o);return{line:e,containerStyle:this.rectToCss(i),lineStyle:this.getSnapLineStyle(e,i)}}getSnapLineStyle(e,t){if(!e)return"";const{scrollX:s,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo();return["top","vCenter","bottom"].includes(e.snappedAxisType)?aR({top:e.position-t.y-o+"px",left:"0px",width:"100%"}):aR({top:"0px",left:e.position-t.x-s+"px",height:"100%"})}getCarouselOverlappingChart(e,t){if("chart"!==e.tag)return;const s=e.x+e.width/2,o=e.y+e.height/2;let i,n=1/0;for(const r of t){if("carousel"!==r.tag)continue;const t=r.x+r.width/2,a=r.y+r.height/2,l=Math.abs(s-t),c=Math.abs(o-a),h=l**2+c**2;l<=e.width/2&&c<=e.height/2&&h<n&&(n=h,i=r)}return i}}class jM extends t.Component{static template="o-spreadsheet-ValidationMessages";static props={messages:Array,msgType:String,singleBox:{type:Boolean,optional:!0}};get divClasses(){return"warning"===this.props.msgType?"o-validation-warning":"info"===this.props.msgType?"o-validation-info":"o-validation-error"}get alertBoxes(){return this.props.singleBox?[this.props.messages]:this.props.messages.map((e=>[e]))}}class YM extends t.Component{static template="o-spreadsheet-GridAddRowsFooter";static props={focusGrid:Function};static components={ValidationMessages:jM};inputRef=t.useRef("inputRef");state=t.useState({inputValue:"100",errorFlag:!1});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}get addRowsPosition(){const e=this.env.model.getters.getActiveSheetId(),{numberOfRows:t}=this.env.model.getters.getSheetSize(e),{scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo();return aR({top:`${this.env.model.getters.getRowDimensions(e,t-1).end-s}px`})}get errorMessages(){return[Go("Please enter a number between 0 and 10000.")]}onKeydown(e){"ESCAPE"===e.key.toUpperCase()?this.props.focusGrid():"ENTER"===e.key.toUpperCase()&&this.onConfirm()}onInput(e){const t=e.target.value;this.state.inputValue=t;const s=Number(t);this.state.errorFlag=Number.isNaN(s)||s<=0||s>1e4}onConfirm(){if(this.state.errorFlag)return;const e=Number(this.state.inputValue),t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getNumberRows(t);this.env.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:t,sheetName:this.env.model.getters.getSheetName(t),position:"after",base:s-1,quantity:e,dimension:"ROW"}),this.props.focusGrid();const{scrollX:o}=this.env.model.getters.getActiveSheetScrollInfo(),{end:i}=this.env.model.getters.getRowDimensions(t,s+e-1);this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o,offsetY:i})}onExternalClick(e){this.inputRef.el===document.activeElement&&e.target!==this.inputRef.el&&this.props.focusGrid()}}function XM(e,...s){t.useEffect((e=>(e?.addEventListener(...s),()=>e?.removeEventListener(...s))),(()=>[e.el]))}const KM=["cell","border","table","conditionalFormat","merge"];class JM extends ph{mutators=["activate","cancel","pasteFormat"];highlightStore=this.get(XR);status="inactive";copiedData;constructor(e){super(e),this.highlightStore.register(this),this.onDispose((()=>{this.highlightStore.unRegister(this)}))}handle(e){if("PAINT_FORMAT"===e.type)this.paintFormat(e.sheetId,e.target)}activate(e){this.copiedData=this.copyFormats(),this.status=e.persistent?"persistent":"oneOff"}cancel(){this.status="inactive",this.copiedData=void 0}pasteFormat(e){this.model.dispatch("PAINT_FORMAT",{target:e,sheetId:this.getters.getActiveSheetId()})}get isActive(){return"inactive"!==this.status}get clipboardHandlers(){return KM.map((e=>({handlerName:e,handler:new(Jc.cellHandlers.get(e))(this.getters,this.model.dispatch)})))}copyFormats(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones(),s={zones:t,sheetId:e};for(const{handlerName:o,handler:i}of this.clipboardHandlers){const n=i.copy(js(e,t),!1);void 0!==n&&(s[o]=n)}return s}paintFormat(e,t){if(!this.copiedData)return;const s={isCutOperation:!1,pasteOption:"onlyFormat"},{target:o,selectedZones:i}=Qs(e,t,this.copiedData,this.clipboardHandlers,s);Js(this.clipboardHandlers,this.copiedData,o,s),eo(this.model.selection,t,i),"oneOff"===this.status&&this.cancel()}get highlights(){const e=this.copiedData;return e?e.zones.map((t=>({range:this.model.getters.getRangeFromZone(e.sheetId,t),color:P,dashed:!0,sheetId:e.sheetId,noFill:!0,thinLine:!0,interactive:!1}))):[]}}class QM extends ph{mutators=["clear","hover"];col;row;overlayColors=new C_;handle(e){if("ACTIVATE_SHEET"===e.type)this.clear()}hover(e){if(!this.getters.isDashboard()||e.col===this.col&&e.row===this.row)return"noStateChange";this.col=e.col,this.row=e.row,this.computeOverlay()}clear(){this.col=void 0,this.row=void 0}computeOverlay(){this.overlayColors=new C_;const{col:e,row:t}=this;if(void 0===e||void 0===t)return;const s=this.getters.getActiveSheetId(),o=this.getters.getTable({sheetId:s,col:e,row:t});if(!o)return;const{left:i,right:n,top:r}=o.range.zone,a=t<r+o.config.numberOfHeaders,l=Je(i,n+1).some((e=>!this.getters.isColHidden(s,e)&&this.getters.getEvaluatedCell({sheetId:s,col:e,row:t}).formattedValue));if(!a&&l)for(let e=i;e<=n;e++)this.overlayColors.set({sheetId:s,col:e,row:t},"#017E8414")}}class eN extends ph{mutators=["setHoveredIcon"];hoveredIcon=void 0;setHoveredIcon(e){this.hoveredIcon=e}}function tN(e,s){const o=rh(wR),i=rh(QM),n={col:void 0,row:void 0},{Date:r}=window;let a,l,c=0;function h(){if(void 0===a||void 0===l)return{col:-1,row:-1};return{col:e.model.getters.getColIndex(a),row:e.model.getters.getRowIndex(l)}}function d(e){const t=Gy(s.el);return{x:e.clientX-t.x,y:e.clientY-t.y}}const{pause:u,resume:g}=function(e,s){let o;const{setInterval:i,clearInterval:n}=window,r=()=>{n(o),o=void 0},a=()=>{try{e()}catch(e){throw r(),e}};return t.useEffect((()=>(o=i(a,s),()=>n(o))),(()=>[s])),{pause:r,resume:()=>{void 0===o&&(o=i(a,s))}}}((function(){const{col:e,row:t}=h(),s=r.now()-c;s>300&&(e!==n.col||t!==n.row)&&m(void 0,void 0);if(s>300){if(e<0||t<0)return;m(e,t)}}),200);function p(e){Hy(s.el,e)&&(({x:a,y:l}=d(e)),c=r.now(),i.hover(h()))}function m(e,t){e===n.col&&t===n.row||(n.col=e,n.row=t,o.hover({col:e,row:t}))}return XM(s,"pointermove",(t=>!e.isMobile()&&p(t))),XM(s,"mouseleave",(function(e){const{x:t,y:o}=d(e),i=Gy(s.el);return o<0||o>i.height||t<0||t>i.width?p(e):u()})),XM(s,"mouseenter",g),XM(s,"pointerdown",(function(){const{col:e,row:t}=h();e===n.col&&t===n.row||m(void 0,void 0)})),XM(s,"pointerdown",(t=>e.isMobile()&&p(t))),t.useExternalListener(window,"click",(function(e){const t=e.target;s.el.contains(t)||m(void 0,void 0)})),n}class sN extends t.Component{static template="o-spreadsheet-GridOverlay";static props={onCellDoubleClicked:{type:Function,optional:!0},onCellClicked:{type:Function,optional:!0},onCellRightClicked:{type:Function,optional:!0},onGridResized:{type:Function,optional:!0},onFigureDeleted:{type:Function,optional:!0},onGridMoved:Function,gridOverlayDimensions:String,slots:{type:Object,optional:!0},getGridSize:Function};static components={FiguresContainer:ZM,GridAddRowsFooter:YM};static defaultProps={onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{},onFigureDeleted:()=>{}};gridOverlay=t.useRef("gridOverlay");cellPopovers;paintFormatStore;hoveredIconStore;setup(){tN(this.env,this.gridOverlay);const e=new ResizeObserver((()=>{const e=this.gridOverlayEl.getBoundingClientRect(),{width:t,height:s}=this.props.getGridSize();this.props.onGridResized({x:e.left,y:e.top,height:s,width:t})}));t.onMounted((()=>{e.observe(this.gridOverlayEl)})),t.onWillUnmount((()=>{e.disconnect()})),this.cellPopovers=rh(RR),this.paintFormatStore=rh(JM),this.hoveredIconStore=rh(eN)}get gridOverlayEl(){if(!this.gridOverlay.el)throw new Error("GridOverlay el is not defined.");return this.gridOverlay.el}get style(){return this.props.gridOverlayDimensions+aR({cursor:this.hoveredIconStore.hoveredIcon?"pointer":"default"})}get isPaintingFormat(){return this.paintFormatStore.isActive}onPointerMove(e){if(this.env.isMobile())return;const t=this.getInteractiveIconAtEvent(e),s=t?.type?{id:t.type,position:t.position}:void 0;St(s,this.hoveredIconStore.hoveredIcon)||this.hoveredIconStore.setHoveredIcon(s)}onPointerDown(e){e.button>0||this.env.isMobile()||this.onCellClicked(e)}onClick(e){e.button>0||!this.env.isMobile()||this.onCellClicked(e)}onCellClicked(e){const t=this.cellPopovers.persistentCellPopover,[s,o]=this.getCartesianCoordinates(e),i=this.getInteractiveIconAtEvent(e);i&&this.env.model.selection.getBackToDefault(),this.props.onCellClicked(s,o,{expandZone:e.shiftKey,addZone:Xy(e)},e),i?.onClick&&i.onClick(i.position,this.env),e.target===this.gridOverlay.el&&this.cellPopovers.isOpen&&St(t,this.cellPopovers.persistentCellPopover)&&this.cellPopovers.close()}onDoubleClick(e){if(this.getInteractiveIconAtEvent(e))return;const[t,s]=this.getCartesianCoordinates(e);this.props.onCellDoubleClicked(t,s)}onContextMenu(e){const[t,s]=this.getCartesianCoordinates(e);this.props.onCellRightClicked(t,s,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){const t=By(this.gridOverlay),s=e.clientX-t.x,o=e.clientY-t.y;return[this.env.model.getters.getColIndex(s),this.env.model.getters.getRowIndex(o)]}getInteractiveIconAtEvent(e){const t=By(this.gridOverlay),s=this.env.model.getters.getGridOffset(),o=e.clientX-t.x+s.x,i=e.clientY-t.y+s.y,[n,r]=this.getCartesianCoordinates(e),a=this.env.model.getters.getActiveSheetId();let l={col:n,row:r,sheetId:a};const c=this.env.model.getters.getMerge(l);c&&(l={col:c.left,row:c.top,sheetId:a});const h=this.env.model.getters.getCellIcons(l).find((e=>{const t=this.env.model.getters.getMerge(l)||Us(l),s=this.env.model.getters.getRect(t);return function(e,t,s){return e>=s.x&&e<=s.x+s.width&&t>=s.y&&t<=s.y+s.height}(o,i,this.env.model.getters.getCellIconRect(e,s))}));return h?.onClick?h:void 0}}class oN extends t.Component{static template="o-spreadsheet-GridPopover";static props={onClosePopover:Function,onMouseWheel:Function,gridRect:Object};static components={Popover:uR};cellPopovers;setup(){this.cellPopovers=rh(RR)}get cellPopover(){const e=this.cellPopovers.cellPopover;if(!e.isOpen)return{isOpen:!1};const t=e.anchorRect;return{...e,anchorRect:{...t,x:t.x+this.props.gridRect.x,y:t.y+this.props.gridRect.y}}}}class iN extends t.Component{static template="o-spreadsheet-UnhideRowHeaders";static props={headersGroups:Array,headerRange:Object,offset:{type:Number,optional:!0}};static defaultProps={offset:0};get sheetId(){return this.env.model.getters.getActiveSheetId()}getUnhidePreviousButtonStyle(e){const t=this.env.model.getters.getRect(Us({col:0,row:e}));return aR({top:t.y+t.height-se-this.props.offset+"px","margin-right":"1px"})}getUnhideNextButtonStyle(e){return aR({top:this.env.model.getters.getRect(Us({col:0,row:e})).y-se-this.props.offset+"px","margin-right":"1px"})}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.sheetId,dimension:"ROW",elements:e})}isVisible(e){return e>=this.props.headerRange.start&&e<=this.props.headerRange.end}}class nN extends t.Component{static template="o-spreadsheet-UnhideColumnHeaders";static props={headersGroups:Array,headerRange:Object,offset:{type:Number,optional:!0}};static defaultProps={offset:0};get sheetId(){return this.env.model.getters.getActiveSheetId()}getUnhidePreviousButtonStyle(e){const t=this.env.model.getters.getRect(Us({col:e,row:0}));return aR({left:t.x+t.width-oe-this.props.offset+"px"})}getUnhideNextButtonStyle(e){return aR({left:this.env.model.getters.getRect(Us({col:e,row:0})).x-oe-this.props.offset+"px"})}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.sheetId,dimension:"COL",elements:e})}isVisible(e){return e>=this.props.headerRange.start&&e<=this.props.headerRange.end}}class rN extends t.Component{static props={onOpenContextMenu:Function};composerFocusStore;PADDING=0;MAX_SIZE_MARGIN=0;MIN_ELEMENT_SIZE=0;lastSelectedElementIndex=null;state=t.useState({resizerIsActive:!1,isResizing:!1,isMoving:!1,isSelecting:!1,waitingForMove:!1,activeElement:0,draggerLinePosition:0,draggerShadowPosition:0,draggerShadowThickness:0,delta:0,base:0,position:"before"});dragNDropGrid=yM(this.env);setup(){this.composerFocusStore=rh(fh)}_computeHandleDisplay(e){const t=this._getEvOffset(e),s=this._getElementIndex(t);if(s<0)return;const o=this._getDimensionsInViewport(s);t-o.start<this.PADDING&&s!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=o.start,this.state.activeElement=this._getPreviousVisibleElement(s)):o.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=o.end,this.state.activeElement=s):this.state.resizerIsActive=!1}_computeGrabDisplay(e){const t=this._getElementIndex(this._getEvOffset(e)),s=this._getActiveElements(),o=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();s.has(o)&&o<=t&&t<=i?this.state.waitingForMove=!0:this.state.waitingForMove=!1}onMouseMove(e){this.env.isMobile()||this.state.isResizing||this.state.isMoving||this.state.isSelecting||(this._computeHandleDisplay(e),this._computeGrabDisplay(e))}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(e){this._fitElementSize(this.state.activeElement),this.state.isResizing=!1,this._computeHandleDisplay(e),this._computeGrabDisplay(e)}onMouseDown(e){this.state.isResizing=!0,this.state.delta=0;const t=this._getClientPosition(e),s=this.state.draggerLinePosition,o=this._getElementSize(this.state.activeElement),i=s-o+this.MIN_ELEMENT_SIZE,n=this._getMaxSize();ax((e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=s+this.state.delta,this.state.draggerLinePosition<i&&(this.state.draggerLinePosition=i,this.state.delta=this.MIN_ELEMENT_SIZE-o),this.state.draggerLinePosition>n&&(this.state.draggerLinePosition=n,this.state.delta=n-s)}),(e=>{this.state.isResizing=!1,0!==this.state.delta&&this._updateSize()}))}onClick(e){if(!this.env.isMobile())return;if(e.button>0)return;const t=this._getElementIndex(this._getEvOffset(e));this._selectElement(t,!1)}select(e){if(this.env.isMobile())return;if(e.button>0)return;const t=this._getElementIndex(this._getEvOffset(e));t<0||(this.state.waitingForMove?this.env.model.getters.isGridSelectionActive()?this.startMovement(e):this._selectElement(t,!1):("editing"===this.composerFocusStore.activeComposer.editionMode&&this.env.model.selection.getBackToDefault(),this.startSelection(e,t)))}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;const t=this._getDimensionsInViewport(this._getSelectedZoneStart()),s=this._getDimensionsInViewport(this._getSelectedZoneEnd()),o=t.start;this.state.draggerLinePosition=o,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=o,this.state.draggerShadowThickness=s.end-t.start;this.dragNDropGrid.start(e,((e,s)=>{const o="COL"===this._getType()?e:s;if(o>=0){const e=this._getDimensionsInViewport(o);o<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=o,this.state.position="before"):this._getSelectedZoneEnd()<o?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=o,this.state.position="after"):(this.state.draggerLinePosition=t.start,this.state.draggerShadowPosition=t.start,this.state.base=this._getSelectedZoneStart())}}),(()=>{this.state.isMoving=!1,this.state.base!==this._getSelectedZoneStart()&&this._moveElements(),this._computeGrabDisplay(e)}))}startSelection(e,t){if(this.env.isMobile())return;this.state.isSelecting=!0,e.shiftKey?this._increaseSelection(t):this._selectElement(t,Xy(e)),this.lastSelectedElementIndex=t;this.dragNDropGrid.start(e,((e,t)=>{const s="COL"===this._getType()?e:t;s!==this.lastSelectedElementIndex&&-1!==s&&(this._increaseSelection(s),this.lastSelectedElementIndex=s)}),(()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this._computeGrabDisplay(e)}))}onMouseUp(e){this.lastSelectedElementIndex=null}onContextMenu(e){e.preventDefault();const t=this._getElementIndex(this._getEvOffset(e));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);const s=this._getType();this.props.onOpenContextMenu(s,e.clientX,e.clientY)}}class aN extends rN{static props={onOpenContextMenu:Function};static template="o-spreadsheet-ColResizer";static components={UnhideColumnHeaders:nN};colResizerRef;setup(){super.setup(),this.colResizerRef=t.useRef("colResizer"),this.PADDING=15,this.MAX_SIZE_MARGIN=90,this.MIN_ELEMENT_SIZE=5}get sheetId(){return this.env.model.getters.getActiveSheetId()}_getEvOffset(e){return e.offsetX}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().left}_getClientPosition(e){return e.clientX}_getElementIndex(e){return this.env.model.getters.getColIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().left}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().right}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollCol(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getColDimensionsInViewport(this.sheetId,e)}_getElementSize(e){return this.env.model.getters.getColSize(this.sheetId,e)}_getMaxSize(){return this.colResizerRef.el.clientWidth}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),s=this.env.model.getters.getActiveCols();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"COL",sheetId:this.sheetId,elements:s.has(e)?[...s]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),s=this._getSelectedZoneEnd();for(let o=t;o<=s;o++)e.push(o);const o=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.sheetId,sheetName:this.env.model.getters.getActiveSheetName(),dimension:"COL",base:this.state.base,elements:e,position:this.state.position});!o.isSuccessful&&o.reasons.includes("WillRemoveExistingMerge")&&this.env.raiseError(sb)}_selectElement(e,t){this.env.model.selection.selectColumn(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectColumn(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveCols();this.env.model.dispatch("AUTORESIZE_COLUMNS",{sheetId:this.sheetId,cols:t.has(e)?[...t]:[e]})}_getType(){return"COL"}_getActiveElements(){return this.env.model.getters.getActiveCols()}_getPreviousVisibleElement(e){const t=this.sheetId;let s;for(s=e-1;s>=0&&this.env.model.getters.isColHidden(t,s);s--);return s}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.sheetId,elements:e,dimension:"COL"})}get mainUnhideHeadersProps(){const{left:e,right:t}=this.env.model.getters.getActiveMainViewport(),{xSplit:s}=this.env.model.getters.getPaneDivisions(this.sheetId),o=this.env.model.getters.getHiddenColsGroups(this.sheetId),i=o.findIndex((e=>e[0]>=s-1));return{headersGroups:o.slice(i),offset:this.env.model.getters.getMainViewportCoordinates().x,headerRange:{start:e,end:t}}}get frozenUnhideHeadersProps(){const{xSplit:e}=this.env.model.getters.getPaneDivisions(this.sheetId),t=this.env.model.getters.getHiddenColsGroups(this.sheetId),s=t.findIndex((t=>t[0]>=e-1));return{headersGroups:t.slice(0,s+1),headerRange:{start:0,end:e-1}}}get frozenContainerStyle(){return aR({width:this.env.model.getters.getMainViewportCoordinates().x+"px"})}get hasFrozenPane(){return this.env.model.getters.getPaneDivisions(this.sheetId).xSplit>0}}class lN extends rN{static props={onOpenContextMenu:Function};static template="o-spreadsheet-RowResizer";static components={UnhideRowHeaders:iN};setup(){super.setup(),this.rowResizerRef=t.useRef("rowResizer"),this.PADDING=5,this.MAX_SIZE_MARGIN=60,this.MIN_ELEMENT_SIZE=10}rowResizerRef;get sheetId(){return this.env.model.getters.getActiveSheetId()}_getEvOffset(e){return e.offsetY}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().top}_getClientPosition(e){return e.clientY}_getElementIndex(e){return this.env.model.getters.getRowIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().top}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().bottom}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollRow(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getRowDimensionsInViewport(this.sheetId,e)}_getElementSize(e){return this.env.model.getters.getRowSize(this.sheetId,e)}_getMaxSize(){return this.rowResizerRef.el.clientHeight}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),s=this.env.model.getters.getActiveRows();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"ROW",sheetId:this.sheetId,elements:s.has(e)?[...s]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),s=this._getSelectedZoneEnd();for(let o=t;o<=s;o++)e.push(o);const o=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.sheetId,sheetName:this.env.model.getters.getActiveSheetName(),dimension:"ROW",base:this.state.base,elements:e,position:this.state.position});o.isSuccessful||(o.reasons.includes("WillRemoveExistingMerge")?this.env.raiseError(sb):o.reasons.includes("CannotMoveTableHeader")&&this.env.raiseError(ob))}_selectElement(e,t){this.env.model.selection.selectRow(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectRow(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveRows();this.env.model.dispatch("AUTORESIZE_ROWS",{sheetId:this.sheetId,rows:t.has(e)?[...t]:[e]})}_getType(){return"ROW"}_getActiveElements(){return this.env.model.getters.getActiveRows()}_getPreviousVisibleElement(e){const t=this.sheetId;let s;for(s=e-1;s>=0&&this.env.model.getters.isRowHidden(t,s);s--);return s}get mainUnhideHeadersProps(){const{top:e,bottom:t}=this.env.model.getters.getActiveMainViewport(),{ySplit:s}=this.env.model.getters.getPaneDivisions(this.sheetId),o=this.env.model.getters.getHiddenRowsGroups(this.sheetId),i=o.findIndex((e=>e[0]>=s-1));return{headersGroups:o.slice(i),offset:this.env.model.getters.getMainViewportCoordinates().y,headerRange:{start:e,end:t}}}get frozenUnhideHeadersProps(){const{ySplit:e}=this.env.model.getters.getPaneDivisions(this.sheetId),t=this.env.model.getters.getHiddenRowsGroups(this.sheetId),s=t.findIndex((t=>t[0]>=e-1));return{headersGroups:t.slice(0,s+1),headerRange:{start:0,end:e-1}}}get frozenContainerStyle(){return aR({height:this.env.model.getters.getMainViewportCoordinates().y+"px"})}get hasFrozenPane(){return this.env.model.getters.getPaneDivisions(this.sheetId).ySplit>0}}class cN extends t.Component{static props={onOpenContextMenu:Function};static template="o-spreadsheet-HeadersOverlay";static components={ColResizer:aN,RowResizer:lN};selectAll(){this.env.model.selection.selectAll()}}class hN extends ph{fingerprints;hoveredTables;hoveredIcon;lastRenderBoxes=new Map;preventNewAnimationsInNextFrame=!1;zonesWithPreventedAnimationsInNextFrame=[];animations=new Map;constructor(e){super(e),this.getters=e(dh).getters,this.fingerprints=e(y_),this.hoveredTables=e(QM),this.hoveredIcon=e(eN)}handle(e){switch(e.type){case"START":case"ACTIVATE_SHEET":case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":this.animations.clear(),this.preventNewAnimationsInNextFrame=!0;break;case"RESIZE_COLUMNS_ROWS":this.preventNewAnimationsInNextFrame=!0;break;case"REDO":this.zonesWithPreventedAnimationsInNextFrame=[];break;case"UNDO":for(const t of e.commands)if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type||"RESIZE_COLUMNS_ROWS"===t.type){this.animations.clear(),this.preventNewAnimationsInNextFrame=!0;break}break;case"PASTE":this.zonesWithPreventedAnimationsInNextFrame.push(...this.getters.getSelectedZones());break;case"UPDATE_CELL":const t=this.getters.getCommandZones(e);this.zonesWithPreventedAnimationsInNextFrame.push(...t)}}get renderingLayers(){return["Background","Headers"]}drawLayer(e,t,s){switch(t){case"Background":this.drawGlobalBackground(e);const t=this.lastRenderBoxes;this.lastRenderBoxes=new Map;for(const{zone:o,rect:i}of this.getters.getAllActiveViewportsZonesAndRect()){const{ctx:n}=e;n.save(),n.beginPath(),n.rect(i.x,i.y,i.width,i.height),n.clip();const r=this.getGridBoxes(o),a=this.getBoxesWithAnimations(r,t,s);this.drawBackground(e,a),this.drawOverflowingCellBackground(e,a),this.drawCellBackground(e,a),this.drawBorders(e,a),this.drawTexts(e,a),this.drawIcon(e,a),n.restore()}this.drawFrozenPanes(e),this.preventNewAnimationsInNextFrame=!1,this.zonesWithPreventedAnimationsInNextFrame=[];break;case"Headers":this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawGlobalBackground(e){const{ctx:t}=e,{width:s,height:o}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,s+T,o+T)}drawBackground(e,t){const{ctx:s,thinLineWidth:o}=e,i=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),n=i?.1*o:0;if(i)for(const e of t)e.skipCellGridLines||(s.strokeStyle="#E2E3E3",s.lineWidth=o,s.strokeRect(e.x+n,e.y+n,e.width-2*n,e.height-2*n))}drawCellBackground(e,t){const{ctx:s}=e;for(const e of t){const t=e.style;if(t.fillColor&&"#ffffff"!==t.fillColor&&(s.fillStyle=t.fillColor||"#ffffff",s.fillRect(e.x,e.y,e.width,e.height)),e.dataBarFill){s.fillStyle=e.dataBarFill.color;const t=e.dataBarFill.percentage,o=e.width*(t/100);s.fillRect(e.x,e.y,o,e.height)}if(e?.chip){s.save(),s.beginPath(),s.rect(e.x,e.y,e.width,e.height),s.clip();const t=e.chip;s.fillStyle=t.color;const o=10;s.beginPath(),s.roundRect(t.x,t.y,t.width,t.height,o),s.fill(),s.restore()}e.overlayColor&&(s.fillStyle=e.overlayColor,s.fillRect(e.x,e.y,e.width,e.height)),e.isError&&(s.fillStyle="red",s.beginPath(),s.moveTo(e.x+e.width-5,e.y),s.lineTo(e.x+e.width,e.y),s.lineTo(e.x+e.width,e.y+5),s.fill())}}drawOverflowingCellBackground(e,t){const{ctx:s,thinLineWidth:o}=e;for(const e of t)if(e.content&&e.isOverflow){const t=e.content.align||"left";let i,n;const r=e.y+o/2,a=e.height-o,l=Math.min(e.clipRect?.width||1/0,e.content.width);"left"===t?(i=e.x+o/2,n=l-2*o):"right"===t?(i=e.x+e.width-o/2,n=2*o-l):(i=(e.clipRect?.x||e.x+e.width/2-e.content.width/2)+o/2,n=l-2*o),s.fillStyle="#ffffff",s.fillRect(i,r,n,a)}}drawBorders(e,t){const{ctx:s}=e;for(const e of t){const t=e.border;if(t){const{x:s,y:i,width:n,height:r}=e;t.left&&o(t.left,s,i,s,i+r),t.top&&o(t.top,s,i,s+n,i),t.right&&o(t.right,s+n,i,s+n,i+r),t.bottom&&o(t.bottom,s,i+r,s+n,i+r)}}function o({color:e,style:t,opacity:o},i,n,r,a){switch(s.globalAlpha=o??1,s.strokeStyle=e,t){case"medium":s.lineWidth=2,n+=(i+=n===a?-.5:.5)===(r+=n===a?1.5:.5)?-.5:.5,a+=i===r?1.5:.5;break;case"thick":s.lineWidth=3,n===a&&(i--,r++),i===r&&(n--,a++);break;case"dashed":s.lineWidth=1,s.setLineDash([1,3]);break;case"dotted":s.lineWidth=1,n===a&&(i+=.5,r+=.5),i===r&&(n+=.5,a+=.5),s.setLineDash([1,1]);break;default:s.lineWidth=1}s.beginPath(),s.moveTo(i,n),s.lineTo(r,a),s.stroke(),s.lineWidth=1,s.setLineDash([]),s.globalAlpha=1}}drawTexts(e,t){const{ctx:s}=e;let o;s.textBaseline="top";for(const e of t)if(e.content){s.globalAlpha=e.textOpacity??1;const t=e.style||{},i=e.content.align||"left",n=za(t);if(n!==o&&(o=n,s.font=n),s.fillStyle=t.textColor||"#000",s.textAlign=i,e.clipRect){s.save(),s.beginPath();const{x:t,y:o,width:i,height:n}=e.clipRect;s.rect(t,o,i,n),s.clip()}const r=e.content.x;let a=e.content.y;for(const o of e.content.textLines)ja(s,o,{x:r,y:a},t.underline,t.strikethrough),a+=ae+e.content.fontSizePx;e.clipRect&&s.restore(),s.globalAlpha=1}}drawIcon(e,t){const{ctx:s}=e;for(const e of t)for(const t of Object.values(e.icons)){if(!t)continue;const o=St({id:t.type,position:t.position},this.hoveredIcon.hoveredIcon)&&t.hoverSvg||t.svg;if(!o)continue;s.save(),s.globalAlpha=t.opacity??1,s.beginPath();const i=t.clipRect||e;s.rect(i.x,i.y,i.width,i.height),s.clip();const n=t.size,{x:r,y:a}=this.getters.getCellIconRect(t,e);s.translate(r,a),s.scale(n/o.width,n/o.height);for(const e of o.paths)s.fillStyle=e.fillColor,s.fill(OT(e.path));s.restore()}}drawHeaders(e){const{ctx:t,thinLineWidth:s}=e,o=this.getters.getSheetViewVisibleCols(),i=o[0],n=this.getters.getSheetViewVisibleRows(),r=n[0],{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders(),c=this.getters.getSelectedZones(),h=function(e){const t=new Set;for(const s of ls(e))for(const e of Je(s.left,s.right+1))t.add(e);return t}(c),d=function(e){const t=new Set;for(const s of ls(e))for(const e of Je(s.top,s.bottom+1))t.add(e);return t}(c),u=this.getters.getActiveSheetId(),g=this.getters.getNumberCols(u),p=this.getters.getNumberRows(u),m=this.getters.getActiveCols(),f=this.getters.getActiveRows();t.font=`400 11px ${ve}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=s,t.strokeStyle="#333";for(const e of o){const s={left:e,right:e,top:0,bottom:p-1},{x:o,width:i}=this.getters.getVisibleRect(s),n=m.has(e),r=h.has(e);t.fillStyle=n?F:r?_:D,t.fillRect(o,0,i,se)}for(const e of n){const s={top:e,bottom:e,left:0,right:g-1},{y:o,height:i}=this.getters.getVisibleRect(s),n=f.has(e),r=d.has(e);t.fillStyle=n?F:r?_:D,t.fillRect(0,o,oe,i)}t.beginPath(),t.moveTo(oe,0),t.lineTo(oe,l),t.moveTo(0,se),t.lineTo(a,se),t.strokeStyle="#C0C0C0",t.stroke();for(const e of o){const s=Xt(e);t.fillStyle=m.has(e)?"#fff":O;const o={left:e,right:e,top:r,bottom:r},{x:i,width:n}=this.getters.getRect(o),{x:a,width:l}=this.getters.getVisibleRect(o);t.save(),t.beginPath(),t.rect(a,0,l,se),t.clip(),t.fillText(s,i+n/2,13),t.restore(),t.beginPath(),t.moveTo(i+n,0),t.lineTo(i+n,se),t.stroke()}for(const e of n){t.fillStyle=f.has(e)?"#fff":O;const s={top:e,bottom:e,left:i,right:i},{y:o,height:n}=this.getters.getRect(s),{y:r,height:a}=this.getters.getVisibleRect(s);t.save(),t.beginPath(),t.rect(0,r,oe,a),t.clip(),t.fillText(String(e+1),24,o+n/2),t.restore(),t.beginPath(),t.moveTo(0,o+n),t.lineTo(oe,o+n),t.stroke()}}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:s}=e,{x:o,y:i}=this.getters.getMainViewportCoordinates(),n=this.getters.isDashboard()?0:oe,r=this.getters.isDashboard()?0:se;t.lineWidth=6*s,t.strokeStyle="#BCBCBC",t.beginPath(),o&&(t.moveTo(n+o,0),t.lineTo(n+o,r)),i&&(t.moveTo(0,r+i),t.lineTo(n,r+i)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:s}=e,{x:o,y:i}=this.getters.getMainViewportCoordinates(),n=this.getters.getSheetViewVisibleCols(),r=n[0],a=n[n.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:r,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:oe,u=this.getters.isDashboard()?0:se;t.lineWidth=6*s,t.strokeStyle="#DADFE8",t.beginPath(),o&&(t.moveTo(d+o,u),t.lineTo(d+o,h.height+u)),i&&(t.moveTo(d,u+i),t.lineTo(h.width+d,u+i)),t.stroke()}findNextEmptyCol(e,t,s){const o=this.getters.getActiveSheetId();let i=e;for(;i<t;){const e={sheetId:o,col:i+1,row:s},t=this.getters.getEvaluatedCell(e),n=this.getters.getCellComputedBorder(e),a=this.getters.doesCellHaveGridIcon(e);if(t.type!==r.empty||this.getters.isInMerge(e)||n?.left||a)return i;i++}return i}findPreviousEmptyCol(e,t,s){const o=this.getters.getActiveSheetId();let i=e;for(;i>t;){const e={sheetId:o,col:i-1,row:s},t=this.getters.getEvaluatedCell(e),n=this.getters.getCellComputedBorder(e),a=this.getters.doesCellHaveGridIcon(e);if(t.type!==r.empty||this.getters.isInMerge(e)||n?.right||a)return i;i--}return i}computeCellAlignment(e,t){const s=this.getters.getCell(e);if(s?.isFormula&&this.getters.shouldShowFormulas())return"left";const{align:o}=this.getters.getCellStyle(e),i=this.getters.getEvaluatedCell(e);return function(e,t){if(!t)return!1;try{const s=qn(t),{format:o}=ir(e,s);if("text"===o?.type||"date"===o?.type)return o.tokens.some((e=>"REPEATED_CHAR"===e.type));if("number"===o?.type)return o.integerPart.some((e=>"REPEATED_CHAR"===e.type))||!!o.decimalPart&&o.decimalPart.some((e=>"REPEATED_CHAR"===e.type))}catch{}return!1}(i.value,i.format)?"left":t&&i.type===r.number?"center"!==o?"left":o:o||i.defaultAlign}createZoneBox(e,t,s,o){const{left:i,right:n}=s,a=t.left,l=t.top,c={sheetId:e,col:a,row:l},h=this.getters.getEvaluatedCell(c),d=this.getters.shouldShowFormulas(),{x:u,y:g,width:p,height:m}=this.getters.getRect(t),f=this.getters.getDataValidationChipStyle(c),v=this.getters.getCellComputedBorder(c,o);let b=this.getters.getCellComputedStyle(c);if(this.fingerprints.isEnabled){const e=this.fingerprints.colors.get(c);b={...b,fillColor:e}}f?.textColor&&(b={...b,textColor:f.textColor});const S=this.fingerprints.isEnabled?void 0:this.getters.getConditionalDataBar(c),C=this.getters.getCellIcons(c),y={left:C.find((e=>"left"===e?.horizontalAlign)),right:C.find((e=>"right"===e?.horizontalAlign)),center:C.find((e=>"center"===e?.horizontalAlign))},I={id:Ss(t),x:u,y:g,width:p,height:m,border:v||void 0,style:b,dataBarFill:S,overlayColor:this.hoveredTables.overlayColors.get(c),isError:h.type===r.error&&!!h.message||this.getters.isDataValidationInvalid(c),icons:y,disabledAnimation:this.zonesWithPreventedAnimationsInNextFrame.some((e=>_s(t,e)||As(t,e)))},w=Ba(I.style);if(h.type===r.empty||I.icons.center)return I;const E=b.wrapping||"overflow",R="wrap"===E&&!d,x=p-2*ae,T=this.getters.getCellMultiLineText(c,{maxWidth:x,wrapText:R}),A=Math.max(...T.map((e=>this.getters.getTextWidth(e,b)+ae))),D=f?5:0,_=(I.icons.left?I.icons.left.size+I.icons.left.margin:0)+D,F=(I.icons.right?I.icons.right.size+I.icons.right.margin:0)+D,O=_+A+F,P=this.computeCellAlignment(c,O>p),M=T.length,N=Math.round(this.getters.computeTextYCoordinate(I,w,b.verticalAlign,M));let L=I.x;L+="left"===P?ae+_:"right"===P?I.width-ae-F:I.width/2,L=Math.round(L);const k=Oa(w,M);if(I.content={textLines:T,width:"overflow"===E?A:p,align:P,x:L,y:N,fontSizePx:w},f?.fillColor){const e=_,t=5;I.chip={color:f.fillColor,width:I.width-e-t,height:k+2,x:I.x+e,y:N-2}}const V=O>p||w>m;if(I.icons.left||I.icons.right||I.chip)I.clipRect={x:I.x+_,y:I.y,width:Math.max(0,p-_-F),height:m};else if(V&&"overflow"===E){let e,s;switch(this.getters.isInMerge(c)?(e=this.getters.getMerge(c).right,s=a):(e=I.border?.right?t.right:this.findNextEmptyCol(a,n,l),s=I.border?.left?t.left:this.findPreviousEmptyCol(a,i,l),I.isOverflow=!0),P){case"left":{const s=Us({col:e,row:l}),{x:o,y:i,width:n,height:r}=this.getters.getVisibleRect(Es(t,s));(n<O||w>r||T.length>1)&&(I.clipRect={x:o,y:i,width:n,height:r});break}case"right":{const e=Us({col:s,row:l}),{x:o,y:i,width:n,height:r}=this.getters.getVisibleRect(Es(t,e));(n<O||w>r||T.length>1)&&(I.clipRect={x:o,y:i,width:n,height:r});break}case"center":{const o={...t,left:s,right:e},{x:i,y:n,height:r,width:a}=this.getters.getVisibleRect(o),l=O/2,c=I.x+I.width/2;if(i+a<c+l||i>c-l||w>r||T.length>1){const e=i>c-l?i:c-l,t=i+a-e;I.clipRect={x:e,y:n,width:t,height:r}}break}}}else("clip"===E||"wrap"===E||T.length>1)&&(I.clipRect={x:I.x,y:I.y,width:p,height:m});return I}getGridBoxes(e){const t=[],s=this.getters.getSheetViewVisibleCols().filter((t=>t>=e.left&&t<=e.right)),o=s[0],i=s[s.length-1],n=this.getters.getSheetViewVisibleRows().filter((t=>t>=e.top&&t<=e.bottom)),r={left:o,right:i,top:n[0],bottom:n[n.length-1]},a=this.getters.getActiveSheetId();for(const o of n)for(const i of s){const s={sheetId:a,col:i,row:o};this.getters.isInMerge(s)||t.push(this.createZoneBox(a,Us(s),r,e))}for(const s of this.getters.getMerges(a))if(!this.getters.isMergeHidden(a,s)&&As(s,r)){const o=this.createZoneBox(a,s,r,e),i=this.getters.getCellComputedBorder({sheetId:a,col:s.right,row:s.bottom},e);o.border={...o.border,bottom:i?i.bottom:void 0,right:i?i.right:void 0},o.isMerge=!0,t.push(o)}return t}getBoxesWithAnimations(e,t,s){return this.updateAnimationsProgress(s),this.addNewAnimations(e,t,s),this.animations.size>0?(this.renderer.startAnimation("grid_renderer_animation"),this.updateBoxesWithAnimations(e)):(this.renderer.stopAnimation("grid_renderer_animation"),e)}updateBoxesWithAnimations(e){const t=[];for(const s of e){const e=this.animations.get(s.id);if(!e){t.push(s);continue}const o=qe(s);t.push(o);for(const i of e.animationTypes){const n=Xw.get(i).updateAnimation(e.progress,o,e.oldBox,s);n&&t.push(...n.newBoxes)}}return t}updateAnimationsProgress(e){if(void 0!==e)for(const t of this.animations.keys()){const s=this.animations.get(t);if(void 0===s.startTime){s.startTime=e;continue}const o=e-s.startTime,i=Math.min(1,o/200);i>=1&&this.animations.delete(t),s.progress=i}}addNewAnimations(e,t,s){for(const o of e){this.lastRenderBoxes.set(o.id,o);const e=t.get(o.id);if(this.preventNewAnimationsInNextFrame||!e||o.disabledAnimation)continue;const i=[];for(const t of Xw.getAll())t.hasAnimation(e,o)&&i.push(t.id);const n=i.length>0?{animationTypes:i,oldBox:e,progress:0,startTime:s}:void 0;n&&this.animations.set(o.id,n)}}}function dN(e,s,o){const i=t.useRef(e);t.useEffect((function(){const e=i.el,t=window.devicePixelRatio||1,s=e.getContext("2d",{alpha:!1}),r={ctx:s,dpr:t,thinLineWidth:.4*t},{width:a,height:l}=o();if(e.style.width=`${a}px`,e.style.height=`${l}px`,e.width=a*t,e.height=l*t,e.setAttribute("style",`width:${a}px;height:${l}px;`),0===a||0===l)return;s.translate(-.5,-.5),s.scale(t,t),n.draw(r)}));const n=rh(gh);rh(hN)}function uN(e,t,s){let o=0,i=0,n=0,r=0,a=!1,l=0,c=null;function h(){if(Math.abs(n)<.05&&(n=0),Math.abs(r)<.05&&(r=0),!n&&!r)return;const e=Date.now(),s=Math.abs(e-l);t(1*(n*s),1*(r*s)),l=e,n*=.95,r*=.95,requestAnimationFrame(h)}XM(e,"touchstart",(function(e){a=!0,({clientX:o,clientY:i}=e.touches[0]),n=0,r=0}),{capture:!1}),XM(e,"touchmove",(function(e){if(!a)return;c&&(clearTimeout(c),c=null);const h=Date.now(),{clientX:d,clientY:u}=e.touches[0],g=o-d,p=i-u,m=h-l;if(!m)return;n=g/m,r=p/m,o=d,i=u,l=h,s()&&(e.cancelable&&e.preventDefault(),e.stopPropagation());c=setTimeout((()=>{n=0,r=0}),100),t(1*g,1*p)}),{capture:!1}),XM(e,"touchend",(function(e){a=!1,o=i=0,c&&clearTimeout(c);n*=1.2,r*=1.2,requestAnimationFrame(h)}),{capture:!1})}function gN(e){function t(e,t){return e*(0===t?1:ne)}return s=>{const o=t(s.shiftKey&&!Yy()?s.deltaY:s.deltaX,s.deltaMode),i=t(s.shiftKey&&!Yy()?s.deltaX:s.deltaY,s.deltaMode);e(o,i)}}class pN extends t.Component{static template="o-spreadsheet-Border";static props={zone:Object,orientation:String,isMoving:Boolean,onMoveHighlight:Function};get style(){const e=["n","w","e"].includes(this.props.orientation),t=["n","w","s"].includes(this.props.orientation),s=["n","s"].includes(this.props.orientation),o=["w","e"].includes(this.props.orientation),i=this.props.zone,n=this.env.model.getters.getVisibleRect(i),r=n.x,a=n.x+n.width-4,l=n.y,c=n.y+n.height-4;return aR({left:`${t?r:a}px`,top:`${e?l:c}px`,width:`${s?a-r:4}px`,height:`${o?c-l:4}px`})}onMouseDown(e){this.props.onMoveHighlight(e)}}class mN extends t.Component{static template="o-spreadsheet-Corner";static props={zone:Object,color:String,orientation:String,isResizing:Boolean,onResizeHighlight:Function};dirX;dirY;setup(){const{dirX:e,dirY:t}=function(e){const t=e.includes("w")?-1:e.includes("e")?1:0,s=e.includes("n")?-1:e.includes("s")?1:0;return{dirX:t,dirY:s}}(this.props.orientation);this.dirX=e,this.dirY=t}get handlerStyle(){const e=this.props.zone,t=this.env.model.getters.getVisibleRect({left:1===this.dirX?e.right:e.left,right:-1===this.dirX?e.left:e.right,top:1===this.dirY?e.bottom:e.top,bottom:-1===this.dirY?e.top:e.bottom});if(t.width*t.height==0)return"display: none !important;";const s=t.x+t.width/2+this.dirX*t.width/2,o=t.y+t.height/2+this.dirY*t.height/2,i=this.getHandlerEdgeLength(),n={left:s-i/2+"px",top:o-i/2+"px",height:`${i}px`,width:`${i}px`};return this.env.isMobile()&&(n["border-radius"]=i/2+"px"),aR(n)}getHandlerEdgeLength(){return this.env.isMobile()?40:8}get buttonLook(){const e={"background-color":this.props.color,cursor:`${this.props.orientation}-resize`};return this.env.isMobile()&&(e["border-radius"]="4px"),aR(e)}onMouseDown(e){this.props.onResizeHighlight(e,this.dirX,this.dirY)}}class fN extends t.Component{static template="o-spreadsheet-Highlight";static props={range:Object,color:String};static components={Corner:mN,Border:pN};highlightState=t.useState({shiftingMode:"none"});dragNDropGrid=yM(this.env);get cornerOrientations(){if(!this.env.isMobile())return["nw","ne","sw","se"];const e=this.props.range.unboundedZone;return void 0===e.bottom?["w","e"]:void 0===e.right?["n","s"]:["nw","se"]}onResizeHighlight(e,t,s){const o=this.env.model.getters.getActiveSheetId();this.highlightState.shiftingMode="isResizing";const i=this.props.range.zone,n=1===t?i.left:i.right,r=1===s?i.top:i.bottom;let a=1===t?i.right:i.left,l=1===s?i.bottom:i.top,c=i,h="all";this.env.isMobile()&&(h=0===t?"vertical":0===s?"horizontal":"all"),this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{zone:c});this.dragNDropGrid.start(e,((e,t)=>{if(a!==e||l!==t){let{left:s,right:i,top:d,bottom:u}=c;"horizontal"!==h&&(l=l=Ke(-1===t?l:t,0,this.env.model.getters.getNumberRows(o)-1),d=Math.min(r,l),u=Math.max(r,l)),"vertical"!==h&&(a=Ke(-1===e?a:e,0,this.env.model.getters.getNumberCols(o)-1),s=Math.min(n,a),i=Math.max(n,a));const g={left:s,right:i,top:d,bottom:u};xs(g,c)||(this.env.model.selection.selectZone({cell:{col:g.left,row:g.top},zone:g},{unbounded:!0}),c=g)}}),(()=>{this.highlightState.shiftingMode="none"}),h)}onMoveHighlight(e){this.highlightState.shiftingMode="isMoving";const t=this.props.range.zone,s=zy(),o=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getColIndex(e.clientX-s.left),n=this.env.model.getters.getRowIndex(e.clientY-s.top),r=-t.left,a=this.env.model.getters.getNumberCols(o)-t.right-1,l=-t.top,c=this.env.model.getters.getNumberRows(o)-t.bottom-1;let h=t;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{zone:h});let d=i,u=n;this.dragNDropGrid.start(e,((e,s)=>{if(d!==e||u!==s){d=-1===e?d:e,u=-1===s?u:s;const o=Ke(d-i,r,a),g=Ke(u-n,l,c),p={left:t.left+o,top:t.top+g,right:t.right+o,bottom:t.bottom+g};xs(p,h)||(this.env.model.selection.selectZone({cell:{col:p.left,row:p.top},zone:p},{unbounded:!0}),h=p)}}),(()=>{this.highlightState.shiftingMode="none"}))}}class vN extends t.Component{static props={width:{type:Number,optional:!0},height:{type:Number,optional:!0},direction:String,position:Object,offset:Number,onScroll:Function};static template=t.xml`
6
- <div
7
- t-attf-class="o-scrollbar {{props.direction}}"
8
- t-on-scroll="onScroll"
9
- t-ref="scrollbar"
10
- t-att-style="positionCss">
11
- <div t-att-style="sizeCss"/>
12
- </div>
13
- `;static defaultProps={width:1,height:1};scrollbarRef;scrollbar;setup(){this.scrollbarRef=t.useRef("scrollbar"),this.scrollbar=new class{direction;el;constructor(e,t){this.el=e,this.direction=t}get scroll(){return"horizontal"===this.direction?this.el.scrollLeft:this.el.scrollTop}set scroll(e){"horizontal"===this.direction?this.el.scrollLeft=e:this.el.scrollTop=e}}(this.scrollbarRef.el,this.props.direction),t.onMounted((()=>{this.scrollbar.el=this.scrollbarRef.el})),t.useEffect((()=>{this.scrollbar.scroll!==this.props.offset&&(this.scrollbar.scroll=this.props.offset)}),(()=>[this.scrollbar.scroll,this.props.offset]))}get sizeCss(){return aR({width:`${this.props.width}px`,height:`${this.props.height}px`})}get positionCss(){return aR(this.props.position)}onScroll(e){this.props.offset!==this.scrollbar.scroll&&this.props.onScroll(this.scrollbar.scroll)}}class bN extends t.Component{static props={leftOffset:{type:Number,optional:!0}};static components={ScrollBar:vN};static template=t.xml`
14
- <ScrollBar
15
- t-if="isDisplayed"
16
- width="width"
17
- position="position"
18
- offset="offset"
19
- direction="'horizontal'"
20
- onScroll.bind="onScroll"
21
- />`;static defaultProps={leftOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollX}get width(){return this.env.model.getters.getMainViewportRect().width}get isDisplayed(){const{xRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{x:e}=this.env.model.getters.getMainViewportRect();return{left:`${this.props.leftOffset+e}px`,bottom:"0px",height:"15px",right:Qy()?"15px":"0"}}onScroll(e){const{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:e,offsetY:t})}}class SN extends t.Component{static props={topOffset:{type:Number,optional:!0}};static components={ScrollBar:vN};static template=t.xml`
22
- <ScrollBar
23
- t-if="isDisplayed"
24
- height="height"
25
- position="position"
26
- offset="offset"
27
- direction="'vertical'"
28
- onScroll.bind="onScroll"
29
- />`;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:Qy()?"15px":"0"}}onScroll(e){const{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:t,offsetY:e})}}class CN extends t.Component{static template="o-spreadsheet-Selection";static props={};static components={Highlight:fN};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:P}}}function yN({refName:e}){const s=t.useRef(e);t.useEffect((e=>{e?.focus()}),(()=>[s.el]))}class IN 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&&yN({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(ut).join(" ")}}class wN extends t.Component{static template="o-spreadsheet-ActionButton";static props={action:Object,hasTriangleDownIcon:{type:Boolean,optional:!0},selectedColor:{type:String,optional:!0},class:{type:String,optional:!0},onClick:{type:Function,optional:!0}};actionButton=i(this.props.action);setup(){t.onWillUpdateProps((e=>{e.action!==this.props.action&&(this.actionButton=i(e.action))}))}get isVisible(){return this.actionButton.isVisible(this.env)}get isEnabled(){return this.actionButton.isEnabled(this.env)}get isActive(){return this.actionButton.isActive?.(this.env)}get title(){const e=this.actionButton.name(this.env),t=this.actionButton.description(this.env);return e+(t?` (${t})`:"")}get iconTitle(){return this.actionButton.icon(this.env)}onClick(e){this.isEnabled&&(this.props.onClick?.(e),this.actionButton.execute?.(this.env))}get buttonStyle(){return this.props.selectedColor?aR({"border-bottom":`4px solid ${this.props.selectedColor}`,height:"16px","margin-top":"2px"}):""}}class EN 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:cx};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 RN 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:uR};fontSizes=Le;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){Hy(this.fontSizeListRef.el,e)||Hy(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=Ke(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 xN extends t.Component{static template="o-spreadsheet.TextStyler";static components={ColorPickerWidget:EN,ActionButton:wN,FontSizeEditor:RN};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??ue.fontSize}get boldButtonAction(){return{name:Go("Bold"),execute:()=>this.toggleBold(),isActive:()=>this.bold||!1,icon:"o-spreadsheet-Icon.BOLD"}}get italicButtonAction(){return{name:Go("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:Go("Horizontal alignment"),icon:e}}get horizontalAlignActions(){return[{name:Go("Left"),execute:()=>this.updateAlignment("left"),isActive:()=>"left"===this.align,icon:"o-spreadsheet-Icon.ALIGN_LEFT"},{name:Go("Center"),execute:()=>this.updateAlignment("center"),isActive:()=>"center"===this.align,icon:"o-spreadsheet-Icon.ALIGN_CENTER"},{name:Go("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:Go("Vertical alignment"),icon:e}}get verticalAlignActions(){return[{name:Go("Top"),execute:()=>this.updateVerticalAlignment("top"),isActive:()=>"top"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_TOP"},{name:Go("Middle"),execute:()=>this.updateVerticalAlignment("middle"),isActive:()=>"middle"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},{name:Go("Bottom"),execute:()=>this.updateVerticalAlignment("bottom"),isActive:()=>"bottom"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"}]}}class TN extends t.Component{static template="o-spreadsheet-CogWheelMenu";static components={MenuPopover:fR};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=Gy(this.buttonRef.el),this.menuState.menuItems=s(this.props.items))}}class AN extends t.Component{static template="o-spreadsheet-CarouselPanel";static props={onCloseSidePanel:Function,figureId:String};static components={Section:hx,TextInput:IN,TextStyler:xN,CogWheelMenu:TN};DEFAULT_CAROUSEL_TITLE_STYLE=He;dragAndDrop=ux();previewListRef=t.useRef("previewList");setup(){let e=[...this.carouselItems];t.onWillUpdateProps((()=>{St(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 St(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=>St(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=>!St(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=>Gy(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=>St(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 sR(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(DE.getAll().find((e=>e.matcher?.(s)))||DE.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 Go("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:Go("Edit chart"),execute:()=>this.editCarouselItem(e),icon:"o-spreadsheet-Icon.EDIT"}),t.push({name:Go("Pop out chart"),execute:()=>this.popOutCarouselItem(e),icon:"o-spreadsheet-Icon.EXTERNAL"})),t.push({name:Go("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 Go("The data view makes the carousel transparent, revealing the data underneath.")}}class DN extends t.Component{static template="o-spreadsheet.ChartDataSeries";static components={SelectionInput:Sx,Section:hx};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?Go("Data range"):Go("Data series")}}class _N extends t.Component{static template="o-spreadsheet.ChartErrorSection";static components={Section:hx,ValidationMessages:jM};static props={messages:{type:Array,element:String}}}class FN extends t.Component{static template="o-spreadsheet.ChartLabelRange";static components={SelectionInput:Sx,Checkbox:Rx,Section:hx};static props={title:{type:String,optional:!0},range:String,isInvalid:Boolean,onSelectionChanged:Function,onSelectionConfirmed:Function,options:{type:Array,optional:!0}};static defaultProps={title:Go("Categories / Labels"),options:[]}}class ON extends t.Component{static template="o-spreadsheet-GenericChartConfigPanel";static components={ChartDataSeries:DN,ChartLabelRange:FN,Section:hx,Checkbox:Rx,ChartErrorSection:_N};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=eb;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=>eb.Errors[e]||eb.Errors.Unexpected))}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause("InvalidDataSet")}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause("InvalidLabelRange")}get dataSetsHaveTitleLabel(){return"rows"===this.datasetOrientation?Go("Use col %(column_name)s as headers",{column_name:Xt(this.calculateHeaderPosition()||0)}):Go("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(!fs(i))return!1;const o=na(i),n=ps(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=qs(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(!fs(s.dataRange))return;const o=ps(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=my({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=my({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}=na(s),i=o?`${o}!`:"",n=ps(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}${Ss({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}${Ss({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}${Ss({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}${Ss({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=Ca(e,t,this.labelRange),o=DC(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 xE.get(this.props.definition.type).dataSeriesLimit}transposeDataSet(e,t){const s=this.env.model.getters;if(void 0===t)return e.filter(ut).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(!fs(t))return e.filter(ut).map((e=>({dataRange:e})));let{sheetName:s,xc:i}=na(t);s=s??a,o[s]||(o[s]=[]),o[s].push(ms(i))}for(const e in o){const s=qs(o[e]);if("columns"===t)for(const t of s)for(let s=t.left;s<=t.right;s++){const o=`${e===a?"":e+"!"}${Ss({...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+"!"}${Ss({...t,top:s,bottom:s})}`;i.push({dataRange:o})}}return i}}class PN extends ON{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 MN extends t.Component{static template="o-spreadsheet.BadgeSelection";static props={choices:Array,onChange:Function,selectedValue:String}}class NN extends t.Component{static template="o-spreadsheet.ChartTitle";static components={Section:hx,TextStyler:xN};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 LN extends t.Component{static template="o-spreadsheet-AxisDesignEditor";static components={Section:hx,ChartTitle:NN,BadgeSelection:MN};static props={chartId:String,definition:Object,updateChart:Function,axesList:Array};state=t.useState({currentAxis:"x"});defaultFontSize=Q;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=qe(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=qe(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:e},this.props.updateChart(this.props.chartId,{axesDesign:t})}}class kN 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 VN extends t.Component{static template="o-spreadsheet-GeneralDesignEditor";static components={RoundColorPicker:dx,ChartTitle:NN,Section:hx,SidePanelCollapsible:DR,RadioSelection:kN};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function,defaultChartTitleFontSize:{type:Number,optional:!0},slots:{type:Object,optional:!0}};static defaultProps={defaultChartTitleFontSize:J};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 UN extends t.Component{static template="o-spreadsheet-ChartHumanizeNumbers";static components={Checkbox:Rx};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function}}class HN extends t.Component{static template="o-spreadsheet-ChartLegend";static components={Section:hx};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e.target.value})}}class zN extends t.Component{static template="o-spreadsheet-SeriesDesignEditor";static components={SidePanelCollapsible:DR,Section:hx,RoundColorPicker:dx};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=>!$C(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?ro(t):_o(this.state.index,Fo(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 BN extends t.Component{static template="o-spreadsheet-SeriesWithAxisDesignEditor";static components={SeriesDesignEditor:zN,Checkbox:Rx,RadioSelection:kN,Section:hx,RoundColorPicker:dx};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function,slots:{type:Object,optional:!0}};axisChoices=BC;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 Je(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 De}onChangeMovingAverageWindow(e,t){const s=t.target;let o=parseInt(s.value)||De;o<=1&&(o=De),this.updateTrendLineValue(e,{window:o})}getDataSeriesColor(e){const t=this.props.definition.dataSets;if(!t?.[e])return"";const s=t[e].backgroundColor;return s?ro(s):_o(e,Fo(this.props.definition.dataSets.length))}getTrendLineColor(e){return this.getTrendLineConfiguration(e)?.color??So(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 GN extends t.Component{static template="o-spreadsheet-ChartShowValues";static components={Checkbox:Rx};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function,defaultValue:{type:Boolean,optional:!0}}}class WN extends t.Component{static template="o-spreadsheet-ChartWithAxisDesignPanel";static components={GeneralDesignEditor:VN,SidePanelCollapsible:DR,Section:hx,AxisDesignEditor:LN,SeriesWithAxisDesignEditor:BN,ChartLegend:HN,ChartShowValues:GN,ChartHumanizeNumbers:UN};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function};get axesList(){const{useLeftAxis:e,useRightAxis:t}=UC(this.props.definition),s=[{id:"x",name:Go("Horizontal axis")}];return e&&s.push({id:"y",name:Go(t?"Left axis":"Vertical axis")}),t&&s.push({id:"y1",name:Go(e?"Right axis":"Vertical axis")}),s}}class $N extends t.Component{static template="o-spreadsheet-ChartShowDataMarkers";static components={Checkbox:Rx};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function}}class qN extends WN{static template="o-spreadsheet-GenericZoomableChartDesignPanel";static components={...WN.components,Checkbox:Rx};onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}}class ZN extends qN{static template="o-spreadsheet-ComboChartDesignPanel";static components={...qN.components,ChartShowDataMarkers:$N,RadioSelection:kN};seriesTypeChoices=[{value:"bar",label:Go("Bar")},{value:"line",label:Go("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 jN extends t.Component{static template="o-spreadsheet-FunnelChartDesignPanel";static components={ChartShowValues:GN,GeneralDesignEditor:VN,SidePanelCollapsible:DR,RoundColorPicker:dx,Section:hx,ChartHumanizeNumbers:UN};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=ry(e,this.props.definition.funnelColors);return e.map(((e,s)=>({label:e||Go("Value %s",s+1),color:t[s]})))}updateFunnelItemColor(e,t){const s=Pt(this.props.definition.funnelColors||[],t,e);this.props.updateChart(this.props.chartId,{funnelColors:s})}}class YN extends t.Component{static template="o-spreadsheet-GaugeChartConfigPanel";static components={ChartErrorSection:_N,ChartDataSeries:DN};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=>eb.Errors[e]||eb.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 XN extends t.Component{static template="o-spreadsheet-GaugeChartDesignPanel";static components={SidePanelCollapsible:DR,Section:hx,RoundColorPicker:dx,GeneralDesignEditor:VN,ChartErrorSection:_N,StandaloneComposer:tx,ChartHumanizeNumbers:UN};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:qe(this.props.definition.sectionRule)})}get designErrorMessages(){return[...this.state.sectionRuleCancelledReasons||[]].map((e=>eb.Errors[e]||eb.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=qe(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=qe(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:Go("Value"),title:Go("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!==Xi(e,t);const s=this.env.model.getters.evaluateFormula(this.sheetId,e);return!Yl(s)&&void 0!==Xi(Zl(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 KN extends t.Component{static template="o-spreadsheet-GeoChartRegionSelectSection";static components={Section:hx};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 JN extends ON{static template="o-spreadsheet-GeoChartConfigPanel";static components={...ON.components,GeoChartRegionSelectSection:KN};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 QN={minColor:"#FFF5EB",midColor:"#FD8D3C",maxColor:"#7F2704"};class eL extends WN{static template="o-spreadsheet-GeoChartDesignPanel";static components={...WN.components,RoundColorPicker:dx};colorScalesChoices=eb.GeoChart.ColorScales;updateColorScaleType(e){const t=e.target.value;"custom"===t?this.updateColorScale(QN):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 tL extends ON{static template="o-spreadsheet-HierarchicalChartConfigPanel";static components={...ON.components};getLabelRangeOptions(){return[{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}}class sL extends ON{static template="o-spreadsheet-LineConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.chartId);return!!(e&&e instanceof mE)&&kI(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 oL extends qN{static template="o-spreadsheet-LineChartDesignPanel";static components={...qN.components,ChartShowDataMarkers:$N}}class iL extends t.Component{static template="o-spreadsheet.PieHoleSize";static components={Section:hx};static props={onValueChange:Function,value:Number};debouncedOnChange=pt(this.onChange.bind(this),100);onChange(e){isNaN(Number(e))||this.props.onValueChange(Ke(Number(e),0,95))}}class nL extends t.Component{static template="o-spreadsheet-PieChartDesignPanel";static components={GeneralDesignEditor:VN,Section:hx,ChartLegend:HN,ChartShowValues:GN,PieHoleSize:iL,Checkbox:Rx,ChartHumanizeNumbers:UN};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 Hh}}class rL extends t.Component{static template="o-spreadsheet-RadarChartDesignPanel";static components={GeneralDesignEditor:VN,SeriesDesignEditor:zN,Section:hx,ChartLegend:HN,ChartShowValues:GN,ChartShowDataMarkers:$N,Checkbox:Rx,ChartHumanizeNumbers:UN};static props={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function}}class aL extends t.Component{static template="o-spreadsheet-ScorecardChartConfigPanel";static components={SelectionInput:Sx,ChartErrorSection:_N,Section:hx};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=>eb.Errors[e]||eb.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 lL extends t.Component{static template="o-spreadsheet-ScorecardChartDesignPanel";static components={GeneralDesignEditor:VN,RoundColorPicker:dx,SidePanelCollapsible:DR,Section:hx,Checkbox:Rx,ChartTitle:NN,ChartHumanizeNumbers:UN};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};get colorsSectionTitle(){return"progress"===this.props.definition.baselineMode?Go("Progress bar colors"):Go("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 cL extends t.Component{static template="o-spreadsheet-SunburstChartDesignPanel";static components={GeneralDesignEditor:VN,Section:hx,SidePanelCollapsible:DR,ChartShowValues:GN,Checkbox:Rx,TextStyler:xN,RoundColorPicker:dx,ChartLegend:HN,PieHoleSize:iL};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};defaults=yw;get showValues(){return this.props.definition.showValues??yw.showValues}get showLabels(){return this.props.definition.showLabels??yw.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=qe(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 hL extends t.Component{static template="o-spreadsheet-TreeMapCategoryColors";static components={Checkbox:Rx,RoundColorPicker:dx};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){const e=this.props.definition.coloringOptions??YC.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=qe(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 dL extends t.Component{static template="o-spreadsheet-TreeMapColorScale";static components={RoundColorPicker:dx};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){const e=this.props.definition.coloringOptions??YC.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 uL={type:"colorScale",minColor:"#FFF5EB",midColor:"#FD8D3C",maxColor:"#7F2704"},gL={type:"categoryColor",colors:[],useValueBasedGradient:!0};class pL extends t.Component{static template="o-spreadsheet-TreeMapChartDesignPanel";static components={GeneralDesignEditor:VN,Section:hx,SidePanelCollapsible:DR,ChartShowValues:GN,Checkbox:Rx,TextStyler:xN,RoundColorPicker:dx,BadgeSelection:MN,TreeMapCategoryColors:hL,TreeMapColorScale:dL};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};savedColors={categoryColors:gL,colorScale:uL};defaults=YC;get showHeaders(){return this.props.definition.showHeaders??YC.showHeaders}get showValues(){return this.props.definition.showValues??YC.showValues}get showLabels(){return this.props.definition.showLabels??YC.showLabels}get coloringOptions(){return this.props.definition.coloringOptions??YC.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:Go("Category color"),value:"categoryColor"},{label:Go("Color scale"),value:"colorScale"}]}}class mL extends t.Component{static template="o-spreadsheet-WaterfallChartDesignPanel";static components={GeneralDesignEditor:VN,ChartShowValues:GN,Checkbox:Rx,SidePanelCollapsible:DR,Section:hx,RoundColorPicker:dx,AxisDesignEditor:LN,RadioSelection:kN,ChartLegend:HN,ChartHumanizeNumbers:UN};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:{type:Function,optional:!0}};axisChoices=BC;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:Go("Horizontal axis")},{id:"y",name:Go("Vertical axis")}]}get positiveValuesColor(){return this.props.definition.positiveValuesColor||H}get negativeValuesColor(){return this.props.definition.negativeValuesColor||z}get subTotalValuesColor(){return this.props.definition.subTotalValuesColor||B}updateVerticalAxisPosition(e){this.props.updateChart(this.props.chartId,{verticalAxisPosition:e})}onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}}const fL=new n;fL.add("line",{configuration:sL,design:oL}).add("scatter",{configuration:class extends ON{static template="o-spreadsheet-ScatterConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.chartId);return!!(e&&e instanceof yE)&&kI(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:qN}).add("bar",{configuration:PN,design:qN}).add("combo",{configuration:ON,design:ZN}).add("pie",{configuration:ON,design:nL}).add("gauge",{configuration:YN,design:XN}).add("scorecard",{configuration:aL,design:lL}).add("waterfall",{configuration:ON,design:mL}).add("pyramid",{configuration:ON,design:WN}).add("radar",{configuration:ON,design:rL}).add("sunburst",{configuration:tL,design:cL}).add("geo",{configuration:JN,design:eL}).add("funnel",{configuration:class extends ON{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:jN}).add("treemap",{configuration:tL,design:pL});class vL extends t.Component{static template="o-spreadsheet-ChartTypePicker";static components={Section:hx,Popover:uR};static props={chartId:String,chartPanelStore:Object};categories=AE;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 DE.getAll())this.chartTypeByCategories[e.category]?this.chartTypeByCategories[e.category].push(e):this.chartTypeByCategories[e.category]=[e]}onExternalClick(e){Hy(this.popoverRef.el?.parentElement,e)||Hy(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 DE.getAll().find((t=>t.matcher?.(e)||!1))||DE.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=aR({width:`${i}px`})}closePopover(){this.state.popoverProps=void 0}}class bL extends ph{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)=>St(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=DE.get(t);return{...xE.get(s.chartType).getChartDefinitionFromContextCreation(this.creationContexts[e]),...s.subtypeDefinition}}}class SL extends t.Component{static template="o-spreadsheet-ChartPanel";static components={Section:hx,ChartTypePicker:vL};static props={onCloseSidePanel:Function,chartId:String};panelContentRef;scrollPositions={configuration:0,design:0};store;get chartId(){return this.props.chartId}setup(){this.store=ah(bL),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=fL.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 CL extends t.Component{static template="o-spreadsheet-IconPicker";static props={onIconPicked:Function};icons=DT;iconSets=_T;onIconClick(e){e&&this.props.onIconPicked(e)}}function yL(e,s){const o=function(e){const s=t.useState({hovered:!1});return XM(e,"mouseenter",(()=>s.hovered=!0)),XM(e,"mouseleave",(()=>s.hovered=!1)),s}(e);IL({get highlights(){return o.hovered?s.highlights:[]}})}function IL(e){const s=nh(),o=ah(XR);t.onMounted((()=>{o.register(e)}));let i=e.highlights;t.useEffect((e=>{St(e,i)||(i=e,s.trigger("store-updated"))}),(()=>[e.highlights]))}class wL extends t.Component{static template="o-spreadsheet-ConditionalFormatPreview";icons=DT;ref=t.useRef("cfPreview");setup(){yL(this.ref,this)}getPreviewImageStyle(){const e=this.props.conditionalFormat.rule;if("CellIsRule"===e.type)return aR(nR(e.style));if("ColorScaleRule"===e.type){const t=io(e.minimum.color),s=e.midpoint?io(e.midpoint.color):null,o=io(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, ${io(e.color)} 50%, white 50%)`}return""}getDescription(){const e=this.props.conditionalFormat;switch(e.rule.type){case"CellIsRule":return FR.get(e.rule.operator).getPreview({...e.rule,type:e.rule.operator},this.env.model.getters);case"ColorScaleRule":return Qv.ColorScale;case"IconSetRule":return Qv.IconSet;case"DataBarRule":return Qv.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:A,fillAlpha:.06})))}}wL.props={conditionalFormat:Object,onPreviewClick:Function,onMouseDown:Function,class:String};class EL extends t.Component{static template="o-spreadsheet-ConditionalFormatPreviewList";static props={conditionalFormats:Array,onPreviewClick:Function,onAddConditionalFormat:Function};static components={ConditionalFormatPreview:wL};icons=DT;dragAndDrop=ux();cfListRef=t.useRef("cfList");setup(){t.onWillUpdateProps((e=>{St(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=>Gy(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 RL extends t.Component{static template="o-spreadsheet-ConditionalFormattingEditor";static props={editedCf:Object,onCancel:Function,onExit:Function,isNewCf:Boolean};static components={SelectionInput:Sx,IconPicker:CL,ColorPickerWidget:EN,ConditionalFormatPreviewList:EL,Section:hx,RoundColorPicker:dx,StandaloneComposer:tx,BadgeSelection:MN,ValidationMessages:jM,SelectMenu:wx};icons=DT;iconSets=_T;getTextDecoration=iR;colorNumberToHex=io;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=>Qv.Errors[e]||Qv.Errors.Unexpected))}get cfTypesValues(){return[{value:"CellIsRule",label:Go("Single color")},{value:"ColorScaleRule",label:Go("Color scale")},{value:"IconSetRule",label:Go("Icon set")},{value:"DataBarRule",label:Go("Data bar")}]}updateConditionalFormat(e){const t=e.ranges||this.state.ranges;if(this.state.ranges.some((e=>!e.match(ea))))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:Tl(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:lA("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=Av({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 Ix((e=>this.editOperator(e)),C)}get selectedCriterionName(){return FR.get(this.state.rules.cellIs.operator).name}get criterionComponent(){return yx.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(!ao(t))return;const s=this.state.rules.colorScale[e];s&&(s.color=no(t)),this.updateConditionalFormat({rule:this.state.rules.colorScale}),this.closeMenus()}getPreviewGradient(){const e=this.state.rules.colorScale,t=io(e.minimum.color),s=io(e.midpoint?.color||N),o=io(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 io(e?e.color:N)}onMidpointChange(e){const t=e.target.value,s=this.state.rules.colorScale;s.midpoint="none"===t?void 0:{color:N,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:Go("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:Go("Formula"),defaultStatic:!0,invalid:s,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getRangeValues(){return[this.state.rules.dataBar.rangeValues||""]}updateDataBarColor(e){ao(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 xL extends t.Component{static template="o-spreadsheet-ConditionalFormattingPanel";static props={selection:{type:Object,optional:!0},onCloseSidePanel:Function};static components={ConditionalFormatPreviewList:EL,ConditionalFormattingEditor:RL,Section:hx};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:Al(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 TL=new n;class AL extends t.Component{static template="o-spreadsheet-CustomCurrencyPanel";static components={Section:hx,Checkbox:Rx};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=br(e);if((e.symbol||e.code)&&!a.has(t))return a.add(t),{format:t,accountingFormat:Sr(e),example:or(1e3,{format:t,locale:l})}})).filter(ut)}get isSameFormat(){return!!this.selectedFormat&&this.selectedFormat===this.getCommonFormat()}async updateAvailableCurrencies(){if(0===TL.getAll().length){(await(this.env.loadCurrencies?.())||[]).forEach(((e,t)=>{TL.add(t.toString(),e)}))}const e={name:tb.Custom,code:"",symbol:"",decimalPlaces:2,position:"after"};this.availableCurrencies=[e,...TL.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:Go("positive")+":",value:or(1234.56,{format:e,locale:t})},{label:Go("negative")+":",value:or(-1234.56,{format:e,locale:t})},{label:Go("zero")+":",value:or(0,{format:e,locale:t})}]}get selectedFormat(){const e=this.formatProposals[this.state.selectedFormatIndex];return this.state.isAccountingFormat?e?.accountingFormat:e?.format}}class DL extends t.Component{static template="o-spreadsheet-DataValidationEditor";static components={SelectionInput:Sx,SelectMenu:wx,Section:hx,ValidationMessages:jM};static props={rule:{type:Object,optional:!0},onExit:Function,onCloseSidePanel:{type:Function,optional:!0}};state=t.useState({rule:this.defaultDataValidationRule,errors:[]});setup(){if(this.props.rule){const e=this.env.model.getters.getActiveSheetId();this.state.rule={...this.props.rule,ranges:this.props.rule.ranges.map((t=>this.env.model.getters.getRangeString(t,e)))},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=FR.get(s.type),i=this.env.model.getters.getActiveSheetId(),n=s.values.slice(0,o.numberOfValues(s)).map((e=>e?.trim())).filter((e=>""!==e&&void 0!==e)).map((e=>Cl(e,t)));return e.criterion={...s,values:n},{sheetId:i,ranges:this.state.rule.ranges.map((e=>this.env.model.getters.getRangeDataFromXc(i,e))),rule:e}}get dvCriterionMenuItems(){return Ix((e=>this.onCriterionTypeChanged(e)),y)}get selectedCriterionName(){const e=this.state.rule.criterion.type;return FR.get(e).name}get defaultDataValidationRule(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones().map((t=>Ss(this.env.model.getters.getUnboundedZone(e,t))));return{id:this.env.model.uuidGenerator.smallUuid(),criterion:{type:"containsText",values:[""]},ranges:t}}get criterionComponent(){return yx.get(this.state.rule.criterion.type).component}get errorMessages(){return this.state.errors.map((e=>rb.Errors[e]||rb.Errors.Unexpected))}}class _L extends t.Component{static template="o-spreadsheet-DataValidationPreview";static props={onClick:Function,rule:Object};ref=t.useRef("dvPreview");setup(){yL(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:A,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 FR.get(this.props.rule.criterion.type).getPreview(this.props.rule.criterion,this.env.model.getters)}}class FL extends t.Component{static template="o-spreadsheet-DataValidationPanel";static props={onCloseSidePanel:Function};static components={DataValidationPreview:_L,DataValidationEditor:DL};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 Dl(e,this.env.model.getters.getLocale())}get validationRules(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getDataValidationRules(e)}}const OL="#8B008B";var PL;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(PL||(PL={}));class ML extends ph{mutators=["updateSearchOptions","updateSearchContent","searchFormulas","selectPreviousMatch","selectNextMatch","replace"];allSheetsMatches=[];activeSheetMatches=[];specificRangeMatches=[];currentSearchRegex=null;initialShowFormulaState;preserveSelectedMatchIndex=!1;irreplaceableMatchCount=0;isSearchDirty=!1;shouldFinalizeUpdateSelection=!1;notificationStore=this.get(KR);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(XR);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(PL.previous,{jumpToMatchSheet:!0,updateSelection:!0})}selectNextMatch(){this.selectNextCell(PL.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=Lt(this.toSearch,this.searchOptions),this.refreshSearch({jumpToMatchSheet:!0,updateSelection:!0})}refreshSearch(e){this.preserveSelectedMatchIndex||(this.selectedMatchIndex=null),this.findMatches(),this.selectNextCell(PL.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&&Ds(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:Go("Match(es) cannot be replaced as they are part of a formula.")}):this.notificationStore.notifyUser({type:"warning",sticky:!1,text:Go("%(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=Lt(t,o),r=new RegExp(n.source,n.flags+"g"),a=Sl(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=Us(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:OL,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:OL,noFill:!0,thinLine:!0})}return e}}class NL extends t.Component{static template="o-spreadsheet-FindAndReplacePanel";static components={SelectionInput:Sx,Section:hx,Checkbox:Rx,ValidationMessages:jM};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 Go("%s matches in all sheets",this.store.allSheetMatchesCount)}get currentSheetMatchesCount(){return Go("%(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 Go("%(matches)s matches in range %(range)s of %(sheetName)s",{matches:this.store.specificRangeMatchesCount,range:Ss(s),sheetName:this.env.model.getters.getSheetName(t)})}get searchInfo(){return this.store.toSearch?[this.specificRangeMatchesCount,this.currentSheetMatchesCount,this.allSheetsMatchesCount]:[]}setup(){this.store=ah(ML),this.state=t.useState({dataRange:""}),t.onMounted((()=>this.searchInput.el?.focus())),t.onWillUnmount((()=>this.updateSearchContent.stopDebounce())),this.updateSearchContent=pt(this.store.updateSearchContent,200),t.useExternalListener(window,"keydown",(e=>{const t=jy(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 LL=s([_P,FP,OP,PP,MP,NP,LP,kP,VP,wP,EP,RP,xP,TP,AP]);class kL extends t.Component{static template="o-spreadsheet-MoreFormatsPanel";static props={onCloseSidePanel:Function};get dateFormatsActions(){return LL}}class VL extends ph{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=qe(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=dO),{type:e,fieldNameWithGranularity:t,value:s??dO}}}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:Gc(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:dO,label:Go("(previous)")},{value:uO,label:Go("(next)")}],s=this.fields.find((t=>t.nameWithGranularity===e));if(!s)return[];return[...t,...this.getters.getPivot(this.pivotId).getPossibleFieldValues(s)]}cancelMeasureDisplayEdition(){const e=qe(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 UL extends t.Component{static template="o-spreadsheet-PivotMeasureDisplayPanel";static props={onCloseSidePanel:Function,pivotId:String,measure:Object};static components={Section:hx,Checkbox:Rx,RadioSelection:kN};measureDisplayTypeLabels=lb.labels;measureDisplayDescription=lb.documentation;store;setup(){this.store=ah(VL,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 HL(e,t){const s=e.getActiveSheetId(),o=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 qs(o.map(Us)).map((t=>({range:e.getRangeFromZone(s,t),noFill:!0,color:A})))}class zL extends t.Component{static template="o-spreadsheet-PivotDeferUpdate";static props={deferUpdate:Boolean,isDirty:Boolean,toggleDeferUpdate:Function,discard:Function,apply:Function};static components={Section:hx,Checkbox:Rx};get deferUpdatesLabel(){return Go("Defer updates")}get deferUpdatesTooltip(){return Go("Changing the pivot definition requires to reload the data. It may take some time.")}}class BL extends t.Component{static template="o-spreadsheet-PivotCustomGroupsCollapsible";static props={pivotId:String,customField:Object,onCustomFieldUpdated:Function};static components={SidePanelCollapsible:DR,TextInput:IN,Checkbox:Rx};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:$c(Go("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=qe(this.props.customField.groups),o=s[e];o&&(o.name=$c(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 GL(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 WL extends t.Component{static template="o-spreadsheet-AddDimensionButton";static components={Popover:uR,TextValueProvider:HR};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=ah(JR),this.autoComplete.useProvider(this.getProvider()),t.useExternalListener(window,"click",(e=>{e.target!==this.buttonRef.el&&(this.popover.isOpen=!1)})),yN({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?Fa(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:GL(this.search.input,t,V,"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 $L 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:TN,TextInput:IN};updateName(e){this.props.onNameUpdated?.(this.props.dimension,""===e||e.startsWith("=")?void 0:e)}}class qL extends t.Component{static template="o-spreadsheet-PivotDimensionGranularity";static props={dimension:Object,onUpdated:Function,availableGranularities:Set,allGranularities:Array};periods=_c}class ZL extends t.Component{static template="o-spreadsheet-PivotDimensionOrder";static props={dimension:Object,onUpdated:Function}}class jL extends t.Component{static template="o-spreadsheet-PivotMeasureEditor";static components={PivotDimension:$L,StandaloneComposer:tx};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=Ye(e.id);return{text:t,description:e.displayName,htmlContent:[{value:t,color:ee}],fuzzySearchKey:e.displayName+t+e.fieldName}})),i=e.rows.concat(e.columns).map((e=>{const t=Ye(e.nameWithGranularity);return{text:t,description:e.displayName,htmlContent:[{value:t,color:ee}],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=je(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))?ee:void 0}get isCalculatedMeasureInvalid(){return gC(this.props.measure.computedBy?.formula??"").isBadExpression}}class YL extends t.Component{static template="o-spreadsheet-PivotSortSection";static components={Section:hx};static props={definition:Object,pivotId:String};get hasValidSort(){const e=this.env.model.getters.getPivot(this.props.pivotId);return!!this.props.definition.sortedColumn&&Wc(this.props.definition.sortedColumn,e)}get sortDescription(){const e="asc"===this.props.definition.sortedColumn?.order?Go("ascending"):Go("descending");return Go("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=or(e,{format:r,locale:s}),l=t.definition.getDimension(n.field);i.push({field:Gc(l),value:a})}0===e.domain.length&&i.push({value:Go("Total")});const n=t.getMeasure(e.measure).displayName;return i.push({value:n,field:Go("Measure")}),i}}class XL extends t.Component{static template="o-spreadsheet-PivotLayoutConfigurator";static components={AddDimensionButton:WL,PivotDimension:$L,PivotDimensionOrder:ZL,PivotDimensionGranularity:qL,PivotMeasureEditor:jL,PivotSortSection:YL,PivotCustomGroupsCollapsible:BL};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=ux();AGGREGATORS=Tc;composerFocus;isDateOrDatetimeField=Pc;setup(){this.composerFocus=rh(fh)}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(ut),rows:n.map((e=>a.find((t=>t.nameWithGranularity===e)))).filter(ut)})}})}getGranularitiesFor(e){return Pc(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(ut)})}})}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?Gc(o):"";return lb.descriptions[t.type](i)}getHugeDimensionErrorMessage(e){const t=this.env.model.getters.getPivot(this.props.pivotId).getPossibleFieldValues(e);return t.length>100?Go("This dimension contains a lot of values (%s), and might slow down the pivot table.",t.length):void 0}}class KL extends t.Component{static template="o-spreadsheet-PivotTitleSection";static components={CogWheelMenu:TN,Section:hx,TextInput:IN};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:Go("Flip axes"),icon:"o-spreadsheet-Icon.EXCHANGE",execute:this.props.flipAxis},{name:Go("Duplicate"),icon:"o-spreadsheet-Icon.COPY",execute:()=>this.duplicatePivot()},{name:Go("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?Go("Pivot duplicated."):s.isCancelledBecause("PivotInError")?Go("Cannot duplicate a pivot in error."):Go("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(Go("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}})}}const JL=["PIVOT.VALUE","PIVOT.HEADER","PIVOT"];function QL(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:Ge.STRING}],fuzzySearchKey:o}}function ek(e){const t=e.functionContext?.args[0];if(t&&["STRING","NUMBER"].includes(t.type))return t.value}function tk(e){return bC(e,JL)[0]}function sk(e){return bC(e,JL).length}class ok extends ph{pivotId;mutators=["reset","deferUpdates","applyUpdate","discardPendingUpdate","update"];updatesAreDeferred;draft=null;notification=this.get(KR);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=HO.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:Go("Count"),type:"integer",aggregator:"sum"}],t=this.fields;for(const s in t){const o=t[s];o&&(HO.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&&(HO.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=>Pc(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 HO.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return HO.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:Go("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>Ve&&(this.alreadyNotifiedForPivotSize=!0,this.notification.notifyUser({type:"warning",text:cb(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&&St(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=tk(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=qe(s),n=qe(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))&&St(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 ik extends t.Component{static template="o-spreadsheet-PivotSpreadsheetSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:XL,Section:hx,SelectionInput:Sx,Checkbox:Rx,PivotDeferUpdate:zL,PivotTitleSection:KL};store;state;pivotSidePanelRef=t.useRef("pivotSidePanel");setup(){this.store=ah(ok,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 nk=new n;nk.add("SPREADSHEET",{editor:ik});class rk extends t.Component{static template="o-spreadsheet-PivotSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:XL,Section:hx};setup(){IL(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 nk.get(e.type).editor}get highlights(){return HL(this.env.model.getters,this.props.pivotId)}}class ak extends t.Component{static template="o-spreadsheet-RemoveDuplicatesPanel";static components={ValidationMessages:jM,Section:hx,Checkbox:Rx};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=Go("Column %s",Xt(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(nb.Errors[s]||nb.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){const e=Fs(this.env.model.getters.getSelectedZone());return Go("%(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 lk extends t.Component{static template="o-spreadsheet-SettingsPanel";static components={Section:hx,ValidationMessages:jM,BadgeSelection:MN};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=bl(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t})).sort(((e,t)=>e.name.localeCompare(t.name)))}get numberFormatPreview(){return or(1234567.89,{format:"#,##0.00",locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){const e=this.env.model.getters.getLocale();return or(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){const e=this.env.model.getters.getLocale();return or(1.6,{format:Ol(e),locale:e})}get firstDayOfWeek(){const e=this.env.model.getters.getLocale().weekStart;return tr[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(!St(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 ck={SplitIsDestructive:Go("This will overwrite data in the subsequent columns. Split anyway?")};const hk=[{name:Go("Detect automatically"),value:"auto"},{name:Go("Custom separator"),value:"custom"},{name:Go("Space"),value:" "},{name:Go("Comma"),value:","},{name:Go("Semicolon"),value:";"},{name:Go("Line Break"),value:Ne}];class dk extends t.Component{static template="o-spreadsheet-SplitIntoColumnsPanel";static components={ValidationMessages:jM,Section:hx,Checkbox:Rx};static props={onCloseSidePanel:Function};state=t.useState({separatorValue:"auto",addNewColumns:!1,customSeparator:""});setup(){const e=rh(fh);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(ck.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(ib.Errors[s]||ib.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(ib.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 hk}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}}function uk(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 gk extends t.Component{static template="o-spreadsheet-TableStylePreview";static components={MenuPopover:fR};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=>{St(this.props.tableConfig,e.tableConfig)&&St(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;uk(t,Q_(e.tableConfig,e.tableStyle,5,5),(s-1)/5,(o-1)/5)}onContextMenu(e){var t,o;this.props.styleId&&(this.menu.menuItems=(t=this.env,o=this.props.styleId,t.model.getters.isTableStyleEditable(o)?s([{id:"editTableStyle",name:Go("Edit table style"),execute:e=>e.openSidePanel("TableStyleEditorPanel",{styleId:o}),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.EDIT"},{id:"deleteTableStyle",name:Go("Delete table style"),execute:e=>e.model.dispatch("REMOVE_TABLE_STYLE",{tableStyleId:o}),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 pk extends t.Component{static template="o-spreadsheet-TableStylesPopover";static components={Popover:uR,TableStylePreview:gk};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0}};categories=Jx;tableStyleListRef=t.useRef("tableStyleList");state=t.useState({selectedCategory:this.initialSelectedCategory});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!Hy(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 mk extends t.Component{static template="o-spreadsheet-TableStylePicker";static components={TableStylesPopover:pk,TableStylePreview:gk};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 fk extends t.Component{static template="o-spreadsheet-TablePanel";static components={TableStylePicker:mk,SelectionInput:Sx,ValidationMessages:jM,Checkbox:Rx,Section:hx};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(X_(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(X_(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===Gs(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=X_(a);this.env.model.selection.selectZone({zone:Us(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=>ab.Errors[e]||ab.Errors.Unexpected))}getCheckboxLabel(e){return ab.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:ab.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 ab.Tooltips.isDynamic}}const vk="#3C78D8";class bk extends t.Component{static template="o-spreadsheet-TableStyleEditorPanel";static components={Section:hx,RoundColorPicker:dx,TableStylePreview:gk};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||vk,selectedTemplateName:e?.templateName||"lightColoredText",styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=ao(e)?e:vk,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 aR({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(fT).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 vT(this.state.styleName,e,this.state.primaryColor)}}const Sk=new n;Sk.add("ConditionalFormatting",{title:Go("Conditional formatting"),Body:xL}),Sk.add("ChartPanel",{title:Go("Chart"),Body:SL,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}}}),Sk.add("FindAndReplace",{title:Go("Find and Replace"),Body:NL}),Sk.add("CustomCurrency",{title:Go("Custom currency format"),Body:AL}),Sk.add("SplitToColumns",{title:Go("Split text into columns"),Body:dk}),Sk.add("Settings",{title:Go("Spreadsheet settings"),Body:lk}),Sk.add("RemoveDuplicates",{title:Go("Remove duplicates"),Body:ak}),Sk.add("DataValidation",{title:Go("Data validation"),Body:FL}),Sk.add("DataValidationEditor",{title:Go("Data validation"),Body:DL}),Sk.add("MoreFormats",{title:Go("More date formats"),Body:kL}),Sk.add("TableSidePanel",{title:Go("Edit table"),Body:fk,computeState:e=>{const t=e.getFirstTableInSelection();if(!t)return{isOpen:!1};return{isOpen:!0,props:{table:e.getCoreTable(X_(t))},key:t.id}}}),Sk.add("TableStyleEditorPanel",{title:Go("Create custom table style"),Body:bk,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??"new"})}),Sk.add("PivotSidePanel",{title:(e,t)=>Go("Pivot #%s",e.model.getters.getPivotFormulaId(t.pivotId)),Body:rk,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),Sk.add("PivotMeasureDisplayPanel",{title:(e,t)=>{const s=e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id);return Go('Measure "%s" options',s.displayName)},Body:UL,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}}}}),Sk.add("CarouselPanel",{title:Go("Carousel"),Body:AN,computeState:(e,t)=>{const s=t.figureId||e.getSelectedFigureId();return s&&e.doesCarouselExist(s)?{isOpen:!0,props:{figureId:s}}:{isOpen:!1}}});class Ck{mutators=["setSmallThreshhold"];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}}const yk=350,Ik=150;class wk extends ph{mutators=["open","replace","toggle","close","changePanelSize","resetPanelSize","togglePinPanel","closeMainPanel","changeSpreadsheetWidth","toggleCollapsePanel"];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(Ck);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:yk},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?yk:this.mainPanel.size;!this.secondaryPanel&&i+yk>this.availableWidth?this.get(KR).notifyUser({sticky:!1,type:"warning",text:Go("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:yk},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||yk,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,yk);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,yk),o=this.secondaryPanel.size),t=Math.max(this.availableWidth-o,yk)),s.size=t}resetPanelSize(e){this[e]&&(this[e].size=yk)}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,yk)):(t.isCollapsed=!0,t.size=45))}computeState({componentTag:e,initialPanelProps:t}){const s=Sk.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-Ik,this.secondaryPanel&&e-this.totalPanelSize<Ik&&(this.secondaryPanel?.initialPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0),this.mainPanel&&e-this.totalPanelSize<Ik&&(this.mainPanel.size=Math.max(e-Ik,yk))}}class Ek extends t.Component{static template="o-spreadsheet-TableResizer";static props={table:Object};state=t.useState({highlightZone:void 0});dragNDropGrid=yM(this.env);setup(){IL(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?aR({display:"none"}):aR({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 Rk={ROW:bM,COL:uM,CELL:eP,GROUP_HEADERS:fM,UNGROUP_HEADERS:vM};class xk extends t.Component{static template="o-spreadsheet-Grid";static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:BM,GridOverlay:sN,GridPopover:oN,HeadersOverlay:cN,MenuPopover:fR,Autofill:wM,ClientTag:RM,Highlight:fN,Popover:uR,VerticalScrollBar:SN,HorizontalScrollBar:bN,TableResizer:Ek,Selection:CN};HEADER_HEIGHT=se;HEADER_WIDTH=oe;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=yM(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=rh(XR),this.menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.hoveredCell=rh(wR),this.composerFocusStore=rh(fh),this.DOMFocusableElementStore=rh(kR),this.sidePanel=rh(wk),this.paintFormatStore=rh(JM),this.clientFocusStore=rh(CM),rh(SM),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())),dN("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),this.onMouseWheel=gN(((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()})),this.cellPopovers=rh(RR),t.useEffect(((e,t)=>{e||t||this.DOMFocusableElementStore.focus()}),(()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen])),uN(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 aR({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===r.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===r.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":()=>d_(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&&Ko(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":()=>n_(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?c_(this.env):i&&!o&&l_(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":()=>u_(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-oe,height:e-se,gridOffsetX:oe,gridOffsetY:se})}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{...By(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===r.empty?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),UR(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){const t=jy(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";Ds(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=Rk[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement))return;if("inactive"!==this.composerFocusStore.activeComposer.editionMode)return;e?nF(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=>Yt.includes(e.type))),o={content:{[a.PlainText]:t?.getData(a.PlainText),[a.Html]:t?.getData(a.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(),l=Ks(o.content),c=l.data?.clipboardId;r===c?e_(this.env,i):await t_(this.env,i,l),n&&await this.env.clipboard.write({[a.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(!j_(this.env,"COL")&&!j_(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(J_)}get displaySelectionHandler(){return this.env.isMobile()&&"inactive"===this.composerFocusStore.activeComposer.editionMode}}const Tk=new n;Tk.add("SPREADSHEET",!1);class Ak extends t.Component{static template="o-spreadsheet-ClickableCellSortIcon";static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=rh(QM)}get style(){const e=this.env.model.getters.getCellComputedStyle(this.props.position);return aR({color:e.textColor||Z,"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=go(t),o=go(e),i=s.a+o.a*(1-s.a);return uo({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 Dk extends t.Component{static template="o-spreadsheet-FullScreenFigure";static props={};static components={ChartFigure:SR};fullScreenFigureStore;ref=t.useRef("fullScreenFigure");spreadsheetRect=dR();figureRegistry=yR;setup(){this.fullScreenFigureStore=rh(oR);const e=rh(Sh);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 yR.get(this.figureUI.tag).Component}}class _k extends t.Component{static template="o_spreadsheet.PivotHTMLRenderer";static components={Checkbox:Rx};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(tn(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Mc(e,i).join(",")})`,value:or(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(${Mc(e,i).join(",")})`,value:or(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(${Mc(e,i).join(",")})`,value:or(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=tn(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(${Mc(e,r,n).join(",")})`,value:or(a,{format:l,locale:c}),isMissing:!this.tracker?.isValuePresent(n,r)})}s.push(i)}return s}}class Fk extends Ed{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:s,dispatch:o,canDispatch:i}){super(t),s.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=o,this.canDispatch=i}import(e){}export(e){}adaptRanges(e,t,s){}garbageCollectExternalResources(){}}class Ok{id;format;style;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,s,o,i,n,r){this.id=e,this.format=s,this.style=o,this.sheetId=n,this.getRangeString=r;let a=0;const l=t.tokens.map((e=>{if("REFERENCE"===e.type){const e=a++;return new Pk(i,e,this.sheetId,this.getRangeString)}return e}));this.compiledFormula={...t,dependencies:i,tokens:l}}get content(){return mt(this.compiledFormula.tokens.map((e=>e.value)))}get contentWithFixedReferences(){let e=0;return mt(this.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=e++;return this.getRangeString(this.compiledFormula.dependencies[t],this.sheetId,{useBoundedReference:!0})}return t.value})))}}class Pk{ranges;rangeIndex;sheetId;getRangeString;type="REFERENCE";constructor(e,t,s,o){this.ranges=e,this.rangeIndex=t,this.sheetId=s,this.getRangeString=o}get value(){const e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}}function Mk(e){return""===e?NaN:Number(e)}function Nk(e){return Object.entries(e).map((([e,t])=>t?Lk(parseInt(e,10),t):void 0)).filter(ut).map((e=>as(e.left,e.top)+":"+as(e.right,e.bottom)))}function Lk(e,t){return{...t.zone,id:e}}class kk{getters;providers=[];constructor(e){this.getters=e}static getters=["adaptFormulaStringDependencies","copyFormulaStringForSheet","extendRange","getRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeData","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData","getRangeFromZone","getRangesUnion","recomputeRanges","isRangeValid","removeRangesSheetPrefix"];allowDispatch(e){return"MOVE_RANGES"===e.type?1===e.target.length?"Success":"InvalidZones":"Success"}beforeHandle(e){}handle(e){const t=Ia(e);t?.applyChange&&this.executeOnAllRanges(t.applyChange,t.sheetId,t.sheetName)}finalize(){}verifyRangeRemoved(e){return t=>{const s=e(t);return"NONE"===s.changeType||vs(s.range.zone)?s:{range:s.range,changeType:"REMOVE"}}}executeOnAllRanges(e,t,s){const o=this.verifyRangeRemoved(e);for(const e of this.providers)e(o,t,s)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,s,o){return e.map((e=>{if(!vs(e.zone))return e;const i=e.prefixSheet?e.sheetId:o,n=va(e),r=fa(e),a={...e.unboundedZone,left:n&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:n?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:r&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:s),bottom:r?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:s)};return function(e){if(bs(e.zone))return e;const t={...e.unboundedZone},s={...e.zone};let o=e.parts;if(void 0!==t.right&&t.right<t.left){const e=t.right;t.right=t.left,t.left=e,s.right=s.left,s.left=e,o=[{colFixed:o[1]?.colFixed||!1,rowFixed:o[0]?.rowFixed||!1},{colFixed:o[0]?.colFixed||!1,rowFixed:o[1]?.rowFixed||!1}]}if(void 0!==t.bottom&&t.bottom<t.top){const e=t.bottom;t.bottom=t.top,t.top=e,s.bottom=s.top,s.top=e,o=[{colFixed:o[0]?.colFixed||!1,rowFixed:o[1]?.rowFixed||!1},{colFixed:o[1]?.colFixed||!1,rowFixed:o[0]?.rowFixed||!1}]}return{unboundedZone:t,zone:s,parts:o,invalidXc:e.invalidXc,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}(ga({...e,sheetId:i,zone:a},this.getters.getSheetSize))}))}removeRangesSheetPrefix(e,t){return t.map((t=>t.prefixSheet&&t.sheetId===e?{...t,prefixSheet:!1}:t))}extendRange(e,t,s){const o="COL"===t?e.zone.right+s:e.zone.right,i="ROW"===t?e.zone.bottom+s:e.zone.bottom,n={left:e.zone.left,top:e.zone.top,right:va(e)?void 0:o,bottom:fa(e)?void 0:i};return ga({...e,zone:n},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!ea.test(t)||!this.getters.tryGetSheet(e))return ma(t);const{sheetName:s}=na(t);return pa({xc:t,sheetId:this.getters.getSheetIdByName(s)||e,invalidSheetName:s&&!this.getters.getSheetIdByName(s)?s:void 0},this.getters.getSheetSize)}getRangeString(e,t,s={useBoundedReference:!1,useFixedReference:!1}){return e?e.invalidXc?e.invalidXc:this.getters.tryGetSheet(e.sheetId)?ba(e,t,this.getters.getSheetName,s):Mi.InvalidReference:Mi.InvalidReference}getRangeDataFromXc(e,t){const s=this.getters.getRangeFromSheetXC(e,t);return this.getRangeDataFromZone(s.sheetId,s.unboundedZone)}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t=this.getters.getUnboundedZone(e,t)}}getRangeData(e){return this.getRangeDataFromZone(e.sheetId,e.unboundedZone)}getRangeFromZone(e,t){return ga({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){const s=e.map((e=>e.unboundedZone)),o=t.map((e=>e.unboundedZone));return ls(s,o).map((t=>this.getRangeFromZone(e[0].sheetId,t)))}getRangeFromRangeData(e){if(!this.getters.tryGetSheet(e._sheetId))return ma(Mi.InvalidReference);return ga({prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]},this.getters.getSheetSize)}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:s}=na(e);return null!==t.match(ea)&&(!s||void 0!==this.getters.getSheetIdByName(s))}getRangesUnion(e){const t=e.map((e=>e.unboundedZone)),s=function(...e){return{top:Math.min(...e.map((e=>e.top))),left:Math.min(...e.map((e=>e.left))),bottom:e.some((e=>void 0===e.bottom))?void 0:Math.max(...e.map((e=>e.bottom))),right:e.some((e=>void 0===e.right))?void 0:Math.max(...e.map((e=>e.right)))}}(...t);return this.getRangeFromZone(e[0].sheetId,s)}adaptFormulaStringDependencies(e,t,s){if(!t.startsWith("="))return t;const o=gC(t),i=o.dependencies.map((t=>{const o=this.getters.getRangeFromSheetXC(e,t),i=s(o);return"NONE"===i.changeType?o:i.range}));return this.getters.getFormulaString(e,o.tokens,i)}copyFormulaStringForSheet(e,t,s,o){if(!s.startsWith("="))return s;const i=gC(s),n=i.dependencies.map((s=>{const i=this.getters.getRangeFromSheetXC(e,s);return"keepSameReference"===o?i:Sa(e,t,i)}));return this.getters.getFormulaString(t,i.tokens,n)}}function Vk(e,t){if(!e)return;const s=t(e);switch(s.changeType){case"NONE":return e;case"REMOVE":return;default:return s.range}}class Uk extends Ed{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}}const Hk=new n;Hk.add("pivots",(e=>{for(const t of e.getPivotIds()){const s=e.getPivot(t);s.markAsDirtyForEvaluation?.()}}));const zk=JS.mapping;function Bk(e,t,s){return new Gk(e,t,s).getParameters()}class Gk{getters;computeCell;evalContext;rangeCache={};constructor(e,t,s){this.getters=t,this.computeCell=s,this.evalContext=Object.assign(Object.create(zk),e,{getters:this.getters,locale:this.getters.getLocale()})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e,t){const s=this.getRangeError(e);if(s)return s;const o={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};if(t){this.computeCell(o);return{value:ra(this.getters.getSheetName(e.sheetId),Ss(e.zone))}}return this.computeCell(o)}range(e,t){const s=this.getRangeError(e);if(s)return[[s]];const o=e.sheetId,i=e.zone,n=Rs(i,this.getters.getSheetZone(o));if(!n)return[[]];const{top:r,left:a,bottom:l,right:c}=i,h=`${o}-${r}-${a}-${l}-${c}-${t}`;if(h in this.rangeCache)return this.rangeCache[h];const d=n.bottom-n.top+1,u=n.right-n.left+1,g=new Array(u),p=this.getters.getSheetName(e.sheetId);for(let e=n.left;e<=n.right;e++){const s=e-n.left;g[s]=new Array(d);for(let i=n.top;i<=n.bottom;i++){const r=i-n.top,a=this.computeCell({sheetId:o,col:e,row:i});g[s][r]=t?{value:ra(p,as(e,i))}:a}}return this.rangeCache[h]=g,g}getRangeError(e){return vs(e.zone)?e.invalidSheetName?new Ui(Go("Invalid sheet name: %s",e.invalidSheetName)):void 0:new Ui}}function Wk(e,t,s,o,i){$k(e,t,s||0,o||e.length-1,i||Zk)}function $k(e,t,s,o,i){for(;o>s;){if(o-s>600){var n=o-s+1,r=t-s+1,a=Math.log(n),l=.5*Math.exp(2*a/3),c=.5*Math.sqrt(a*l*(n-l)/n)*(r-n/2<0?-1:1);$k(e,t,Math.max(s,Math.floor(t-r*l/n+c)),Math.min(o,Math.floor(t+(n-r)*l/n+c)),i)}var h=e[t],d=s,u=o;for(qk(e,s,t),i(e[o],h)>0&&qk(e,s,o);d<u;){for(qk(e,d,u),d++,u--;i(e[d],h)<0;)d++;for(;i(e[u],h)>0;)u--}0===i(e[s],h)?qk(e,s,u):qk(e,++u,o),u<=t&&(s=u+1),t<=u&&(o=u-1)}}function qk(e,t,s){var o=e[t];e[t]=e[s],e[s]=o}function Zk(e,t){return e<t?-1:e>t?1:0}class jk{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const s=[];if(!nV(e,t))return s;const o=this.toBBox,i=[];for(;t;){for(let n=0;n<t.children.length;n++){const r=t.children[n],a=t.leaf?o(r):r;nV(e,a)&&(t.leaf?s.push(r):iV(e,a)?this._all(r,s):i.push(r))}t=i.pop()}return s}collides(e){let t=this.data;if(!nV(e,t))return!1;const s=[];for(;t;){for(let o=0;o<t.children.length;o++){const i=t.children[o],n=t.leaf?this.toBBox(i):i;if(nV(e,n)){if(t.leaf||iV(e,n))return!0;s.push(i)}}t=s.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let t=0;t<e.length;t++)this.insert(e[t]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const e=this.data;this.data=t,t=e}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=rV([]),this}remove(e,t){if(!e)return this;let s=this.data;const o=this.toBBox(e),i=[],n=[];let r,a,l;for(;s||i.length;){if(s||(s=i.pop(),a=i[i.length-1],r=n.pop(),l=!0),s.leaf){const o=Yk(e,s.children,t);if(-1!==o)return s.children.splice(o,1),i.push(s),this._condense(i),this}l||s.leaf||!iV(s,o)?a?(r++,s=a.children[r],l=!1):s=null:(i.push(s),n.push(r),r=0,a=s,s=s.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const s=[];for(;e;)e.leaf?t.push(...e.children):s.push(...e.children),e=s.pop();return t}_build(e,t,s,o){const i=s-t+1;let n,r=this._maxEntries;if(i<=r)return n=rV(e.slice(t,s+1)),Xk(n,this.toBBox),n;o||(o=Math.ceil(Math.log(i)/Math.log(r)),r=Math.ceil(i/Math.pow(r,o-1))),n=rV([]),n.leaf=!1,n.height=o;const a=Math.ceil(i/r),l=a*Math.ceil(Math.sqrt(r));aV(e,t,s,l,this.compareMinX);for(let i=t;i<=s;i+=l){const t=Math.min(i+l-1,s);aV(e,i,t,a,this.compareMinY);for(let s=i;s<=t;s+=a){const i=Math.min(s+a-1,t);n.children.push(this._build(e,s,i,o-1))}}return Xk(n,this.toBBox),n}_chooseSubtree(e,t,s,o){for(;o.push(t),!t.leaf&&o.length-1!==s;){let s,o=1/0,r=1/0;for(let a=0;a<t.children.length;a++){const l=t.children[a],c=tV(l),h=(i=e,n=l,(Math.max(n.maxX,i.maxX)-Math.min(n.minX,i.minX))*(Math.max(n.maxY,i.maxY)-Math.min(n.minY,i.minY))-c);h<r?(r=h,o=c<o?c:o,s=l):h===r&&c<o&&(o=c,s=l)}t=s||t.children[0]}var i,n;return t}_insert(e,t,s){const o=s?e:this.toBBox(e),i=[],n=this._chooseSubtree(o,this.data,t,i);for(n.children.push(e),Jk(n,o);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(o,i,t)}_split(e,t){const s=e[t],o=s.children.length,i=this._minEntries;this._chooseSplitAxis(s,i,o);const n=this._chooseSplitIndex(s,i,o),r=rV(s.children.splice(n,s.children.length-n));r.height=s.height,r.leaf=s.leaf,Xk(s,this.toBBox),Xk(r,this.toBBox),t?e[t-1].children.push(r):this._splitRoot(s,r)}_splitRoot(e,t){this.data=rV([e,t]),this.data.height=e.height+1,this.data.leaf=!1,Xk(this.data,this.toBBox)}_chooseSplitIndex(e,t,s){let o,i=1/0,n=1/0;for(let r=t;r<=s-t;r++){const t=Kk(e,0,r,this.toBBox),a=Kk(e,r,s,this.toBBox),l=oV(t,a),c=tV(t)+tV(a);l<i?(i=l,o=r,n=c<n?c:n):l===i&&c<n&&(n=c,o=r)}return o||s-t}_chooseSplitAxis(e,t,s){const o=e.leaf?this.compareMinX:Qk,i=e.leaf?this.compareMinY:eV;this._allDistMargin(e,t,s,o)<this._allDistMargin(e,t,s,i)&&e.children.sort(o)}_allDistMargin(e,t,s,o){e.children.sort(o);const i=this.toBBox,n=Kk(e,0,t,i),r=Kk(e,s-t,s,i);let a=sV(n)+sV(r);for(let o=t;o<s-t;o++){const t=e.children[o];Jk(n,e.leaf?i(t):t),a+=sV(n)}for(let o=s-t-1;o>=t;o--){const t=e.children[o];Jk(r,e.leaf?i(t):t),a+=sV(r)}return a}_adjustParentBBoxes(e,t,s){for(let o=s;o>=0;o--)Jk(t[o],e)}_condense(e){for(let t,s=e.length-1;s>=0;s--)0===e[s].children.length?s>0?(t=e[s-1].children,t.splice(t.indexOf(e[s]),1)):this.clear():Xk(e[s],this.toBBox)}}function Yk(e,t,s){if(!s)return t.indexOf(e);for(let o=0;o<t.length;o++)if(s(e,t[o]))return o;return-1}function Xk(e,t){Kk(e,0,e.children.length,t,e)}function Kk(e,t,s,o,i){i||(i=rV(null)),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(let n=t;n<s;n++){const t=e.children[n];Jk(i,e.leaf?o(t):t)}return i}function Jk(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function Qk(e,t){return e.minX-t.minX}function eV(e,t){return e.minY-t.minY}function tV(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function sV(e){return e.maxX-e.minX+(e.maxY-e.minY)}function oV(e,t){const s=Math.max(e.minX,t.minX),o=Math.max(e.minY,t.minY),i=Math.min(e.maxX,t.maxX),n=Math.min(e.maxY,t.maxY);return Math.max(0,i-s)*Math.max(0,n-o)}function iV(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function nV(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function rV(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function aV(e,t,s,o,i){const n=[t,s];for(;n.length;){if((s=n.pop())-(t=n.pop())<=o)continue;const r=t+Math.ceil((s-t)/o/2)*o;Wk(e,r,t,s,i),n.push(t,r,r,s)}}class lV{rTrees={};constructor(e=[]){const t={};for(const s of e){const e=s.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(s)}for(const e in t)this.rTrees[e]=new cV,this.rTrees[e].load(t[e])}insert(e){const t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new cV),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){const t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&St(e.data,t.data)}}class cV extends jk{toBBox({boundingBox:e}){const t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}}class hV{createEmptyPositionSet;dependencies=new C_;rTree;constructor(e,t=[]){this.createEmptyPositionSet=e,this.rTree=new lV(t)}removeAllDependencies(e){const t=this.dependencies.get(e);if(t){for(const e of t)this.rTree.remove(e);this.dependencies.delete(e)}}addDependencies(e,t){const s=t.map((({sheetId:t,zone:s})=>({data:e,boundingBox:{zone:s,sheetId:t}})));for(const e of s)this.rTree.insert(e);const o=this.dependencies.get(e);o?o.push(...s):this.dependencies.set(e,s)}getCellsDependingOn(e){const t=this.createEmptyPositionSet(),s=Array.from(e).reverse();for(;s.length>0;){const e=s.pop(),o=e.zone,i=e.sheetId;for(let e=o.left;e<=o.right;e++)for(let s=o.top;s<=o.bottom;s++)t.add({sheetId:i,col:e,row:s});const n=this.rTree.search(e).map((e=>e.data)),r={};for(const e of n)t.has(e)||(r[e.sheetId]||(r[e.sheetId]=[]),r[e.sheetId].push(Us(e)));for(const e in r){const t=ls(r[e],[]);s.push(...t.map((t=>({sheetId:e,zone:t}))))}}for(const s of e){const e=s.zone,o=s.sheetId;for(let s=e.left;s<=e.right;s++)for(let i=e.top;i<=e.bottom;i++)t.delete({sheetId:o,col:s,row:i})}return t}}class dV extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){const s=function(e){if(0===e)return-1/0;if(e<0)return NaN;return 32-Math.clz32(--e)}(t),o=new this((e<<s>>5)+1);return o.columnOffset=s,o.cols=t,o.rows=e,o}getValue(e){const[t,s]=this.getCoordinates(e);return this[t]>>s&1}setValue(e,t){const[s,o]=this.getCoordinates(e),i=0===(this[s]>>o&1)&&1===t;return this[s]=this[s]&~(1<<o)|t<<o,i}isEmpty(){return!this.some((e=>0!==e))}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){const{row:t,col:s}=e,o=(t<<this.columnOffset)+s,i=o>>5;return[i,o-(i<<5)]}}class uV{sheets={};insertions=[];maxSize=0;constructor(e){for(const t in e){const s=e[t].cols,o=e[t].rows;this.maxSize+=s*o,this.sheets[t]=dV.create(o,s)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(const t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(const t of e)this.delete(t)}has(e){return 1===this.sheets[e.sheetId].getValue(e)}clear(){const e=[...this];this.insertions=[];for(const e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(0===this.insertions.length)return!0;for(const e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=new Array(this.maxSize);let e=0;for(const t in this.sheets){const s=this.sheets[t];s.fillAllPositions();for(let o=0;o<s.rows;o++)for(let i=0;i<s.cols;i++)this.insertions[e++]={sheetId:t,row:o,col:i}}}*[Symbol.iterator](){for(const e of this.insertions)1===this.sheets[e.sheetId].getValue(e)&&(yield e)}}class gV{resultsToArrayFormulas=new lV;arrayFormulasToResults=new C_;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map((e=>e.data))||pV}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:Us(e)},data:e}),this.arrayFormulasToResults.delete(e)}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}}const pV=[],mV=Object.freeze(Pr({...new Vi,origin:void 0})),fV=Object.freeze(Pr({value:null}));class vV{context;getters;compilationParams;evaluatedCells=new C_;formulaDependencies=ft(new hV(this.createEmptyPositionSet.bind(this)));blockedArrayFormulas=new uV({});spreadingRelations=new gV;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=Bk(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||fV}getSpreadZone(e,t={ignoreSpillError:!1}){const s=this.spreadingRelations.getArrayResultZone(e);if(!s)return;const o=this.evaluatedCells.get(e);return o?.type!==r.error||t.ignoreSpillError&&o?.value===Mi.SpilledBlocked?Es(Us(e),s):Us(e)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type===r.empty)return;const t=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,Us(e));return Array.from(t).find((e=>!this.blockedArrayFormulas.has(e)))}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);const t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t);for(const e of t){const t=e.sheetId,{left:s,bottom:o,right:i,top:n}=e.zone;for(let e=s;e<=i;e++)for(let s=n;s<=o;s++)this.computeAndSave({sheetId:t,col:e,row:s})}}updateCompilationParameters(){this.compilationParams=Bk(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){const e={};for(const t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new uV(e)}evaluateCells(e){const t=performance.now(),s=this.createEmptyPositionSet();s.addMany(e);const o=this.getArrayFormulasImpactedByChangesOf(e);s.addMany(this.getCellsDependingOn(e)),s.addMany(o),s.addMany(this.getCellsDependingOn(o)),this.evaluate(s),console.debug("evaluate Cells",performance.now()-t,"ms")}getArrayFormulasImpactedByChangesOf(e){const t=this.createEmptyPositionSet();for(const s of e){const e=this.getters.getCell(s)?.content,o=this.getArrayFormulaSpreadingOn(s);void 0!==o&&t.add(o),e||t.add(s)}const s=Ps(t);for(const e in s)for(const o of s[e])t.addMany(this.getArrayFormulasBlockedBy(e,o));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new gV,this.formulaDependencies=ft((()=>{const e=[...this.getAllCells()].flatMap((e=>this.getDirectDependencies(e).filter((e=>!e.invalidSheetName&&!e.invalidXc)).map((t=>({data:e,boundingBox:{zone:t.zone,sheetId:t.sheetId}})))));return new hV(this.createEmptyPositionSet.bind(this),e)}))}evaluateAllCells(){const e=performance.now();this.evaluatedCells=new C_,this.evaluate(this.getAllCells()),console.debug("evaluate all cells",performance.now()-e,"ms")}evaluateFormulaResult(e,t){const s=gC(t),o=s.dependencies.map((t=>this.getters.getRangeFromSheetXC(e,t)));return this.updateCompilationParameters(),this.evaluateCompiledFormula(e,{...s,dependencies:o})}evaluateCompiledFormula(e,t,s){try{const o=CV(t,this.compilationParams,e,this.buildSafeGetSymbolValue(s),this.compilationParams.evalContext.__originCellPosition);return R(o)?fn(o,SV):SV(o)}catch(e){return QS(e,"")}}getAllCells(){const e=this.createEmptyPositionSet();return e.fillAllPositions(),e}getArrayFormulasBlockedBy(e,t){const s=this.createEmptyPositionSet(),o=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);s.addMany(o);const i=[...o].filter((e=>!this.blockedArrayFormulas.has(e)));return i.length&&s.deleteMany(i),s.addMany(this.getCellsDependingOn(s)),s}nextPositionsToUpdate=new uV({});cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextPositionsToUpdate=e;let t=0;for(;!this.nextPositionsToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();const e=this.nextPositionsToUpdate.clear();for(let t=0;t<e.length;++t)this.evaluatedCells.delete(e[t]);for(let t=0;t<e.length;++t){const s=e[t];if(this.nextPositionsToUpdate.has(s))continue;const o=this.computeCell(s);o!==fV&&this.evaluatedCells.set(s,o)}Hk.getAll().forEach((e=>e(this.getters)))}t>=30&&console.warn("Maximum iteration reached while evaluating cells")}computeCell(e){const t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);const s=this.getters.getCell(e);if(void 0===s)return fV;const o=s.id,i={format:s.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(o)?mV:(this.cellsBeingComputed.add(o),s.isFormula?this.computeFormulaCell(e,s):Fr(s,i,e))}catch(t){return t.value=t?.value||Mi.GenericError,t.message=t?.message||tC,t.origin=e,Pr(t)}finally{this.cellsBeingComputed.delete(o)}}computeAndSave(e){const t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){const s=CV(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!R(s)){const o=Pr(SV(s),this.getters.getLocale(),t,e);return o.type===r.error&&(o.errorOriginPosition=s.errorOriginPosition??e),o}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,s);const o=s.length,i=s[0].length,n={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+o-1};return this.spreadingRelations.addRelation({resultZone:n,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,s),bV(o,i,this.checkCollision(e)),bV(o,i,this.spreadValues(e,s)),this.invalidatePositionsDependingOnSpread(e.sheetId,n),Pr(SV(s[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){const s=this.formulaDependencies().getCellsDependingOn(function(e){const{top:t,left:s,bottom:o,right:i}=e;if(1===Gs(e))return[];const n={top:t+1,bottom:o,left:s,right:s};if(i===s)return[n];const r={top:t,bottom:o,left:s+1,right:i};return t===o?[r]:[n,r]}(t).map((t=>({sheetId:e,zone:t}))));s.delete({sheetId:e,col:t.left,row:t.top}),this.nextPositionsToUpdate.addMany(s)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:s},o){const i=this.getters.getNumberCols(e),n=this.getters.getNumberRows(e),r=t+o.length<=i,a=s+o[0].length<=n;if(!r||!a){if(r)throw new Bi(Go("Result couldn't be automatically expanded. Please insert more rows."));if(a)throw new Bi(Go("Result couldn't be automatically expanded. Please insert more columns."));throw new Bi(Go("Result couldn't be automatically expanded. Please insert more columns and rows."))}}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:s},o){if(0!==this.getters.getMergesInZone(e,{top:s,bottom:s+o[0].length-1,left:t,right:t+o.length-1}).length)throw new Bi(Go("Merged cells found in the spill zone. Please unmerge cells before using array formulas."))}checkCollision(e){const{sheetId:t,col:s,row:o}=e;return(i,n)=>{const a={sheetId:t,col:i+s,row:n+o},l=this.getters.getCell(a);if(l?.content||this.getters.getEvaluatedCell(a).type!==r.empty)throw this.blockedArrayFormulas.add(e),new Bi(Go("Array result was not expanded because it would overwrite data in %s.",as(a.col,a.row)));this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:s},o){return(i,n)=>{const a={sheetId:e,col:i+t,row:n+s},l=this.getters.getCell(a),c=Pr(SV(o[i][n]),this.getters.getLocale(),l,a);c.type===r.error&&(c.errorOriginPosition=o[i][n].errorOriginPosition??a),this.evaluatedCells.set(a,c)}}invalidateSpreading(e){const t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let s=t.left;s<=t.right;s++)for(let o=t.top;o<=t.bottom;o++){const t={sheetId:e.sheetId,col:s,row:o},i=this.getters.getCell(t)?.content;i||this.evaluatedCells.delete(t)}const s=e.sheetId;this.invalidatePositionsDependingOnSpread(s,t),this.nextPositionsToUpdate.addMany(this.getArrayFormulasBlockedBy(s,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return mV;this.symbolsBeingComputed.add(t);try{const s=e?.(t);return s||new ki(Go("Invalid formula"))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){const t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){const t=[],s=Ps(e);for(const e in s)t.push(...s[e].map((t=>({sheetId:e,zone:t}))));return this.formulaDependencies().getCellsDependingOn(t)}}function bV(e,t,s){for(let o=0;o<e;++o)for(let e=0;e<t;++e)0===o&&0===e||s(o,e)}function SV(e){return null===e.value||void 0===e.value?{...e,value:0}:e}function CV(e,t,s,o,i){return t.evalContext.__originCellPosition=i,t.evalContext.__originSheetId=s,e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,o,t.evalContext)}const yV=/"(#[0-9a-fA-F]{6})"/g;const IV={isValid:!0};const wV=new n;function EV(e,t){const s=t.model.getters.getPivotCellFromPosition(e),o=t.model.getters.getPivotIdFromPosition(e);if(!o||"HEADER"!==s.type)return;const i=t.model.getters.getPivotCoreDefinition(o),n=i.collapsedDomains?.[s.dimension]?[...i.collapsedDomains[s.dimension]]:[],r=n.findIndex((e=>St(e,s.domain)));-1!==r?n.splice(r,1):n.push(s.domain);const a=i.collapsedDomains?{...i.collapsedDomains}:{COL:[],ROW:[]};a[s.dimension]=n,t.model.dispatch("UPDATE_PIVOT",{pivotId:o,pivot:{...i,collapsedDomains:a}})}wV.add("data_validation_checkbox",((e,t)=>{if(e.isCellValidCheckbox(t)){const s=!!e.getEvaluatedCell(t).value;return{svg:s?xT:ET,hoverSvg:s?xT:RT,priority:2,horizontalAlign:"center",size:17,margin:2,position:t,type:"data_validation_checkbox",onClick:(e,t)=>{const o=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||!!o?.isFormula)return;const i=s?"FALSE":"TRUE";t.model.dispatch("UPDATE_CELL",{...e,content:i})}}}})),wV.add("data_validation_chip_icon",((e,t)=>{const s=e.getDataValidationChipStyle(t);if(s){const o=e.getCellComputedStyle(t);return{svg:IT(s),hoverSvg:wT(s),priority:10,horizontalAlign:"right",size:Ba(o),margin:4,position:t,onClick:(e,t)=>{const{col:s,row:o}=e;t.model.selection.selectCell(s,o),t.startCellEdition()},type:"data_validation_chip_icon"}}})),wV.add("data_validation_list_icon",((e,t)=>{if(!e.isReadonly()&&e.cellHasListDataValidationIcon(t)){const o=e.getCellComputedStyle(t);return{svg:ST(o),hoverSvg:(s=o,{name:"CARET_DOWN",width:512,height:512,paths:[{fillColor:s.textColor||Z,path:"M15 15 h482 v482 h-482"},{fillColor:s.fillColor||"#fff",path:"M120 195 h270 l-135 130"}]}),priority:2,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const{col:s,row:o}=e;t.model.selection.selectCell(s,o),t.startCellEdition()},type:"data_validation_list_icon"}}var s})),wV.add("filter_icon",((e,t)=>{if(e.isFilterHeader(t)){const s=e.isFilterActive(t),o=ho(e.getCellComputedStyle(t).fillColor||"#fff")<.45;return{type:"filter_icon",svg:AT(s,o,!1),hoverSvg:AT(s,o,!0),priority:3,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const s=t.getStore(RR),o=s.persistentCellPopover;o.isOpen&&o.col===e.col&&o.row===e.row&&"FilterMenu"===o.type?s.close():s.open(e,"FilterMenu")}}}})),wV.add("conditional_formatting",((e,t)=>{const s=e.getConditionalIcon(t);if(s){const o=e.getCellStyle(t);return{type:"conditional_formatting",svg:DT[s].svg,priority:1,horizontalAlign:"left",size:Ba(o),margin:4,position:t}}})),wV.add("pivot_collapse",((e,t)=>{if(!e.isSpillPivotFormula(t))return;const s=e.getPivotCellFromPosition(t),o=e.getPivotIdFromPosition(t);if("HEADER"===s.type&&o&&s.domain.length){const i=e.getPivotCoreDefinition(o),n=e.isDashboard(),r="COL"===s.dimension?i.columns:i.rows,a=!n&&s.domain.length!==r.length,l=(i.collapsedDomains?.[s.dimension]??[]).some((e=>St(e,s.domain))),c="ROW"===s.dimension?15*(s.domain.length-1):0;return{type:"pivot_collapse",priority:4,horizontalAlign:"left",size:a||!n&&"ROW"===s.dimension&&i.rows.length>1?12:0,margin:a?4+c:c,svg:a?TT(l,!1):void 0,hoverSvg:a?TT(l,!0):void 0,position:t,onClick:EV}}})),wV.add("pivot_dashboard_sorting",((e,t)=>{if(!e.isDashboard())return;if("MEASURE_HEADER"!==e.getPivotCellFromPosition(t).type)return;const s=e.getPivotCellSortDirection(t);if("asc"!==s&&"desc"!==s)return;const o=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${s}`,priority:5,horizontalAlign:"right",size:17,margin:2,svg:"asc"===s?CT(o):ST(o),position:t,onClick:void 0}}));const RV="0.00%";function xV(e){return class extends e{getters;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t){super(e,t),this.getters=t.getters}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){const s=`${e}-${t.map((e=>e.field+"="+e.value)).join(",")}`;if(this.cache[s])return this.cache[s];const o=this.getMeasure(e),i=o.computedBy?this.computeMeasure(o,t):super.getPivotCellValueAndFormat(e,t);return o.format?this.cache[s]={...i,format:o.format}:this.cache[s]=i,this.cache[s]}computeMeasure(e,t){if(!e.computedBy)return{value:0};const{columns:s,rows:o}=super.definition;if(e.aggregator&&s.length+o.length!==t.length){const s=this.getValuesToAggregate(e,t),o=Ac[e.aggregator];if(!o)return{value:0};try{return o([s],this.getters.getLocale())}catch(t){return QS(t,e.aggregator.toUpperCase())}}const i=this.getters.getMeasureCompiledFormula(e),n=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,(e=>{const{columns:s,rows:o}=this.definition;if(s.find((t=>t.nameWithGranularity===e))){const{colDomain:s}=gO(this,t),o=s.findIndex((t=>t.field===e));return-1===o?new Hi:this.getPivotHeaderValueAndFormat(s.slice(0,o+1))}if(o.find((t=>t.nameWithGranularity===e))){const{rowDomain:s}=gO(this,t),o=s.findIndex((t=>t.field===e));return-1===o?new Hi:this.getPivotHeaderValueAndFormat(s.slice(0,o+1))}return this.getPivotCellValueAndFormat(e,t)}));return R(n)?n[0][0]:n}getValuesToAggregate(e,t){const{rowDomain:s,colDomain:o}=gO(this,t),i=super.getExpandedTableStructure(),n=[];if(0===o.length&&s.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){const t=this.treeToLeafDomains(i.getColTree()),o=this.getSubTreeMatchingDomain(i.getRowTree(),s),r=this.treeToLeafDomains(o);for(const o of t)for(const t of r)n.push(this._getPivotCellValueAndFormat(e.id,s.concat(t).concat(o)));return n}if(s.length===this.definition.rows.length&&0===o.length){const t=i.getColTree(),r=this.getSubTreeMatchingDomain(t,o),a=this.treeToLeafDomains(r,o);for(const t of a)n.push(this._getPivotCellValueAndFormat(e.id,s.concat(t)));return n}if(s.length===this.definition.rows.length&&o.length&&o.length<this.definition.columns.length){const t=this.getSubTreeMatchingDomain(i.getColTree(),o),r=this.treeToLeafDomains(t,o);for(const t of r)n.push(this._getPivotCellValueAndFormat(e.id,s.concat(t)));return n}{const t=i.getRowTree(),r=this.getSubTreeMatchingDomain(t,s),a=this.treeToLeafDomains(r,s);for(const t of a)n.push(this._getPivotCellValueAndFormat(e.id,t.concat(o)));return n}}getSubTreeMatchingDomain(e,t,s=0){if(s>t.length)return[];if(t.length===s)return e;for(const o of e){const e=kc(this.definition.getDimension(o.field),t[s]?.value);if(o.field===t[s]?.field&&o.value===e)return this.getSubTreeMatchingDomain(o.children,t,s+1)}return[]}treeToLeafDomains(e,t=[]){const s=[];for(const o of e){const e=this.definition.getDimension(o.field),i=[...t,{field:o.field,value:o.value,type:e.type}];0===o.children.length?s.push(i):s.push(...this.treeToLeafDomains(o.children,i))}return s}getMeasureDisplayValue(e,t){const s=this.getMeasure(e),o=this._getPivotCellValueAndFormat(e,t);if(!s.display||"no_calculations"===s.display.type||o.message)return o;const i=s.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:Mi.NotAvailable,message:Go('Field "%s" not found in pivot for measure display calculation',i)};try{const e=s.display;switch(e.type){case"%_of_grand_total":return this.asPercentOfGrandTotal(o,s);case"%_of_col_total":return this.asPercentOfColumnTotal(o,s,t);case"%_of_row_total":return this.asPercentOfRowTotal(o,s,t);case"%_of_parent_row_total":return this.asPercentOfParentRowTotal(o,s,t);case"%_of_parent_col_total":return this.asPercentOfParentColumnTotal(o,s,t);case"index":return this.asIndex(o,s,t);case"%_of_parent_total":return this.asPercentOfParentTotal(o,s,t,e);case"running_total":return this.asRunningTotal(o,s,t,e,"running_total");case"%_running_total":return this.asRunningTotal(o,s,t,e,"%_running_total");case"rank_asc":return this.asRank(o,s,t,e,"asc");case"rank_desc":return this.asRank(o,s,t,e,"desc");case"%_of":return this.asPercentOf(o,s,t,e);case"difference_from":return this.asDifferenceFrom(o,s,t,e);case"%_difference_from":return this.asDifferenceFromInPercent(o,s,t,e)}return o}catch(e){return QS(e,"COMPUTE_MEASURE_DISPLAY_VALUE")}}asPercentOfGrandTotal(e,t){const s=this.getGrandTotal(t.id);return 0===s?{value:Mi.DivisionByZero}:{value:this.measureValueToNumber(e)/s,format:RV}}asPercentOfRowTotal(e,t,s){const o=this.getRowTotal(t.id,s);return 0===o?{value:Mi.DivisionByZero}:{value:this.measureValueToNumber(e)/o,format:RV}}asPercentOfColumnTotal(e,t,s){const o=this.getColumnTotal(t.id,s);return 0===o?{value:Mi.DivisionByZero}:{value:this.measureValueToNumber(e)/o,format:RV}}asPercentOfParentRowTotal(e,t,s){const o=function(e,t){const{colDomain:s,rowDomain:o}=gO(e,t);return[...s,...o.slice(0,o.length-1)]}(this,s),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,o));return 0===i?{value:""}:{value:this.measureValueToNumber(e)/i,format:RV}}asPercentOfParentColumnTotal(e,t,s){const o=function(e,t){const{colDomain:s,rowDomain:o}=gO(e,t);return[...s.slice(0,s.length-1),...o]}(this,s),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,o));return 0===i?{value:""}:{value:this.measureValueToNumber(e)/i,format:RV}}asPercentOfParentTotal(e,t,s,o){const{fieldNameWithGranularity:i}=o;if(!i)return e;if(!bO(i,s))return{value:""};const n=function(e,t,s){let{rowDomain:o,colDomain:i}=gO(e,s);if("row"===SO(e,t)){const e=o.findIndex((e=>e.field===t));if(-1===e)return s;o=o.slice(0,e+1)}else{const e=i.findIndex((e=>e.field===t));if(-1===e)return s;i=i.slice(0,e+1)}return[...o,...i]}(this,i,s),r=this._getPivotCellValueAndFormat(t.id,n),a=this.measureValueToNumber(r);return 0===a?{value:""}:{value:this.measureValueToNumber(e)/a,format:RV}}asIndex(e,t,s){const o=this.measureValueToNumber(e),i=this.getRowTotal(t.id,s),n=this.getColumnTotal(t.id,s),r=this.getGrandTotal(t.id);return 0===i||0===n?{value:Mi.DivisionByZero}:{value:o*r/(n*i),format:void 0}}asRunningTotal(e,t,s,o,i){const{fieldNameWithGranularity:n}=o;if(!n)return e;const r="running_total"===i?this.runningTotal:this.runningTotalInPercent;let a=r[t.id]?.[n];a||(a=this.computeRunningTotal(t,n,i),r[t.id]||(r[t.id]={}),r[t.id][n]=a);const{rowDomain:l,colDomain:c}=gO(this,s),h=CO(c),d=CO(l),u=a[h]?.[d];return{value:u??"",format:"running_total"===i?e.format:RV}}asPercentOf(e,t,s,o){const{fieldNameWithGranularity:i,value:n}=o;if(void 0===n||!i)return e;if(!bO(i,s))return{value:""};const r=this.getComparisonValue(t,s,i,n),a=this.strictMeasureValueToNumber(e);return 0===r||"sameValue"===r&&0===a?{value:Mi.DivisionByZero}:!r||"sameValue"===r&&!a?{value:""}:"sameValue"===r?{value:1,format:RV}:void 0===a?{value:Mi.NullError}:{value:a/r,format:RV}}asDifferenceFrom(e,t,s,o){const{fieldNameWithGranularity:i,value:n}=o;if(void 0===n||!i)return e;if(!bO(i,s))return{value:""};const r=this.getComparisonValue(t,s,i,n)||0;return"sameValue"===r?{value:""}:{value:this.measureValueToNumber(e)-r,format:e.format}}asDifferenceFromInPercent(e,t,s,o){const{fieldNameWithGranularity:i,value:n}=o;if(void 0===n||!i)return e;if(!bO(i,s))return{value:""};const r=this.getComparisonValue(t,s,i,n),a=this.strictMeasureValueToNumber(e);return 0===r?{value:Mi.DivisionByZero}:r&&"sameValue"!==r?void 0===a?{value:Mi.NullError}:{value:(a-r)/r,format:RV}:{value:""}}asRank(e,t,s,o,i){const{fieldNameWithGranularity:n}=o;if(!n)return e;if(!bO(n,s))return{value:""};const r="asc"===i?this.rankAsc:this.rankDesc;let a=r[t.id]?.[n];a||(a=this.computeRank(t,n,i),r[t.id]||(r[t.id]={}),r[t.id][n]=a);const{rowDomain:l,colDomain:c}=gO(this,s),h=CO(c),d=CO(l),u=a[h]?.[d];return{value:u??""}}computeRank(e,t,s){const o={},i=SO(this,t),n="row"===i?"column":"row";let r=this.getPivotValueCells(e.id);"column"===i&&(r=vn(r));for(const a of r){const r=CO(pO(this,n,a[0].domain)),l=a.map((t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:pO(this,i,t.domain)}))).filter((e=>bO(t,e.rowDomain))),c=Object.groupBy(l,(e=>IO(e.rowDomain,t)));for(const e in c)c[e]=Ht(c[e]||[],(e=>e.value)).filter((e=>void 0!==e.value)).sort(((e,t)=>"asc"===s?e.value-t.value:t.value-e.value));o[r]={};for(const e of l){const s=CO(pO(this,i,e.domain)),n=c[IO(e.rowDomain,t)];if(!n)continue;const a=n.findIndex((t=>t.value===e.value));-1!==a&&(o[r][s]=a+1)}}return"row"===i?o:zt(o)}computeRunningTotal(e,t,s){const o={},i=SO(this,t),n="row"===i?"column":"row";let r=this.getPivotValueCells(e.id);"column"===i&&(r=vn(r));for(const a of r){const r=CO(pO(this,n,a[0].domain));o[r]={};const l={},c=a.map((t=>({...t,rowDomain:pO(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))}))).filter((e=>bO(t,e.rowDomain)));for(const e of c){const s=CO(e.rowDomain),i=wO(e.rowDomain,t),n=(l[i]||0)+e.value;l[i]=n,o[r][s]=n}if("%_running_total"===s)for(const e of c){const s=e.rowDomain,i=CO(s),n=wO(s,t),a=o[r][i]||0,c=l[n];o[r][i]=c?a/c:void 0}}return"row"===i?o:zt(o)}getGrandTotal(e){const t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){const s=gO(this,t).rowDomain,o=this._getPivotCellValueAndFormat(e,s);return this.measureValueToNumber(o)}getColumnTotal(e,t){const s=gO(this,t).colDomain,o=this._getPivotCellValueAndFormat(e,s);return this.measureValueToNumber(o)}isFieldInPivot(e){return this.definition.columns.some((t=>t.nameWithGranularity===e))||this.definition.rows.some((t=>t.nameWithGranularity===e))}getComparisonValue(e,t,s,o){const i=o===dO||o===uO?function(e,t,s,o){const i=SO(e,s),n="row"===i?e.getExpandedTableStructure().getRowTree():e.getExpandedTableStructure().getColTree(),r=fO(pO(e,i,t),n,s),a=r?.map((e=>e.value))??[],l=function(e,t){const s=t.find((t=>t.field===e));return s?.value}(s,t);if(void 0===l)return;const c=a.indexOf(l);if(void 0===l||-1===c)return;return vO(t,s,a[Ke(c+(o===dO?-1:1),0,a.length-1)])}(this,t,s,o):vO(t,s,o);if(St(i,t))return"sameValue";if(!i||!function(e,t){for(const s of t)if(void 0===e.definition.rows.find((e=>e.nameWithGranularity===s.field))&&void 0===e.definition.columns.find((e=>e.nameWithGranularity===s.field)))return!1;const{rowDomain:s,colDomain:o}=gO(e,t);return mO(s,e.getExpandedTableStructure().getRowTree())&&mO(o,e.getExpandedTableStructure().getColTree())}(this,i))throw new Hi;const n=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(n)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map((t=>t.filter((t=>"VALUE"===t.type&&t.measure===e)))).filter((e=>e.length>0))}measureValueToNumber(e){if("number"==typeof e.value)return e.value;if(!e.value)return 0;throw new Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if("number"==typeof e.value)return e.value;if(e.value)throw new Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){const e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){const e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;const t=this.definition.sortedColumn.measure;Wc(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,((e,t)=>this._getPivotCellValueAndFormat(e,t)))}}}const TV=["ADD_PIVOT","UPDATE_PIVOT","REMOVE_PIVOT"];function AV(e){return TV.includes(e.type)}const DV=new n;DV.add("ALPHANUMERIC_INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;let s=Math.abs(e.current).toString();s="0".repeat(Math.max(e.numberPostfixLength-s.length,0))+s;const o=`${e.prefix}${s}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:{props:{content:o}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t,s)=>{e.current+=e.increment;const o=e.current.toString(),i=s.getLocale(),n=or(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:n}}:void 0}}}).add("DATE_INCREMENT_MODIFIER",{apply:(e,t,s)=>{const o=rn(e.current,s.getLocale());o.setFullYear(o.getFullYear()+e.increment.years||0),o.setMonth(o.getMonth()+e.increment.months||0),o.setDate(o.getDate()+e.increment.days||0);const i=bi(o);e.current=i;const n=s.getLocale(),r=or(i,{format:t.cell?.format,locale:n});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:r}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,s)=>{const o=t.cell?.content||"",i={locale:s.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:t.cell?Fr(t.cell,i).formattedValue:""}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,s,o)=>{e.current+=e.increment;let i=0,n=0;switch(o){case"up":i=0,n=-e.current;break;case"down":i=0,n=e.current;break;case"left":i=-e.current,n=0;break;case"right":i=e.current,n=0}const r=t.cell;if(!r||!r.isFormula)return{cellData:{}};const a=t.sheetId,l=s.getTranslatedCellFormula(a,i,n,r.compiledFormula.tokens);return{cellData:{border:t.border,style:r.style,format:r.format,content:l},tooltip:l?{props:{content:l}}:void 0}}});const _V=new n,FV=/(\d+)$/,OV=/^(.*\D+)/,PV=/^(.*\D+)(\d+)$/,MV=/^0*/;function NV(e,t,s){let o=[],i=!1;for(const n of t){n===e&&(i=!0);const t=void 0===n||n.isFormula?void 0:Fr(n,{locale:w,format:n.format});if(t&&s(t))o.push(t);else{if(i)return o;o=[]}}return o}function LV(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let s=e[0];for(let o=1;o<e.length;o++){const i=e[o];t.push(i-s),s=i}return t.reduce(((e,t)=>e+t),0)/t.length}(e)*e.length),t}function kV(e){if(e.length<2)return 1;const t=e.map((e=>rn(e,w))),s=function(e){if(e.length<2)return[{years:0,months:0,days:0}];const t=e.map(((t,s)=>{if(0===s)return{years:0,months:0,days:0};const o=Qo.fromTimestamp(e[s-1].getTime()),i=xi(o,t),n=Ei(o,t)%12;o.setFullYear(o.getFullYear()+i),o.setMonth(o.getMonth()+n);return{years:i,months:n,days:Ri(o,t)}}));return t.slice(1)}(t),o=(i=s).length<2?i[0]||{years:0,months:0,days:0}:i.every((e=>e.years===i[0].years&&e.months===i[0].months&&e.days===i[0].days))?i[0]:void 0;var i;if(void 0===o)return;const n=1===Object.values(o).filter((e=>0!==e)).length,r=Object.values(o).every((e=>0===e));if(!n||r){const s=t.map(((e,s)=>{if(0===s)return 0;const o=t[s-1];return Math.floor(e.getTime())-Math.floor(o.getTime())})).slice(1);if(s.every((e=>e===s[0])))return e.length*(e[1]-e[0])}return{years:o.years*e.length,months:o.months*e.length,days:o.days*e.length}}_V.add("simple_value_copy",{condition:(e,t)=>!(1!==t.length||e.isFormula||e.format&&ur(e.format)),generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&Fr(e,{locale:w}).type===r.text&&PV.test(e.content),generateRule:(e,t,s)=>{const o=parseInt(e.content.match(FV)[0]),i=e.content.match(OV)[0],n=NV(e,t,(e=>e.type===r.text&&PV.test(e.value))).filter((e=>i===(e.value??"").toString().match(OV)[0])).map((e=>(e.value??"").toString().match(FV)[0])),a=n.reduce(((e,t)=>{const s=t.match(MV)[0].length;return s>e[1]?[t,s]:e}),[n[0],0]),l=a[1]?a[0].length:0;let c=LV(n.map((e=>parseInt(e))));return["up","left"].includes(s)&&1===n.length&&(c=-c),{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:i,current:o,increment:c,numberPostfixLength:l}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&Fr(e,{locale:w}).type===r.text,generateRule:()=>({type:"COPY_MODIFIER"}),sequence:20}).add("update_formula",{condition:e=>e.isFormula,generateRule:(e,t)=>({type:"FORMULA_MODIFIER",increment:t.length,current:0}),sequence:30}).add("increment_dates",{condition:(e,t)=>!e.isFormula&&Fr(e,{locale:w}).type===r.number&&!!e.format&&ur(e.format),generateRule:(e,t)=>{const s=kV(NV(e,t,(e=>e.type===r.number&&!!e.format&&ur(e.format))).map((e=>Number(e.value))));if(void 0===s)return{type:"COPY_MODIFIER"};const o=Fr(e,{locale:w});return"object"==typeof s?{type:"DATE_INCREMENT_MODIFIER",increment:s,current:o.type===r.number?o.value:0}:{type:"INCREMENT_MODIFIER",increment:s,current:o.type===r.number?o.value:0}},sequence:25}).add("increment_number",{condition:e=>!e.isFormula&&Fr(e,{locale:w}).type===r.number,generateRule:(e,t,s)=>{const o=NV(e,t,(e=>e.type===r.number&&!ur(e.format||""))).map((e=>Number(e.value)));let i=LV(o);["up","left"].includes(s)&&1===o.length&&(i=-i);const n=Fr(e,{locale:w});return{type:"INCREMENT_MODIFIER",increment:i,current:n.type===r.number?n.value:0}},sequence:40});class VV{cells;getters;index=0;direction;constructor(e,t,s){this.cells=e,this.getters=t,this.direction=s}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:s,tooltip:o}=DV.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:s,tooltip:o,origin:{col:e.data.col,row:e.data.row}}}}const UV=new class extends n{addTransformation(e,t,s){this.content[e]||(this.content[e]=new Map);for(const o of t)this.content[e].set(o,s);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}};const HV=new class extends n{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};function zV(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId!==t.sheetId)return e;const s=Qc(e.pivot.dataSet.zone,t),o=s?{...e.pivot.dataSet,zone:s}:void 0;return{...e,pivot:{...e.pivot,dataSet:o}}}function BV(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let s=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(const t of e)s>t&&s--}if("ADD_COLUMNS_ROWS"===t.type){s=s>("before"===t.position?t.base-1:t.base)?s+t.quantity:s}return s>0?{...e,quantity:s}:void 0}function GV(e,t){if(e.sheetId!==t.sheetId)return e;const s=Qc(e.zone,t);if(!s)return;const o=e.newTableRange?eh(e.newTableRange,t):void 0;return{...e,newTableRange:o,zone:s}}function WV(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let s;if("REMOVE_COLUMNS_ROWS"===t.type)s=ca(t.elements,[e.base])[0];else if("ADD_COLUMNS_ROWS"===t.type){s=la(bt(t.position,t.base),t.quantity,[e.base])[0]}return void 0!==s?{...e,base:s}:void 0}function $V(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;const s=Je(e.start,e.end+1);let o=[];if("REMOVE_COLUMNS_ROWS"===t.type)o=ca(t.elements,s);else if("ADD_COLUMNS_ROWS"===t.type){o=la(bt(t.position,t.base),t.quantity,s)}return 0!==o.length?{...e,start:Math.min(...o),end:Math.max(...o)}:void 0}function qV(e,t){return(e=qe(e)).pivot.measures.map((e=>{e.computedBy&&(e.computedBy.formula=SC(e.computedBy.sheetId,e.computedBy.formula,t))})),e}function ZV(e,t){return{...e,definition:PE(e.sheetId,e.definition,t)}}UV.addTransformation("ADD_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],WV),UV.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],WV),UV.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const s=t.sheetId;if(e.targetSheetId===s||e.sheetId===s)return;return e})),UV.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART","UPDATE_CAROUSEL"],(function(e,t){if(e.figureId===t.figureId)return;return e})),UV.addTransformation("DELETE_CHART",["UPDATE_CHART"],(function(e,t){if(e.chartId===t.chartId)return;return e})),UV.addTransformation("DELETE_CHART",["UPDATE_CAROUSEL"],(function(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter((e=>!("chart"===e.type&&e.chartId===t.chartId)))}}})),UV.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`});if(e.name===t.name)return{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),UV.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const s=[];for(const o of e.target)t.target.every((e=>!As(o,e)))&&s.push(o);if(s.length)return{...e,target:s};return})),UV.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],BV),UV.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],BV),UV.addTransformation("ADD_COLUMNS_ROWS",["UPDATE_TABLE"],GV),UV.addTransformation("REMOVE_COLUMNS_ROWS",["UPDATE_TABLE"],GV),UV.addTransformation("REMOVE_TABLE_STYLE",["CREATE_TABLE","UPDATE_TABLE"],(function(e,t){if(e.config?.styleId!==t.tableStyleId)return e;return{...e,config:{...e.config,styleId:Qx.styleId}}})),UV.addTransformation("ADD_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],$V),UV.addTransformation("REMOVE_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],$V),UV.addTransformation("REMOVE_PIVOT",["RENAME_PIVOT","DUPLICATE_PIVOT","INSERT_PIVOT","UPDATE_PIVOT"],(function(e,t){if(e.pivotId===t.pivotId)return;return e})),UV.addTransformation("DELETE_SHEET",["ADD_PIVOT","UPDATE_PIVOT"],(function(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId===t.sheetId)return{...e,pivot:{...e.pivot,dataSet:void 0}};return e})),UV.addTransformation("ADD_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],zV),UV.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],zV),HV.add("UPDATE_CELL",(function(e,t){const s=e.content&&SC(e.sheetId,e.content,t);return{...e,content:s}})),HV.add("ADD_CONDITIONAL_FORMAT",(function(e,t){const s=e.cf.rule;if(e={...e,cf:{...e.cf}},"CellIsRule"===s.type)e.cf.rule={...s,values:s.values.map((s=>SC(e.sheetId,s,t)))};else if("ColorScaleRule"===s.type){const{minimum:o,maximum:i,midpoint:n}=s;e.cf.rule={...s,minimum:{...o,value:o.value&&SC(e.sheetId,o.value,t)},maximum:{...i,value:i.value&&SC(e.sheetId,i.value,t)},midpoint:n?{...n,value:SC(e.sheetId,n.value,t)}:void 0}}else if("IconSetRule"===s.type){const{upperInflectionPoint:o,lowerInflectionPoint:i}=s;e.cf.rule={...s,upperInflectionPoint:{...o,value:SC(e.sheetId,o.value,t)},lowerInflectionPoint:{...i,value:SC(e.sheetId,i.value,t)}}}else"DataBarRule"===s.type&&(e.cf.rule={...s,rangeValues:s.rangeValues?CC(e.sheetId,s.rangeValues,t):void 0});return e})),HV.add("ADD_DATA_VALIDATION_RULE",(function(e,t){return(e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}}).rule.criterion.values=e.rule.criterion.values.map((s=>SC(e.sheetId,s,t))),e})),HV.add("ADD_PIVOT",qV),HV.add("UPDATE_PIVOT",qV),HV.add("CREATE_CHART",ZV),HV.add("UPDATE_CHART",ZV);const jV=[{match:function(e){return"sheetId"in e},fn:KV},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const s=KV(e,t);if("SKIP_TRANSFORMATION"!==s)return"IGNORE_COMMAND"===s?"IGNORE_COMMAND":e;const o=[];for(const s of e.target){const e=Qc(s,t);e&&o.push(e)}if(!o.length)return"IGNORE_COMMAND";return{...e,target:o}}},{match:function(e){return"sheetId"in e&&"zone"in e},fn:function(e,t){const s=KV(e,t);if("SKIP_TRANSFORMATION"!==s)return"IGNORE_COMMAND"===s?"IGNORE_COMMAND":e;const o=Qc(e.zone,t);if(o)return{...e,zone:o};return"IGNORE_COMMAND"}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const s=KV(e,t);if("SKIP_TRANSFORMATION"!==s)return"IGNORE_COMMAND"===s?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const s="COL"===t.dimension?"col":"row";let o=e[s];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(o))return"IGNORE_COMMAND";for(const t of e)o>=t&&o--}"ADD_COLUMNS_ROWS"===t.type&&(o>t.base||o===t.base&&"before"===t.position)&&(o+=t.quantity);return{...e,[s]:o}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const s of t.target){if(!(e.col===s.left&&e.row===s.top)&&Ds(e.col,e.row,s))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e&&"elements"in e},fn:function(e,t){const s=KV(e,t);if("SKIP_TRANSFORMATION"!==s)return"IGNORE_COMMAND"===s?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"!==t.type&&"REMOVE_COLUMNS_ROWS"!==t.type)return"SKIP_TRANSFORMATION";if(t.dimension!==e.dimension)return e;let o=[];if("REMOVE_COLUMNS_ROWS"===t.type)o=ca(t.elements,e.elements);else if("ADD_COLUMNS_ROWS"===t.type){o=la(bt(t.position,t.base),t.quantity,e.elements)}if(0===o.length)return"IGNORE_COMMAND";return{...e,elements:o}}},{match:function(e){return"ranges"in e},fn:function(e,t){if(!("sheetId"in t))return e;const s=e.ranges.map((e=>eh(e,t))).filter(ut);if(!s.length)return"IGNORE_COMMAND";return{...e,ranges:s}}}];function YV(e,t){const s=UV.getTransformation(e.type,t.type),o=s?s(e,t):function(e,t){for(const{match:s,fn:o}of jV)if(s(e)){const s=o(e,t);if("SKIP_TRANSFORMATION"===s)continue;if("IGNORE_COMMAND"===s)return;e=s}return e}(e,t);return o?function(e,t){const s=HV.get(e.type);if(!s)return e;const o=Ia(t);if(o)return s(e,o);return e}(o,t):o}function XV(e,t){let s=[...e];const o=new Set(UV.getKeys());for(const e of t)(o.has(e.type)||wa.contains(e.type))&&(s=s.reduce(((t,s)=>{const o=YV(s,e);return o&&t.push(o),t}),[]));return s}function KV(e,t){if(!("sheetId"in t))return e;const s="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===s?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class JV{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,s,o,i,n){this.rootCommand=o,this.timestamp=n,this.id=e,this.clientId=t,this._commands=[...s],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class QV extends Error{}class eU extends th{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new Xa;lastLocalOperation;constructor(e,t,s=Ce){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=s,this.debouncedMove=pt(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,s){if(!t.length||!s.length||!this.canApplyOptimisticUpdate())return;const o=new JV(this.uuidGenerator.uuidv4(),this.clientId,t,e,s,Date.now());this.revisions.append(o.id,o),"REQUEST_REDO"!==e.type&&(this.lastLocalOperation=o),this.trigger("new-local-state-update",{id:o.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:o.id,clientId:o.clientId,commands:o.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_UNDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_REDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:"local",name:"local"},this.clientId="local"),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&(this._move(this.awaitingClientPosition),this.awaitingClientPosition=void 0)}loadInitialMessages(e){const t=performance.now(),s=e.reduce(((e,t)=>e+("REMOTE_REVISION"===t.type?t.commands.length:1)),0);this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug("Replayed",s,"commands in",performance.now()-t,"ms")}async leave(e){e&&1===Object.keys(this.clients).length&&this.lastRevisionMessage&&"SNAPSHOT_CREATED"!==this.lastRevisionMessage?.type&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}async snapshot(e){if(0!==this.pendingMessages.length)return;const t=this.uuidGenerator.uuidv4();await this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){const t=this.clients[e];if(!t)throw new QV("The client left the session");return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(ut))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId])return void(this.awaitingClientPosition=e);const t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;const s=t?"CLIENT_MOVED":"CLIENT_JOINED",o=this.getCurrentClient();this.clients[this.clientId]={...o,position:e},this.transportService.sendMessage({type:s,version:1,client:{...o,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:s,timestamp:o}=e,i=new JV(e.nextRevisionId,t,s,void 0,void 0,o);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:XV(s,t)})}break;case"SNAPSHOT_CREATED":{const t=new JV(e.nextRevisionId,"server",[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger("snapshot"),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger("collaborative-event-received")}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;const t=this.clients[this.clientId];if(t){const{position:e}=t;e&&this.transportService.sendMessage({type:"CLIENT_MOVED",version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),this.waitingAck||this.sendPendingMessage()}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if("REMOTE_REVISION"===e.type){let t=this.revisions.get(e.nextRevisionId);0===t.commands.length&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw new Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.\n ${JSON.stringify(e)}`);this.waitingAck=!0,this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(this.waitingUndoRedoAck=!1),e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"SNAPSHOT_CREATED":this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter((t=>t.nextRevisionId!==e.nextRevisionId)),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case"REVISION_UNDONE":{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter((t=>t.nextRevisionId!==e.nextRevisionId));const t=this.pendingMessages.findIndex((e=>"REMOTE_REVISION"===e.type));-1!==t&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if("CLIENT_MOVED"===e.type&&e.client.id===this.clientId)return!0;switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter((({type:e})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const tU=new Set(["HIDE_COLUMNS_ROWS","UNHIDE_COLUMNS_ROWS","UNFOLD_HEADER_GROUP","UNGROUP_HEADERS","FOLD_HEADER_GROUP","FOLD_ALL_HEADER_GROUPS","UNFOLD_ALL_HEADER_GROUPS","FOLD_HEADER_GROUPS_IN_ZONE","UNFOLD_HEADER_GROUPS_IN_ZONE","CREATE_TABLE","UPDATE_TABLE","UPDATE_FILTER","REMOVE_TABLE","RESIZE_TABLE","CREATE_TABLE_STYLE","REMOVE_TABLE_STYLE"]);function sU(e){return tU.has(e.type)}const oU=[iU,function(e,t){return"target"in t&&Array.isArray(t.target)?{...qe(t),target:e.getSelectedZones()}:t},rU,function(e,t){return"ranges"in t?{...qe(t),ranges:e.getSelectedZones().map((t=>e.getRangeDataFromZone(e.getActiveSheetId(),t)))}:t}];function iU(e,t){return"sheetId"in t?{...qe(t),sheetId:e.getActiveSheetId()}:t}function nU(e,t){return"zone"in t?{...qe(t),zone:e.getSelectedZone()}:t}function rU(e,t){if(!("row"in t)||!("col"in t))return t;const{col:s,row:o}=e.getActivePosition();return{...qe(t),col:s,row:o}}const aU=new Xa;function lU(e,t){const s=e.getSelectedZone();return{...iU(e,t),elements:"COL"===t.dimension?Je(s.left,s.right+1):Je(s.top,s.bottom+1)}}function cU(e,t){const s=e.getSelectedZone();return{...qe(t),zone:s}}function hU(e,t){const s=qe(t),o=e.getSelectedZone(),{top:i,bottom:n,left:r,right:a}=o;return"cols"in s?s.cols=Je(r,a+1):"rows"in s&&(s.rows=Je(i,n+1)),s}function dU(e,t){const s=e.getSelectedZone();return{...iU(e,t),start:"COL"===t.dimension?s.left:s.top,end:"COL"===t.dimension?s.right:s.bottom}}const uU=new n;uU.add("UPDATE_CELL",pU),uU.add("CLEAR_CELL",pU),uU.add("CLEAR_CELLS",pU),uU.add("DELETE_CONTENT",pU),uU.add("ADD_MERGE",pU),uU.add("REMOVE_MERGE",pU),uU.add("SET_FORMATTING",pU),uU.add("CLEAR_FORMATTING",pU),uU.add("SET_BORDER",pU),uU.add("CREATE_TABLE",pU),uU.add("REMOVE_TABLE",pU),uU.add("HIDE_SHEET",pU),uU.add("ADD_COLUMNS_ROWS",(function(e,t){const s=e.getActivePosition();return{...iU(e,t),base:"COL"===t.dimension?s.col:s.row}})),uU.add("REMOVE_COLUMNS_ROWS",lU),uU.add("HIDE_COLUMNS_ROWS",lU),uU.add("RESIZE_COLUMNS_ROWS",lU),uU.add("CREATE_SHEET",(function(e,t){const s=qe(t);s.sheetId=aU.smallUuid();const o=t.name||e.getSheet(e.getActiveSheetId()).name,i=o.match(/(.+?)\d*$/)?.[1]||o;return s.name=e.getNextSheetName(i),s})),uU.add("CREATE_FIGURE",(function(e,t){const s=rU(e,iU(e,t));return s.figureId=aU.smallUuid(),s})),uU.add("CREATE_CHART",(function(e,t){const s=aU.smallUuid();return{...iU(e,t),figureId:s,chartId:s}})),uU.add("CREATE_IMAGE",(function(e,t){return{...iU(e,t),figureId:aU.smallUuid()}})),uU.add("GROUP_HEADERS",dU),uU.add("UNGROUP_HEADERS",dU),uU.add("UNFOLD_HEADER_GROUPS_IN_ZONE",nU),uU.add("FOLD_HEADER_GROUPS_IN_ZONE",nU);const gU=new n;function pU(e,t){let s=qe(t);for(const t of oU)s=t(e,s);return s}function mU(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return f(e.rootCommand)?function(e,t){if(!t)return;if(!uU.contains(t.type))return;return uU.get(t.type)(e,t)}(t,e.rootCommand):function(e,t,s){if(!gU.contains(t.type))return;return gU.get(t.type)(e,t,s)}(t,e.rootCommand,e.commands)}gU.add("PASTE",(function(e,t){return{type:"REPEAT_PASTE",pasteOption:qe(t.pasteOption),target:e.getSelectedZones()}})),gU.add("INSERT_CELL",cU),gU.add("DELETE_CELL",cU),gU.add("AUTORESIZE_COLUMNS",hU),gU.add("AUTORESIZE_ROWS",hU),gU.add("SORT_CELLS",(function(e,t){const s=e.getSelectedZone();return{...iU(e,t),col:s.left,row:s.top,zone:s}})),gU.add("SUM_SELECTION",pU),gU.add("SET_DECIMAL",pU),gU.add("DELETE_UNFILTERED_CONTENT",pU);class fU{trackedValues=new Set;domainToArray(e){return e.flatMap((e=>[e.field,tn(e.value)]))}isValuePresent(e,t){const s=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(s)}isHeaderPresent(e){const t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){const s=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(s)}trackHeader(e){const t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}}const vU=5242880;const bU={filterType:"criterion",type:"none",values:[]};class SU{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,s,o,i,n){if(this.getters=e,this.sheetId=t,this.boundaries=s,o.width<0||o.height<0)throw new Error("Viewport size cannot be negative");this.viewportWidth=o.height&&o.width,this.viewportHeight=o.width&&o.height,this.top=s.top,this.bottom=s.bottom,this.left=s.left,this.right=s.right,this.offsetX=n.x,this.offsetY=n.y,this.canScrollVertically=i.canScrollVertically,this.canScrollHorizontally=i.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:s}=this.getters.getColDimensions(this.sheetId,e),{end:o}=this.getters.getRowDimensions(this.sheetId,t);let i=s-this.offsetCorrectionX;this.canScrollHorizontally&&(i=Math.max(i,this.viewportWidth));let n=o-this.offsetCorrectionY;return this.canScrollVertically&&(n=Math.max(n,this.viewportHeight),o+de>n&&!this.getters.isReadonly()&&(n+=de)),{width:i,height:n}}getColIndex(e){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX+this.snapCorrection.x,this.left)}getRowIndex(e){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY+this.snapCorrection.y,this.top)}adjustPosition(e){const t=this.sheetId,s=this.getters.getMainCellPosition({sheetId:t,...e}),{col:o,row:i}=this.getters.getNextVisibleCellPosition(s);Ds(o,this.boundaries.top,this.boundaries)&&this.adjustPositionX(o),Ds(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){const t=this.sheetId,{start:s,end:o}=this.getters.getColDimensions(t,e);this.offsetX+this.viewportWidth+this.offsetCorrectionX<o?this.offsetX=o-this.viewportWidth:this.offsetX+this.offsetCorrectionX>s&&(this.offsetX=s-this.offsetCorrectionX),this.adjustViewportZoneX()}adjustPositionY(e){const t=this.sheetId,{start:s,end:o}=this.getters.getRowDimensions(t,e);this.offsetY+this.viewportHeight+this.offsetCorrectionY<o?this.offsetY=o-this.viewportHeight:this.offsetY+this.offsetCorrectionY>s&&(this.offsetY=s-this.offsetCorrectionY),this.adjustViewportZoneY()}willNewOffsetScrollViewport(e,t){return this.canScrollHorizontally&&this.offsetX!==e||this.canScrollVertically&&this.offsetY!==t}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){const t=Rs(e,this),s=this.snapCorrection.x,o=this.snapCorrection.y;if(t){return{x:this.getters.getColRowOffset("COL",this.left,t.left)+this.offsetCorrectionX-(this.left!==t.left?s:0),y:this.getters.getColRowOffset("ROW",this.top,t.top)+this.offsetCorrectionY-(this.top!==t.top?o:0),width:Math.min(this.getters.getColRowOffset("COL",t.left,t.right+1)-(this.left===t.left?s:0),this.viewportWidth),height:Math.min(this.getters.getColRowOffset("ROW",t.top,t.bottom+1)-(this.top===t.top?o:0),this.viewportHeight)}}}getFullRect(e){const t=Rs(e,this.boundaries),s=this.snapCorrection.x,o=this.snapCorrection.y;if(t){return{x:this.getters.getColRowOffset("COL",this.left,e.left)+this.offsetCorrectionX-s,y:this.getters.getColRowOffset("ROW",this.top,e.top)+this.offsetCorrectionY-o,width:this.getters.getColRowOffset("COL",e.left,e.right+1),height:this.getters.getColRowOffset("ROW",e.top,e.bottom+1)}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,s=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;const o=this.sheetId,i=this.getters.getNumberHeaders(o,e);let n=s,r=i;for(;n<=r&&n!==i&&-1!==r;){const i=Math.floor((n+r)/2),a=this.getters.getColRowOffset(e,s,i),l=this.getters.getHeaderSize(o,e,i);if(t>=a&&t<a+l)return i;t>=a+l?n=i+1:r=i-1}return-1}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){const{width:e}=this.getMaxSize();this.viewportWidth+this.offsetX>e&&(this.offsetX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){const{height:e}=this.getMaxSize();this.viewportHeight+this.offsetY>e&&(this.offsetY=Math.max(0,e-this.viewportHeight))}this.adjustViewportZoneY()}adjustViewportZoneX(){this.left=this.searchHeaderIndex("COL",this.offsetX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex("COL",Math.max(this.viewportWidth+this.snapCorrection.x-.1),this.left)),this.viewportWidth&&(-1===this.left&&(this.left=this.boundaries.left),-1===this.right&&(this.right=this.boundaries.right))}adjustViewportZoneY(){this.top=this.searchHeaderIndex("ROW",this.offsetY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex("ROW",Math.max(this.viewportHeight+this.snapCorrection.y-.1,0),this.top)),this.viewportHeight&&(-1===this.top&&(this.top=this.boundaries.top),-1===this.bottom&&(this.bottom=this.boundaries.bottom))}get snapCorrection(){return{x:Math.abs(this.offsetX-this.getters.getColRowOffset("COL",this.boundaries.left,Math.max(0,this.left))),y:Math.abs(this.offsetY-this.getters.getColRowOffset("ROW",this.boundaries.top,Math.max(0,this.top)))}}}const CU=(new n).add("settings",class extends Fk{static getters=["getLocale"];locale=w;allowDispatch(e){return"UPDATE_LOCALE"===e.type?bl(e.locale)?"Success":"InvalidLocale":"Success"}handle(e){if("UPDATE_LOCALE"===e.type){const t=this.locale,s=e.locale;this.history.update("locale",s),this.changeCellsDateFormatWithLocale(t,s)}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(const s of this.getters.getSheetIds())for(const[o,i]of Object.entries(this.getters.getCells(s))){let s;if(i.format===e.dateFormat&&(s=t.dateFormat),i.format===e.timeFormat&&(s=t.timeFormat),i.format===Ol(e)&&(s=Ol(t)),s){const{col:e,row:t,sheetId:i}=this.getters.getCellPosition(o);this.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:i,format:s})}}}import(e){this.locale=e.settings?.locale??w}export(e){e.settings={locale:this.locale}}}).add("sheet",class extends Fk{static getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheetIds","getVisibleSheetIds","isSheetVisible","doesHeaderExist","doesHeadersExist","getCell","getCellPosition","getColsZone","getRowCells","getRowsZone","getNumberCols","getNumberRows","getNumberHeaders","getGridLinesVisibility","getNextSheetName","getSheetSize","getSheetZone","getPaneDivisions","checkZonesExistInSheet","getCommandZones","getUnboundedZone","checkElementsIncludeAllNonFrozenHeaders","getDuplicateSheetName"];sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if("Success"!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?"NotEnoughSheets":"Success";case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"DUPLICATE_SHEET":return this.sheets[e.sheetIdTo]?"DuplicatedSheetId":this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?"DuplicatedSheetName":"Success";case"MOVE_SHEET":try{const t=this.orderedSheetIds.findIndex((t=>t===e.sheetId));return this.findIndexOfTargetSheet(t,e.delta),"Success"}catch(e){return"WrongSheetMove"}case"RENAME_SHEET":return this.isRenameAllowed(e);case"COLOR_SHEET":return!e.color||ao(e.color)?"Success":"InvalidColor";case"DELETE_SHEET":return this.getVisibleSheetIds().length>1?"Success":"NotEnoughSheets";case"ADD_COLUMNS_ROWS":return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?"InvalidQuantity":"Success":"InvalidHeaderIndex";case"REMOVE_COLUMNS_ROWS":{const t=Vt(e.elements),s=kt(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,s)?"InvalidHeaderIndex":this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?"NotEnoughElements":"Success"}case"FREEZE_ROWS":return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case"FREEZE_COLUMNS":return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return"Success"}}handle(e){switch(e.type){case"SET_GRID_LINES_VISIBILITY":this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case"CREATE_SHEET":const t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update("sheetIdsMapName",t.name,t.id);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.delta);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.newName);break;case"COLOR_SHEET":this.history.update("sheets",e.sheetId,"color",e.color);break;case"HIDE_SHEET":this.hideSheet(e.sheetId);break;case"SHOW_SHEET":this.showSheet(e.sheetId);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e);break;case"FREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,e.quantity,"COL");break;case"FREEZE_ROWS":this.setPaneDivisions(e.sheetId,e.quantity,"ROW");break;case"UNFREEZE_ROWS":this.setPaneDivisions(e.sheetId,0,"ROW");break;case"UNFREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,0,"COL");break;case"UNFREEZE_COLUMNS_ROWS":this.setPaneDivisions(e.sheetId,0,"COL"),this.setPaneDivisions(e.sheetId,0,"ROW")}}import(e){for(const t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(const t of e.sheets){const e=t.name||"Sheet"+(Object.keys(this.sheets).length+1),{colNumber:s,rowNumber:o}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:s,rows:aa(o),areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(ut).map((e=>{const t=this.sheets[e],s={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(s.panes=t.panes),s}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e){const t=Ze(e);for(const e in this.sheetIdsMapName)if(ua(e,t))return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,s){return"COL"===t?s>=0&&s<this.getNumberCols(e):s>=0&&s<this.getNumberRows(e)}doesHeadersExist(e,t,s){return s.every((s=>this.doesHeaderExist(e,t,s)))}getCell({sheetId:e,col:t,row:s}){const o=this.tryGetSheet(e),i=o?.rows[s]?.cells[t];if(void 0!==i)return this.getters.getCellById(i)}getColsZone(e,t,s){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:s}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(ut)}getRowsZone(e,t,s){return{top:t,bottom:s,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){return ha(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(void 0===t.bottom||void 0===t.right)return t;const s=0===t.left&&t.right===this.getNumberCols(e)-1,o=0===t.top&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:o?void 0:t.bottom,right:s&&!o?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,s){const o={...this.getPaneDivisions(e)};"COL"===s?o.xSplit=t:"ROW"===s&&(o.ySplit=t),this.history.update("sheets",e,"panes",o)}checkElementsIncludeAllNonFrozenHeaders(e,t,s){const o=this.getters.getPaneDivisions(e),i="ROW"===t?o.ySplit:o.xSplit,n=this.getters.getNumberHeaders(e,t);if(!i)return!1;return It(s,Je(i,n))}getCommandZones(e){const t=[];return"zone"in e&&t.push(e.zone),"target"in e&&t.push(...e.target),"ranges"in e&&t.push(...e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone))),"col"in e&&void 0!==e.col&&"row"in e&&void 0!==e.row&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(vs))return"InvalidRange";if(t.length){const s=this.getSheetZone(e);return t.every((e=>_s(e,s)))?"Success":"TargetOutOfSheet"}return"Success"}updateCellPosition(e){const{sheetId:t,cellId:s,col:o,row:i}=e;s?this.setNewPosition(s,t,o,i):this.clearPosition(t,o,i)}setNewPosition(e,t,s,o){const i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update("cellPosition",e,{row:o,col:s,sheetId:t}),this.history.update("sheets",t,"rows",o,"cells",s,e)}clearPosition(e,t,s){const o=this.sheets[e]?.rows[s].cells[t];o&&(this.history.update("cellPosition",o,void 0),this.history.update("sheets",e,"rows",s,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}createSheet(e,t,s,o,i){const n={id:e,name:t,numberOfCols:s,rows:aa(o),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},r=this.orderedSheetIds.slice();r.splice(i,0,n.id);const a=this.sheets;return this.history.update("orderedSheetIds",r),this.history.update("sheets",Object.assign({},a,{[n.id]:n})),n}moveSheet(e,t){const s=this.orderedSheetIds.slice(),o=s.findIndex((t=>t===e)),i=s.splice(o,1),n=this.findIndexOfTargetSheet(o,t);s.splice(n,0,i[0]),this.history.update("orderedSheetIds",s)}findIndexOfTargetSheet(e,t){for(;0!==t&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(0===t)return e;throw new Error("There is not enough visible sheets")}checkSheetName(e){const t=this.getters.tryGetSheetName(e.sheetId),s="RENAME_SHEET"===e.type?e.newName:e.name;if(void 0!==t&&s===t)return"UnchangedSheetName";const{orderedSheetIds:o,sheets:i}=this,n=s&&s.trim().toLowerCase();return o.find((t=>ua(i[t]?.name,n)&&t!==e.sheetId))?"DuplicatedSheetName":Fe.test(n)?"ForbiddenCharactersInSheetName":"Success"}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?"WrongSheetPosition":"Success"}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?"Success":"InvalidFreezeQuantity"}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?"Success":"InvalidFreezeQuantity"}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(const s of t)if(s.top<e.quantity&&e.quantity<=s.bottom)return"MergeOverlap";return"Success"}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(const s of t)if(s.left<e.quantity&&e.quantity<=s.right)return"MergeOverlap";return"Success"}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):"MissingSheetName"}renameSheet(e,t){const s=e.name;this.history.update("sheets",e.id,"name",t.trim());const o=Object.assign({},this.sheetIdsMapName);delete o[s],o[t]=e.id,this.history.update("sheetIdsMapName",o)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t,s){const o=qe(this.getSheet(e));o.id=t,o.name=s;for(let e=0;e<=o.numberOfCols;e++)for(let t=0;t<=o.rows.length;t++)o.rows[t]&&(o.rows[t].cells[e]=void 0);const i=this.orderedSheetIds.slice(),n=i.indexOf(e);i.splice(n+1,0,o.id),this.history.update("orderedSheetIds",i),this.history.update("sheets",Object.assign({},this.sheets,{[o.id]:o}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:s}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:o.id,col:e,row:s,content:t.content,format:t.format,style:t.style})}const r=Object.assign({},this.sheetIdsMapName);r[o.name]=o.id,this.history.update("sheetIdsMapName",r)}getDuplicateSheetName(e){return da(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){const t=e.name,s=Object.assign({},this.sheets);delete s[e.id],this.history.update("sheets",s);const o=this.orderedSheetIds.slice(),i=o.indexOf(e.id);o.splice(i,1),this.history.update("orderedSheetIds",o);const n=Object.assign({},this.sheetIdsMapName);delete n[t],this.history.update("sheetIdsMapName",n)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(const s of t)this.moveCellOnColumnsDeletion(e,s);const s=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",s-t.length);const o=t.filter((t=>t<e.panes.xSplit)).length;o&&this.setPaneDivisions(e.id,e.panes.xSplit-o,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(const s of Qe(t)){const t=s[s.length-1],o=s[0];this.moveCellOnRowsDeletion(e,t,o),this.updateRowsStructureOnDeletion(e,t,o)}const s=t.filter((t=>t<e.panes.ySplit)).length;s&&this.setPaneDivisions(e.id,e.panes.ySplit-s,"ROW")}addColumns(e,t,s,o){const i="before"===s?t:t+1;this.moveCellsOnAddition(e,i,o,"columns");const n=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",n+o),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+o,"COL")}addRows(e,t,s,o){const i="before"===s?t:t+1;this.addEmptyRows(e,o),this.moveCellsOnAddition(e,i,o,"rows"),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+o,"ROW")}moveCellOnColumnsDeletion(e,t){this.dispatch("CLEAR_CELLS",{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let s=0;s<e.rows.length;s++){const o=e.rows[s];for(const i in o.cells){const n=Number(i),r=o.cells[i];r&&n>t&&this.setNewPosition(r,e.id,n-1,s)}}}moveCellsOnAddition(e,t,s,o){const i=[];for(let n=0;n<e.rows.length;n++){const r=e.rows[n];if("rows"!==o||n>=t)for(const a in r.cells){const l=Number(a),c=r.cells[a];c&&("rows"===o||l>=t)&&i.push({sheetId:e.id,cellId:c,col:l+("columns"===o?s:0),row:n+("rows"===o?s:0),type:"UPDATE_CELL_POSITION"})}}for(const e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,s){this.dispatch("CLEAR_CELLS",{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:s}]});const o=s-t+1;for(let t=0;t<e.rows.length;t++){const i=e.rows[t];if(t>s)for(const s in i.cells){const n=Number(s),r=i.cells[s];r&&this.setNewPosition(r,e.id,n,t-o)}}}updateRowsStructureOnDeletion(e,t,s){const o=[],i=e.rows.map((e=>e.cells)).reverse();for(const n in e.rows){const e=Number(n);e>=t&&e<=s||o.push({cells:i.pop()})}this.history.update("sheets",e.id,"rows",o)}addEmptyRows(e,t){const s=e.rows.slice();for(let e=0;e<t;e++)s.push({cells:{}});this.history.update("sheets",e.id,"rows",s)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(rs);let s=e.rowNumber,o=e.colNumber;for(const{col:e,row:i}of t)s=Math.max(s,i+1),o=Math.max(o,e+1);return{rowNumber:s,colNumber:o}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?"InvalidSheetId":"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?"DuplicatedSheetId":"Success"}checkZonesAreInSheet(e){return"sheetId"in e?"ranges"in e&&e.ranges.some((e=>""!==e._sheetId&&!this.getters.tryGetSheet(e._sheetId)))?"InvalidSheetId":this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):"Success"}}).add("header grouping",class extends Fk{static getters=["getHeaderGroups","getGroupsLayers","getVisibleGroupLayers","getHeaderGroup","getHeaderGroupsInZone","isGroupFolded","isRowFolded","isColFolded"];groups={};allowDispatch(e){switch(e.type){case"GROUP_HEADERS":{const{start:t,end:s,sheetId:o}=e;if(!this.getters.tryGetSheet(o))return"InvalidSheetId";if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,s]))return"InvalidHeaderGroupStartEnd";if(t>s)return"InvalidHeaderGroupStartEnd";if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,s))return"HeaderGroupAlreadyExists";break}case"UNGROUP_HEADERS":{const{start:t,end:s,sheetId:o}=e;if(!this.getters.tryGetSheet(o))return"InvalidSheetId";if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,s]))return"InvalidHeaderGroupStartEnd";if(t>s)return"InvalidHeaderGroupStartEnd";break}case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUP":if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return"UnknownHeaderGroup";if(Je(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every((s=>s>=t.start&&s<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,s))))return"NotEnoughElements"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("groups",e.sheetId,{ROW:[],COL:[]});break;case"GROUP_HEADERS":this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case"UNGROUP_HEADERS":this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case"DUPLICATE_SHEET":{const t=qe(this.groups[e.sheetId]);this.history.update("groups",e.sheetIdTo,t);break}case"DELETE_SHEET":{const t={...this.groups};delete t[e.sheetId],this.history.update("groups",t);break}case"ADD_COLUMNS_ROWS":const t=bt(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case"REMOVE_COLUMNS_ROWS":this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case"UNFOLD_HEADER_GROUP":{const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case"FOLD_HEADER_GROUP":{const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case"UNFOLD_ALL_HEADER_GROUPS":{const t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(const s of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,s);break}case"FOLD_ALL_HEADER_GROUPS":{const t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(const s of t)this.foldHeaderGroup(e.sheetId,e.dimension,s);break}case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":{const t="UNFOLD_HEADER_GROUPS_IN_ZONE"===e.type?"unfold":"fold",s=this.getGroupsLayers(e.sheetId,e.dimension);"fold"===t&&s.reverse();const o=s.flat(),i="ROW"===e.dimension?e.zone.top:e.zone.left,n="ROW"===e.dimension?e.zone.bottom:e.zone.right,r=new Set;for(let e=i;e<=n;e++){const s=o.filter((t=>t.start-1<=e&&e<=t.end));for(const e of s)if(!("fold"===t&&e.isFolded||"unfold"===t&&!e.isFolded)){r.add(e);break}}for(const s of r)"unfold"===t?this.unfoldHeaderGroup(e.sheetId,e.dimension,s):this.foldHeaderGroup(e.sheetId,e.dimension,s);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,s,o){return this.getHeaderGroups(e,t).find((e=>e.start===s&&e.end===o))}getHeaderGroupsInZone(e,t,s){return this.getHeaderGroups(e,t).filter((e=>{const o="ROW"===t?s.top:s.left,i="ROW"===t?s.bottom:s.right;return this.doGroupOverlap(e,o,i)}))}getGroupsLayers(e,t){const s=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(s,0,0)}getVisibleGroupLayers(e,t){const s=this.getGroupsLayers(e,t);for(const o of s)for(let s=o.length-1;s>=0;s--){const i=o[s];if(0===i.start)continue;Je(i.start-1,i.end+1).every((s=>this.getters.isHeaderHiddenByUser(e,t,s)))&&o.splice(s,1)}return s.filter((e=>e.length>0))}isGroupFolded(e,t,s,o){return this.getHeaderGroup(e,t,s,o)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,"ROW").some((e=>e.start<=t&&t<=e.end&&e.isFolded))}isColFolded(e,t){return this.getters.getHeaderGroups(e,"COL").some((e=>e.start<=t&&t<=e.end&&e.isFolded))}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,s,o=0){const i={};for(const t of e)i[this.getGroupId(t)]=t.isFolded;const n={};for(const t of e)for(let e=t.start;e<=t.end;e++)n[e]=n[e]?n[e]+1:1;for(let e=t;e<=s;e++)n[e]=n[e]?n[e]+o:o;const r=Math.max(...Object.values(n),0),a=Array.from({length:r},(()=>[])),l=Math.max(s,...e.map((e=>e.end))),c=Math.min(t,...e.map((e=>e.start)));for(let e=c;e<=l;e++){const t=n[e]||0;for(let s=0;s<t;s++){const t=a[s].at(-1);if(t&&Dt([t.end,e]))t.end++;else{const t={start:e,end:e};a[s].push(t)}}}for(const e of a)for(const t of e)t.isFolded=i[this.getGroupId(t)];return a}groupHeaders(e,t,s,o){const i=this.getHeaderGroups(e,t),n=this.bricksFallingAlgorithm(i,s,o,1).flat();this.history.update("groups",e,t,this.removeDuplicateGroups(n))}unGroupHeaders(e,t,s,o){const i=this.getHeaderGroups(e,t),n=this.bricksFallingAlgorithm(i,s,o,-1).flat();this.history.update("groups",e,t,this.removeDuplicateGroups(n))}moveGroupsOnHeaderInsertion(e,t,s,o){const i=this.groups[e][t];for(let n=0;n<i.length;n++){const r=i[n],[a,l]=la(s,o,[r.start,r.end]);a===r.start&&l===r.end||this.history.update("groups",e,t,n,{...r,start:a,end:l})}}moveGroupsOnHeaderDeletion(e,t,s){const o=this.getHeaderGroups(e,t),i=[];for(const e of o){const t=ca(s,Je(e.start,e.end+1));0!==t.length&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update("groups",e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,s){return e.start<=s&&e.end>=t}removeDuplicateGroups(e){const t={};for(const s of e)t[this.getGroupId(s)]=s;return Object.values(t)}findGroupWithStartEnd(e,t,s,o){return this.getHeaderGroups(e,t).find((e=>e.start===s&&e.end===o))}foldHeaderGroup(e,t,s){const o=this.getGroupIndex(e,t,s.start,s.end);if(void 0===o)return;this.history.update("groups",e,t,o,"isFolded",!0);const i=this.getters.getHeaderGroups(e,t);for(let o=0;o<i.length;o++){const n=i[o];n.start===s.start&&n.end<=s.end&&this.history.update("groups",e,t,o,"isFolded",!0)}}unfoldHeaderGroup(e,t,s){const o=this.getGroupIndex(e,t,s.start,s.end);if(void 0===o)return;this.history.update("groups",e,t,o,"isFolded",!1);const i=this.getters.getHeaderGroups(e,t);for(let o=0;o<i.length;o++){const n=i[o];n.start===s.start&&n.end>=s.end&&this.history.update("groups",e,t,o,"isFolded",!1)}}getGroupIndex(e,t,s,o){const i=this.groups[e][t].findIndex((e=>e.start===s&&e.end===o));return-1===i?void 0:i}import(e){for(const t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(const e of["ROW","COL"])for(const s of t.headerGroups[e]||[])this.groups[t.id][e].push({...s})}export(e){for(const t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(const t of e.sheets)for(const e of["ROW","COL"]){const s=this.getGroupsLayers(t.id,e);for(let o=0;o<s.length;o++){const i=s[o];for(const s of i){for(let i=s.start;i<=s.end;i++){const n=uA(t,e,i);n.outlineLevel=o+1,s.isFolded&&(n.isHidden=!0)}if(s.isFolded){uA(t,e,s.end+1).collapsed=!0}}}}}}).add("header visibility",class extends Fk{static getters=["checkElementsIncludeAllVisibleHeaders","getHiddenColsGroups","getHiddenRowsGroups","isHeaderHiddenByUser","isRowHiddenByUser","isColHiddenByUser"];hiddenHeaders={};allowDispatch(e){switch(e.type){case"HIDE_COLUMNS_ROWS":{if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";const t="COL"===e.dimension?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),s="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=s?"TooManyHiddenElements":Vt(e.elements)<0||kt(e.elements)>s?"InvalidHeaderIndex":"Success"}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?"NotEnoughElements":"Success":"InvalidSheetId"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":const t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update("hiddenHeaders",e.sheetId,t);break;case"DUPLICATE_SHEET":this.history.update("hiddenHeaders",e.sheetIdTo,qe(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(const s of[...e.elements].sort(((e,t)=>t-e)))t.splice(s,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=bt(e.position,e.base),s=Ot([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update("hiddenHeaders",e.sheetId,e.dimension,s);break}case"HIDE_COLUMNS_ROWS":for(const t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(const t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}checkElementsIncludeAllVisibleHeaders(e,t,s){return It(s,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,s){return"COL"===t?this.isColHiddenByUser(e,s):this.isRowHiddenByUser(e,s)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){const t=[[]],s=this.hiddenHeaders[e].COL;for(let e=0;e<s.length;e++){s[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],s=this.hiddenHeaders[e].ROW;for(let e=0;e<s.length;e++){s[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){const s=Je(0,this.getters.getNumberHeaders(e,t)),o=[];return this.getters.getHeaderGroups(e,t).forEach((e=>{e.isFolded&&o.push(...Je(e.start,e.end+1))})),s.filter((s=>!this.hiddenHeaders[e][t][s]&&!o.includes(s)))}import(e){for(const t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=Boolean(t.rows[e]?.isHidden);for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=Boolean(t.cols[e]?.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(const s of e.sheets){void 0===s.rows&&(s.rows={});for(let e=0;e<this.getters.getNumberRows(s.id);e++)(t||this.hiddenHeaders[s.id].ROW[e])&&(void 0===s.rows[e]&&(s.rows[e]={}),s.rows[e].isHidden||=this.hiddenHeaders[s.id].ROW[e]);void 0===s.cols&&(s.cols={});for(let e=0;e<this.getters.getNumberCols(s.id);e++)(t||this.hiddenHeaders[s.id].COL[e])&&(void 0===s.cols[e]&&(s.cols[e]={}),s.cols[e].isHidden||=this.hiddenHeaders[s.id].COL[e])}}}).add("tables",class extends Fk{static getters=["getCoreTable","getCoreTables","getCoreTableMatchingTopLeft"];tables={};nextTableId=1;adaptRanges(e,t){for(const s of this.getCoreTables(t))this.applyRangeChangeOnTable(t,s,e)}allowDispatch(e){switch(e.type){case"CREATE_TABLE":if(e.ranges.some((t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId)))return"InvalidSheetId";const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone));return $s(t)?this.checkValidations(e,(e=>this.getTablesOverlappingZones(e.sheetId,t).length?"TableOverlap":"Success"),(e=>this.checkTableConfigUpdateIsValid(e.config))):"NonContinuousTargets";case"UPDATE_TABLE":return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,(e=>this.checkTableConfigUpdateIsValid(e.config))):"TableNotFound";case"ADD_MERGE":for(const t of this.getCoreTables(e.sheetId)){const s=t.range.zone;for(const t of e.target)if(As(s,t))return"MergeInTable"}}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":{const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break}case"DUPLICATE_SHEET":{const t={};for(const s of this.getCoreTables(e.sheetId))t[s.id]="dynamic"===s.type?this.copyDynamicTableForSheet(e.sheetIdTo,s):this.copyStaticTableForSheet(e.sheetIdTo,s);this.history.update("tables",e.sheetIdTo,t);break}case"CREATE_TABLE":{const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e))),s=this.getters.getRangesUnion(t),o=this.getters.getMergesInZone(e.sheetId,s.zone);o.length&&this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:o});const i=this.consumeNextId(),n=e.config||Qx,r="dynamic"===e.tableType?this.createDynamicTable(i,s,n):this.createStaticTable(i,e.tableType,s,n);this.history.update("tables",e.sheetId,r.id,r);break}case"REMOVE_TABLE":{const t={};for(const s of this.getCoreTables(e.sheetId))e.target.every((e=>!Rs(s.range.zone,e)))&&(t[s.id]=s);this.history.update("tables",e.sheetId,t);break}case"UPDATE_TABLE":this.updateTable(e);break;case"UPDATE_CELL":{const t=e.sheetId;for(const s of this.getCoreTables(t)){if("dynamic"===s.type)continue;const o=this.canUpdateCellCmdExtendTable(e,s);"down"===o?this.extendTableDown(t,s):"right"===o&&this.extendTableRight(t,s)}break}case"DELETE_CONTENT":{const t={...this.tables[e.sheetId]};for(const s in t){const o=t[s];o&&e.target.some((e=>_s(o.range.zone,e)))&&this.dispatch("REMOVE_TABLE",{sheetId:e.sheetId,target:[o.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(ut):[]}getCoreTable({sheetId:e,col:t,row:s}){return this.getCoreTables(e).find((e=>Ds(t,s,e.range.zone)))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter((e=>t.some((t=>As(e.range.zone,t)))))}extendTableDown(e,t){const s=this.getters.extendRange(t.range,"ROW",1);this.history.update("tables",e,t.id,this.updateStaticTable(t,s))}extendTableRight(e,t){const s=this.getters.extendRange(t.range,"COL",1);this.history.update("tables",e,t.id,this.updateStaticTable(t,s))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:s,row:o},i){if(!e)return"none";const n=i.range.zone;let r="none";if(n.bottom+1===o&&s>=n.left&&s<=n.right?r="down":n.right+1===s&&o>=n.top&&o<=n.bottom&&(r="right"),"none"===r)return"none";const a="down"===r?{...n,bottom:n.bottom+1,top:n.bottom+1}:{...n,right:n.right+1,left:n.right+1};for(let e=a.top;e<=a.bottom;e++)for(let s=a.left;s<=a.right;s++){const o={sheetId:t,col:s,row:e},i=this.getters.getCell(o)?.content;if(i||this.getters.isInMerge(o)||this.getTablesOverlappingZones(t,[Us(o)]).length)return"none"}return r}getCoreTableMatchingTopLeft(e,t){for(const s of this.getCoreTables(e)){const e=s.range.zone;if(e.left===t.left&&e.top===t.top)return s}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return"Success";const t=this.getters.getRangeFromRangeData(e.newTableRange).zone,s=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if("Success"!==s)return s;const o=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!o)return"TableNotFound";return this.getTablesOverlappingZones(e.sheetId,[t]).filter((e=>e.id!==o.id)).length?"TableOverlap":"Success"}checkTableConfigUpdateIsValid(e){return e&&(void 0!==e.numberOfHeaders&&e.numberOfHeaders<0||e.hasFilters&&0===e.numberOfHeaders)?"InvalidTableConfig":"Success"}createStaticTable(e,t,s,o,i){const n=s.zone;if(!i){i=[];for(const e of Je(n.left,n.right+1)){const t={...n,left:e,right:e},r=this.consumeNextId();i.push(this.createFilterFromZone(r,s.sheetId,t,o))}}return{id:e,range:s,filters:i,config:o,type:t}}createDynamicTable(e,t,s){const o=Hs(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,o),config:s,type:"dynamic"}}updateTable(e){const t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;const s=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(s){const t=this.getters.getMergesInZone(e.sheetId,s.zone);this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:t})}const o=s||t.range,i=this.updateTableConfig(e.config,t.config),n=e.tableType??t.type;if("dynamic"===n&&"dynamic"!==t.type||"dynamic"!==n&&"dynamic"===t.type){const s="dynamic"===n?this.createDynamicTable(t.id,o,i):this.createStaticTable(t.id,n,o,i);this.history.update("tables",e.sheetId,t.id,s)}else{const s="dynamic"===t.type?this.updateDynamicTable(t,o,i):this.updateStaticTable(t,o,i,n);this.history.update("tables",e.sheetId,t.id,s)}}updateStaticTable(e,t,s,o=e.type){if("dynamic"===o)throw new Error("Cannot use updateStaticTable to update a dynamic table");const i=t||e.range,n=i.zone,r=this.updateTableConfig(s,e.config),a=r||e.config,l=[];if(t||r&&"numberOfHeaders"in r)for(const t of Je(n.left,n.right+1)){const s=n.top===e.range.zone.top?e.filters.find((e=>e.col===t)):void 0,o={...n,left:t,right:t},r=s?.id||this.consumeNextId();l.push(this.createFilterFromZone(r,i.sheetId,o,a))}return{...e,range:i,config:a,filters:l.length?l:e.filters,type:o}}updateDynamicTable(e,t,s){const o=t?this.getters.getRangeFromZone(t.sheetId,Hs(t.zone)):e.range,i=s||e.config;return{...e,range:o,config:i}}updateTableConfig(e,t){if(!e)return t;const s={...t,...e};return 0===e.numberOfHeaders?s.hasFilters=!1:!0===e.hasFilters&&(s.numberOfHeaders||=1),s}createFilterFromZone(e,t,s,o){return K_(e,this.getters.getRangeFromZone(t,s),o,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){const s=this.getters.getRangeFromZone(e,t.range.zone),o=t.filters.map((s=>{const o=this.getters.getRangeFromZone(e,s.rangeWithHeaders.zone);return K_(s.id,o,t.config,this.getters.getRangeFromZone)}));return{id:t.id,range:s,filters:o,config:qe(t.config),type:t.type}}copyDynamicTableForSheet(e,t){const s=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:s,config:qe(t.config),type:"dynamic"}}applyRangeChangeOnTable(e,t,s){const o=s(t.range);let i;switch(o.changeType){case"REMOVE":return void this.history.update("tables",e,t.id,void 0);case"NONE":return;default:i=o.range}if("dynamic"===t.type){const s=this.updateDynamicTable(t,i);return void this.history.update("tables",e,t.id,s)}const n=[];for(const e of t.filters){const o=s(e.rangeWithHeaders);switch(o.changeType){case"REMOVE":continue;case"NONE":n.push(e);break;default:const s=o.range,i=K_(e.id,s,t.config,this.getters.getRangeFromZone);n.push(i)}}const r=i.zone;if(n.length<Fs(r).numberOfCols){for(let s=r.left;s<=r.right;s++)if(!n.find((e=>e.col===s))){const o=this.consumeNextId(),i={...r,left:s,right:s};n.push(this.createFilterFromZone(o,e,i,t.config))}n.sort(((e,t)=>e.col-t.col))}const a=this.createStaticTable(t.id,t.type,i,t.config,n);this.history.update("tables",e,t.id,a)}consumeNextId(){const e=`${this.nextTableId}`;return this.history.update("nextTableId",this.nextTableId+1),e}import(e){for(const t of e.sheets)for(const e of t.tables||[]){const s=this.consumeNextId(),o=e.config||Qx,i=this.getters.getRangeFromSheetXC(t.id,e.range),n=e.type||"static",r="dynamic"===n?this.createDynamicTable(s,i,o):this.createStaticTable(s,n,i,o);this.history.update("tables",t.id,r.id,r)}}export(e){for(const t of e.sheets)for(const e of this.getCoreTables(t.id)){const s={range:Ss(e.range.zone),type:e.type};St(e.config,Qx)||(s.config=e.config),t.tables.push(s)}}exportForExcel(e){for(const t of e.sheets)for(const e of this.getCoreTables(t.id)){const s=Ss(e.range.zone);t.tables.push({range:s,filters:[],config:e.config})}}}).add("dataValidation",class extends Fk{static getters=["cellHasListDataValidationIcon","getDataValidationRule","getDataValidationRules","getValidationRuleForCell"];rules={};adaptRanges(e,t){this.adaptDVRanges(t,e),this.adaptDVFormulas(e)}adaptDVFormulas(e){for(const t in this.rules){for(let s=this.rules[t].length-1;s>=0;s--){const o=this.rules[t][s];for(let i=0;i<o.criterion.values.length;i++){const n=this.getters.adaptFormulaStringDependencies(t,o.criterion.values[i],e);this.history.update("rules",t,s,"criterion","values",i,n)}}}}adaptDVRanges(e,t){for(let s=this.rules[e].length-1;s>=0;s--){const o=this.rules[e][s];for(let i=o.ranges.length-1;i>=0;i--){const n=t(o.ranges[i]);switch(n.changeType){case"REMOVE":if(1===o.ranges.length)this.removeDataValidationRule(e,o.id);else{const t=o.ranges.slice();t.splice(i,1),this.history.update("rules",e,s,"ranges",t)}break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("rules",e,s,"ranges",i,n.range)}}}}allowDispatch(e){switch(e.type){case"ADD_DATA_VALIDATION_RULE":return this.getters.tryGetSheet(e.sheetId)?e.ranges.some((e=>!this.getters.tryGetSheet(e._sheetId)))?"InvalidSheetId":this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid)):"InvalidSheetId";case"REMOVE_DATA_VALIDATION_RULE":if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";if(!this.rules[e.sheetId].find((t=>t.id===e.id)))return"UnknownDataValidationRule"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("rules",e.sheetId,[]);break;case"DUPLICATE_SHEET":{const t=qe(this.rules[e.sheetId]).map((t=>({...t,ranges:t.ranges.map((t=>Sa(e.sheetId,e.sheetIdTo,t)))})));this.history.update("rules",e.sheetIdTo,t);break}case"DELETE_SHEET":{const t={...this.rules};delete t[e.sheetId],this.history.update("rules",t);break}case"REMOVE_DATA_VALIDATION_RULE":this.removeDataValidationRule(e.sheetId,e.id);break;case"ADD_DATA_VALIDATION_RULE":{const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e)));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case"DELETE_CONTENT":{const t=ls(e.target),s=e.sheetId;for(const e of t)for(let t=e.top;t<=e.bottom;t++)for(let o=e.left;o<=e.right;o++){const e=this.getValidationRuleForCell({sheetId:s,col:o,row:t});if(e&&("isBoolean"===e.criterion.type||"isValueInList"===e.criterion.type&&!this.getters.getCell({sheetId:s,col:o,row:t})?.content)){const e=this.rules[s],i=[this.getters.getRangeFromSheetXC(s,as(o,t))],n=this.removeRangesFromRules(s,i,e);this.history.update("rules",s,n)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find((e=>e.id===t))}getValidationRuleForCell({sheetId:e,col:t,row:s}){if(this.rules[e])for(const o of this.rules[e])for(const e of o.ranges)if(Ds(t,s,e.zone))return o}cellHasListDataValidationIcon(e){const t=this.getValidationRuleForCell(e);return!!t&&!("isValueInList"!==t.criterion.type&&"isValueInRange"!==t.criterion.type||"arrow"!==t.criterion.displayStyle&&"chip"!==t.criterion.displayStyle)}addDataValidationRule(e,t){const s=this.rules[e];"isBoolean"===t.criterion.type?this.setCenterStyleToBooleanCells(t):"isValueInList"===t.criterion.type&&(t.criterion.values=Array.from(new Set(t.criterion.values)));const o=this.removeRangesFromRules(e,t.ranges,s,t.id),i=o.findIndex((e=>e.id===t.id));-1!==i?(o[i]=t,this.history.update("rules",e,o)):this.history.update("rules",e,[...o,t])}removeRangesFromRules(e,t,s,o){s=qe(s);for(const e of s)e.id!==o&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return s.filter((e=>e.ranges.length>0))}removeDataValidationRule(e,t){const s=this.rules[e].filter((e=>e.id!==t));this.history.update("rules",e,s)}setCenterStyleToBooleanCells(e){for(const t of ya(e.ranges)){const e=this.getters.getCell(t),s={...e?.style,align:e?.style?.align??"center",verticalAlign:e?.style?.verticalAlign??"middle"};this.dispatch("UPDATE_CELL",{...t,style:s})}}checkEmptyRange(e){return e.ranges.length?"Success":"EmptyRange"}import(e){for(const t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(const e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map((e=>this.getters.getRangeFromSheetXC(t.id,e)))})}export(e){if(e.sheets)for(const t of e.sheets){t.dataValidationRules=[];for(const e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map((e=>this.getters.getRangeString(e,t.id)))})}}exportForExcel(e){if(e.sheets)for(const t of e.sheets){t.dataValidationRules=[];for(const e of this.rules[t.id]){const s={...qe(e),ranges:e.ranges.map((e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0})))};"isValueInRange"===e.criterion.type&&(s.criterion.values=e.criterion.values.map((e=>{const s=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(s,t.id,{useBoundedReference:!0,useFixedReference:!0})}))),t.dataValidationRules.push(s)}}}checkCriterionTypeIsValid(e){return FR.contains(e.rule.criterion.type)?"Success":"UnknownDataValidationCriterionType"}checkCriterionHasValidNumberOfValues(e){const t=e.rule.criterion,s=FR.get(t.type).numberOfValues(t);return void 0!==s&&t.values.length!==s?"InvalidNumberOfCriterionValues":"Success"}checkCriterionValuesAreValid(e){const t=e.rule.criterion,s=FR.get(t.type);return t.values.some((e=>"onlyFormulas"===s.allowedValues&&!e.startsWith("=")||(e.startsWith("=")?"onlyLiterals"===s.allowedValues||gC(e).isBadExpression:!s.isCriterionValueValid(e))))?"InvalidDataValidationCriterionValue":"Success"}checkValidRange(e){const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e))),s=t.map((t=>this.getters.getRangeString(t,e.sheetId)));return s.some((e=>!this.getters.isRangeValid(e)))?"InvalidRange":"Success"}}).add("cell",class extends Fk{static getters=["zoneToXC","getCells","getTranslatedCellFormula","getCellStyle","getCellById","getFormulaString","getFormulaMovedInSheet"];nextId=1;cells={};adaptRanges(e,t,s){for(const o of Object.keys(this.cells))for(const i of Object.values(this.cells[o]||{}))if(i.isFormula)for(const n of i.compiledFormula.dependencies)if(n.sheetId===t||n.invalidSheetName===s.old){const t=e(n);"NONE"!==t.changeType&&this.history.update("cells",o,i.id,"compiledFormula","dependencies",i.compiledFormula.dependencies.indexOf(n),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case"CLEAR_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case"UPDATE_CELL_POSITION":return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?"Success":"InvalidCellId";default:return"Success"}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearFormatting(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case"UPDATE_CELL":this.updateCell(e.sheetId,e.col,e.row,e);break;case"CLEAR_CELL":this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col,row:e.row,content:"",style:null,format:""});break;case"CLEAR_CELLS":this.clearCells(e.sheetId,e.target);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"DELETE_SHEET":this.history.update("cells",e.sheetId,void 0)}}clearZones(e,t){for(const s of ls(t))for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++){const s=this.getters.getCell({sheetId:e,col:t,row:o});(s?.isFormula||s?.content)&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:o})}}setFormatter(e,t,s){for(const o of ls(t))for(let t=o.top;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:i,row:t,format:s})}clearFormatting(e,t){for(const s of ls(t))for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:null,format:""})}clearCells(e,t){for(const s of t)for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:"",style:null,format:""})}handleAddColumnsRows(e,t){let s,o;"before"===e.position?(s=Je(e.base,e.base+e.quantity),o=e.base+e.quantity):(s=Je(e.base+1,e.base+e.quantity+1),o=e.base),t(e.sheetId,o,s)}import(e){for(const t of e.sheets){const s=t.id,o=new C_;for(const e in t.cells)if(t.cells[e]){const{col:s,row:i}=rs(e),n={sheetId:t.id,col:s,row:i};o.set(n,{content:t.cells[e]})}for(const[e,s]of[["style",t.styles],["format",t.formats]])for(const[i,n]of $r(t.id,s)){const t=o.get(i);t?t[e]=n:o.set(i,{[e]:n})}for(const i of o.keysForSheet(s)){const s=o.get(i);if(s?.content||s?.format||s?.style){const o=this.importCell(t.id,s?.content,s?.style?e.styles[s?.style]:void 0,s?.format?e.formats[s?.format]:void 0);this.history.update("cells",t.id,o.id,o),this.dispatch("UPDATE_CELL_POSITION",{cellId:o.id,...i})}}}}export(e){const t={},s={};for(const o of e.sheets){const e=[],i=[],n={},r=Object.keys(this.cells[o.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const o of r){const r=this.getters.getCell(o),a=as(o.col,o.row),l=this.removeDefaultStyleValues(r.style);if(Object.keys(l).length){const s=Gr(l,t);e[s]??=[],e[s].push(o)}if(r.format){const e=Gr(r.format,s);i[e]??=[],i[e].push(o)}r.content&&(n[a]=r.content)}o.styles=Wr(e),o.formats=Wr(i),o.cells=n}e.styles=t,e.formats=s}importCell(e,t,s,o){const i=this.getNextUid();return this.createCell(i,t||"",o,s,e)}exportForExcel(e){this.export(e);const t=[];for(const s in e.formats||[])Dr(e.formats[s])||(t.push(Number(s)),delete e.formats[s]);if(t.length)for(const s of e.sheets)for(const e in s.formats){const o=s.formats[e];o&&t.includes(o)&&delete s.formats[e]}}removeDefaultStyleValues(e){const t={...e};for(const e in ue)t[e]===ue[e]&&delete t[e];return t}getCells(e){return this.cells[e]||{}}getCellById(e){const t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,s,o=!1){if(!s.length)return mt(t.map((e=>e.value)));let i=0;return mt(t.map((t=>{if("REFERENCE"===t.type){const t=s[i++];return this.getters.getRangeString(t,e,{useBoundedReference:o})}return t.value})))}getTranslatedCellFormula(e,t,s,o){const i=this.getters.createAdaptedRanges(pC(o).dependencies.map((t=>this.getters.getRangeFromSheetXC(e,t))),t,s,e);return this.getFormulaString(e,o,i)}getFormulaMovedInSheet(e,t,s){const o=pC(s).dependencies.map((t=>this.getters.getRangeFromSheetXC(e,t))),i=this.getters.removeRangesSheetPrefix(t,o);return this.getFormulaString(t,s,i)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,s=[{colFixed:!1,rowFixed:!1}]){const o=as((t=this.getters.expandZone(e,t)).left,t.top,s[0]),i=as(t.right,t.bottom,s.length>1?s[1]:s[0]),n=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),r=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=n.col===r.col&&n.row===r.row;return o===i||a?o:o+":"+i}setStyle(e,t,s){for(const o of ls(t))for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++){const o=this.getters.getCell({sheetId:e,col:t,row:i});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:s?{...o?.style,...s}:void 0})}}copyColumnStyle(e,t,s){for(let o=0;o<this.getters.getNumberRows(e);o++){const i=this.getFormat(e,t,o);if(i.style||i.format)for(const t of s)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,...i})}}copyRowStyle(e,t,s){for(let o=0;o<this.getters.getNumberCols(e);o++){const i=this.getFormat(e,o,t);if(i.style||i.format)for(const t of s)this.dispatch("UPDATE_CELL",{sheetId:e,col:o,row:t,...i})}}getFormat(e,t,s){const o={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:s}),n=this.getters.getCell(i);return n&&(n.style&&(o.style=n.style),n.format&&(o.format=n.format)),o}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,s,o){const i=this.getters.getCell({sheetId:e,col:t,row:s}),n="content"in o||"formula"in o,r=n?At(o?.content):i?.content||"";let a;a=void 0!==o.style?o.style||void 0:i?i.style:void 0;const l="format"in o?o.format:i&&i.format;if((n&&!r&&!o.formula||!n&&(!i||""===i.content))&&!a&&!l)return void(i&&(this.history.update("cells",e,i.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:s,sheetId:e})));const c=i?.id||this.getNextUid(),h=this.createCell(c,r,l,a,e);this.history.update("cells",e,h.id,h),this.dispatch("UPDATE_CELL_POSITION",{cellId:h.id,col:t,row:s,sheetId:e})}createCell(e,t,s,o,i){return t.startsWith("=")?this.createFormulaCell(e,t,s,o,i):this.createLiteralCell(e,t,s,o)}createLiteralCell(e,t,s,o){const i=this.getters.getLocale(),n=Or(t,i);return _r(s=s||("number"==typeof n?fr(t,i)||vr(t):void 0))||qi(t)||(t=tn(n)),{id:e,content:t,style:o,format:s,isFormula:!1,parsedValue:n}}createFormulaCell(e,t,s,o,i){const n=gC(t);return n.dependencies.length?this.createFormulaCellWithDependencies(e,n,s,o,i):{id:e,content:t,style:o,format:s,isFormula:!0,compiledFormula:{...n,dependencies:[]}}}createFormulaCellWithDependencies(e,t,s,o,i){const n=[];for(const e of t.dependencies)n.push(this.getters.getRangeFromSheetXC(i,e));return new Ok(e,t,s,o,n,i,this.getters.getRangeString)}checkCellOutOfSheet(e){const{sheetId:t,col:s,row:o}=e;if(!this.getters.tryGetSheet(t))return"InvalidSheetId";return Ds(s,o,this.getters.getSheetZone(t))?"Success":"TargetOutOfSheet"}checkUselessClearCell(e){const t=this.getters.getCell(e);return t&&(t.content||t.style||t.format)?"Success":"NoChanges"}checkUselessUpdateCell(e){const t=this.getters.getCell(e),s="style"in e,o="format"in e;return("content"in e||"formula"in e)&&t?.content!==e.content||s&&!St(t?.style,e.style)||o&&t?.format!==e.format?"Success":"NoChanges"}}).add("merge",class extends Fk{static getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge","getSelectionRangeString","isMainCellPosition"];nextId=1;merges={};mergeCellMap={};allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return"Success"}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;for(const s of Object.values(t).filter(ut))this.addMerge(e.sheetIdTo,s.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(ut)}getMerge({sheetId:e,col:t,row:s}){const o=this.mergeCellMap[e],i=o?t in o&&o[t]?.[s]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){const s=this.mergeCellMap[e];if(!s)return[];const o=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){const t=s[e]?.[i];t&&o.add(t)}return Array.from(o).map((t=>this.getMergeById(e,t))).filter(ut)}getSelectionRangeString(e,t){const s=this.getters.expandZone(e.sheetId,e.zone),o=ga({...e,zone:{...s,bottom:fa(e)?void 0:s.bottom,right:va(e)?void 0:s.right}},this.getters.getSheetSize),i=this.getters.getRangeString(o,t);if(this.isSingleCellOrMerge(e.sheetId,e.zone)){const{sheetName:e,xc:t}=na(i);return ra(e,t.split(":")[0])}return i}doesIntersectMerge(e,t){for(const s of this.getMerges(e))if(As(t,s))return!0;return!1}doesColumnsHaveCommonMerges(e,t,s){const o=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(o.id,t,i,s,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,s){const o=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(o.id,i,t,i,s))return!0;return!1}expandZone(e,t){const{left:s,right:o,top:i,bottom:n}=t;let r={left:s,right:o,top:i,bottom:n};for(const t in this.merges[e]){const s=this.getMergeById(e,parseInt(t));s&&As(s,r)&&(r=Es(s,r))}return xs(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,s,o,i){const n=this.getMerge({sheetId:e,col:t,row:s}),r=this.getMerge({sheetId:e,col:o,row:i});return!(!n||!r)&&xs(n,r)}isInMerge({sheetId:e,col:t,row:s}){const o=this.mergeCellMap[e];return!!o&&(t in o&&Boolean(o[t]?.[s]))}getMainCellPosition(e){const t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){const s=this.getters.getHiddenColsGroups(e),o=this.getters.getHiddenRowsGroups(e);for(const e of s)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(const e of o)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const s=this.getMerge({sheetId:e,col:t.left,row:t.top});if(s)return xs(t,s);const{numberOfCols:o,numberOfRows:i}=Fs(t);return 1===o&&1===i}isMainCellPosition(e){return St(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:s,right:o,top:i,bottom:n}=t;o=Ke(o,0,this.getters.getNumberCols(e)-1),n=Ke(n,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=n;t++)for(let n=s;n<=o;n++)if(n!==s||t!==i){const s=this.getters.getCell({sheetId:e,col:n,row:t});if(s&&""!==s.content)return!0}return!1}getMergeById(e,t){const s=this.merges[e]?.[t];return void 0!==s?Lk(t,s):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return"Success";return t.some((t=>this.isMergeDestructive(e,t)))?"MergeIsDestructive":"Success"}checkOverlap({target:e}){for(const t of e)for(const s of e)if(t!==s&&As(t,s))return"MergeOverlap";return"Success"}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return"Success";const{xSplit:s,ySplit:o}=this.getters.getPaneDivisions(e);return Ws(t,s,o)?"FrozenPaneOverlap":"Success"}checkMergedContentUpdate(e){const{col:t,row:s,content:o}=e;if(void 0===o)return"Success";const{col:i,row:n}=this.getMainCellPosition(e);return i===t&&n===s?"Success":"CellIsMerged"}checkMergeExists(e){const{sheetId:t,target:s}=e;for(const e of s){const{left:s,top:o}=e,i=this.getMerge({sheetId:t,col:s,row:o});if(void 0===i||!xs(e,i))return"InvalidTarget"}return"Success"}addMerge(e,t){let{left:s,right:o,top:i,bottom:n}=t;o=Ke(o,0,this.getters.getNumberCols(e)-1),n=Ke(n,0,this.getters.getNumberRows(e)-1);if(as(s,i)===as(o,n))return;const r=this.getters.getCell({sheetId:e,col:s,row:i}),a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,Ss({left:s,top:i,right:o,bottom:n})));const l=new Set;for(let t=i;t<=n;t++)for(let n=s;n<=o;n++){n===s&&t===i||this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,style:r?r.style:null,content:""});const o=this.getMerge({sheetId:e,col:n,row:t});o&&l.add(o.id),this.history.update("mergeCellMap",e,n,t,a)}for(const t of l){const{top:s,bottom:o,left:i,right:n}=this.getMergeById(e,t);for(let t=s;t<=o;t++)for(let s=i;s<=n;s++){const o={sheetId:e,col:s,row:t},i=this.getMerge(o);i&&i.id===a||(this.history.update("mergeCellMap",e,s,t,void 0),this.dispatch("CLEAR_CELL",o))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:s,top:o,bottom:i,right:n}=t,r=this.getMerge({sheetId:e,col:s,row:o});if(void 0!==r&&xs(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=o;t<=i;t++)for(let o=s;o<=n;o++)this.history.update("mergeCellMap",e,o,t,void 0)}}applyRangeChangeOnSheet(e,t){const s=Object.entries(this.merges[e]||{});for(const[o,i]of s)if(i){const s=i.zone,n=t(i);switch(n.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,s);break;default:const{numberOfCols:t,numberOfRows:i}=Fs(n.range.zone);1===t&&1===i?this.removeMerge(e,s):this.history.update("merges",e,parseInt(o,10),n.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:s,row:o}of Ms(t))this.history.update("mergeCellMap",e,s,o,t.id)}import(e){const t=e.sheets||[];for(const e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(const s of t)this.addMerge(e,ms(s))}export(e){for(const t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...Nk(e))}}exportForExcel(e){this.export(e)}}).add("headerSize",class extends Fk{static getters=["getUserRowSize","getColSize"];sizes={};handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("sizes",e.sheetId,{COL:Array(this.getters.getNumberCols(e.sheetId)).fill(void 0),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(void 0)});break;case"DUPLICATE_SHEET":this.history.update("sizes",e.sheetIdTo,qe(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const t={...this.sizes};delete t[e.sheetId],this.history.update("sizes",t);break;case"REMOVE_COLUMNS_ROWS":{const t=Ft(this.sizes[e.sheetId][e.dimension],e.elements);this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=this.sizes[e.sheetId][e.dimension],s=bt(e.position,e.base),o=t[e.base],i=Ot(t,Array(e.quantity).fill(o),s);this.history.update("sizes",e.sheetId,e.dimension,i);break}case"RESIZE_COLUMNS_ROWS":if("ROW"===e.dimension)for(const t of e.elements)this.history.update("sizes",e.sheetId,e.dimension,t,e.size||void 0);else for(const t of e.elements)this.history.update("sizes",e.sheetId,e.dimension,t,e.size||void 0)}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||ie)}getUserRowSize(e,t){const s=this.sizes[e]?.ROW[t];return s?Math.round(s):void 0}import(e){for(const t of e.sheets){const e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(const[s,o]of Object.entries(t.rows))o.size&&(e.ROW[s]=o.size);for(const[s,o]of Object.entries(t.cols))o.size&&(e.COL[s]=o.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(const s of e.sheets){void 0===s.rows&&(s.rows={});for(const e of Je(0,this.getters.getNumberRows(s.id)))(t||this.sizes[s.id].ROW[e])&&(s.rows[e]={...s.rows[e],size:this.getUserRowSize(s.id,e)??ne});void 0===s.cols&&(s.cols={});for(const e of Je(0,this.getters.getNumberCols(s.id)))(t||this.sizes[s.id].COL[e])&&(s.cols[e]={...s.cols[e],size:this.getColSize(s.id,e)})}}}).add("borders",class extends Fk{static getters=["getCellBorder","getBorders","getBordersColors","getCellBordersInZone"];borders={};allowDispatch(e){return"SET_BORDER"===e.type?this.checkValidations(e,this.checkBordersUnchanged,this.ensureHasBorder):"Success"}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":this.history.update("borders",e.sheetIdTo,qe(this.borders[e.sheetId]));break;case"DELETE_SHEET":const t={...this.borders};delete t[e.sheetId],this.history.update("borders",t);break;case"SET_BORDER":e.border&&this.addBorders(e.sheetId,[Us(e)],e.border);break;case"SET_BORDERS_ON_TARGET":for(const t of e.target)for(let s=t.left;s<=t.right;s++)for(let o=t.top;o<=t.bottom;o++)this.addBorder(e.sheetId,{left:s,right:s,top:o,bottom:o},e.border&&Object.keys(e.border).length?e.border:void 0);break;case"SET_ZONE_BORDERS":const s=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));"clear"===e.border.position?this.clearBorders(e.sheetId,s):this.addBorders(e.sheetId,s,this.borderDataToNewBorderData(e.border));break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target)}}beforeHandle(e){"REMOVE_COLUMNS_ROWS"===e.type&&("ROW"===e.dimension?this.onRowRemove(e.sheetId,e.elements):this.onColRemove(e.sheetId,e.elements))}adaptRanges(e,t){const s=[];for(const o of this.borders[t]??[]){const i=e(this.getters.getRangeFromZone(t,o.zone));switch(i.changeType){case"RESIZE":case"CHANGE":case"MOVE":s.push({...o,zone:i.range.unboundedZone});break;case"NONE":s.push(o)}}this.history.update("borders",t,s.filter((e=>!this.borderIsClear(e))))}onRowRemove(e,t){const s=new Set(t),o=[];for(const t of this.borders[e]??[]){let e=t;s.has(t.zone.top)&&(e=qe(t),e.style.top=t.style.horizontal),void 0!==t.zone.bottom&&s.has(t.zone.bottom)&&(e=e===t?qe(t):e,e.style.bottom=t.style.horizontal),o.push(e)}this.history.update("borders",e,o)}onColRemove(e,t){const s=new Set(t),o=[];for(const t of this.borders[e]??[]){let e=t;s.has(t.zone.left)&&(e=qe(t),e.style.left=t.style.vertical),void 0!==t.zone.right&&s.has(t.zone.right)&&(e=e===t?qe(t):e,e.style.right=t.style.vertical),o.push(e)}this.history.update("borders",e,o.filter((e=>!this.borderIsClear(e))))}getCellBorder(e){return this.getZoneExternalBorders(e.sheetId,Us(e))}getZoneExternalBorders(e,t){const s={};for(const o of this.borders[e]??[])As(o.zone,t)&&(s.right=(t.right===o.zone.right?o.style.right:o.style.vertical)??s.right,s.left=(t.left===o.zone.left?o.style.left:o.style.vertical)??s.left,s.bottom=(t.bottom===o.zone.bottom?o.style.bottom:o.style.horizontal)??s.bottom,s.top=(t.top===o.zone.top?o.style.top:o.style.horizontal)??s.top);return s}getCellBordersInZone(e,t){const s=new C_;for(const o of this.borders[e]??[]){const{zone:i,style:n}=o,r=Rs(i,t);if(r)for(let t=r.left;t<=r.right;t++)for(let o=r.top;o<=r.bottom;o++){const r=s.get({sheetId:e,col:t,row:o})??{};r.right=(t===i.right?n.right:n.vertical)??r.right,r.left=(t===i.left?n.left:n.vertical)??r.left,r.bottom=(o===i.bottom?n.bottom:n.horizontal)??r.bottom,r.top=(o===i.top?n.top:n.horizontal)??r.top,s.set({sheetId:e,col:t,row:o},r)}}return s}getBordersColors(e){const t=new Set;for(const s of this.borders[e]??[])for(const e of Object.values(s.style))e?.color&&t.add(e.color);return[...t]}getBorders(e,t){const s=[];for(const o of this.borders[e]??[]){const e=Rs(o.zone,t);e&&s.push(this.computeBorderFromZone(e,o))}return s}computeBorderFromZone(e,t){const s=t.style,o=t.zone,i=e.top===o.top,n=e.bottom===o.bottom,r=e.left===o.left,a=e.right===o.right;return{zone:e,style:{top:i?s.top:s.horizontal,bottom:n?s.bottom:s.horizontal,left:r?s.left:s.vertical,right:a?s.right:s.vertical,vertical:s.vertical,horizontal:s.horizontal}}}borderIsClear(e){const t=e.style;if(t.left||t.right||t.bottom||t.top)return!1;const s=e.zone;return(!(void 0===s.bottom||s.top<s.bottom)||!t.horizontal)&&(!(void 0===s.right||s.left<s.right)||!t.vertical)}clearBorders(e,t){for(const s of t)this.removeAndClearAdjacent(e,s)}removeAndClearAdjacent(e,t){const s=[];for(const o of this.borders[e]??[])for(const e of ls([o.zone],[t]))for(const i of Zs(e,t)){const e=this.computeBorderFromZone(i,o),n=Ts(i,t);switch(n?.position){case"left":e.style.left=void 0;break;case"right":e.style.right=void 0;break;case"top":e.style.top=void 0;break;case"bottom":e.style.bottom=void 0}s.push(e)}this.history.update("borders",e,s)}addBorders(e,t,s){for(const o of t)this.addBorder(e,o,s)}addBorder(e,t,s,o=!1){const i=[],n=s?{zone:t,style:s}:void 0,r={left:o||!!s?.left,right:o||!!s?.right,top:o||!!s?.top,bottom:o||!!s?.bottom};let a=[t];for(const s of this.borders[e]??[]){const e=Rs(s.zone,t);if(e){if(n){let t=this.computeBorderFromZone(e,n).style;o||(t={...this.computeBorderFromZone(e,s).style,...wt(t)}),i.push({zone:e,style:t})}a=ls(a,[e]);for(const t of ls([s.zone],[e]))i.push(this.computeBorderFromZone(t,s))}else{const e=Ts(s.zone,t);if(e&&r[e.position])for(const e of Zs(s.zone,t)){const o=this.computeBorderFromZone(e,s),n=Ts(e,t);switch(n?.position){case"left":o.style.left=void 0;break;case"right":o.style.right=void 0;break;case"top":o.style.top=void 0;break;case"bottom":o.style.bottom=void 0}i.push(o)}else i.push(s)}}n&&i.push(...a.map((e=>this.computeBorderFromZone(e,n)))),this.history.update("borders",e,i.filter((e=>!this.borderIsClear(e))))}borderDataToNewBorderData(e){const t={},s={color:e.color??"#000000",style:e.style??"thin"};return["all","external","top"].includes(e.position)&&(t.top={...s}),["all","external","bottom"].includes(e.position)&&(t.bottom={...s}),["all","external","left"].includes(e.position)&&(t.left={...s}),["all","external","right"].includes(e.position)&&(t.right={...s}),["all","hv","v"].includes(e.position)&&(t.vertical={...s}),["all","hv","h"].includes(e.position)&&(t.horizontal={...s}),t}checkBordersUnchanged(e){const t=this.getCellBorder(e),s=!(e.border?.bottom||e.border?.left||e.border?.right||e.border?.top);return!t&&s||St(t,e.border)?"NoChanges":"Success"}ensureHasBorder(e){return e.border?"Success":"NoChanges"}addBordersToMerge(e,t){const s={...this.getZoneExternalBorders(e,t),...wt(this.getCellBorder({sheetId:e,col:t.left,row:t.top}))};this.addBorder(e,t,s,!0)}import(e){if(Object.keys(e.borders||{}).length)for(const t of e.sheets)for(const s in t.borders){const o=t.borders[s];this.addBorder(t.id,ms(s),e.borders[o])}for(const t of e.sheets)if(t.merges)for(const e of t.merges)this.addBordersToMerge(t.id,ms(e))}export(e){const t={};for(const s of e.sheets){s.borders={};for(const e of this.borders[s.id]??[])s.borders[Ss(e.zone)]=Gr(e.style,t)}e.borders=t}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends Fk{static getters=["getConditionalFormats","getRulesSelection","getRulesByCell","getAdaptedCfRanges"];cfRules={};adaptCFFormulas(e){for(const t in this.cfRules)for(const s of this.cfRules[t])if("DataBarRule"===s.rule.type&&s.rule.rangeValues){const o=e(s.rule.rangeValues);switch(o.changeType){case"REMOVE":this.history.update("cfRules",t,this.cfRules[t].indexOf(s),"rule","rangeValues",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",t,this.cfRules[t].indexOf(s),"rule","rangeValues",o.range)}}else if("CellIsRule"===s.rule.type)for(let o=0;o<s.rule.values.length;o++)this.history.update("cfRules",t,this.cfRules[t].indexOf(s),"rule","values",o,this.getters.adaptFormulaStringDependencies(t,s.rule.values[o],e));else if("IconSetRule"===s.rule.type)for(const o of["lowerInflectionPoint","upperInflectionPoint"])"formula"===s.rule[o].type&&this.history.update("cfRules",t,this.cfRules[t].indexOf(s),"rule",o,"value",this.getters.adaptFormulaStringDependencies(t,s.rule[o].value,e));else if("ColorScaleRule"===s.rule.type)for(const o of["minimum","maximum","midpoint"]){const i=s.rule[o];"formula"===i?.type&&i?.value&&this.history.update("cfRules",t,this.cfRules[t].indexOf(s),"rule",o,"value",this.getters.adaptFormulaStringDependencies(t,i.value,e))}}adaptCFRanges(e,t){for(const s of this.cfRules[e])for(const o of s.ranges){const i=t(o);switch(i.changeType){case"REMOVE":const t=s.ranges.slice();t.splice(s.ranges.indexOf(o),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(s),"ranges",t):this.removeConditionalFormatting(s.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(s),"ranges",s.ranges.indexOf(o),i.range)}}}adaptRanges(e,t){const s=t?[t]:Object.keys(this.cfRules);for(const t of s)this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return e.ranges.some((e=>!this.getters.tryGetSheet(e._sheetId)))?"InvalidSheetId":this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case"CHANGE_CONDITIONAL_FORMAT_PRIORITY":return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const s={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(s,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"CHANGE_CONDITIONAL_FORMAT_PRIORITY":this.changeCFPriority(e.cfId,e.delta,e.sheetId)}}import(e){for(const t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map((e=>this.mapToConditionalFormatInternal(t.id,e)))}export(e){if(e.sheets)for(const t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e))))}exportForExcel(e){if(e.sheets)for(const t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0}))))}getConditionalFormats(e){return this.cfRules[e]?.map((t=>this.mapToConditionalFormat(e,t)))||[]}getRulesSelection(e,t){const s=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{s.add(e)}))})),Array.from(s)}getRulesByZone(e,t){const s=new Set;for(let o=t.top;o<=t.bottom;o++)for(let i=t.left;i<=t.right;i++){this.getRulesByCell(e,i,o).forEach((e=>{s.add(e.id)}))}return s}getRulesByCell(e,t,s){const o=[];for(const i of this.cfRules[e])for(const e of i.ranges)Ds(t,s,e.zone)&&o.push(i);return new Set(o.map((t=>this.mapToConditionalFormat(e,t))))}getAdaptedCfRanges(e,t,s,o){if(0===s.length&&0===o.length)return;const i=this.getters.getConditionalFormats(e),n=i.findIndex((e=>e.id===t.id));let r=[];n>-1&&(r=i[n].ranges.map(ps));const a=ls(r,o);return ls([...s,...a],[]).map((t=>this.getters.getRangeDataFromZone(e,t)))}mapToConditionalFormat(e,t,{useBoundedReference:s}={useBoundedReference:!1}){const o=t.ranges.map((t=>this.getters.getRangeString(t,e,{useBoundedReference:s})));return"DataBarRule"!==t.rule.type?{...t,rule:{...t.rule},ranges:o}:{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:s})},ranges:o}}mapToConditionalFormatInternal(e,t){const s=t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)));return"DataBarRule"!==t.rule.type?{...t,rule:{...t.rule},ranges:s}:{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:s}}addConditionalFormatting(e,t){const s=this.cfRules[t].slice(),o=s.findIndex((t=>t.id===e.id)),i=this.mapToConditionalFormatInternal(t,e);o>-1?s.splice(o,1,i):s.push(i),this.history.update("cfRules",t,s)}checkValidPriorityChange(e,t,s){if(!this.cfRules[s])return"InvalidSheetId";const o=this.cfRules[s].findIndex((t=>t.id===e));if(-1===o)return"InvalidConditionalFormatId";const i=o-t;return i<0||i>=this.cfRules[s].length?"InvalidConditionalFormatId":"Success"}checkEmptyRange(e){return e.ranges.length?"Success":"EmptyRange"}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues);case"ColorScaleRule":return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case"IconSetRule":return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)))}return"Success"}checkCFHasChanged(e){const t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))}),s=this.cfRules[e.sheetId]?.find((t=>t.id===e.cf.id));return s&&St(t,s)?"NoChanges":"Success"}checkOperatorArgsNumber(e){const t=FR.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(void 0===t||t>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");const s=[],o=e=>void 0===e||""===e;return t>=1&&o(e.values[0])&&s.push("FirstArgMissing"),t>=2&&o(e.values[1])&&s.push("SecondArgMissing"),s.length?s:"Success"}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return"MinNaN";case"max":return"MaxNaN";case"mid":return"MidNaN";case"upperInflectionPoint":return"ValueUpperInflectionNaN";case"lowerInflectionPoint":return"ValueLowerInflectionNaN"}return"Success"}checkFormulaCompilation(e,t){if("formula"!==e.type)return"Success";if(gC(e.value||"").isBadExpression)switch(t){case"min":return"MinInvalidFormula";case"max":return"MaxInvalidFormula";case"mid":return"MidInvalidFormula";case"upperInflectionPoint":return"ValueUpperInvalidFormula";case"lowerInflectionPoint":return"ValueLowerInvalidFormula"}return"Success"}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):"Success"))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,s=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(s)?"LowerBiggerThanUpper":"Success"}checkMinBiggerThanMax(e){const t=e.minimum.value,s=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&Mk(t)>=Mk(s)?"MinBiggerThanMax":"Success"}checkMidBiggerThanMax(e){const t=e.midpoint?.value,s=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&Mk(t)>=Mk(s)?"MidBiggerThanMax":"Success"}checkMinBiggerThanMid(e){const t=e.minimum.value,s=e.midpoint?.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&Mk(t)>=Mk(s)?"MinBiggerThanMid":"Success"}checkCFValues(e){for(const t of e.values){if(!t.startsWith("="))continue;if(gC(t||"").isBadExpression)return"ValueCellIsInvalidFormula"}return"Success"}removeConditionalFormatting(e,t){const s=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==s){const e=this.cfRules[t].slice();e.splice(s,1),this.history.update("cfRules",t,e)}}changeCFPriority(e,t,s){const o=this.cfRules[s].findIndex((t=>t.id===e)),i=this.cfRules[s][o],n=o-t,r=[...this.cfRules[s]];r.splice(o,1),r.splice(n,0,i),this.history.update("cfRules",s,r)}}).add("figures",class extends Fk{static getters=["getFigures","getFigure","getFigureSheetId"];figures={};insertionOrders=[];adaptRanges(e,t){for(const s of this.getFigures(t)){const o=e(this.getters.getRangeFromZone(t,{left:s.col,right:s.col,top:s.row,bottom:s.row}));if("MOVE"===o.changeType)this.history.update("figures",t,s.id,"col",o.range.zone.right),this.history.update("figures",t,s.id,"row",o.range.zone.bottom);else if("REMOVE"===o.changeType){const o=e(this.getters.getRangeFromZone(t,{left:0,right:s.col-1,top:0,bottom:s.row-1}));let{offset:i,col:n,row:r}=s;"NONE"!==o.changeType&&(n=o.range.zone.right+1,r=o.range.zone.bottom+1),({offset:i,col:n,row:r}=this.getPositionInSheet(t,{...s,col:n,row:r})),this.history.update("figures",t,s.id,"offset",i),this.history.update("figures",t,s.id,"col",n),this.history.update("figures",t,s.id,"row",r)}}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case"UPDATE_FIGURE":return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case"DELETE_FIGURE":return this.checkFigureExists(e);default:return"Success"}}beforeHandle(e){if("DELETE_SHEET"===e.type)this.getters.getFigures(e.sheetId).forEach((t=>{this.dispatch("DELETE_FIGURE",{figureId:t.id,sheetId:e.sheetId})}))}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":const t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case"UPDATE_FIGURE":this.updateFigure(e);break;case"DELETE_FIGURE":this.removeFigure(e.figureId,e.sheetId);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case"DUPLICATE_SHEET":for(const t in this.figures[e.sheetId]){const s=this.figures[e.sheetId]?.[t];if(!s)continue;const o=t.split(we).pop(),i=`${e.sheetIdTo}${we}${o}`;this.dispatch("CREATE_FIGURE",{figureId:i,...s,size:{width:s.width,height:s.height},sheetId:e.sheetIdTo})}}}onColRemove(e){const t=this.getters.getNumberCols(e),s=new Array(t+1);s[t]=0;for(let o=t-1;o>=0;o--)s[o]=s[o+1]+this.getters.getColSize(e,o);for(const t of this.getFigures(e))if(t.offset.x+t.width>s[t.col]){let o=t.offset.x,i=t.col;for(o=Math.min(o,s[i]-t.width);o<0&&i>0;)i--,o=s[i]-t.width;o!==t.offset.x&&this.history.update("figures",e,t.id,"offset",{x:Math.max(o,0),y:t.offset.y}),i!==t.col&&this.history.update("figures",e,t.id,"col",i)}}onRowRemove(e){const t=this.getters.getNumberRows(e),s=new Array(t+1);s[t]=0;for(let o=t-1;o>=0;o--)s[o]=s[o+1]+(this.getters.getUserRowSize(e,o)??ne);for(const t of this.getFigures(e))if(t.offset.y+t.height>s[t.row]){let o=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??ne;t<o;t=this.getters.getUserRowSize(e,i)??ne)i+=1,o-=t;for(o=Math.min(o,s[i]-t.height);o<0&&i>0;)i--,o=s[i]-t.height;o!==t.offset.y&&this.history.update("figures",e,t.id,"offset",{x:t.offset.x,y:Math.max(0,o)}),i!==t.row&&this.history.update("figures",e,t.id,"row",i)}else t.offset.y+t.height>s[0]&&this.history.update("figures",e,t.id,"offset",{x:t.offset.x,y:Math.max(s[0]-t.height,0)})}getPositionInSheet(e,t){const{numberOfRows:s,numberOfCols:o}=this.getters.getSheetSize(e);let i,n,r=0,a=0,{col:l,row:c}=t;const h={...t.offset};for(i=s;r<t.height&&i>0;i--)r+=this.getters.getUserRowSize(e,i-1)??ne;for(c>i?(c=i,h.y=Math.max(r-t.height,0)):c===i&&(h.y=Ke(h.y,0,Math.max(r-t.height,0))),n=o;a<t.width&&n>0;n--)a+=this.getters.getColSize(e,n-1);return l>n?(l=n,h.x=Math.max(a-t.width,0)):n===l&&(h.x=Ke(h.x,0,Math.max(a-t.width,0))),{col:l,row:c,offset:h}}updateFigure(e){if(!("figureId"in e)||!("sheetId"in e))return;const{figureId:t,sheetId:s,...o}=e,i={...this.getFigure(s,t),...o};for(const[e,t]of Object.entries(o))switch(e){case"tag":case"offset":this.history.update("figures",s,i.id,e,t);break;case"col":case"row":case"width":case"height":void 0!==t&&this.history.update("figures",s,i.id,e,t)}}addFigure(e,t){this.history.update("figures",t,e.id,e),this.history.update("insertionOrders",this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update("insertionOrders",this.insertionOrders.filter((t=>!this.figures[e]?.[t]))),this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("insertionOrders",this.insertionOrders.filter((t=>t!==e))),this.history.update("figures",t,e,void 0)}checkFigureExists(e){return void 0===this.figures[e.sheetId]?.[e.figureId]?"FigureDoesNotExist":"Success"}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>t?.[e.figureId]))?"DuplicatedFigureId":"Success"}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?"WrongSheetPosition":"Success"}getFigures(e){const t=[];for(const s of this.insertionOrders){const o=this.figures[e]?.[s];o&&t.push(o)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>void 0!==this.figures[t]?.[e]))}import(e){for(const t of e.sheets)for(const e of t.figures)this.addFigure(e,t.id)}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const s=void 0;t.figures.push({...e,data:s})}}exportForExcel(e){return this.export(e)}}).add("chart",class extends Fk{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getFigureIdFromChartId","getContextCreationChart"];charts={};createChart=_E(this.getters);validateChartDefinition=e=>OE(this,e.definition);adaptRanges(e,t,s){for(const[o,i]of Object.entries(this.charts)){if(!i)continue;const n=i.chart.updateRanges(e,t,s);this.history.update("charts",o,n?{figureId:i.figureId,chart:n}:void 0)}}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.checkFigureArguments,this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists,this.checkChartChanged));case"DELETE_CHART":return this.checkChartExists(e);default:return"Success"}}handle(e){switch(e.type){case"CREATE_CHART":const{col:t,row:s,offset:o,size:i,sheetId:n,figureId:r}=e;this.getters.getFigure(n,r)||void 0===o||void 0===t||void 0===s||this.addFigure(r,n,t,s,o,i),this.addChart(e.figureId,e.chartId,e.definition);break;case"UPDATE_CHART":this.addChart(e.figureId,e.chartId,e.definition);break;case"DUPLICATE_SHEET":for(const t of this.getChartIds(e.sheetId)){const{chart:s,figureId:o}=this.charts[t]||{};if(!s||!o)continue;const i=this.getters.getFigure(e.sheetId,o);if(!i)continue;const n=o.split(we).pop(),r=`${e.sheetIdTo}${we}${n}`,a=t.split(we).pop(),l=`${e.sheetIdTo}${we}${a}`,c=s.duplicateInDuplicatedSheet(e.sheetIdTo);c&&this.dispatch("CREATE_CHART",{figureId:r,chartId:l,col:i.col,row:i.row,offset:i.offset,size:{width:i.width,height:i.height},definition:c.getDefinition(),sheetId:e.sheetIdTo})}break;case"DELETE_FIGURE":for(const t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch("DELETE_CHART",{chartId:t,sheetId:e.sheetId});break;case"DELETE_CHART":this.isChartDefined(e.chartId)&&this.history.update("charts",e.chartId,void 0);break;case"DELETE_SHEET":for(const t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw new Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){const t=this.charts[e]?.chart.type;if(!t)throw new Error("Chart not defined.");return t}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter((([,t])=>t?.chart.sheetId===e)).map((([e])=>e))}getChartDefinition(e){const t=this.charts[e]?.chart.getDefinition();if(!t)throw new Error(`There is no chart with the given id: ${e}`);return t}import(e){for(const t of e.sheets)if(t.figures)for(const e of t.figures)if("chart"===e.tag){const s=e.data.chartId,o=this.createChart(e.id,e.data,t.id);this.charts[s]={chart:o,figureId:e.id}}else if("carousel"===e.tag)for(const s in e.data.chartDefinitions||{}){const o=e.data.chartDefinitions[s],i=this.createChart(e.id,o,t.id);this.charts[s]={chart:i,figureId:e.id}}}export(e){if(e.sheets)for(const t of e.sheets){const e=this.getters.getFigures(t.id),s=[];for(const t of e){const e=t,o=Object.keys(this.charts).find((e=>this.charts[e]?.figureId===t.id));if(e&&"chart"===e.tag&&o){const t=this.charts[o]?.chart.getDefinition();t&&(e.data={...t,chartId:o},s.push(e))}else if(e&&"carousel"===e.tag){const o=Object.keys(this.charts).filter((e=>this.charts[e]?.figureId===t.id)),i={};for(const e of o)i[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:i},s.push(e)}else s.push(e)}t.figures=s}}addFigure(e,t,s,o,i,n={width:536,height:335}){this.dispatch("CREATE_FIGURE",{sheetId:t,figureId:e,col:s,row:o,offset:i,size:n,tag:"chart"})}addChart(e,t,s){const o=this.getters.getFigureSheetId(e);if(o){const i=this.createChart(e,s,o);this.history.update("charts",t,{figureId:e,chart:i})}}checkChartDuplicate(e){return this.isChartDefined(e.chartId)?"DuplicatedChartId":"Success"}checkChartExists(e){return this.isChartDefined(e.chartId)?"Success":"ChartDoesNotExist"}checkChartChanged(e){return e.figureId!==this.charts[e.chartId]?.figureId?"Success":St(this.getChartDefinition(e.chartId),e.definition)?"NoChanges":"Success"}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||void 0!==e.offset&&void 0!==e.col&&void 0!==e.row?"Success":"MissingFigureArguments"}}).add("carousel",class extends Fk{static getters=["getCarousel","doesCarouselExist"];carousels={};allowDispatch(e){switch(e.type){case"CREATE_CAROUSEL":return this.getters.getFigure(e.sheetId,e.figureId)?"DuplicatedFigureId":"Success";case"UPDATE_CAROUSEL":return this.carousels[e.sheetId]?.[e.figureId]?"Success":"InvalidFigureId"}return"Success"}handle(e){switch(e.type){case"CREATE_CAROUSEL":this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch("CREATE_FIGURE",{...e,tag:"carousel"}),this.history.update("carousels",e.sheetId,e.figureId,e.definition);break;case"UPDATE_CAROUSEL":this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update("carousels",e.sheetId,e.figureId,e.definition);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const s of t)if("carousel"===s.tag){const t=s.id.split(we).pop(),o=`${e.sheetIdTo}${we}${t}`,i=this.getCarousel(s.id);if(i){const t={width:s.width,height:s.height};this.dispatch("CREATE_CAROUSEL",{sheetId:e.sheetIdTo,figureId:o,offset:s.offset,col:s.col,row:s.row,size:t,definition:{items:i.items.map((t=>{if("carouselDataView"===t.type)return{...t};const s=t.chartId.split(we).pop(),o=`${e.sheetIdTo}${we}${s}`;return{...t,chartId:o}}))}})}}break}case"DELETE_FIGURE":this.history.update("carousels",e.sheetId,e.figureId,void 0);break;case"DELETE_SHEET":this.history.update("carousels",e.sheetId,void 0)}}doesCarouselExist(e){for(const t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(const t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw new Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){const s=new Set(e.definition.items.filter((e=>"chart"===e.type)).map((e=>e.chartId)));for(const o of t)"chart"!==o.type||s.has(o.chartId)||this.dispatch("DELETE_CHART",{chartId:o.chartId,sheetId:e.sheetId})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter((e=>"carousel"===e.tag));for(const s of e)this.history.update("carousels",t.id,s.id,{items:s.data.items,title:s.data.title})}}export(e){for(const t of e.sheets){const e=t.figures.filter((e=>"carousel"===e.tag));for(const s of e)this.carousels[t.id]?.[s.id]&&(s.data={...s.data,...this.carousels[t.id]?.[s.id]})}}}).add("image",class extends Fk{static getters=["getImage","getImagePath","getImageSize"];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?"InvalidFigureId":"Success"}handle(e){switch(e.type){case"CREATE_IMAGE":this.getters.getFigure(e.sheetId,e.figureId)||this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const s of t)if("image"===s.tag){const t=s.id.split(we).pop(),o=`${e.sheetIdTo}${we}${t}`,i=this.getImage(s.id);if(i){const t={width:s.width,height:s.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:o,offset:s.offset,col:s.col,row:s.row,size:t,definition:qe(i)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.figureId,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}garbageCollectExternalResources(){const e=new Set(this.getAllImages().map((e=>e.path)));for(const t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,s,o,i,n){this.dispatch("CREATE_FIGURE",{sheetId:t,figureId:e,col:s,row:o,offset:i,size:n,tag:"image"})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter((e=>"image"===e.tag));for(const s of e)this.history.update("images",t.id,s.id,s.data),this.syncedImages.add(s.data.path)}}export(e){for(const t of e.sheets){const e=t.figures.filter((e=>"image"===e.tag));for(const s of e)s.data=this.images[t.id]?.[s.id]}}exportForExcel(e){for(const t of e.sheets){t.images||(t.images=[]);const e=this.getters.getFigures(t.id),s=[];for(const t of e)if("image"===t?.tag){const e=this.getImage(t.id);e&&s.push({...t,data:qe(e)})}t.images=[...t.images,...s]}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(ut));return e}}).add("pivot_core",class extends Fk{static getters=["getPivotCoreDefinition","getPivotDisplayName","getPivotId","getPivotFormulaId","getPivotIds","getMeasureCompiledFormula","getPivotName","isExistingPivot"];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case"ADD_PIVOT":return this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case"UPDATE_PIVOT":return e.pivotId in this.pivots?St(e.pivot,this.pivots[e.pivotId]?.definition)?"NoChanges":""===e.pivot.name?"EmptyName":this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):"PivotIdNotFound";case"RENAME_PIVOT":if(!(e.pivotId in this.pivots))return"PivotIdNotFound";if(""===e.name)return"EmptyName";break;case"REMOVE_PIVOT":case"DUPLICATE_PIVOT":case"INSERT_PIVOT":case"DUPLICATE_PIVOT":if(!(e.pivotId in this.pivots))return"PivotIdNotFound"}return"Success"}handle(e){switch(e.type){case"ADD_PIVOT":{const{pivotId:t,pivot:s}=e;this.addPivot(t,s);break}case"INSERT_PIVOT":{const{sheetId:t,col:s,row:o,pivotId:i,table:n}=e,r={sheetId:t,col:s,row:o},{cols:a,rows:l,measures:c,fieldsType:h}=n,d=new AO(a,l,c,h||{}),u=this.getPivotFormulaId(i);this.insertPivot(r,u,d);break}case"RENAME_PIVOT":this.history.update("pivots",e.pivotId,"definition","name",e.name);break;case"REMOVE_PIVOT":{const t={...this.pivots};delete t[e.pivotId];const s=this.getPivotFormulaId(e.pivotId);this.history.update("formulaIds",s,void 0),this.history.update("pivots",t);break}case"DUPLICATE_PIVOT":{const{pivotId:t,newPivotId:s}=e,o=qe(this.getPivotCore(t).definition);o.name=e.duplicatedPivotName??o.name+" (copy)",this.addPivot(s,o);break}case"UPDATE_PIVOT":this.history.update("pivots",e.pivotId,"definition",qe(e.pivot)),this.compileCalculatedMeasures(e.pivot.measures)}}adaptRanges(e){for(const t in this.compiledMeasureFormulas)for(const s in this.compiledMeasureFormulas[t]){const o=this.compiledMeasureFormulas[t][s],i=[];for(const t of o.dependencies){const s=e(t);"NONE"===s.changeType?i.push(t):i.push(s.range)}const n=this.getters.getFormulaString(t,o.tokens,i);n!==s&&this.replaceMeasureFormula(t,s,n)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e){if(!e.computedBy)throw new Error(`Measure ${e.fieldName} is not computed by formula`);const t=e.computedBy.sheetId;return this.compiledMeasureFormulas[t][e.computedBy.formula]}addPivot(e,t,s=this.nextFormulaId.toString()){this.history.update("pivots",e,{definition:qe(t),formulaId:s}),this.compileCalculatedMeasures(t.measures),this.history.update("formulaIds",s,e),this.history.update("nextFormulaId",this.nextFormulaId+1)}compileCalculatedMeasures(e){for(const t of e)if(t.computedBy){const e=t.computedBy.sheetId,s=this.compileMeasureFormula(t.computedBy.sheetId,t.computedBy.formula);this.history.update("compiledMeasureFormulas",e,t.computedBy.formula,s)}}insertPivot(e,t,s){this.resizeSheet(e.sheetId,e,s);const o=s.getPivotCells();for(let s=0;s<o.length;s++)for(let i=0;i<o[s].length;i++){const n=o[s][i];this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col+s,row:e.row+i,content:Lc(t,n)})}}resizeSheet(e,{col:t,row:s},o){const i=o.getNumberOfDataColumns()+1,n=this.getters.getNumberCols(e),r=n-t;r<i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:n-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-r,position:"after"});const a=o.columns.length+o.rows.length,l=this.getters.getNumberRows(e),c=l-s;c<a&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:l-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a-c,position:"after"})}getPivotCore(e){const t=this.pivots[e];if(!t)throw new Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){const s=gC(t),o=s.dependencies.map((t=>this.getters.getRangeFromSheetXC(e,t)));return{...s,dependencies:o}}replaceMeasureFormula(e,t,s){this.history.update("compiledMeasureFormulas",e,t,void 0),this.history.update("compiledMeasureFormulas",e,s,this.compileMeasureFormula(e,s));for(const o in this.pivots){const i=this.pivots[o];if(i)for(const n of i.definition.measures)if(n.computedBy?.formula===t){const t=i.definition.measures.indexOf(n);this.history.update("pivots",o,"definition","measures",t,"computedBy",{formula:s,sheetId:e})}}}checkSortedColumnInMeasures(e){const t=e.measures.map((e=>e.id));return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?"InvalidDefinition":"Success"}checkDuplicatedMeasureIds(e){const t=new Set(e.measures.map((e=>e.id)));return e.measures.length!==t.size?"InvalidDefinition":"Success"}checkCustomFieldsAreValid(e){for(const t in e.customFields){const s=e.customFields[t],o=new Set,i=new Set;let n=!1;for(const e of s.groups){if(!e.name||i.has(e.name))return"InvalidPivotCustomField";if(e.values.some((e=>o.has(e))))return"InvalidPivotCustomField";if(e.isOtherGroup&&n)return"InvalidPivotCustomField";e.values.forEach((e=>o.add(e))),i.add(e.name),n||=!!e.isOtherGroup}}return"Success"}import(e){if(e.pivots)for(const[t,s]of Object.entries(e.pivots))this.addPivot(t,s,s.formulaId);this.history.update("nextFormulaId",e.pivotNextId||Dc(this.pivots)+1)}export(e){e.pivots={};for(const t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}}).add("spreadsheet_pivot_core",class extends Fk{allowDispatch(e){switch(e.type){case"ADD_PIVOT":case"UPDATE_PIVOT":const t=e.pivot;return this.checkDataSetValidity(t)}return"Success"}adaptRanges(e){for(const t of this.getters.getPivotIds()){const s=this.getters.getPivotCoreDefinition(t);if("SPREADSHEET"===s.type&&s.dataSet){const{sheetId:o,zone:i}=s.dataSet,n=Vk(this.getters.getRangeFromZone(o,i),e),r=n&&{sheetId:n.sheetId,zone:n.zone};this.dispatch("UPDATE_PIVOT",{pivotId:t,pivot:{...s,dataSet:r}})}}}checkDataSetValidity(e){if("SPREADSHEET"===e.type&&e.dataSet){const{zone:t,sheetId:s}=e.dataSet;return s&&this.getters.tryGetSheet(s)&&t&&vs(t)?this.getters.checkZonesExistInSheet(s,[t]):"InvalidDataSet"}return"Success"}}).add("tableStyle",class extends Fk{static getters=["getNewCustomTableStyleName","getTableStyle","getTableStyles","isTableStyleEditable"];styles={};allowDispatch(e){switch(e.type){case"CREATE_TABLE":case"UPDATE_TABLE":if(e.config?.styleId&&!this.styles[e.config.styleId])return"InvalidTableConfig";break;case"CREATE_TABLE_STYLE":if(!fT[e.templateName])return"InvalidTableStyle";try{ro(e.primaryColor)}catch(e){return"InvalidTableStyle"}}return"Success"}handle(e){switch(e.type){case"CREATE_TABLE_STYLE":const t=vT(e.tableStyleName,e.templateName,e.primaryColor);this.history.update("styles",e.tableStyleId,t);break;case"REMOVE_TABLE_STYLE":const s={...this.styles};delete s[e.tableStyleId],this.history.update("styles",s);for(const t of this.getters.getSheetIds())for(const s of this.getters.getCoreTables(t))s.config.styleId===e.tableStyleId&&this.dispatch("UPDATE_TABLE",{sheetId:t,zone:s.range.zone,config:{styleId:Qx.styleId}})}}getTableStyle(e){if(!this.styles[e])throw new Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return Bt(Go("Custom Table Style"),Object.values(this.styles).map((e=>e.displayName)),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!mT[e]}import(e){for(const e in mT)this.styles[e]=mT[e];for(const t in e.customTableStyles){const s=e.customTableStyles[t];this.styles[t]=vT(s.displayName,s.templateName,s.primaryColor)}}export(e){const t={};for(const e in this.styles)mT[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}}),yU=(new n).add("ui_sheet",class extends Rd{static getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getContiguousZone","computeTextYCoordinate"];ctx=document.createElement("canvas").getContext("2d");allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(const t of e.cols){const s=this.getColMaxWidth(e.sheetId,t);0!==s&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:s,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":this.autoResizeRows(e.sheetId,e.rows);break;case"DELETE_UNFILTERED_CONTENT":const t=[];for(const s of e.target){const o=Qe(Je(s.top,s.bottom+1).filter((t=>!this.getters.isRowFiltered(e.sheetId,t))));for(const e of o)t.push({...s,top:e[0],bottom:e[e.length-1]})}this.dispatch("DELETE_CONTENT",{sheetId:e.sheetId,target:t})}}getCellWidth(e){const t=this.getters.getCellComputedStyle(e);let s=0;const o=this.getters.getEvaluatedCell(e).formattedValue;if(o){const e=Wa(this.ctx,o,t,void 0);s+=Math.max(...e.map((e=>La(this.ctx,e,t))))}for(const t of this.getters.getCellIcons(e))s+=t.margin+t.size;if(this.getters.getDataValidationChipStyle(e)&&(s+=10),0===s)return 0;if(s+=2*ce,"wrap"===t.wrapping){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,s)}return s}getTextWidth(e,t){return La(this.ctx,e,t)}getCellText(e,t){const s=this.getters.getCell(e),o=this.getters.getLocale();if(t?.showFormula&&s?.isFormula)return El(s.content,o);if(t?.showFormula&&!s?.content)return"";{const i=this.getters.getEvaluatedCell(e),n=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>La(this.ctx,e,s?.style||{})}:void 0;return or(i.value,{format:i.format,locale:o,formatWidth:n})}}getCellMultiLineText(e,t){const s=this.getters.getCellStyle(e),o=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.maxWidth});return Wa(this.ctx,o,s,t.wrapText?t.maxWidth:void 0)}computeTextYCoordinate(e,t,s=ge,o=1){const i=e.y+1,n=Oa(t,o);if(e.height>n+2*ae){if("middle"===s)return Math.ceil(i+(e.height-n)/2);if("bottom"===s)return i+e.height-n-ae}return i+ae}getContiguousZone(e,t){const s=t=>{for(const s of Je(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:s,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:s,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(const s of Je(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:s}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:s}))return{...t,right:t.right+1}}return t};let o=!1,i=t;do{o=!1;const e=s(i);xs(i,e)||(o=!0,i=e)}while(o);return i}isCellEmpty(e){const t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===r.empty}getColMaxWidth(e,t){const s=Ms(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,kt(s))}checkSheetExists(e){return"sheetId"in e&&void 0===this.getters.tryGetSheet(e.sheetId)?"InvalidSheetId":"Success"}checkZonesAreInSheet(e){const t="sheetId"in e?e.sheetId:this.getters.tryGetActiveSheetId();if("ranges"in e&&e.ranges.some((e=>!this.getters.tryGetSheet(e._sheetId))))return"InvalidSheetId";const s=this.getters.getCommandZones(e);return!t&&s.length>0?"NoActiveSheet":t&&s.length>0?this.getters.checkZonesExistInSheet(t,s):"Success"}autoResizeRows(e,t){const s=[];for(const o of t){let t=0;for(const s of this.getters.getRowCells(e,o)){const o=this.getters.getCellById(s);if(!o)continue;const i=this.getters.getCellPosition(o.id),n=this.getters.getColSize(e,i.col);if(o.isFormula||this.getters.getArrayFormulaSpreadingOn(i)){const e=this.getters.getEvaluatedCell(i).formattedValue,s=Pa(this.ctx,e,o?.style,n);s>t&&s>ne&&(t=s)}else{const e=o.content,s=Pa(this.ctx,e,o?.style,n);s>=t&&s>ne&&(t=0)}}s.push(t||null)}const o=new Map(s.map((e=>[e,[]])));for(let e=0;e<s.length;e++)o.get(s[e])?.push(t[e]);for(const[t,s]of o)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:s,dimension:"ROW",size:t,sheetId:e})}}).add("ui_options",class extends Rd{static getters=["shouldShowFormulas"];showFormulas=!1;handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}).add("autofill",class extends Rd{static layers=["Autofill"];static getters=["getAutofillTooltip"];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){if("AUTOFILL_SELECT"===e.type){const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:Ke(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:Ke(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?"Success":"InvalidAutofillSelection"}return"Success"}handle(e){switch(e.type){case"AUTOFILL":this.autofill(!0);break;case"AUTOFILL_SELECT":this.select(e.col,e.row);break;case"AUTOFILL_AUTO":this.autofillAuto()}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),s=this.autofillZone,o=[];switch(this.direction){case"down":for(let e=t.left;e<=t.right;e++){const i=[];for(let s=t.top;s<=t.bottom;s++)i.push(as(e,s));const n=this.createGenerator(i);for(let t=s.top;t<=s.bottom;t++)o.push(this.computeNewCell(n,e,t))}break;case"up":for(let e=t.left;e<=t.right;e++){const i=[];for(let s=t.bottom;s>=t.top;s--)i.push(as(e,s));const n=this.createGenerator(i);for(let t=s.bottom;t>=s.top;t--)o.push(this.computeNewCell(n,e,t))}break;case"left":for(let e=t.top;e<=t.bottom;e++){const i=[];for(let s=t.right;s>=t.left;s--)i.push(as(s,e));const n=this.createGenerator(i);for(let t=s.right;t>=s.left;t--)o.push(this.computeNewCell(n,t,e))}break;case"right":for(let e=t.top;e<=t.bottom;e++){const i=[];for(let s=t.left;s<=t.right;s++)i.push(as(s,e));const n=this.createGenerator(i);for(let t=s.left;t<=s.right;t++)o.push(this.computeNewCell(n,t,e))}}if(e){const e={},t={},s={},i=this.getters.getActiveSheetId();for(const n of o)this.collectBordersData(n,e),this.autofillMerge(i,n),this.autofillCell(i,n),this.collectConditionalFormatsData(i,n,t),this.collectDataValidationsData(i,n,s);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,s),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){const s=JSON.stringify(e.border);s in t||(t[s]=[]),t[s].push(Us({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,s){const{originCol:o,originRow:i,col:n,row:r}=t,a=this.getters.getRulesByCell(e,o,i),l=as(n,r);for(const e of a)e.id in s||(s[e.id]=[]),s[e.id].push(l)}collectDataValidationsData(e,t,s){const{originCol:o,originRow:i,col:n,row:r}=t,a={sheetId:e,col:o,row:i},l=this.getters.getValidationRuleForCell(a);l&&(l.id in s||(s[l.id]=[]),s[l.id].push(Us({col:n,row:r})))}autofillCell(e,t){this.dispatch("UPDATE_CELL",{sheetId:e,col:t.col,row:t.row,content:t.content||"",style:t.style||null,format:t.format||""}),this.dispatch("AUTOFILL_CELL",t)}autofillBorders(e,t){for(const s in t){const o="undefined"===s?void 0:JSON.parse(s);this.dispatch("SET_BORDERS_ON_TARGET",{sheetId:e,border:o,target:ls(t[s])})}}autofillConditionalFormats(e,t){for(const s in t){const o=t[s],i=this.getters.getConditionalFormats(e).find((e=>e.id===s));if(!i)continue;const n=this.getters.getAdaptedCfRanges(e,i,o.map(ms),[]);n&&this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:n,sheetId:e})}}autofillDataValidations(e,t){for(const s in t){const o=t[s],i=this.getters.getDataValidationRule(e,s);if(!i)continue;const n=i.ranges.map((e=>e.zone)),r=ls(n.concat(o),[]);this.dispatch("ADD_DATA_VALIDATION_RULE",{rule:i,ranges:r.map((t=>this.getters.getRangeDataFromZone(e,t))),sheetId:e})}}select(e,t){const s=this.getters.getSelectedZone();if(Ds(e,t,s))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,s.top-1,s.left,s.right),this.steps=s.top-t;break;case"down":this.saveZone(s.bottom+1,t,s.left,s.right),this.steps=t-s.bottom;break;case"left":this.saveZone(s.top,s.bottom,e,s.left-1),this.steps=s.left-e;break;case"right":this.saveZone(s.top,s.bottom,s.right+1,e),this.steps=e-s.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getActivePosition(),t=this.getters.getTable(e);let s=t?t.range.zone.bottom:this.getAutofillAutoLastRow();const o=this.getters.getSelectedZone();for(let t=o.bottom+1;t<=s;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==r.empty){s=t-1;break}s>o.bottom&&(this.select(e.col,s),this.autofill(!0))}getAutofillAutoLastRow(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let s=e.left,o=e.bottom;if(s>0){let e={sheetId:t,col:s-1,row:o};for(;this.getters.getEvaluatedCell(e).type!==r.empty;)o+=1,e={sheetId:t,col:s-1,row:o}}if(o===e.bottom&&(s=e.right,s<=this.getters.getNumberCols(t))){let e={sheetId:t,col:s+1,row:o};for(;this.getters.getEvaluatedCell(e).type!==r.empty;)o+=1,e={sheetId:t,col:s+1,row:o}}return o-1}computeNewCell(e,t,s){const{cellData:o,tooltip:i,origin:n}=e.next(),{content:r,style:a,border:l,format:c}=o;return this.tooltip=i,{originCol:n.col,originRow:n.row,col:t,row:s,content:r,style:a,border:l,format:c}}getRule(e,t){const s=_V.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((s=>s.condition(e,t)));return s&&this.direction&&s.generateRule(e,t,this.direction)}createGenerator(e){const t=[],s=[],o=this.getters.getActiveSheetId();for(const t of e){const{col:e,row:i}=rs(t),n=this.getters.getCell({sheetId:o,col:e,row:i});s.push({col:e,row:i,cell:n,sheetId:o})}const i=s.map((e=>e.cell));for(const e of s){let s={type:"COPY_MODIFIER"};if(e&&e.cell){s=this.getRule(e.cell,i)||s}const o=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:o},rule:s})}return new VV(t,this.getters,this.direction)}saveZone(e,t,s,o){this.autofillZone={top:e,bottom:t,left:s,right:o}}getDirection(e,t){const s=this.getters.getSelectedZone(),o={up:{number:s.top-t,value:"up"},down:{number:t-s.bottom,value:"down"},left:{number:s.left-e,value:"left"},right:{number:e-s.right,value:"right"}};if(1===Object.values(o).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(o).find((e=>e.number>0?1:0)).value;const i=o.up.number>0?"up":"down",n=o.left.number>0?"left":"right";return Math.abs(o[i].number)>=Math.abs(o[n].number)?o[i].value:o[n].value}autofillMerge(e,t){const{originCol:s,originRow:o,col:i,row:n}=t,r={sheetId:e,col:i,row:n},a={sheetId:e,col:s,row:o};if(this.getters.isInMerge(r)&&!this.getters.isInMerge(a)){const t=this.getters.getMerge(r);t&&this.dispatch("REMOVE_MERGE",{sheetId:e,target:[t]})}const l=this.getters.getMerge(a);l?.left===s&&l?.top===o&&this.dispatch("ADD_MERGE",{sheetId:e,target:[{top:n,bottom:n+l.bottom-l.top,left:i,right:i+l.right-l.left}]})}drawLayer(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:s}=e,{x:o,y:i,width:n,height:r}=this.getters.getVisibleRect(this.autofillZone);n>0&&r>0&&(t.strokeStyle="black",t.lineWidth=s,t.setLineDash([3]),t.strokeRect(o,i,n,r),t.setLineDash([]))}}).add("sort",class extends Rd{allowDispatch(e){return"SORT_CELLS"===e.type?Ds(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):"InvalidSortAnchor":"Success"}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return"Success";return Ms(t).some((({col:t,row:s})=>!this.getters.isInMerge({sheetId:e,col:t,row:s})))?"InvalidSortZone":"Success"}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return"Success";const s=this.getters.getMerges(e).filter((e=>As(e,t))),o=Fs(s[0]),[i,n]=[o.numberOfCols,o.numberOfRows];return s.every((e=>{const[t,s]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&s===n}))?"Success":"InvalidSortZone"}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return Ms(t).some((({col:t,row:s})=>{const o=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:s});return o&&!St(o,{sheetId:e,col:t,row:s})}))?"SortZoneWithArrayFormulas":"Success"}hasHeader(e,t){if(1===t[0].length)return!1;let s=t.map((t=>t.map((({col:t,row:s})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:s}).type))));return s[0][0]===r.empty&&(s=s.slice(1)),!s.some((e=>e[0]===r.empty))&&!!s.some((e=>e[1]!==r.empty&&e[0]!==e[1]))}sortZone(e,t,s,o,i){const[n,a]=this.mainCellsSteps(e,s),l=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,c=Object.assign({},s);let h=this.mainCells(e,s);!i.sortHeaders&&this.hasHeader(e,h)&&(c.top+=a),h=this.mainCells(e,c);const d=function(e,t,s){const o=e.map(((e,t)=>({index:t,type:e.type,value:e.value})));return(s?o.map((e=>e.type===r.empty?{...e,type:r.number,value:0}:e)):o).sort(Vm(t))}(h[l-c.left].map((e=>this.getters.getEvaluatedCell(e))),o,Boolean(i.emptyCellAsZero)),u=d.map((e=>e.index)),[g,p]=[h.length,h[0].length],m=[];for(let e=0;e<g;e++)for(let t=0;t<p;t++){const{col:s,row:o,sheetId:i}=h[e][u[t]],r=this.getters.getCell({sheetId:i,col:s,row:o}),l=c.left+e*n,d=c.top+t*a,g={sheetId:i,col:l,row:d,content:""};if(r){let e=r.content;if(r.isFormula){const t=this.getters.getCellPosition(r.id);e=this.getters.getTranslatedCellFormula(i,0,d-t.row,r.compiledFormula.tokens)}g.style=r.style,g.content=e,g.format=r.format}m.push(g)}m.forEach((e=>this.dispatch("UPDATE_CELL",e)))}mainCellsSteps(e,t){const s=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[s?s.right-s.left+1:1,s?s.bottom-s.top+1:1]}mainCells(e,t){const[s,o]=this.mainCellsSteps(e,t),i=[],n=Je(t.left,t.right+1,s),r=Je(t.top,t.bottom+1,o);for(const t of n){const s=[];i.push(s);for(const o of r)s.push({sheetId:e,col:t,row:o})}return i}}).add("automatic_sum",class extends Rd{static getters=["getAutomaticSums"];handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:s}=this.getters.getSelection();for(const o of t){const t=this.getAutomaticSums(e,o,s.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,s){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,s):this.sumData(e,t)}sumData(e,t){const s=this.dimensionsToSum(e,t),o=this.sumDimensions(e,t,s).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return s.has("ROW")&&s.has("COL")&&o.push(this.sumTotal(t)),o}sumAdjacentData(e,t,s){const{col:o,row:i}=Ds(s.col,s.row,t)?s:{col:t.left,row:t.top},n=this.findAdjacentData(e,o,i);return n?this.getters.isSingleCellOrMerge(e,t)||Os(Es(n,t))?[{position:{col:o,row:i},zone:n}]:this.sumDimensions(e,Es(n,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,s){const o=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:s}),n=this.findSuitableZoneToSum(o,i.col,i.row);if(n)return this.getters.expandZone(e,n)}findSuitableZoneToSum(e,t,s){const o=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:s-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:s});if(this.isNumber(i)&&!this.isNumber(o))return this.findHorizontalZone(e,t,s);const n=this.findVerticalZone(e,t,s);if(this.isZoneValid(n))return n;const r=this.findHorizontalZone(e,t,s);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,s){const o={top:0,bottom:s-1,left:t,right:t},i=this.reduceZoneStart(e,o,o.bottom);return{...o,top:i}}findHorizontalZone(e,t,s){const o={top:s,bottom:s,left:0,right:t-1},i=this.reduceZoneStart(e,o,o.right);return{...o,left:i}}reduceZoneStart(e,t,s){const o=this.getters.getEvaluatedCellsInZone(e.id,t),i=Je(s,-1,-1),n=kt(i.filter((e=>o[e]&&!o[e].isAutoSummable))),r=Qe(i.filter((e=>this.isNumber(o[e]))))[0]||[];return kt(r)<n?1/0:Vt(r)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===r.number&&!(e.format&&ur(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){const s=new Set;return Os(t)?(s.add(1===Fs(t).numberOfCols?"COL":"ROW"),s):(this.lastColIsEmpty(e,t)&&s.add("ROW"),this.lastRowIsEmpty(e,t)&&s.add("COL"),0===s.size&&s.add("COL"),s)}sumDimensions(e,t,s){return[...s.has("COL")?this.sumColumns(t,e):[],...s.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:s}=e;return{position:{col:s,row:t},zone:{...e,top:t,right:s-1}}}sumColumns(e,t){const s=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,s.bottom-1)},Ms(s).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const s=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,s.right-1)},Ms(s).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const s of t){const{col:t,row:o}=s.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:`=SUM(${this.getters.zoneToXC(e,s.zone)})`})}}nextEmptyRow(e,t){let s=t.bottom+1;const{left:o,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:s,top:s,left:o,right:i});)s++;return{...t,top:s,bottom:s}}nextEmptyCol(e,t){let s=t.right+1;const{top:o,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:s,right:s,top:o,bottom:i});)s++;return{...t,left:s,right:s}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}).add("format",class extends Rd{handle(e){switch(e.type){case"SET_DECIMAL":this.setDecimal(e.sheetId,e.target,e.step);break;case"SET_FORMATTING_WITH_PIVOT":this.setContextualFormat(e.sheetId,e.target,e.format)}}setContextualFormat(e,t,s){const o=[],i={};for(const s of ls(t))for(let t=s.left;t<=s.right;t++)for(let n=s.top;n<=s.bottom;n++){const s={sheetId:e,col:t,row:n},r=this.getters.getPivotCellFromPosition(s);if(this.isSpilledPivotValueFormula(s,r)){o.push(s);const e=this.getters.getPivotIdFromPosition(s)||"";i[e]??=new Set,i[e].add(r.measure)}}const n=ls(o.map(Us));for(const e in i){const t=i[e],o=this.getters.getPivotCoreDefinition(e);this.dispatch("UPDATE_PIVOT",{pivotId:e,pivot:{...o,measures:o.measures.map((e=>t.has(e.id)?{...e,format:s}:e))}})}this.dispatch("SET_FORMATTING",{sheetId:e,target:n,format:""}),this.dispatch("SET_FORMATTING",{sheetId:e,target:ls(t,n),format:s})}isSpilledPivotValueFormula(e,t){const s=this.getters.getCell(e);return"VALUE"===t.type&&!s?.isFormula}setDecimal(e,t,s){const o={};for(const i of ls(t))for(const t of Ms(i)){const i=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==i){const e=Tr(i,s);o[e]=o[e]||[],o[e].push(t)}}for(const t in o){const s=ls(o[t].map((e=>Us(e))));this.setContextualFormat(e,s,t)}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==r.number||e.format&&ur(e.format)))return e.format||mr(e.value)}}}).add("insert_pivot",class extends Rd{static getters=[];allowDispatch(e){if("DUPLICATE_PIVOT_IN_NEW_SHEET"===e.type){if(!this.getters.isExistingPivot(e.pivotId))return"PivotIdNotFound";if(!this.getters.getPivot(e.pivotId).isValid())return"PivotInError"}return"Success"}handle(e){switch(e.type){case"INSERT_NEW_PIVOT":this.insertNewPivot(e.pivotId,e.newSheetId);break;case"DUPLICATE_PIVOT_IN_NEW_SHEET":this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case"INSERT_PIVOT_WITH_TABLE":this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case"SPLIT_PIVOT_FORMULA":this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){1===Gs(this.getters.getSelectedZone())&&this.selection.selectTableAroundSelection();const s=this.getters.getActiveSheetId();this.dispatch("ADD_PIVOT",{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:s},columns:[],rows:[],measures:[],name:Go("New pivot"),type:"SPREADSHEET"}});const o=this.getters.getSheetIds().findIndex((e=>e===s))+1,i=this.getters.getPivotFormulaId(e);this.dispatch("CREATE_SHEET",{sheetId:t,name:Go("Pivot #%(formulaId)s",{formulaId:i}),position:o}),this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:s,sheetIdTo:t});const n=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,n.getCollapsedTableStructure().export(),"dynamic")}duplicatePivotInNewSheet(e,t,s){this.dispatch("DUPLICATE_PIVOT",{pivotId:e,newPivotId:t,duplicatedPivotName:Go("%s (copy)",this.getters.getPivotCoreDefinition(e).name)});const o=this.getters.getActiveSheetId(),i=this.getters.getSheetIds().indexOf(o)+1,n=this.getters.getPivotFormulaId(t),r=this.getters.getPivotName(t);if(this.dispatch("CREATE_SHEET",{sheetId:s,name:this.getPivotDuplicateSheetName(Go("%(newPivotName)s (Pivot #%(formulaId)s)",{newPivotName:r,formulaId:n})),position:i}).isSuccessful){this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:o,sheetIdTo:s});const i=this.getters.getPivot(e);this.insertPivotWithTable(s,0,0,t,i.getCollapsedTableStructure().export(),"dynamic")}}getPivotDuplicateSheetName(e){const t=this.getters.getSheetIds().map((e=>this.getters.getSheetName(e)));return Bt(Xe(e),t)}insertPivotWithTable(e,t,s,o,i,n){const{cols:r,rows:a,measures:l,fieldsType:c}=i,h=new AO(r,a,l,c||{}),d=h.columns.length-1;this.resizeSheet(e,t,s,h);const u=this.getters.getPivotFormulaId(o);let g;"dynamic"===n?(this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:s,content:`=PIVOT(${u})`}),g={left:t,right:t,top:s,bottom:s}):(this.dispatch("INSERT_PIVOT",{sheetId:e,col:t,row:s,pivotId:o,table:h.export()}),g={left:t,right:t+h.getNumberOfDataColumns(),top:s,bottom:s+d+h.rows.length}),this.dispatch("CREATE_TABLE",{tableType:n,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,g)],config:{...ke,numberOfHeaders:d}})}resizeSheet(e,t,s,o){const i=o.getNumberOfDataColumns()+1,n=this.getters.getNumberCols(e),r=n-t;r<i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:n-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-r,position:"after"});const a=o.columns.length+o.rows.length,l=this.getters.getNumberRows(e),c=l-s;c<a&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:l-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a-c,position:"after"})}splitPivotFormula(e,t,s,o){const i=this.getters.getSpreadZone({sheetId:e,col:t,row:s});if(!i)return;const n=this.getters.getPivotFormulaId(o),r=new Map;for(let t=i.left;t<=i.right;t++)for(let s=i.top;s<=i.bottom;s++){const o={sheetId:e,col:t,row:s};r.set(o,this.getters.getPivotCellFromPosition(o))}for(const[e,t]of r)this.dispatch("UPDATE_CELL",{...e,content:Lc(n,t)});const a=this.getters.getCoreTable({sheetId:e,col:t,row:s});if("dynamic"===a?.type){const o=Us({col:t,row:s}),n=this.getters.getRangeDataFromZone(e,i);this.dispatch("UPDATE_TABLE",{sheetId:e,zone:o,newTableRange:n,tableType:"static"})}}}).add("pivot_presence",class extends Rd{static getters=["getPivotPresenceTracker"];trackPresencePivotId;tracker;handle(e){switch(e.type){case"PIVOT_START_PRESENCE_TRACKING":this.tracker=new fU,this.trackPresencePivotId=e.pivotId;break;case"PIVOT_STOP_PRESENCE_TRACKING":this.trackPresencePivotId=void 0}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw new Error("Tracker not initialized");return this.tracker}}}).add("split_to_columns",class extends Rd{static getters=["getAutomaticSeparator"];allowDispatch(e){return"SPLIT_TEXT_INTO_COLUMNS"===e.type?this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e):"Success"}handle(e){if("SPLIT_TEXT_INTO_COLUMNS"===e.type)this.splitIntoColumns(e)}getAutomaticSeparator(){const e=this.getters.getSelectedCells();for(const t of e)if(t.value&&t.type===r.text){const e=this.getAutoSeparatorForString(t.value);if(e)return e}return" "}getAutoSeparatorForString(e){const t=[Ne,";",","," ","."];for(const s of t)if(e.includes(s))return s}splitIntoColumns({separator:e,addNewColumns:t}){const s=this.getters.getSelectedZone(),o=this.getters.getActiveSheetId(),i=this.getSplittedCols(s,e);t&&this.addColsToAvoidCollisions(s,i),this.removeMergesInSplitZone(s,i),this.addColumnsToNotOverflowSheet(s,i);for(let e=0;e<i.length;e++){const t=s.top+e,n=i[e],r=s.left,a=this.getters.getCell({sheetId:o,col:r,row:t});if(1!==n.length||n[0]!==a?.content)for(const[e,s]of n.entries())this.dispatch("UPDATE_CELL",{sheetId:o,col:r+e,row:t,content:Sl(s,this.getters.getLocale()),format:"",style:a?.style||null})}}getSplittedCols(e,t){if(!t)throw new Error("Separator cannot be empty");const s=this.getters.getActiveSheetId(),o=[];for(const i of Je(e.top,e.bottom+1)){const n=this.getters.getEvaluatedCell({sheetId:s,col:e.left,row:i}).formattedValue;o.push(this.splitAndRemoveTrailingEmpty(n,t))}return o}splitAndRemoveTrailingEmpty(e,t){const s=e.split(t);for(;s.length>1&&""===s[s.length-1];)s.pop();return s}willSplittedColsOverwriteContent(e,t){const s=this.getters.getActiveSheetId();for(const o of Je(e.top,e.bottom+1)){const i=t[o-e.top];for(let t=1;t<i.length;t++){const i=this.getters.getCell({sheetId:s,col:e.left+t,row:o});if(i&&i.content)return!0}}return!1}removeMergesInSplitZone(e,t){const s=this.getters.getActiveSheetId(),o=Math.max(...t.map((e=>e.length))),i={...e,right:e.left+o-1},n=this.getters.getMergesInZone(s,i);this.dispatch("REMOVE_MERGE",{sheetId:s,target:n})}addColsToAvoidCollisions(e,t){const s=this.getters.getActiveSheetId();let o=0;for(const i of Je(e.top,e.bottom+1)){const n={sheetId:s,col:e.left,row:i},r=t[i-e.top],a=this.getColsToAddToAvoidCollision(n,r);o=Math.max(o,a)}o&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:e.left,sheetId:s,sheetName:this.getters.getSheetName(s),quantity:o,position:"after"})}getColsToAddToAvoidCollision(e,t){const s=t.length;for(let t=1;t<s;t++){const o=e.col+t,i=this.getters.getCell({...e,col:o});if(i&&i.content)return s-t}return 0}addColumnsToNotOverflowSheet(e,t){const s=this.getters.getActiveSheetId(),o=Math.max(...t.map((e=>e.length-1))),i=this.getters.getNumberCols(s)-1;e.left+o>i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:i,sheetId:s,sheetName:this.getters.getSheetName(s),quantity:e.left+o-i,position:"after"})}checkSingleColSelected(){return this.getters.isSingleColSelected()?"Success":"MoreThanOneColumnSelected"}checkNonEmptySelector(e){return""===e.separator?"EmptySplitSeparator":"Success"}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return"Success";const t=this.getters.getSelectedZones()[0],s=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,s)?"SplitWillOverwriteContent":"Success"}checkSeparatorInSelection({separator:e}){const t=this.getters.getSelectedCells();for(const s of t)if(s.formattedValue.includes(e))return"Success";return"NoSplitSeparatorInSelection"}}).add("subtotal_evaluation",class extends Rd{subtotalCells=new Set;handle(e){switch(e.type){case"START":this.subtotalCells.clear();for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t){const s=t[e];xd(s)&&this.subtotalCells.add(s.id)}}break;case"UPDATE_CELL":{if(!("content"in e))return;const t=this.getters.getCell(e);if(!t)return;xd(t)?this.subtotalCells.add(t.id):this.subtotalCells.delete(t.id);break}}g.has(e.type)&&this.dispatch("EVALUATE_CELLS",{cellIds:Array.from(this.subtotalCells)})}}).add("collaborative",class extends Rd{static getters=["getClientsToDisplay","getClient","getCurrentClient","getConnectedClients","isFullySynchronized"];static layers=["Selection"];colors=new Mo(12);session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}getClient(e){return this.session.getClient(e)}getCurrentClient(){return this.session.getCurrentClient()}getConnectedClients(){return[...this.session.getConnectedClients()].map((e=>({...e,color:this.colors.get(e.id)})))}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getCurrentClient()}catch(e){if(e instanceof QV)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const s of this.getters.getConnectedClients())s.id!==this.getters.getCurrentClient().id&&s.position&&s.position.sheetId===e&&this.isPositionValid(s.position)&&t.push({...s,position:s.position});return t}drawLayer(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:s}=e,o=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:i,col:n}=e.position,r=this.getters.expandZone(o,{top:i,bottom:i,left:n,right:n}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);if(c<=0||h<=0)continue;const d=e.color;t.fillStyle=`${d}10`,t.lineWidth=4*s,t.strokeStyle=d,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,h),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,h),t.font=`bold ${fe+1}px ${ve}`}}}).add("history",class extends Rd{static getters=["canUndo","canRedo"];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on("new-local-state-update",this,this.onNewLocalStateUpdate),this.session.on("snapshot",this,(()=>{this.undoStack=[],this.redoStack=[]}))}allowDispatch(e){switch(e.type){case"REQUEST_UNDO":if(!this.canUndo())return"EmptyUndoStack";break;case"REQUEST_REDO":if(!this.canRedo())return"EmptyRedoStack"}return"Success"}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();if(t)"UNDO"===e?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t));else{const e=this.getPossibleRevisionToRepeat();if(!e)return;const t=mU(e,this.getters);if(!t)return;if(!Array.isArray(t))return void this.dispatch(t.type,t);for(const e of t)this.dispatch(e.type,e)}}canUndo(){return this.undoStack.length>0}canRedo(){if(this.redoStack.length>0)return!0;const e=this.getPossibleRevisionToRepeat();return!(!(t=e)||!t.rootCommand||"object"!=typeof t.rootCommand)&&(f(t.rootCommand)?uU.contains(t.rootCommand.type):gU.contains(t.rootCommand.type));var t}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}}).add("data_cleanup",class extends Rd{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===Fs(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 Kc(this.getters,this.dispatch),l=a.copy(js(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 Je(t,s+1)){const t=o.map((t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).value));!Object.values(i).some((e=>St(e,t)))&&(i[n]=t)}return Object.keys(i).map((e=>parseInt(e)))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:"info",text:Go("%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=ls(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId();let s=0;for(const{col:o,row:i}of e.map(Ms).flat()){const e=this.getters.getCell({col:o,row:i,sheetId:t});if(!e)continue;const n=Mt(e.content);n!==e.content&&(s+=1,this.dispatch("UPDATE_CELL",{sheetId:t,col:o,row:i,content:n}))}const o=s?Go("Trimmed whitespace from %s cells.",s):Go("No selected cells had whitespace trimmed.");this.ui.notifyUI({type:"info",text:o,sticky:!1})}}).add("table_autofill",class extends Rd{handle(e){if("AUTOFILL_TABLE_COLUMN"===e.type){const t=this.getters.getCoreTable(e),s=this.getters.getCell(e);if(!t?.config.automaticAutofill||"dynamic"===t.type||!s?.isFormula)return;const{col:o,row:i}=e,n=function(e,t){const s=t.numberOfHeaders,o={...e,top:e.top+s};return o.top<=o.bottom?o:void 0}(t.range.zone,t.config);if(n&&Ds(o,i,n)){const t=e.autofillRowStart??n.top,s=e.autofillRowEnd??n.bottom,o={...n,top:t,bottom:s};this.autofillTableZone(e,o)}}}autofillTableZone(e,t){if(t.top===t.bottom)return;const{col:s,row:o,sheetId:i}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==o&&this.getters.getEvaluatedCell({col:s,row:e,sheetId:i}).type!==r.empty)return;const n={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(s,o),this.dispatch("AUTOFILL_SELECT",{col:s,row:t.bottom}),this.dispatch("AUTOFILL"),this.selection.selectCell(s,o),this.dispatch("AUTOFILL_SELECT",{col:s,row:t.top}),this.dispatch("AUTOFILL"),this.selection.selectZone(n)}}).add("table_ui_resize",class extends Rd{allowDispatch(e){if("RESIZE_TABLE"===e.type){const t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return"TableNotFound";const s=t.range.zone,o=this.getters.getRangeFromRangeData(e.newTableRange).zone;return o.top!==s.top||o.left!==s.left?"InvalidTableResize":this.canDispatch("UPDATE_TABLE",{...e}).reasons}return"Success"}handle(e){switch(e.type){case"RESIZE_TABLE":{const t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch("UPDATE_TABLE",{...e}),!t)return;const s=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(s.right,s.bottom),!t.config.automaticAutofill)return;const o=t.range.zone;if(s.bottom>=o.bottom){for(let t=s.left;t<=s.right;t++){const i={col:t,row:o.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.content.startsWith("=")&&this.dispatch("AUTOFILL_TABLE_COLUMN",{...i,autofillRowStart:o.bottom,autofillRowEnd:s.bottom})}break}}}}}).add("datavalidation_insert",class extends Rd{handle(e){if("ADD_DATA_VALIDATION_RULE"===e.type)if("isBoolean"===e.rule.criterion.type){const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e)));for(const e of ya(t)){const t=this.getters.getCell(e),s=this.getters.getEvaluatedCell(e);if(t?.content)if(t?.content&&s.type===r.empty){let s;if(t.content.startsWith("=")){const o=this.getters.evaluateFormula(e.sheetId,t.content);s=(R(o)?o[0][0]:o)?.toString()}else s=t.content;s&&tt(s)||this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}else s.type!==r.boolean&&this.dispatch("UPDATE_CELL",{...e,content:"FALSE"});else this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}}}}).add("checkbox_toggle",class extends Rd{static getters=["hasBooleanValidationInZones"];handle(e){if("TOGGLE_CHECKBOX"===e.type)this.toggleCheckbox(e.sheetId,e.target)}hasBooleanValidationInZones(e){const t=this.getters.getActiveSheetId();for(const s of e)for(let e=s.left;e<=s.right;e++)for(let o=s.top;o<=s.bottom;o++)if(this.getters.isCellValidCheckbox({col:e,row:o,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(const s of t)for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++){const s={col:t,row:o,sheetId:e};if(this.getters.isCellValidCheckbox(s)){const e=this.getters.getEvaluatedCell(s).value?"FALSE":"TRUE";this.dispatch("UPDATE_CELL",{...s,content:e})}}}}).add("dynamic_translate",class extends Rd{static getters=["dynamicTranslate"];dynamicTranslate(e){return e}}).add("geo_features",class extends Rd{static getters=["getGeoJsonFeatures","geoFeatureNameToId","getGeoChartAvailableRegions"];geoJsonService;geoJsonCache={};constructor(e){super(e),this.geoJsonService=e.external.geoJsonService}getGeoChartAvailableRegions(){return this.geoJsonService?this.geoJsonService.getAvailableRegions()||[]:(console.error("No geoJsonService provided to the model"),[])}getGeoJsonFeatures(e){if(!this.geoJsonService)return void console.error("No geoJsonService provided to the model");const t=this.geoJsonCache[e];return t instanceof Promise?void 0:void 0!==t?t??void 0:void(this.geoJsonCache[e]=new Promise((async t=>{const s=await(this.geoJsonService?.getTopoJson(e));this.geoJsonCache[e]=this.convertToGeoJson(s),this.dispatch("EVALUATE_CHARTS"),t()})))}geoFeatureNameToId(e,t){if(this.geoJsonService)return this.geoJsonService.geoFeatureNameToId(e,t);console.error("No geoJsonService provided to the model")}convertToGeoJson(e){if(!e)return null;if("Topology"===e.type){const t=window.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return"FeatureCollection"===t.type?t.features:[t]}if("FeatureCollection"===e.type)return e.features;throw new Error("Invalid TopoJSON")}}),IU=(new n).add("selection",class extends Rd{static layers=["Selection"];static getters=["getActiveSheet","getActiveSheetId","getActiveSheetName","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getSelectedCells","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSingleColSelected","getElementsFromSelection","tryGetActiveSheetId","isGridSelectionActive","getSelectecUnboundedZone"];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;isUnbounded;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient,this.isUnbounded=!1}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return"SheetIsHidden";break}catch(e){return"InvalidSheetId"}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return"Success"}handleEvent(e){const t=e.anchor;let s=[];switch(this.isUnbounded=e.options?.unbounded||!1,e.mode){case"overrideSelection":s=[t.zone];break;case"updateAnchor":s=[...this.gridSelection.zones];const o=s.findIndex((t=>xs(t,e.previousAnchor.zone)));o>=0&&(s[o]=t.zone);break;case"newAnchor":s=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,s),this.selection.resetDefaultAnchor(this,qe(this.gridSelection.anchor));const{col:o,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:o,row:i}),this.selectedFigureId=null}handle(e){switch(e.type){case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.figureId&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);const{col:s,row:o}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(s,o),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case"ACTIVATE_SHEET":this.activateSheet(e.sheetIdFrom,e.sheetIdTo);break;case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:s,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:s,row:o})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:s,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:s,row:o})}break}case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"SELECT_FIGURE":this.selectedFigureId=e.figureId;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":const i=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of i)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:qe(t)}}this.fallbackToVisibleSheet();const n=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(n,e))),this.gridSelection.anchor.zone=this.getters.expandZone(n,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,qe(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveSheetName(){return this.activeSheet.name}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){const e=new Set;for(const t of this.gridSelection.zones)if(0===t.top&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let s=t.left;s<=t.right;s++)e.add(s);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(const s of this.gridSelection.zones)if(0===s.left&&s.right===this.getters.getNumberCols(t)-1)for(let t=s.top;t<=s.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return qe(this.gridSelection.zones)}getSelectedZone(){return qe(this.gridSelection.anchor.zone)}getSelectecUnboundedZone(){return qe(this.isUnbounded?this.getters.getUnboundedZone(this.activeSheet.id,this.gridSelection.anchor.zone):this.gridSelection.anchor.zone)}getSelection(){return qe(this.gridSelection)}getSelectedCells(){const e=this.getters.getActiveSheetId(),t=[];for(const s of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,s));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{const t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}isSingleColSelected(){const e=this.getters.getSelectedZones();return 1===e.length&&e[0].left===e[0].right}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let s=[];const o="COL"===e?"left":"top",i="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[i]-e[o]+1},((t,s)=>e[o]+s));s=s.concat(t)}return[...new Set(s)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:qe(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,qe(this.gridSelection.anchor));else{const{col:e,row:s}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,s)}const{col:s,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:s,row:o})}setSelectionMixin(e,t){const{anchor:s,zones:o}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=s,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,s)=>t===s.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(o)}selectCell(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.expandZone(s,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:o,cell:{col:e,row:t}},[o])}setActiveSheet(e){this.activeSheet=this.getters.getSheet(e)}activateNextSheet(e){const t=this.getters.getSheetIds(),s=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[s]})}onColumnsRemoved(e){const{cell:t,zone:s}=this.gridSelection.anchor,o=Is(s,"left",[...e.elements]);let i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=Is(i,"left",[...e.elements]);const n={cell:{col:i.left,row:i.top},zone:o},r=this.gridSelection.zones.map((t=>Is(t,"left",[...e.elements])));this.setSelectionMixin(n,r)}onRowsRemoved(e){const{cell:t,zone:s}=this.gridSelection.anchor,o=Is(s,"top",[...e.elements]);let i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=Is(i,"top",[...e.elements]);const n={cell:{col:i.left,row:i.top},zone:o},r=this.gridSelection.zones.map((t=>Is(t,"top",[...e.elements])));this.setSelectionMixin(n,r)}onAddElements(e){const t="COL"===e.dimension?"left":"top",s=ys(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),o=this.gridSelection.zones.map((s=>ys(s,t,e.base,e.position,e.quantity))),i={cell:{col:s.left,row:s.top},zone:s};this.setSelectionMixin(i,o)}onMoveElements(e){const t=e.elements.length,s=this.getFiguresUpdates(e);this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,base:e.base,quantity:t,position:e.position});const o="COL"===e.dimension,i=e.elements[0],n=e.elements[t-1],r=e.base<i,a=r&&o?t:0,l=r&&!o?t:0,c=r?e.elements.map((e=>e+t)):e.elements,h={};for(const t of c)h[t]=this.getters.getHeaderSize(e.sheetId,e.dimension,t);const d=[{left:o?i+a:0,right:o?n+a:this.getters.getNumberCols(e.sheetId)-1,top:o?0:i+l,bottom:o?this.getters.getNumberRows(e.sheetId)-1:n+l}],u=this.getActiveSheetId(),g=r?e.base:e.base+1,p=[{left:o?g:0,right:o?g+t-1:this.getters.getNumberCols(e.sheetId)-1,top:o?0:g,bottom:o?this.getters.getNumberRows(e.sheetId)-1:g+t-1}],m=Jc.cellHandlers.getKeys().map((e=>[e,new(Jc.cellHandlers.get(e))(this.getters,this.dispatch)])),f={};for(const[e,t]of m)f[e]=t.copy(js(u,d),!1,"shiftCells");for(const[e,t]of m)f[e]&&t.paste({zones:p,sheetId:u},f[e],{isCutOperation:!0});const v=p[0],b=v.left,S=v.top;this.setSelectionMixin({zone:v,cell:{col:b,row:S}},[v]);let C=r?e.base:e.base+1;const y={};for(const t of c){const s=h[t];s!==this.getters.getHeaderSize(e.sheetId,e.dimension,C)&&(y[s]??=[],y[s].push(C)),C+=1}for(const t in y)this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:parseInt(t,10),elements:y[t]});this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,elements:c}),this.applyFigureUpdates(s)}getFiguresUpdates(e){const t=[],s={},o=e.elements[0]<e.base?e.base-e.elements.length+1:e.base;for(let t=0;t<e.elements.length;t++)s[e.elements[t]]=o+t;for(const o of this.getters.getFigures(e.sheetId))"COL"===e.dimension&&o.col in s&&t.push({type:"UPDATE_FIGURE",sheetId:e.sheetId,figureId:o.id,col:s[o.col],row:o.row}),"ROW"===e.dimension&&o.row in s&&t.push({type:"UPDATE_FIGURE",sheetId:e.sheetId,figureId:o.id,row:s[o.row],col:o.col});return t}applyFigureUpdates(e){for(const t of e)this.dispatch(t.type,{...t})}isMoveElementAllowed(e){const t="COL"===e.dimension,s=e.elements[0],o=e.elements[e.elements.length-1],i=e.sheetId,n=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(n(i,s-1,s)||n(i,o,o+1)||n(i,e.base-1,e.base))return"WillRemoveExistingMerge";const r=[e.base,...e.elements],a=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return r.some((e=>e<0||e>=a))?"InvalidHeaderIndex":t||this.isTableRowMoveAllowed(i,e.elements)?"Success":"CannotMoveTableHeader"}isTableRowMoveAllowed(e,t){const s=this.getters.getCoreTables(e);if(0===s.length)return!0;const o=new Set(t);return s.every((({range:{zone:e},config:s})=>{const{top:i,bottom:n}=e;if(0===s.numberOfHeaders)return!0;const r=i+s.numberOfHeaders-1;if(!t.some((e=>e>=i&&e<=r)))return!0;return Je(i,n+1).every((e=>o.has(e)))}))}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:s}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:s})}}clipSelection(e,t){const s=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:Ke(e.left,0,s),right:Ke(e.right,0,s),top:Ke(e.top,0,o),bottom:Ke(e.bottom,0,o)}))),anchor:{cell:{col:Ke(t.anchor.cell.col,0,s),row:Ke(t.anchor.cell.row,0,o)},zone:{left:Ke(t.anchor.zone.left,0,s),right:Ke(t.anchor.zone.right,0,s),top:Ke(t.anchor.zone.top,0,o),bottom:Ke(t.anchor.zone.bottom,0,o)}}}}drawLayer(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:s}=e,o=this.getSelectedZones();t.fillStyle="#f3f7fe";const i=1===o.length&&o[0].left===o[0].right&&o[0].top===o[0].bottom;t.fillStyle=i?"#f3f7fe":"#e9f0ff",t.strokeStyle=P,t.lineWidth=1.5*s;for(const e of o){const{x:s,y:o,width:i,height:n}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(s,o,i,n),t.globalCompositeOperation="source-over",t.strokeRect(s,o,i,n)}t.globalCompositeOperation="source-over";const n=this.getActivePosition();let r;t.strokeStyle=P,t.lineWidth=3*s,r=this.getters.isInMerge(n)?this.getters.getMerge(n):Us(n);const{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);c>0&&h>0&&t.strokeRect(a,l,c,h)}}).add("evaluation_filter",class extends Rd{static getters=["getFilterValue","getFilterHiddenValues","getFilterCriterionValue","getFirstTableInSelection","isRowFiltered","isFilterActive"];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){if("UPDATE_FILTER"===e.type)if(!this.getters.getFilterId(e))return"FilterNotFound";return"Success"}handle(e){switch(e.type){case"UNDO":case"REDO":case"UPDATE_CELL":case"EVALUATE_CELLS":case"ACTIVATE_SHEET":case"REMOVE_TABLE":case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":case"UPDATE_TABLE":this.isEvaluationDirty=!0;break;case"START":for(const e of this.getters.getSheetIds())this.filterValues[e]={};break;case"CREATE_SHEET":this.filterValues[e.sheetId]={};break;case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"GROUP_HEADERS":case"UNGROUP_HEADERS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_ALL_HEADER_GROUPS":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":this.updateHiddenRows(e.sheetId);break;case"UPDATE_FILTER":this.updateFilter(e),this.updateHiddenRows(e.sheetId);break;case"DUPLICATE_SHEET":this.filterValues[e.sheetIdTo]=qe(this.filterValues[e.sheetId])}}finalize(){if(this.isEvaluationDirty){for(const e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterValue(e){const t=this.getters.getFilterId(e),s=e.sheetId;return t?this.filterValues[s]?.[t]:void 0}getFilterHiddenValues(e){const t=this.getters.getFilterId(e),s=e.sheetId;if(!t||!this.filterValues[s])return[];const o=this.filterValues[s][t]||[];return"values"===o.filterType?o.hiddenValues:[]}getFilterCriterionValue(e){const t=this.getters.getFilterId(e),s=e.sheetId;if(!t||!this.filterValues[s])return bU;const o=this.filterValues[s][t];return o&&"criterion"===o.filterType?o:bU}isFilterActive(e){const t=this.getters.getFilterId(e);if(!t)return!1;const s=e.sheetId,o=this.filterValues[s]?.[t];return!!o&&("values"===o.filterType?o.hiddenValues.length>0:"none"!==o.type)}getFirstTableInSelection(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,value:s,sheetId:o}){const i=this.getters.getFilterId({sheetId:o,col:e,row:t});i&&(this.filterValues[o]||(this.filterValues[o]={}),this.filterValues[o][i]=s)}updateHiddenRows(e){const t=this.getters.getFilters(e).sort(((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top)),s=new Set;for(const o of t){const t=this.filterValues[e]?.[o.id],i=o.filteredRange?.zone;if(t&&i&&!s.has(o.rangeWithHeaders.zone.top)&&!this.getters.isRowHiddenByUser(e,o.rangeWithHeaders.zone.top))if("values"===t.filterType){const n=t.hiddenValues?.map($a);if(!n)continue;const r=new Set(n);for(let t=i.top;t<=i.bottom;t++){const i=this.getCellValueAsString(e,o.col,t);r.has(i)&&s.add(t)}}else{if("none"===t.type)continue;const n=FR.get(t.type),r=t.values.map((t=>t.startsWith("=")?this.getters.evaluateFormula(e,t)??"":Or(t,w)));if(r.some(Yl))continue;const a={type:t.type,values:r.map(Zl),dateValue:t.dateValue};for(let t=i.top;t<=i.bottom;t++){const i={sheetId:e,col:o.col,row:t},r=this.getters.getEvaluatedCell(i).value??"";n.isValueValid(r,a,this.getters,e)||s.add(t)}}}this.hiddenRows[e]=s}getCellValueAsString(e,t,s){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:s}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets){const e=t.id;for(const s of t.tables){const o=ms(s.range),i=[],n=[];for(const s of Je(0,Fs(o).numberOfCols)){const r={sheetId:t.id,col:o.left+s,row:o.top},a=this.getFilterHiddenValues(r),l=this.getters.getFilter(r),c=l?.filteredRange?Ms(l.filteredRange.zone).map((t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue)):[];if(a.length){const e=c.filter((e=>e)).filter((e=>!a.includes(e)));i.push({colId:s,displayedValues:[...new Set(e)],displayBlanks:!a.includes("")&&c.some((e=>!e))})}const h=this.getters.getEvaluatedCell(r).formattedValue,d=this.getUniqueColNameForExcel(s,h,n);n.push(d);const u=as(r.col,r.row);t.cells[u]=d,t.cellValues[u]=d}s.filters=i}}}getUniqueColNameForExcel(e,t,s){return t||(t=`Column${e}`),Bt(t,s,{compute:(e,s)=>t+String(s),start:2})}}).add("header_visibility_ui",class extends Rd{static getters=["getNextVisibleCellPosition","findVisibleHeader","findLastVisibleColRowIndex","findFirstVisibleColRowIndex","isRowHidden","isColHidden","isHeaderHidden"];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,s){return"COL"===t?this.isColHidden(e,s):this.isRowHidden(e,s)}getNextVisibleCellPosition({sheetId:e,col:t,row:s}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",s,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,s,o){if(s<=o)for(let i=s;i<=o;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i;if(s>o)for(let i=s;i>=o;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}findLastVisibleColRowIndex(e,t,{last:s,first:o}){return Je(s,o,-1).find((s=>!this.isHeaderHidden(e,t,s)))||o}findFirstVisibleColRowIndex(e,t){const s=this.getters.getNumberHeaders(e,t);for(let o=0;o<s;o++){if("COL"===t&&!this.isColHidden(e,o))return o;if("ROW"===t&&!this.isRowHidden(e,o))return o}}exportForExcel(e){for(const t of e.sheets)for(const[e,s]of Object.entries(t.rows))s.isHidden=this.isRowHidden(t.id,Number(e))}}).add("cell_computed_style",class extends Rd{static getters=["getCellComputedBorder","getCellComputedStyle"];styles=new C_;borders=new C_;handle(e){if(l.has(e.type)||"UPDATE_CELL"===e.type||"SET_FORMATTING"===e.type||"ADD_DATA_VALIDATION_RULE"===e.type||"REMOVE_DATA_VALIDATION_RULE"===e.type||"EVALUATE_CELLS"===e.type)return this.styles=new C_,void(this.borders=new C_);sU(e)?"sheetId"in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new C_,this.borders=new C_):d.has(e.type)?this.styles=new C_:u.has(e.type)&&(this.borders=new C_)}getCellComputedBorder(e,t){let s=this.borders.get(e);return void 0===s&&(this.precomputeCellBorders(e.sheetId,t??Us(e)),s=this.borders.get(e)),s??null}precomputeCellBorders(e,t){const s=this.getters.getCellBordersInZone(e,t),o=this.getters.getCellTableBorderZone(e,t);for(let i=t.left;i<=t.right;i++)for(let n=t.top;n<=t.bottom;n++){const t={sheetId:e,col:i,row:n};if(void 0!==this.borders.get(t))continue;const r=s.get(t),a={...wt(o.get(t)),...wt(r)};gt(a)?this.borders.set(t,null):this.borders.set(t,a)}}getCellComputedStyle(e){let t=this.styles.get(e);return void 0===t&&(t=this.computeCellStyle(e),this.styles.set(e,t)),t}computeCellStyle(e){const t=this.getters.getCell(e),s=this.getters.getCellConditionalFormatStyle(e),o=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e),n={...wt(o),...wt(i),...wt(t?.style),...wt(s)};return this.getters.getEvaluatedCell(e).link&&!n.textColor&&(n.textColor=L),n}}).add("table_computed_style",class extends Rd{static getters=["getCellTableStyle","getCellTableBorder","getCellTableBorderZone"];tableStyles={};handle(e){l.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e)||"EVALUATE_CELLS"===e.type?this.tableStyles={}:sU(e)&&("sheetId"in e?delete this.tableStyles[e.sheetId]:this.tableStyles={})}finalize(){for(const e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(const t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){const t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}getCellTableBorder(e){const t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}getCellTableBorderZone(e,t){const s=new C_;for(const o of this.getters.getTablesOverlappingZones(e,[t])){const t=this.tableStyles[e][o.id]().borders;for(const[o,i]of Object.entries(t)){const t=parseInt(o);for(const[o,n]of Object.entries(i))n&&s.set({sheetId:e,col:t,row:parseInt(o)},n)}}return s}computeTableStyle(e,t){return ft((()=>{const{config:s,numberOfCols:o,numberOfRows:i}=this.getTableRuntimeConfig(e,t),n=Q_(s,this.getters.getTableStyle(t.config.styleId),o,i),r=this.getTableMapping(e,t),a={borders:{},styles:{}};for(let e=0;e<o;e++){const t=r.colMapping[e];a.borders[t]={},a.styles[t]={};for(let s=0;s<i;s++){const o=r.rowMapping[s];a.borders[t][o]=n.borders[e][s],a.styles[t][o]=n.styles[e][s]}}return a}))}getTableRuntimeConfig(e,t){const s=t.range.zone,o={...t.config};let i=s.right-s.left+1,n=s.bottom-s.top+1;for(let i=s.top;i<=s.bottom;i++)this.getters.isRowHidden(e,i)&&(n--,i-s.top<t.config.numberOfHeaders&&(o.numberOfHeaders--,o.numberOfHeaders<0&&(o.numberOfHeaders=0)),i===s.bottom&&(o.totalRow=!1));for(let t=s.left;t<=s.right;t++)this.getters.isColHidden(e,t)&&(i--,t===s.left&&(o.firstColumn=!1),t===s.right&&(o.lastColumn=!1));return{config:o,numberOfCols:i,numberOfRows:n}}getTableMapping(e,t){const s={},o={};let i=0,n=0;const r=t.range.zone;for(let t=r.left;t<=r.right;t++)if(!this.getters.isColHidden(e,t)){s[i]=t,i++;for(let t=r.top;t<=r.bottom;t++)this.getters.isRowHidden(e,t)||(o[n]=t,n++)}return{colMapping:s,rowMapping:o}}}).add("header_positions",class extends Rd{static getters=["getColDimensions","getRowDimensions","getColRowOffset"];headerPositions={};isDirty=!0;handle(e){switch(l.has(e.type)&&(this.headerPositions={},this.isDirty=!0),e.type){case"START":for(const e of this.getters.getSheetIds())this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e);break;case"UPDATE_CELL":case"UPDATE_FILTER":case"UPDATE_TABLE":case"REMOVE_TABLE":this.headerPositions={},this.isDirty=!0;break;case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_ALL_HEADER_GROUPS":case"UNGROUP_HEADERS":case"GROUP_HEADERS":case"CREATE_SHEET":this.getters.tryGetSheet(e.sheetId)&&(this.headerPositions[e.sheetId]=this.computeHeaderPositionsOfSheet(e.sheetId));break;case"DUPLICATE_SHEET":this.headerPositions[e.sheetIdTo]=qe(this.headerPositions[e.sheetId])}}finalize(){for(const e of this.getters.getSheetIds())!this.isDirty&&this.headerPositions[e]||(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){const s=this.headerPositions[e].COL[t],o=this.getters.getColSize(e,t);return{start:s,size:o,end:s+(this.getters.isColHidden(e,t)?0:o)}}getRowDimensions(e,t){const s=this.headerPositions[e].ROW[t],o=this.getters.getRowSize(e,t);return{start:s,size:o,end:s+(this.getters.isRowHidden(e,t)?0:o)}}getColRowOffset(e,t,s,o=this.getters.getActiveSheetId()){const i=this.headerPositions[o][e][t];return this.headerPositions[o][e][s]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,"COL"),ROW:this.computePositions(e,"ROW")}}computePositions(e,t){const s={};let o=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)s[i]=o,this.getters.isHeaderHidden(e,t,i)||(o+=this.getters.getHeaderSize(e,t,i));return s}}).add("viewport",class extends Rd{static getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getVisibleRectWithoutHeaders","getVisibleCellPositions","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio","isPixelPositionVisible","getColDimensionsInViewport","getRowDimensionsInViewport","getAllActiveViewportsZonesAndRect","getRect","getFigureUI","getPositionAnchorOffset","getGridOffset"];viewports={};sheetViewWidth=Me();sheetViewHeight=Me();gridOffsetX=0;gridOffsetY=0;sheetsWithDirtyViewports=new Set;shouldAdjustViewports=!1;allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.chainValidations(this.checkScrollingDirection,this.checkIfViewportsWillChange)(e);case"RESIZE_SHEETVIEW":return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return"Success"}}handleEvent(e){const t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:s,row:o}=Vs(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const i=e.previousAnchor.zone,n=e.anchor.zone,{top:r,bottom:a,left:l,right:c}=this.getMainInternalViewport(t);i.left===n.left&&i.right===n.right&&(s=l>s||s>c?l:s),i.top===n.top&&i.bottom===n.bottom&&(o=r>o||o>a?r:o)}s=Math.min(s,this.getters.getNumberCols(t)-1),o=Math.min(o,this.getters.getNumberRows(t)-1),this.sheetsWithDirtyViewports.has(t)||this.refreshViewport(this.getters.getActiveSheetId(),{col:s,row:o})}}handle(e){if(l.has(e.type))for(const e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);switch(e.type){case"START":this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case"UNDO":case"REDO":this.cleanViewports();for(const e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);this.shouldAdjustViewports=!0;break;case"RESIZE_SHEETVIEW":this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case"SET_VIEWPORT_OFFSET":this.setSheetViewOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const t=this.getters.getActiveSheetId(),{top:s,viewportHeight:o,offsetCorrectionY:i}=this.getMainInternalViewport(t),n=this.getters.getRowDimensions(t,s);this.shiftVertically(n.start+o-i);break;case"SHIFT_VIEWPORT_UP":{const e=this.getters.getActiveSheetId(),{top:t,viewportHeight:s,offsetCorrectionY:o}=this.getMainInternalViewport(e),i=this.getters.getRowDimensions(e,t);this.shiftVertically(i.end-o-s);break}case"REMOVE_TABLE":case"UPDATE_TABLE":case"UPDATE_FILTER":case"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UNGROUP_HEADERS":case"GROUP_HEADERS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_ALL_HEADER_GROUPS":this.sheetsWithDirtyViewports.add(e.sheetId);break;case"UPDATE_CELL":if("content"in e||"format"in e||void 0!==e.style?.fontSize)for(const e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);break;case"DELETE_SHEET":this.cleanViewports(),this.sheetsWithDirtyViewports.delete(e.sheetId);break;case"ACTIVATE_SHEET":this.sheetsWithDirtyViewports.add(e.sheetIdTo);break;case"SCROLL_TO_CELL":this.refreshViewport(this.getters.getActiveSheetId(),{col:e.col,row:e.row})}}finalize(){for(const e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){const t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach((e=>{e.adjustPosition(t)}))}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){const e=this.getters.getSheetIds();for(const t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getColIndex(e))))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getRowIndex(e))))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getGridOffset(){return{x:this.gridOffsetX,y:this.gridOffsetY}}getActiveMainViewport(){const e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getSheetViewVisibleCols(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>Je(e.left,e.right+1))).flat())].filter((t=>t>=0&&!this.getters.isHeaderHidden(e,"COL",t)))}getSheetViewVisibleRows(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>Je(e.top,e.bottom+1))).flat())].filter((t=>t>=0&&!this.getters.isHeaderHidden(e,"ROW",t)))}getVisibleCellPositions(){const e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),s=this.getters.getActiveSheetId(),o=[];for(const i of e)for(const e of t){const t={sheetId:s,col:i,row:e},n=this.getters.getMainCellPosition(t);n.row===e&&n.col===i&&o.push(t)}return o}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:s,ySplit:o}=this.getters.getPaneDivisions(e),{width:i,height:n}=t.getMaxSize();return{x:this.getters.getColDimensions(e,s).start,y:this.getters.getRowDimensions(e,o).start,width:i,height:n}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:s}=this.getMainViewportRect(),o=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-o.viewportWidth),maxOffsetY:Math.max(0,s-o.viewportHeight)}}getColRowOffsetInViewport(e,t,s){if(s<t)return-this.getColRowOffsetInViewport(e,s,t);const o=this.getters.getActiveSheetId(),i="COL"===e?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),n=i.findIndex((e=>t>=e));let r=i.findIndex((e=>s<=e));r=-1===r?i.length:r;const a=i.slice(n,r);let l=0;for(const t of a)l+=this.getters.getHeaderSize(o,e,t);return l}isVisibleInViewport({sheetId:e,col:t,row:s}){return this.getSubViewports(e).some((e=>e.isVisible(t,s)))}getEdgeScrollCol(e,t,s){let o=!1,i=0,n=0;const{xSplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(o=!0,n=Zr(e-a),i=1):e<l&&s>=l&&c>0?(o=!0,n=Zr(l-e),i=-1):r&&t<l&&e>l&&(o=!0,n=Zr(e),i="reset"),{canEdgeScroll:o,direction:i,delay:n}}getEdgeScrollRow(e,t,s){let o=!1,i=0,n=0;const{ySplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(o=!0,n=Zr(e-a),i=1):e<l&&s>=l&&c>0?(o=!0,n=Zr(l-e),i=-1):r&&t<l&&e>l&&(o=!0,n=Zr(e),i="reset"),{canEdgeScroll:o,direction:i,delay:n}}getVisibleRect(e){const t=this.getVisibleRectWithoutHeaders(e);return{...t,x:t.x+this.gridOffsetX,y:t.y+this.gridOffsetY}}getVisibleRectWithoutHeaders(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,(t=>t.getVisibleRect(e)))}getRect(e){const t=this.getters.getActiveSheetId(),s=this.mapViewportsToRect(t,(t=>t.getFullRect(e)));return{...s,x:s.x+this.gridOffsetX,y:s.y+this.gridOffsetY}}getRectWithoutHeaders(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,(t=>t.getFullRect(e)))}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:s}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,s).start}}getColDimensionsInViewport(e,t){const{top:s}=this.getMainInternalViewport(e),o={left:t,right:t,top:s,bottom:s},{x:i,width:n}=this.getVisibleRect(o),r=i-this.gridOffsetX;return{start:r,size:n,end:r+n}}getRowDimensionsInViewport(e,t){const{left:s}=this.getMainInternalViewport(e),o={left:0,right:s,top:t,bottom:t},{y:i,height:n}=this.getVisibleRect(o),r=i-this.gridOffsetY;return{start:r,size:n,end:r+n}}getAllActiveViewportsZonesAndRect(){const e=this.getters.getActiveSheetId();return this.getSubViewports(e).map((e=>({zone:e,rect:{x:e.offsetCorrectionX+this.gridOffsetX,y:e.offsetCorrectionY+this.gridOffsetY,...e.getMaxSize()}})))}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(ut)}checkPositiveDimension(e){return e.width<0||e.height<0?"InvalidViewportSize":"Success"}checkValuesAreDifferent(e){const{height:t,width:s}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===s&&e.height===t?"ValuesNotChanged":"Success"}checkScrollingDirection({offsetX:e,offsetY:t}){const s=this.getMainInternalViewport(this.getters.getActiveSheetId());return!s.canScrollHorizontally&&e>0||!s.canScrollVertically&&t>0?"InvalidScrollingDirection":"Success"}checkIfViewportsWillChange({offsetX:e,offsetY:t}){const s=this.getters.getActiveSheetId(),{maxOffsetX:o,maxOffsetY:i}=this.getMaximumSheetOffset();return this.getSubViewports(s).some((s=>s.willNewOffsetScrollViewport(Ke(e,0,o),Ke(t,0,i))))?"Success":"ViewportScrollLimitsReached"}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e={};for(const t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,s=0,o=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=s,this.gridOffsetY=o,this.recomputeViewports()}recomputeViewports(){for(const e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){const s=this.getters.getActiveSheetId(),{maxOffsetX:o,maxOffsetY:i}=this.getMaximumSheetOffset();this.getSubViewports(s).forEach((s=>s.setViewportOffset(Ke(e,0,o),Ke(t,0,i))))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetX||0,y:this.viewports[e]?.bottomRight.offsetY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:s}=this.getters.getPaneDivisions(e),o=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),n=Math.min(this.getters.getColRowOffset("COL",0,t,e),this.sheetViewWidth),r=Math.min(this.getters.getColRowOffset("ROW",0,s,e),this.sheetViewHeight),a=Math.max(this.sheetViewWidth-n,0),l=Math.max(this.sheetViewHeight-r,0),{xRatio:c,yRatio:h}=this.getFrozenSheetViewRatio(e),d=c<1,u=h<1,g=this.getViewportOffset(e),p={topLeft:s&&t&&new SU(this.getters,e,{left:0,right:t-1,top:0,bottom:s-1},{width:n,height:r},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:s&&new SU(this.getters,e,{left:t,right:o-1,top:0,bottom:s-1},{width:a,height:r},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?g.x:0,y:0})||void 0,bottomLeft:t&&new SU(this.getters,e,{left:0,right:t-1,top:s,bottom:i-1},{width:n,height:l},{canScrollHorizontally:!1,canScrollVertically:u},{x:0,y:u?g.y:0})||void 0,bottomRight:new SU(this.getters,e,{left:t,right:o-1,top:s,bottom:i-1},{width:a,height:l},{canScrollHorizontally:d,canScrollVertically:u},{x:d?g.x:0,y:u?g.y:0})};this.viewports[e]=p}refreshViewport(e,t){this.getSubViewports(e).forEach((e=>{e.adjustViewportZone(),e.adjustPosition(t)}))}shiftVertically(e){const t=this.getters.getActiveSheetId(),{top:s}=this.getMainInternalViewport(t),{scrollX:o}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(o,e);const{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){const e=this.getMainInternalViewport(t).top-s;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getColIndexLeftOfMainViewport(e){if(e>=0)return-1;const t=this.getters.getActiveSheetId();let s=this.getActiveMainViewport().left,o=-this.getActiveSheetScrollInfo().scrollX-this.getters.getColRowOffset("COL",s,0);for(;e<o;s--)o-=this.getters.getColSize(t,s-1);return Math.max(s,0)}getRowIndexTopOfMainViewport(e){if(e>=0)return-1;const t=this.getters.getActiveSheetId();let s=this.getActiveMainViewport().top,o=-this.getActiveSheetScrollInfo().scrollY-this.getters.getColRowOffset("ROW",s,0);for(;e<o;s--)o-=this.getters.getRowSize(t,s-1);return Math.max(s,0)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],s=this.getters.getFigures(e),{scrollX:o,scrollY:i}=this.getters.getActiveSheetScrollInfo(),{x:n,y:r}=this.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const c of s){const s=this.getFigureUI(e,c),{x:h,y:d}=s;h>=n&&(h+c.width<o+n||h>a+o+n)||(d>=r&&(d+c.height<i+r||d>l+i+r)||t.push(s))}return t}getFigureUI(e,t){const s=t.offset.x+this.getters.getColDimensions(e,t.col).start,o=t.offset.y+this.getters.getRowDimensions(e,t.row).start;return{...t,x:s,y:o}}getPositionAnchorOffset(e){const{scrollX:t,scrollY:s}=this.getters.getActiveSheetScrollInfo(),o=e.x-t,i=e.y-s,n=o>=0?this.getColIndex(o):this.getColIndexLeftOfMainViewport(o),r=i>=0?this.getRowIndex(i):this.getRowIndexTopOfMainViewport(i),{x:a,y:l}=this.getRect(Us({col:n,row:r}));return{col:n,row:r,offset:{x:Math.max(o-a+this.gridOffsetX,0),y:Math.max(i-l+this.gridOffsetY,0)}}}isPixelPositionVisible(e){const{scrollX:t,scrollY:s}=this.getters.getActiveSheetScrollInfo(),{x:o,y:i}=this.getters.getMainViewportCoordinates(),{width:n,height:r}=this.getters.getSheetViewDimension();return!(e.x>=o&&(e.x<o+t||e.x>n+t+o))&&!(e.y>=i&&(e.y<i+s||e.y>r+s+i))}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:s}=this.getters.getPaneDivisions(e),o=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,s).start;return{xRatio:o/(this.sheetViewWidth+this.gridOffsetX),yRatio:i/(this.sheetViewHeight+this.gridOffsetY)}}mapViewportsToRect(e,t){let s=1/0,o=1/0,i=0,n=0,r=!1;for(const a of this.getSubViewports(e)){const e=t(a);e&&(r=!0,s=Math.min(s,e.x),o=Math.min(o,e.y),i=Math.max(i,e.x+e.width),n=Math.max(n,e.y+e.height))}return r?{x:s,y:o,width:i-s,height:n-o}:{x:0,y:0,width:0,height:0}}}).add("clipboard",class extends Rd{static layers=["Clipboard"];static getters=["getClipboardTextAndImageContent","getClipboardId","getClipboardTextContent","isCutOperation"];status="invisible";originSheetId;copiedData;_isCutOperation=!1;clipboardId=(new Xa).uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new Xa}allowDispatch(e){switch(e.type){case"CUT":const t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case"PASTE_FROM_OS_CLIPBOARD":{const t=this.convertTextToClipboardData(e.clipboardContent.text??""),s=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:s,isCutOperation:!1})}case"PASTE":{if(!this.copiedData)return"EmptyClipboard";const t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case"COPY_PASTE_CELLS_ABOVE":{const e=this.getters.getSelectedZones();if(e.length>1||0===e[0].top&&0===e[0].bottom)return"InvalidCopyPasteSelection";break}case"COPY_PASTE_CELLS_ON_LEFT":{const e=this.getters.getSelectedZones();if(e.length>1||0===e[0].left&&0===e[0].right)return"InvalidCopyPasteSelection";break}case"INSERT_CELL":{const{cut:t,paste:s}=this.getInsertCellsTargets(e.zone,e.shiftDimension),o=this.copy(t,"shiftCells");return this.isPasteAllowed(s,o,{isCutOperation:!0})}case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),o=this.copy(t,"shiftCells");return this.isPasteAllowed(s,o,{isCutOperation:!0})}}return"Success"}handle(e){switch(e.type){case"COPY":case"CUT":const t=this.getters.getSelectedZones();this.status="visible",this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation="CUT"===e.type,this.copiedData=this.copy(t);break;case"PASTE_FROM_OS_CLIPBOARD":{this._isCutOperation=!1;const t=e.clipboardContent.data;if(e.clipboardContent.imageData){const t=this.getters.getActiveSheetId(),s=this.uuidGenerator.uuidv4(),o=e.clipboardContent.imageData,i=LE(this.getters,o.size);this.dispatch("CREATE_IMAGE",{definition:o,size:i,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:t,figureId:s})}this.copiedData=t||this.convertTextToClipboardData(e.clipboardContent.text??"");const s=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:s,selectTarget:!0,isCutOperation:!1}),this.status="invisible",this.copiedData=void 0;break}case"PASTE":{const t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status="invisible",this._isCutOperation&&(this.copiedData=void 0,this._isCutOperation=!1);break}case"COPY_PASTE_CELLS_ABOVE":{const e=this.getters.getSelectedZone(),t=e.top!==e.bottom,s={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};this.originSheetId=this.getters.getActiveSheetId();const o=this.copy([s]);this.paste([e],o,{isCutOperation:!1,selectTarget:!0})}break;case"COPY_PASTE_CELLS_ON_LEFT":{const e=this.getters.getSelectedZone(),t=e.left!==e.right,s={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};this.originSheetId=this.getters.getActiveSheetId();const o=this.copy([s]);this.paste([e],o,{isCutOperation:!1,selectTarget:!0})}break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!vs(t[0])){this.dispatch("CLEAR_CELLS",{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}const o=this.copy(t,"shiftCells");this.paste(s,o,{isCutOperation:!0});break}case"INSERT_CELL":{const{cut:t,paste:s}=this.getInsertCellsTargets(e.zone,e.shiftDimension),o=this.copy(t,"shiftCells");this.paste(s,o,{isCutOperation:!0});break}case"ADD_COLUMNS_ROWS":if(this.status="invisible",!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible",!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;for(const t of e.elements){if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}}this.status="invisible";break;case"REPEAT_PASTE":this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case"DELETE_SHEET":if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status="invisible");break;default:f(e)&&(this.status="invisible")}}convertTextToClipboardData(e){const t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),s={};for(const{handlerName:o,handler:i}of t){const t=i.convertTextToClipboardData(e);s[o]=t;const n=["sheetId","cells","zones","figureId"];for(const e of n)t&&e in t&&(s[e]=t[e])}return s}selectClipboardHandlers(e){const t="figureId"in e?Jc.figureHandlers:Jc.cellHandlers;return t.getKeys().map((e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)})))}isCutAllowedOn(e){const t=this.getClipboardData(e);for(const{handler:e}of this.selectClipboardHandlers(t)){const s=e.isCutAllowed(t);if("Success"!==s)return s}return"Success"}isPasteAllowed(e,t,s){for(const{handler:o}of this.selectClipboardHandlers(t)){const i=o.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...s});if("Success"!==i)return i}return"Success"}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;const{zones:s}=this.copiedData;for(const o of s){if("COL"===t&&e<=o.right)return!0;if("ROW"===t&&e<=o.bottom)return!0}return!1}copy(e,t="copyPaste"){const s={},o=this.getClipboardData(e);for(const{handlerName:e,handler:i}of this.selectClipboardHandlers(o)){const n=i.copy(o,this._isCutOperation,t);s[e]=n;const r=["sheetId","cells","zones","figureId"];for(const e of r)n&&e in n&&(s[e]=n[e])}return s}paste(e,t,s){if(!t)return;const o=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:n,zone:r,selectedZones:a}=Qs(o,e,t,i,s);void 0!==r&&this.addMissingDimensions(o,r.right-r.left+1,r.bottom-r.top+1,r.left,r.top),Js(i,t,n,s),s?.selectTarget&&eo(this.selection,e,a)}addMissingDimensions(e,t,s,o,i){const n=s+i-this.getters.getNumberRows(e);n>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:n,position:"after"});const r=t+o-this.getters.getNumberCols(e);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:r,position:"after"})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){const e=await this.getImageContent(),t=e?.type,s={[a.PlainText]:this.getPlainTextContent(),[a.Html]:await this.getHTMLContent()};return t&&e&&(s[t]=e),s}getSheetData(){const e={version:zD(),clipboardId:this.clipboardId};return this.copiedData&&"figureId"in this.copiedData?e:{...e,...this.copiedData}}getPlainTextContent(){return this.copiedData?.cells&&this.copiedData.cells.map((e=>e.map((e=>this.getters.shouldShowFormulas()&&e?.tokens?.length?e?.content||"":e.evaluatedCell?.formattedValue||"")).join("\t"))).join("\n")||"\t"}async getHTMLContent(){let e="";const t=this.copiedData?.cells;if(t)if(1===t.length&&1===t[0].length)e=`${this.getters.getCellText(t[0][0].position)}`;else{if(!t[0][0])return"";{let s='<table border="1" style="border-collapse:collapse">';for(const e of t){s+="<tr>";for(const t of e){if(!t)continue;s+=`<td style="${aR(nR(this.getters.getCellComputedStyle(t.position)))}">`+HE(this.getters.getCellText(t.position))+"</td>"}s+="</tr>"}s+="</table>",e=s}}else if(this.copiedData?.figureId){const t=this.copiedData.figureId,s=this.getters.getFigureSheetId(t);e="image"===this.getters.getFigure(s,t).tag?await this.craftImageHTML(t):"\t"}else e="\t";return`<div data-osheet-clipboard='${HE(JSON.stringify(this.getSheetData()))}'>${e}</div>`}readFileAsDataURL(e){return new Promise((t=>{const s=new FileReader;s.onload=()=>t(s.result),s.readAsDataURL(e)}))}async craftImageHTML(e){if(!this.fileStore)return"\t";const t=this.getters.getImage(e).path,s=await(this.fileStore?.getFile(t))||null;if(s){return`<img src="${HE(await this.readFileAsDataURL(s))}" />`}return"\t"}async getImageContent(){const e=this.copiedData?.figureId;if(!e)return;const t=this.getters.getFigureSheetId(e);let s;if("image"===this.getters.getFigure(t,e).tag){if(!this.fileStore)return;const t=this.getters.getImage(e).path;if(s=await(this.fileStore?.getFile(t)),"image/png"!==s.type){if(s.size>vU)return void this.ui.notifyUI({text:Go("The file you are trying to copy is too large (>%sMB).\nIt will not be added to your OS clipboard.\nYou can download it directly instead.",Math.round(5)),sticky:!1,type:"warning"});s=await async function(e){return new Promise(((t,s)=>{const o=new Image;o.addEventListener("load",(()=>{const e=document.createElement("canvas");e.width=o.width,e.height=o.height;const s=e.getContext("2d");s?.drawImage(o,0,0),e.toBlob(t,"image/png")})),o.addEventListener("error",s),o.src=e}))}(t)}}return s?s instanceof File?s:new File([s],"image.png",{type:"image/png"}):void 0}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){const s=this.getters.getActiveSheetId();let o;return o="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(s)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(s)-1},{cut:[o],paste:[e]}}getInsertCellsTargets(e,t){const s=this.getters.getActiveSheetId();let o,i;return"COL"===t?(o={...e,right:this.getters.getNumberCols(s)-1},i={...e,left:e.right+1,right:e.right+1}):(o={...e,bottom:this.getters.getNumberRows(s)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(s)-1}),{cut:[o],paste:[i]}}getClipboardData(e){const t=this.getters.getActiveSheetId(),s=this.getters.getSelectedFigureId();if(s)return{figureId:s,sheetId:t};const o=js(t,e);return this._isCutOperation||(o.rowsIndexes=o.rowsIndexes.filter((e=>!this.getters.isRowFiltered(t,e)))),o}drawLayer(e){if("visible"!==this.status||!this.copiedData)return;const{sheetId:t,zones:s}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!s||!s.length)return;const{ctx:o,thinLineWidth:i}=e;o.setLineDash([8,5]),o.strokeStyle=P,o.lineWidth=3.3*i;for(const e of s){const{x:t,y:s,width:i,height:n}=this.getters.getVisibleRect(e);i>0&&n>0&&o.strokeRect(t,s,i,n)}}}).add("carousel_ui",class extends Rd{static getters=["getSelectedCarouselItem","getChartFromFigureId","getChartIdFromFigureId"];uuidGenerator=new Xa;carouselStates={};allowDispatch(e){switch(e.type){case"ADD_FIGURE_CHART_TO_CAROUSEL":return this.getters.doesCarouselExist(e.carouselFigureId)&&"chart"===this.getters.getFigure(e.sheetId,e.chartFigureId)?.tag?"Success":"InvalidFigureId";case"ADD_NEW_CHART_TO_CAROUSEL":return this.getters.doesCarouselExist(e.figureId)?"Success":"InvalidFigureId";case"UPDATE_CAROUSEL_ACTIVE_ITEM":return this.getters.doesCarouselExist(e.figureId)?this.getters.getCarousel(e.figureId).items.some((t=>St(t,e.item)))?"Success":"InvalidCarouselItem":"InvalidFigureId"}return"Success"}handle(e){switch(e.type){case"ADD_NEW_CHART_TO_CAROUSEL":this.addNewChartToCarousel(e.figureId,e.sheetId);break;case"ADD_FIGURE_CHART_TO_CAROUSEL":this.addFigureChartToCarousel(e.carouselFigureId,e.chartFigureId,e.sheetId);break;case"UPDATE_CAROUSEL_ACTIVE_ITEM":this.carouselStates[e.figureId]=this.getCarouselItemId(e.item);break;case"POPOUT_CHART_FROM_CAROUSEL":this.popOutChartFromCarousel(e.carouselId,e.chartId,e.sheetId);break;case"DELETE_FIGURE":delete this.carouselStates[e.figureId];break;case"UPDATE_CAROUSEL":this.fixWrongCarouselState(e.figureId);break;case"DELETE_CHART":case"UNDO":case"REDO":case"DELETE_SHEET":for(const e in this.carouselStates)this.fixWrongCarouselState(e)}}popOutChartFromCarousel(e,t,s){const o=this.getters.getCarousel(e);if(!o)return;const i=this.getters.getFigure(s,e),n=this.getters.getChartDefinition(t);if(!n||!i)return;const r=this.getters.getFigureUI(s,i),a=this.getters.getPositionAnchorOffset({x:r.x+50,y:r.y+50}),l=this.uuidGenerator.smallUuid();this.dispatch("CREATE_CHART",{...a,chartId:this.uuidGenerator.smallUuid(),figureId:l,sheetId:s,size:{width:i.width,height:i.height},definition:{...n}});const c=o.items.filter((e=>"chart"!==e.type||e.chartId!==t));this.dispatch("UPDATE_CAROUSEL",{sheetId:s,figureId:e,definition:{...o,items:c}}),this.dispatch("SELECT_FIGURE",{figureId:l})}getSelectedCarouselItem(e){const t=this.getters.getCarousel(e);if(t.items.length)return this.carouselStates[e]?t.items.find((t=>this.getCarouselItemId(t)===this.carouselStates[e])):t.items[0]}getChartFromFigureId(e){if(!this.getters.getFigureSheetId(e))return;const t=this.getChartIdFromFigureId(e);return t?this.getters.getChart(t):void 0}getChartIdFromFigureId(e){const t=this.getters.getFigureSheetId(e);if(!t)return;const s=this.getters.getFigure(t,e);if(s&&("chart"===s.tag||"carousel"===s.tag)){if("carousel"===s.tag){const t=this.getSelectedCarouselItem(e);return"chart"===t?.type?t.chartId:void 0}return this.getters.getChartIds(t).find((t=>this.getters.getFigureIdFromChartId(t)===e))}}fixWrongCarouselState(e){if(!this.getters.doesCarouselExist(e))return void delete this.carouselStates[e];const t=this.getters.getCarousel(e);0===t.items.length?delete this.carouselStates[e]:this.carouselStates[e]&&t.items.some((t=>this.getCarouselItemId(t)===this.carouselStates[e]))||(this.carouselStates[e]=this.getCarouselItemId(t.items[0]))}addNewChartToCarousel(e,t){const s=this.getters.getCarousel(e),o=this.uuidGenerator.smallUuid();this.dispatch("CREATE_CHART",{chartId:o,figureId:e,sheetId:t,definition:tR});const i={...s,items:[...s.items,{type:"chart",chartId:o}]};this.dispatch("UPDATE_CAROUSEL",{sheetId:t,figureId:e,definition:i})}addFigureChartToCarousel(e,t,s){const o=this.getChartIdFromFigureId(t);if(!o)return;const i=this.getters.getCarousel(e),n={...i,items:[...i.items,{type:"chart",chartId:o}]};this.dispatch("UPDATE_CAROUSEL",{sheetId:s,figureId:e,definition:n}),this.dispatch("UPDATE_CHART",{sheetId:s,chartId:o,figureId:e,definition:this.getters.getChartDefinition(o)}),this.dispatch("DELETE_FIGURE",{sheetId:s,figureId:t})}getCarouselItemId(e){return"chart"===e.type?e.chartId:"carouselDataView"}}),wU=(new n).add("evaluation",class extends Uk{static getters=["evaluateFormula","evaluateFormulaResult","evaluateCompiledFormula","getCorrespondingFormulaCell","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getEvaluatedCellsInZone","getEvaluatedCellsPositions","getSpreadZone","getArrayFormulaSpreadingOn","isEmpty"];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new vV(e.custom,this.getters)}beforeHandle(e){(l.has(e.type)||h.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case"UPDATE_CELL":if(!("content"in e)&&!("format"in e)||this.shouldRebuildDependenciesGraph)return;const t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),"content"in e&&this.evaluator.updateDependencies(t);break;case"EVALUATE_CELLS":if(e.cellIds)for(let t=0;t<e.cellIds.length;t++)this.positionsToUpdate.push(this.getters.getCellPosition(e.cellIds[t]));else this.evaluator.evaluateAllCells()}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t){const s=this.evaluateFormulaResult(e,t);return R(s)?fn(s,(e=>e.value)):s.value}evaluateFormulaResult(e,t){return this.evaluator.evaluateFormulaResult(e,t)}evaluateCompiledFormula(e,t,s){return this.evaluator.evaluateCompiledFormula(e,t,s)}getRangeFormattedValues(e){return void 0===this.getters.tryGetSheet(e.sheetId)?[]:this.mapVisiblePositions(e,(e=>this.getters.getEvaluatedCell(e).formattedValue))}getRangeValues(e){return void 0===this.getters.tryGetSheet(e.sheetId)?[]:this.mapVisiblePositions(e,(e=>this.getters.getEvaluatedCell(e).value))}getRangeFormats(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.format))}getEvaluatedCell(e){return this.evaluator.getEvaluatedCell(e)}getEvaluatedCells(e){return this.evaluator.getEvaluatedPositionsInSheet(e).map((e=>this.getEvaluatedCell(e)))}getEvaluatedCellsPositions(e){return this.evaluator.getEvaluatedPositionsInSheet(e)}getEvaluatedCellsInZone(e,t){return Ms(t).map((({col:t,row:s})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:s})))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isEmpty(e,t){return Ms(t).map((({col:t,row:s})=>this.getEvaluatedCell({sheetId:e,col:t,row:s}))).every((e=>e.type===r.empty))}mapVisiblePositions(e,t){const{sheetId:s,zone:o}=e;return Ms(o).reduce(((e,o)=>{const{col:i,row:n}=o;return this.getters.isColHidden(s,i)||this.getters.isRowHidden(s,n)||e.push(t({sheetId:s,...o})),e}),[])}exportForExcel(e){for(const t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(const t of this.evaluator.getEvaluatedPositions()){const s=this.evaluator.getEvaluatedCell(t),o=as(t.col,t.row),i=s.value;let n,r=!1,a=!0;const l=e.sheets.find((e=>e.id===t.sheetId)),c=this.getCorrespondingFormulaCell(t);if(c){const h=this.getters.getCell(t);if(a=vC(c.compiledFormula.tokens),r=a&&h?.content===c.content,!a&&""!==i){n=(i??"").toString();const t=s.format;if(t){const s=Gr(t,e.formats);l.formats[o]=s}}}const h=l.cells[o];let d;d=a&&r&&c instanceof Ok?c.contentWithFixedReferences:a?h:n,l.cells[o]=d,l.cellValues[o]="error"!==s.type?i:void 0;const u=this.getSpreadZone(t);u&&(l.formulaSpillRanges[o]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,u),t.sheetId))}}getCorrespondingFormulaCell(e){const t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;const s=this.getArrayFormulaSpreadingOn(e);if(void 0===s)return;const o=this.getters.getCell(s);return o?.isFormula?o:void 0}}).add("evaluation_chart",class extends Uk{static getters=["getChartRuntime","getStyleOfSingleCellChart"];charts={};createRuntimeChart=FE(this.getters);handle(e){if(l.has(e.type)||d.has(e.type)||c.has(e.type))for(const e in this.charts)this.charts[e]=void 0;switch(e.type){case"UPDATE_CHART":case"CREATE_CHART":case"DELETE_CHART":this.charts[e.chartId]=void 0;break;case"DELETE_SHEET":for(const e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0)}}getChartRuntime(e){if(!this.charts[e]){const t=this.getters.getChart(e);if(!t)throw new Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:MC(e)};if(!t)return{background:M,fontColor:MC(M)};const s=t.zone.left,o=t.zone.top,i=t.sheetId,n=this.getters.getCellComputedStyle({sheetId:i,col:s,row:o}),r=n.fillColor||M;return{background:r,fontColor:n.textColor||MC(r)}}exportForExcel(e){for(const t of e.sheets){t.images||(t.images=[]);const e=this.getters.getFigures(t.id),s=[];for(const o of e){if(!o||"chart"!==o.tag)continue;const e=this.getters.getChartIds(t.id).find((e=>this.getters.getFigureIdFromChartId(e)===o.id));if(!e)continue;const i=this.getters.getChart(e),n=i?.getDefinitionForExcel(this.getters);if(n)s.push({...o,data:n});else{if(!i)continue;const s=this.getters.getChartType(e),n=SI(this.getters.getChartRuntime(e),o,s);n&&t.images.push({...o,tag:"image",data:{mimetype:"image/png",path:n,size:{width:o.width,height:o.height}}})}}t.charts=s}}}).add("evaluation_cf",class extends Uk{static getters=["getConditionalIcon","getCellConditionalFormatStyle","getConditionalDataBar"];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(l.has(e.type)||d.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(const e of this.getters.getSheetIds())this.computedStyles[e]=ft((()=>this.getComputedStyles(e))),this.computedIcons[e]=ft((()=>this.getComputedIcons(e))),this.computedDataBars[e]=ft((()=>this.getComputedDataBars(e)));this.isStale=!1}}getCellConditionalFormatStyle(e){const{sheetId:t,col:s,row:o}=e,i=this.computedStyles[t]();return i&&i[s]?.[o]}getConditionalIcon({sheetId:e,col:t,row:s}){const o=this.computedIcons[e]();return o&&o[t]?.[s]}getConditionalDataBar({sheetId:e,col:t,row:s}){const o=this.computedDataBars[e]();return o&&o[t]?.[s]}getComputedStyles(e){const t={};for(const s of this.getters.getConditionalFormats(e).reverse())switch(s.rule.type){case"ColorScaleRule":for(const o of s.ranges)this.applyColorScale(e,o,s.rule,t);break;case"CellIsRule":const o=s.rule.values.map((e=>e.startsWith("=")?gC(e):void 0));for(const i of s.ranges){const n=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=n.top;i<=n.bottom;i++)for(let r=n.left;r<=n.right;r++){const a={sheetId:e,col:r,row:i},l=s.rule.values.map(((t,s)=>{const a=o[s];return a?this.getters.getTranslatedCellFormula(e,r-n.left,i-n.top,a.tokens):t}));this.getRuleResultForTarget(a,{...s.rule,values:l})&&(t[r]||(t[r]=[]),t[r][i]=Object.assign(t[r]?.[i]||{},s.rule.style))}}}return t}getComputedIcons(e){const t={};for(const s of this.getters.getConditionalFormats(e).reverse())if("IconSetRule"===s.rule.type)for(const o of s.ranges)this.applyIcon(e,o,s.rule,t);return t}getComputedDataBars(e){const t={};for(const s of this.getters.getConditionalFormats(e).reverse())if("DataBarRule"===s.rule.type)for(const o of s.ranges)this.applyDataBar(e,o,s.rule,t);return t}parsePoint(e,t,s,o){const i=this.getters.getEvaluatedCellsInZone(e,this.getters.getRangeFromSheetXC(e,t).zone).filter((e=>e.type===r.number)).map((e=>e.value));switch(s.type){case"value":return"max"===o?kt(i):Vt(i);case"number":return Number(s.value);case"percentage":const t=Vt(i);return t+(kt(i)-t)*Number(s.value)/100;case"percentile":return Pi(i,Number(s.value)/100,!0);case"formula":const n=s.value&&this.getters.evaluateFormula(e,s.value);return"number"==typeof n?n:null;default:return null}}applyIcon(e,t,s,o){const i=this.parsePoint(e,t,s.lowerInflectionPoint),n=this.parsePoint(e,t,s.upperInflectionPoint);if(null===i||null===n||i>n)return;const a=this.getters.getRangeFromSheetXC(e,t).zone,l=[s.icons.upper,s.icons.middle,s.icons.lower];for(let t=a.top;t<=a.bottom;t++)for(let c=a.left;c<=a.right;c++){const a=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(a.type!==r.number)continue;const h=this.computeIcon(a.value,n,s.upperInflectionPoint.operator,i,s.lowerInflectionPoint.operator,l);o[c]||(o[c]=[]),o[c][t]=h}}computeIcon(e,t,s,o,i,n){return"ge"===s&&e>=t||"gt"===s&&e>t?n[0]:"ge"===i&&e>=o||"gt"===i&&e>o?n[1]:n[2]}applyDataBar(e,t,s,o){const i=this.getters.getRangeFromSheetXC(e,s.rangeValues||t),n=kt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter((e=>e.type===r.number)).map((e=>e.value)));if(n<=0)return;const a=s.color,l=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=l.top;t<=l.bottom;t++)for(let s=l.left;s<=l.right;s++){const i=s-l.left+c.left,h=t-l.top+c.top,d=this.getters.getEvaluatedCell({sheetId:e,col:i,row:h});!Ds(i,h,c)||d.type!==r.number||d.value<=0||(o[s]||(o[s]=[]),o[s][t]={color:io(a),percentage:100*d.value/n})}}applyColorScale(e,t,s,o){const i=this.parsePoint(e,t,s.minimum,"min"),n=s.midpoint?this.parsePoint(e,t,s.midpoint):null,a=this.parsePoint(e,t,s.maximum,"max");if(null===i||null===a||i>=a||n&&(i>=n||n>=a))return;const l=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:s.minimum.color}];s.midpoint&&n&&c.push({value:n,color:s.midpoint.color}),c.push({value:a,color:s.maximum.color});const h=No(c);for(let t=l.top;t<=l.bottom;t++)for(let s=l.left;s<=l.right;s++){const n=this.getters.getEvaluatedCell({sheetId:e,col:s,row:t});if(n.type===r.number){const e=Ke(n.value,i,a);o[s]||(o[s]=[]),o[s][t]=o[s]?.[t]||{},o[s][t].fillColor=h(e)}}}getRuleResultForTarget(e,t){const s=this.getters.getEvaluatedCell(e);if(s.type===r.error)return!1;const{sheetId:o}=e,i=FR.get(t.operator),n=t.values.map((e=>e.startsWith("=")?this.getters.evaluateFormula(o,e)??"":Or(e,w)));if(n.some(Yl))return!1;const a={type:t.operator,values:n.map(Zl)};return i.isValueValid(s.value??"",a,this.getters,o)}}).add("row_size",class extends Uk{static getters=["getRowSize","getHeaderSize","getMaxAnchorOffset"];tallestCellInRow={};ctx=document.createElement("canvas").getContext("2d");beforeHandle(e){if("ADD_COLUMNS_ROWS"===e.type){if("COL"===e.dimension)return;const t=bt(e.position,e.base),s=Array(e.quantity).fill(void 0),o=Ot(this.tallestCellInRow[e.sheetId],s,t);this.history.update("tallestCellInRow",e.sheetId,o)}}handle(e){switch(e.type){case"START":for(const e of this.getters.getSheetIds())this.initializeSheet(e);break;case"CREATE_SHEET":this.initializeSheet(e.sheetId);break;case"DUPLICATE_SHEET":{const t=qe(this.tallestCellInRow[e.sheetId]);this.history.update("tallestCellInRow",e.sheetIdTo,t);break}case"DELETE_SHEET":const t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update("tallestCellInRow",t);break;case"REMOVE_COLUMNS_ROWS":{if("COL"===e.dimension)return;const t=Ft(this.tallestCellInRow[e.sheetId],e.elements);this.history.update("tallestCellInRow",e.sheetId,t);break}case"RESIZE_COLUMNS_ROWS":{const t=e.sheetId;if("ROW"===e.dimension)for(const s of e.elements){const e=this.getRowTallestCell(t,s);this.history.update("tallestCellInRow",t,s,e)}else for(const s of Je(0,this.getters.getNumberRows(t)))for(const o of e.elements)this.updateRowSizeForCellChange(t,s,o)}break;case"UPDATE_CELL":this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case"ADD_MERGE":case"REMOVE_MERGE":for(const t of e.target)for(const s of Ms(t))this.updateRowSizeForCellChange(e.sheetId,s.row,s.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??ne)}getMaxAnchorOffset(e,t,s){let{numberOfRows:o,numberOfCols:i}=this.getters.getSheetSize(e),n=0;for(;n<t&&o>0;o--)n+=this.getRowSize(e,o-1);let r=0;for(;r<s&&i>0;i--)r+=this.getters.getColSize(e,i-1);return{col:i,row:o,offset:{x:r-s,y:n-t}}}getHeaderSize(e,t,s){return this.getters.isHeaderHidden(e,t,s)?0:"ROW"===t?this.getRowSize(e,s):this.getters.getColSize(e,s)}updateRowSizeForCellChange(e,t,s){const o=this.tallestCellInRow[e]?.[t];if(o?.cell.col===s){const s=this.getRowTallestCell(e,t);this.history.update("tallestCellInRow",e,t,s)}const i=this.getCellHeight({sheetId:e,col:s,row:t});if(!(i<=ne)&&(!o&&i>ne||o&&i>o.size)){const o={cell:{sheetId:e,col:s,row:t},size:i};this.history.update("tallestCellInRow",e,t,o)}}initializeSheet(e){const t=[];for(let s=0;s<this.getters.getNumberRows(e);s++){const o=this.getRowTallestCell(e,s);t.push(o)}this.history.update("tallestCellInRow",e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return ne;const t=this.getters.getCell(e),s=this.getters.getColSize(e.sheetId,e.col);return function(e,t,s){return t&&(t.isFormula||t.content)?Pa(e,t.isFormula?"":t.content,t.style,s):ne}(this.ctx,t,s)}isInMultiRowMerge(e){const t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(void 0!==this.getters.getUserRowSize(e,t))return;const s=this.getters.getRowCells(e,t);let o,i=0;for(let e=0;e<s.length;e++){const t=this.getters.getCellById(s[e]);if(!t)continue;const n=this.getters.getCellPosition(t.id),r=this.getCellHeight(n);r>i&&r>ne&&(i=r,o={cell:n,size:r})}return o&&o.size>ne?o:void 0}}).add("data_validation_ui",class extends Uk{static getters=["getDataValidationInvalidCriterionValueMessage","getInvalidDataValidationMessage","getValidationResultForCellValue","getDataValidationRangeValues","isCellValidCheckbox","getDataValidationCellStyle","getDataValidationChipStyle","isDataValidationInvalid"];validationResults={};handle(e){if(l.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))this.validationResults={};else switch(e.type){case"ADD_DATA_VALIDATION_RULE":case"REMOVE_DATA_VALIDATION_RULE":delete this.validationResults[e.sheetId]}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:$}}getInvalidDataValidationMessage(e){const t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){const s=FR.get(e);return t.startsWith("=")?"onlyLiterals"===s.allowedValues?Go("The value must not be a formula"):this.isValidFormula(t)?void 0:rb.CriterionError.validFormula:"onlyFormulas"===s.allowedValues?Go("The value must be a formula"):s.isCriterionValueValid(t)?void 0:s.criterionValueErrorString}getDataValidationRangeValues(e,t){const s=this.getters.getRangeFromSheetXC(e,String(t.values[0])),o=[],i=new Set;for(const e of Ms(s.zone)){const t=this.getters.getEvaluatedCell({...e,sheetId:s.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),o.push({label:t.formattedValue,value:t.value?.toString()||""}))}return o}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;const t=this.getters.getValidationRuleForCell(e);return!(!t||"isBoolean"!==t.criterion.type)&&this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){const s=this.getters.getValidationRuleForCell(t);if(!s)return IV;const o=this.getRuleErrorForCellValue(e,t,s);return o?{error:o,rule:s,isValid:!1}:IV}hasChip(e){const t=this.getters.getValidationRuleForCell(e);return("isValueInList"===t?.criterion.type||"isValueInRange"===t?.criterion.type)&&"chip"===t.criterion.displayStyle}getDataValidationStyle(e){const t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;const s=this.getters.getEvaluatedCell(e),o=this.getValueColor(t,s.value);if(!o)return;return{fillColor:o,textColor:Io(o)}}getValueColor(e,t){if("isValueInList"===e.criterion.type||"isValueInRange"===e.criterion.type)for(const s in e.criterion.colors)if(s.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[s]}isValidFormula(e){return!gC(e).isBadExpression}getValidationResultForCell(e){const{col:t,row:s,sheetId:o}=e;return this.validationResults[o]||(this.validationResults[o]=this.computeSheetValidationResults(o)),this.validationResults[o][t]?.[s]?.()||IV}computeSheetValidationResults(e){const t={},s=this.getters.getDataValidationRules(e).map((e=>e.ranges));for(const e of ya(s.flat())){const{col:s,row:o}=e;t[s]||(t[s]=[]),t[s][o]=ft((()=>{const t=this.getters.getEvaluatedCell(e);return t.type===r.empty?IV:this.getValidationResultForCellValue(t.value,e)}))}return t}getRuleErrorForCellValue(e,t,s){const{sheetId:o}=t,i=s.criterion,n=FR.get(i.type),r=this.getCellOffsetInRule(t,s),a=this.getEvaluatedCriterionValues(o,r,i);if(a.some(Yl))return;const l={...i,values:a.map(Zl)};return n.isValueValid(e,l,this.getters,o)?void 0:n.getErrorString(l,this.getters,o)}getCellOffsetInRule(e,t){const s=t.ranges.find((t=>Ds(e.col,e.row,t.zone)));if(!s)throw new Error("The cell is not in any range of the rule");return{col:e.col-s.zone.left,row:e.row-s.zone.top}}getEvaluatedCriterionValues(e,t,s){return s.values.map((s=>{if(!s.startsWith("="))return Or(s,w);const o=gC(s),i=this.getters.getTranslatedCellFormula(e,t.col,t.row,o.tokens);return this.getters.evaluateFormula(e,i)}))}}).add("dynamic_tables",class extends Uk{static getters=["canCreateDynamicTableOnZones","doesZonesContainFilter","getFilter","getFilters","getTable","getTables","getTablesOverlappingZones","getFilterId","getFilterHeaders","isFilterHeader"];tables={};handle(e){if(l.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e)||"EVALUATE_CELLS"===e.type)this.tables={};else switch(e.type){case"CREATE_TABLE":case"REMOVE_TABLE":case"UPDATE_TABLE":case"DELETE_CONTENT":this.tables={}}}finalize(){for(const e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){const t=[],s=this.getters.getCoreTables(e);for(const e of s)"dynamic"!==e.type&&t.push(e);const o=[...t];for(const i of s){if("dynamic"!==i.type)continue;const s=this.coreTableToTable(e,i);let n=s.range.zone;for(const e of o)As(n,e.range.zone)&&(n={...n,right:e.range.zone.left-1});t.push({...s,range:this.getters.getRangeFromZone(e,n)})}return t}getFilters(e){return this.getTables(e).filter((e=>e.config.hasFilters)).map((e=>e.filters)).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){const t=this.getTable(e);if(t&&t.config.hasFilters)return t.filters.find((t=>t.col===e.col))}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:s}){return this.getTables(e).find((e=>Ds(t,s,e.range.zone)))}getTablesOverlappingZones(e,t){return this.getTables(e).filter((e=>t.some((t=>As(e.range.zone,t)))))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some((e=>e.config.hasFilters))}getFilterHeaders(e){const t=[];for(const s of this.getTables(e)){if(!s.config.hasFilters)continue;const o=s.range.zone,i=o.top;for(let s=o.left;s<=o.right;s++)t.push({sheetId:e,col:s,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:s}){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===s))}canCreateDynamicTableOnZones(e,t){if(!$s(t))return!1;const s=Es(...t),o={col:s.left,row:s.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(o);if(!i)return!1;if(St(i,o)&&1===Gs(s))return!0;return St(s,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if("dynamic"!==t.type)return t;const s=t.range.zone,o={sheetId:e,col:s.left,row:s.top},i=this.getters.getSpreadZone(o)??t.range.zone,n=this.getters.getRangeFromZone(e,i),r=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:n,filters:r,config:t.config}}getDynamicTableFilters(e,t,s){const o=[],{top:i,bottom:n,left:r,right:a}=s;for(let s=r;s<=a;s++){const a=s-r,l={left:s,right:s,top:i,bottom:n},c=K_(this.getDynamicTableFilterId(t.id,a),this.getters.getRangeFromZone(e,l),t.config,this.getters.getRangeFromZone);o.push(c)}return o}getDynamicTableFilterId(e,t){return e+"_"+t}exportForExcel(e){for(const t of e.sheets)for(const e of t.tables){const s=ms(e.range),o={sheetId:t.id,col:s.left,row:s.top},i=this.getters.getCoreTable(o),n=this.getTable(o);"dynamic"===i?.type&&n&&(e.range=Ss(n.range.zone))}}}).add("custom_colors",class extends Uk{customColors={};shouldUpdateColors=!0;static getters=["getCustomColors"];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case"START":for(const e of this.getters.getSheetIds())for(const t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));break;case"UPDATE_CHART":case"CREATE_CHART":this.tryToAddColors(this.getChartColors(e.chartId));break;case"UPDATE_CELL":case"ADD_CONDITIONAL_FORMAT":case"SET_BORDER":case"SET_ZONE_BORDERS":case"SET_FORMATTING":case"CREATE_TABLE":case"UPDATE_TABLE":this.history.update("shouldUpdateColors",!0)}}finalize(){this.shouldUpdateColors&&(this.history.update("shouldUpdateColors",!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return function(e){const t=[{leadColor:co(255,0,0),colors:[]},{leadColor:co(255,128,0),colors:[]},{leadColor:co(128,128,0),colors:[]},{leadColor:co(128,255,0),colors:[]},{leadColor:co(0,255,0),colors:[]},{leadColor:co(0,255,128),colors:[]},{leadColor:co(0,255,255),colors:[]},{leadColor:co(0,127,255),colors:[]},{leadColor:co(0,0,255),colors:[]},{leadColor:co(127,0,255),colors:[]},{leadColor:co(128,0,128),colors:[]},{leadColor:co(255,0,128),colors:[]}];for(const s of e.map(go)){let e=500,o=0;t.forEach(((t,i)=>{const n=(r=s,a=t.leadColor,Math.sqrt(Math.pow(r.r-a.r,2)+Math.pow(r.g-a.g,2)+Math.pow(r.b-a.b,2)));var r,a;e>n&&(e=n,o=i)})),t[o].colors.push(s)}return t.map((e=>e.colors.sort(((e,t)=>mo(e).s-mo(t).s)))).flat().map(uo)}(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(const t of this.getters.getSheetIds())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getColorsFromCells(e){const t=Object.values(this.getters.getCells(e)),s=new Set;for(const e of t)e.style?.textColor&&s.add(e.style.textColor),e.style?.fillColor&&s.add(e.style.fillColor);for(const t of this.getters.getBordersColors(e))s.add(t);return[...s]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),s=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(s.push(t.style.textColor),s.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(s.push(io(t.minimum.color)),s.push(t.midpoint?io(t.midpoint.color):void 0),s.push(io(t.maximum.color)))}return s.filter(ut)}getChartColors(e){const t=this.getters.getChart(e);if(void 0===t)return[];return[...JSON.stringify(t.getDefinition()).matchAll(yV)].map((e=>e[1]))}getTableColors(e){return this.getters.getTables(e).flatMap((e=>{const t=e.config,s=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(s.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(s.headerRow):[],t.totalRow?this.getTableStyleElementColors(s.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(s.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(s.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(s.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(s.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(s.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(s.lastColumn):[]].flat()}))}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(ut):[]}tryToAddColors(e){for(const t of e){if(!ao(t))continue;const e=ro(t);t&&!te.includes(e)&&this.history.update("customColors",e,!0)}}}).add("pivot_ui",class extends Uk{static getters=["getPivot","getFirstPivotFunction","getPivotCellSortDirection","getPivotIdFromPosition","getPivotCellFromPosition","generateNewCalculatedMeasureName","isPivotUnused","isSpillPivotFormula"];pivots={};unusedPivots;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){if("START"===e.type)for(const e of this.getters.getPivotIds())this.setupPivot(e)}handle(e){if(l.has(e.type))for(const e of this.getters.getPivotIds())HO.get(this.getters.getPivotCoreDefinition(e).type).externalData||this.setupPivot(e,{recreate:!0});switch(e.type){case"REFRESH_PIVOT":this.refreshPivot(e.id);break;case"ADD_PIVOT":this.setupPivot(e.pivotId);break;case"DUPLICATE_PIVOT":this.setupPivot(e.newPivotId);break;case"UPDATE_PIVOT":this.setupPivot(e.pivotId,{recreate:!0});break;case"DELETE_SHEET":case"UPDATE_CELL":this.unusedPivots=void 0;break;case"UNDO":case"REDO":{this.unusedPivots=void 0;const t=e.commands.filter(AV);for(const e of t){const t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case"UPDATE_LOCALE":!function(){for(const e in VO)VO[e].set.clear(),VO[e].values={}}()}}getPivotIdFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){const s=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(s){const e=s.args[0]?.toString();return e&&this.getters.getPivotId(e)}}}isSpillPivotFormula(e){const t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){const s=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);return"PIVOT"===s?.functionName}return!1}getFirstPivotFunction(e,t){const s=tk(t);if(!s)return;const{functionName:o,args:i}=s;return{functionName:o,args:i.map((t=>{if("EMPTY"===t.type)return;if("STRING"===t.type||"BOOLEAN"===t.type||"NUMBER"===t.type)return t.value;const s=LM(t);return this.getters.evaluateFormula(e,s)}))}}getPivotCellFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||0===sk(t.compiledFormula.tokens))return DO;const s=this.getters.getCellPosition(t.id),o=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!o)return DO;let{functionName:i,args:n}=o;const r=n[0];if(!r)return DO;const a=this.getters.getPivotId(r.toString());if(!a)return DO;const l=this.getPivot(a);if(!l.isValid())return DO;if("PIVOT"===i&&!t.content.replaceAll(" ","").toUpperCase().startsWith("=PIVOT"))return DO;if("PIVOT"===i){const t=Zl(n[2]),o=void 0===t||nn(t),i=Zl(n[3]),r=Zl(n[5]),a=void 0===r||nn(r),c={displayColumnHeaders:void 0===i||nn(i),displayTotals:o,displayMeasuresRow:a},h=l.getCollapsedTableStructure().getPivotCells(c),d=e.col-s.col,u=e.row-s.row;return h[d][u]}try{const t=e.row-s.row,o=e.col-s.col;if(n=n.map((e=>R(e)?e[o][t]:e)),"PIVOT.HEADER"===i&&"measure"===n.at(-2)){return{type:"MEASURE_HEADER",domain:l.parseArgsToPivotDomain(n.slice(1,-2).map((e=>({value:e})))),measure:n.at(-1)?.toString()||""}}if("PIVOT.HEADER"===i){const e=l.parseArgsToPivotDomain(n.slice(1).map((e=>({value:e}))));return{type:"HEADER",domain:e,dimension:gO(l,e).colDomain.length?"COL":"ROW"}}const[r,...a]=n.slice(1);return{type:"VALUE",domain:l.parseArgsToPivotDomain(a.map((e=>({value:e})))),measure:r?.toString()||""}}catch(e){return DO}}generateNewCalculatedMeasureName(e){const t=e.map((e=>e.fieldName));return Bt(Go("Calculated measure 1"),t,{compute:(e,t)=>Go("Calculated measure %s",t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw new Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){return this._getUnusedPivots().includes(e)}getPivotCellSortDirection(e){const t=this.getters.getPivotIdFromPosition(e),s=this.getters.getPivotCellFromPosition(e);if("EMPTY"===s.type||"HEADER"===s.type||!t)return;const o=this.getters.getPivot(t),i=gO(o,s.domain).colDomain,n=o.definition.sortedColumn;return n?.measure===s.measure&&St(n.domain,i)?n.order:"none"}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){const s=this.getters.getPivotCoreDefinition(e);if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(s);else{const t=xV(HO.get(s.type).ui);this.pivots[e]=new t(this.custom,{definition:s,getters:this.getters})}}_getUnusedPivots(){if(void 0!==this.unusedPivots)return this.unusedPivots;const e=new Set(this.getters.getPivotIds());for(const t of this.getters.getSheetIds())for(const s in this.getters.getCells(t)){const t=this.getters.getCellPosition(s),o=this.getPivotIdFromPosition(t);if(o&&(e.delete(o),!e.size))return this.unusedPivots=[],[]}return this.unusedPivots=[...e],this.unusedPivots}}).add("cell_icon",class extends Uk{static getters=["doesCellHaveGridIcon","getCellIcons","getCellIconRect"];cellIconsCache={};handle(e){"SET_VIEWPORT_OFFSET"!==e.type&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){const s=e.position,o=this.getters.getCell(s);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,o?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,s){const o=e.x,i=e.x+e.width;switch(t){case"right":return i-s.margin-s.size;case"left":return o+s.margin;default:const e=Math.floor((i-o-s.size)/2);return i-s.size-e}}computeCellIcons(e){const t={left:void 0,right:void 0,center:void 0},s=wV.getAll();for(const o of s){const s=o(this.getters,e);s&&(!t[s.horizontalAlign]||s.priority>t[s.horizontalAlign].priority)&&(t[s.horizontalAlign]=s)}if(t.center&&(t.left||t.right)){const e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(ut)}doesCellHaveGridIcon(e){return Boolean(this.getCellIcons(e).length)}});Xh.add("dataValidation",{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(Gt(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?Io(t):void 0,backgroundColor:t||$,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()}}),Xh.add("functions",{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if("SYMBOL"!==e.type)return[];const t=e.value;if(!Gt(this.composer.currentContent))return[];const s=Object.entries(JS.content).filter((([e,{hidden:t}])=>!t)).map((([e,{description:s}])=>({text:e,description:s,htmlContent:GL(t,e,V,"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)}}),Xh.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:Ge.NUMBER}],fuzzySearchKey:s+t.name,alwaysExpanded:!0}})).filter(ut)},selectProposal:iC}),Xh.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=ek(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:Go("Count"),htmlContent:[{value:e,color:Ge.STRING}],fuzzySearchKey:Go("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:Ge.STRING}],fuzzySearchKey:s}}(e)})).filter(ut):[]},selectProposal:iC}),Xh.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=ek(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(ut),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=Tk.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(ut);return m.map((e=>{const[t,s]=e.split(":"),o=n[t];return o?QL(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:Go("%s (positional)",s.string)+(s.help?` (${s.help})`:""),htmlContent:[{value:o,color:Ge.STRING}],fuzzySearchKey:s.string+o}}))).filter(ut)},selectProposal:iC}),Xh.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=ek(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(er).map(((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:Ge.NUMBER}]}))):"quarter_number"===a.granularity?[1,2,3,4].map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:Go("Quarter %s",e),htmlContent:[{value:`${e}`,color:Ge.NUMBER}]}))):"day_of_month"===a.granularity?Je(1,32).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:Ge.NUMBER}]}))):"iso_week_number"===a.granularity?Je(0,54).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:Ge.NUMBER}]}))):"day_of_week"===a.granularity?Je(1,8).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:Ge.NUMBER}]}))):"hour_number"===a.granularity?Je(0,24).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:Ge.NUMBER}]}))):"minute_number"===a.granularity?Je(0,60).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:Ge.NUMBER}]}))):"second_number"===a.granularity?Je(0,60).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:Ge.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?Ge.STRING:Ge.NUMBER}],fuzzySearchKey:o+i}}))},selectProposal:iC}),Xh.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=Ye(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 EU=new n;EU.add("link",{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,s)=>Ko(t.model.getters.getEvaluatedCell(e).link,t,s),title:(e,t)=>{const s=t.getEvaluatedCell(e).link;return s?s.isExternal?Go("Go to url: %(url)s",{url:s.url}):Go("Go to %(label)s",{label:s.label}):""},sequence:5}),EU.add("dashboard_pivot_sorting",{condition:(e,t)=>{if(!t.isDashboard())return!1;const s=t.getPivotCellFromPosition(e);return XO(t,e)&&"MEASURE_HEADER"===s.type},execute:(e,t)=>{KO(t,e,function(e,t){return RU[e.getPivotCellSortDirection(t)??"none"]}(t.model.getters,e))},component:Ak,componentProps:(e,t)=>({position:e,sortDirection:t.getPivotCellSortDirection(e)}),sequence:2});const RU={none:"asc",asc:"desc",desc:"none"};const xU=(new n).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let s=e.base;"after"===e.position&&s++;for(let o=0;o<e.quantity;o++)t.push(o+s);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId,sheetName:e.sheetName}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],s=[...e.elements].sort(((e,t)=>e-t));for(const o of Qe(s)){const s=0===o[0]?0:o[0]-1,i=0===o[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:o.length,base:s,sheetId:e.sheetId,sheetName:e.sheetName,position:i})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId,sheetName:e.name}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1,name:e.sheetName}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo,sheetName:""}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",figureId:e.figureId,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",figureId:e.figureId,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("CREATE_TABLE_STYLE",(function(e){return[{type:"REMOVE_TABLE_STYLE",tableStyleId:e.tableStyleId}]})).add("ADD_PIVOT",(function(e){return[{type:"REMOVE_PIVOT",pivotId:e.pivotId}]})).add("RENAME_SHEET",(function(e){return[{type:"RENAME_SHEET",sheetId:e.sheetId,oldName:e.newName,newName:e.oldName}]}));for(const e of m.values())xU.contains(e)||xU.add(e,TU);function TU(e){return[e]}const AU=new n;AU.add("format_number_automatic",{...gP,id:"format_number_automatic",sequence:10}).add("format_number_plain_text",{...pP,id:"format_number_plain_text",sequence:15,separator:!0}).add("format_number_number",{...mP,id:"format_number_number",sequence:20}).add("format_number_percent",{...vP,id:"format_number_percent",sequence:30,separator:!0}).add("format_number_currency",{...bP,id:"format_number_currency",sequence:40}).add("format_number_accounting",{...CP,id:"format_number_accounting",sequence:45}).add("format_number_currency_rounded",{...SP,id:"format_number_currency_rounded",sequence:50}).add("format_custom_currency",{...IP,id:"format_custom_currency",sequence:60,separator:!0}).add("format_number_date",{...wP,id:"format_number_date",sequence:70}).add("format_number_time",{...EP,id:"format_number_time",sequence:80}).add("format_number_date_time",{...RP,id:"format_number_date_time",sequence:90}).add("format_number_duration",{...xP,id:"format_number_duration",sequence:100,separator:!0}).add("more_formats",{...DP,id:"more_formats",sequence:120});const DU=_t((e=>ur(e)?"date":e.includes("[$")?"currency":"number")),_U={name:Go("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[e=>{const t=function(e){const t=new Set(AU.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=DU(o.format);"date"!==e&&"currency"!==e||s.set(o.format,uP({descriptionValue:"currency"===e?1e3:yP,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),s([...AU.getAll(),...t])}]};const FU=new Hx;FU.add("file",{name:Go("File"),sequence:10}).addChild("settings",["file"],{name:Go("Settings"),sequence:200,execute:e=>e.openSidePanel("Settings"),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.COG"}).add("edit",{name:Go("Edit"),sequence:20}).addChild("undo",["edit"],{...aF,sequence:10}).addChild("redo",["edit"],{...lF,sequence:20,separator:!0}).addChild("copy",["edit"],{...cF,sequence:30}).addChild("cut",["edit"],{...hF,sequence:40}).addChild("paste",["edit"],{...dF,sequence:50}).addChild("paste_special",["edit"],{...uF,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...gF,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{...pF,sequence:20}).addChild("edit_table",["edit"],{...TF,isVisible:p_,sequence:60}).addChild("find_and_replace",["edit"],{...mF,sequence:65,separator:!0}).addChild("delete",["edit"],{name:Go("Delete"),icon:"o-spreadsheet-Icon.TRASH",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...fF,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...vF,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...CF,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{...EF,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...RF,sequence:50}).addChild("edit_unhide_columns",["edit"],{...R_,sequence:80}).addChild("edit_unhide_rows",["edit"],{...A_,sequence:80}).add("view",{name:Go("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...D_,sequence:4}).addChild("freeze_panes",["view"],{...__,sequence:5}).addChild("unfreeze_rows",["view","freeze_panes"],{...F_,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...O_,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...P_,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...M_,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...N_,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...L_,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...k_,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...V_,sequence:40}).addChild("group_headers",["view"],{name:Go("Group"),sequence:15,separator:!0,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",isVisible:f_}).addChild("group_columns",["view","group_headers"],{...B_,sequence:5}).addChild("ungroup_columns",["view","group_headers"],{...W_,isVisible:e=>j_(e,"COL"),sequence:10}).addChild("group_rows",["view","group_headers"],{...G_,sequence:15}).addChild("ungroup_rows",["view","group_headers"],{...$_,isVisible:e=>j_(e,"ROW"),sequence:20}).addChild("show",["view"],{name:Go("Show"),sequence:1,icon:"o-spreadsheet-Icon.SHOW"}).addChild("view_gridlines",["view","show"],{...U_,sequence:5}).addChild("view_formulas",["view","show"],{...z_,sequence:10}).addChild("view_irregularity_map",["view"],{...H_,sequence:40,separator:!0}).add("insert",{name:Go("Insert"),sequence:40}).addChild("insert_row",["insert"],{...FF,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...PF,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...LF,sequence:20}).addChild("insert_column",["insert"],{...kF,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...UF,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...BF,sequence:20}).addChild("insert_cell",["insert"],{...GF,sequence:30}).addChild("insert_cell_down",["insert","insert_cell"],{...WF,name:Go("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...$F,name:Go("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...aO,sequence:40,separator:!0}).addChild("insert_chart",["insert"],{...qF,sequence:50}).addChild("insert_carousel",["insert"],{...ZF,sequence:51}).addChild("insert_pivot",["insert"],{...jF,sequence:52}).addChild("insert_image",["insert"],{...YF,sequence:55}).addChild("insert_table",["insert"],{...XF,sequence:57}).addChild("insert_function",["insert"],{...KF,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...JF,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...QF,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{...eO,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...tO,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...sO,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...oO,sequence:50}).addChild("categories_function_list",["insert","insert_function"],(()=>{const e=JS.content;return[...new Set(JS.getAll().filter((e=>!e.hidden)).map((e=>e.category)))].filter(ut).sort().map(((t,s)=>{const o=Object.keys(e).filter((s=>e[s].category===t&&!e[s].hidden));return{name:t,children:lO(o)}}))})).addChild("insert_link",["insert"],{...iO,separator:!0,sequence:70}).addChild("insert_checkbox",["insert"],{...nO,sequence:80}).addChild("insert_dropdown",["insert"],{...rO,separator:!0,sequence:90}).add("format",{name:Go("Format"),sequence:50}).addChild("format_number",["format"],{..._U,name:Go("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{...zP,sequence:20}).addChild("format_italic",["format"],{...BP,sequence:30}).addChild("format_underline",["format"],{...GP,sequence:40}).addChild("format_strikethrough",["format"],{...WP,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...$P,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...qP,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...jP,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...YP,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...XP,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{...JP,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...QP,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{...eM,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...tM,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...oM,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...iM,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...nM,sequence:30}).addChild("format_cf",["format"],{...rM,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...aM,sequence:100,separator:!0}).add("data",{name:Go("Data"),sequence:60}).addChild("sort_range",["data"],{...tP,sequence:10,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...sP,sequence:10}).addChild("sort_descending",["data","sort_range"],{...rP,sequence:20}).addChild("data_cleanup",["data"],{...oP,sequence:15}).addChild("remove_duplicates",["data","data_cleanup"],{...iP,sequence:10}).addChild("trim_whitespace",["data","data_cleanup"],{...nP,sequence:20}).addChild("split_to_columns",["data"],{...cP,sequence:20}).addChild("data_validation",["data"],{name:Go("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"],{...aP,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 HL(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(XR).register(i),onStopHover:e=>e.getStore(XR).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"],hP).addChild("reinsert_static_pivot",["data"],dP);const OU=new class extends n{mapping={};uuidGenerator=new Xa;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 PU{listeners=[];async sendMessage(e){for(const{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter((t=>t.id!==e))}}class MU{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 NU=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];class LU 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(NU,{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 aR({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 kU 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:LU};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 aR({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{...Gy(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{...Gy(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 VU 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:kU,ColorPicker:cx};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=rh(kR),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(Go("The sheet name cannot be empty."),o):i.reasons.includes("DuplicatedSheetName")?e.raiseError(Go("A sheet with the name %s already exists. Please select another name.",s),o):i.reasons.includes("ForbiddenCharactersInSheetName")&&e.raiseError(Go("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",_e.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 Gy(this.sheetDivRef.el)}get contextMenuRegistry(){return function(e){const t=new Hx;return t.add("delete",{...Px,sequence:10}).add("hide_sheet",{...Ux,sequence:20}).add("duplicate",{...Mx,sequence:30,separator:!0}).add("rename",{...Nx(e),sequence:40}).add("change_color",{...Lx(e),sequence:50,separator:!0}).add("move_right",{...kx,sequence:60}).add("move_left",{...Vx,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 aR({background:this.env.model.getters.getSheet(this.props.sheetId).color||""})}}const UU=[{name:Go("Sum"),types:[r.number],compute:(e,t)=>Nl([[e]],t)},{name:Go("Avg"),types:[r.number],compute:(e,t)=>Kl([[e]],t)},{name:Go("Min"),types:[r.number],compute:(e,t)=>tc([[e]],t).value},{name:Go("Max"),types:[r.number],compute:(e,t)=>ec([[e]],t).value},{name:Go("Count"),types:[r.number,r.text,r.boolean,r.error],compute:e=>Ql([[e]])},{name:Go("Count Numbers"),types:[r.number,r.text,r.boolean,r.error],compute:(e,t)=>Jl([[e]],t)}];class HU extends ph{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)})}handle(e){switch((l.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=ls(e.getSelectedZones(),[]),i=this.getters.getSheetSize(t).numberOfRows-1,n=this.getters.getSheetSize(t).numberOfCols-1;for(const a of o)for(let o=a.left;o<=(a.right??n);o++)for(let n=a.top;n<=(a.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!==r.empty&&s.push(i)}const a=e.getLocale(),l={},c=_t((e=>{const t=e.split(",");return s.filter((e=>t.includes(e.type)))}));for(const e of UU){let t;const s=c(e.types.sort().join(","));s.length&&(t=ft((()=>e.compute(s,a)))),l[e.name]=t}return l}}class zU extends t.Component{static template="o-spreadsheet-BottomBarStatistic";static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:kU};selectedStatisticFn="";store;setup(){this.store=rh(HU),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 Hx;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?or(s(),{locale:t}):"__")}}class BU extends t.Component{static template="o-spreadsheet-BottomBar";static props={onClick:Function};static components={MenuPopover:fR,Ripple:kU,BottomBarSheet:VU,BottomBarStatistic:zU};bottomBarRef=t.useRef("bottomBar");sheetListRef=t.useRef("sheetList");dragAndDrop=ux();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();St(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(Go("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 Hx,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 GU extends ph{_clickableCells=t.markRaw({});_registryItems=t.markRaw(EU.getAll().sort(((e,t)=>e.sequence-t.sequence)));handle(e){(l.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(EU.getAll().sort(((e,t)=>e.sequence-t.sequence))))}getClickableItem(e){const{sheetId:t,col:s,row:o}=e,i=this._clickableCells,n=as(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,Us(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 WU extends t.Component{static template="o-spreadsheet-SpreadsheetDashboard";static props={getGridSize:Function};static components={GridOverlay:sN,GridPopover:oN,Popover:uR,VerticalScrollBar:SN,HorizontalScrollBar:bN};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;gridRef;setup(){this.gridRef=t.useRef("grid"),this.hoveredCell=rh(wR),this.clickableCellsStore=rh(GU),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),dN("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimension())),this.onMouseWheel=gN(((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()})),this.cellPopovers=rh(RR),uN(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 aR({"max-width":`${s}px`})}get gridOverlayDimensions(){return aR({height:"100%",width:"100%"})}getCellClickableStyle(e){return aR({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,Ky(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{...By(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}}class $U 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;pM(this.env,e,this.dimension,t,s)}get groupBoxStyle(){const e=this.groupBox;return aR({top:`${e.groupRect.y}px`,left:`${e.groupRect.x}px`,width:`${e.groupRect.width}px`,height:`${e.groupRect.height}px`})}get groupButtonStyle(){return aR({"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(),o={x:e.clientX,y:e.clientY},i=this.props.group,n=function(e,t,o,i){const n=s([{id:"toggle_group",name:e=>{const s=e.model.getters.getActiveSheetId(),n=e.model.getters.isGroupFolded(s,t,o,i);return Go(n?"ROW"===t?"Expand row group":"Expand column group":"ROW"===t?"Collapse row group":"Collapse column group")},execute:e=>{const s=e.model.getters.getActiveSheetId();pM(e,s,t,o,i)}},{id:"remove_group",name:Go("ROW"===t?"Remove row group":"Remove column group"),execute:e=>{const s=e.model.getters.getActiveSheetId();e.model.dispatch("UNGROUP_HEADERS",{sheetId:s,dimension:t,start:o,end:i})},separator:!0}]);return[...n,...mM(e,t)]}(t,this.dimension,i.start,i.end);this.props.openContextMenu(o,n)}}class qU extends $U{dimension="ROW";get groupBorderStyle(){const e=this.groupBox;return 0===this.groupBox.groupRect.height?"":aR({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 aR({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=se;if(0!==t){const s=this.env.model.getters.getRowDimensions(e,t-1);n=se+s.start,r=s.end-s.start}const a={x:this.props.layerOffset,y:n,width:he,height:r};return{headerRect:a,groupRect:{x:this.props.layerOffset,y:a.y,width:he,height:a.height+(i-o)},isEndHidden:this.env.model.getters.isRowHidden(e,s)}}}class ZU extends $U{dimension="COL";get groupBorderStyle(){const e=this.groupBox;return 0===e.groupRect.width?"":aR({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 aR({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=oe;if(0!==t){const s=this.env.model.getters.getColDimensions(e,t-1);n=oe+s.start,r=s.end-s.start}const a={x:n,y:this.props.layerOffset,width:r,height:he};return{headerRect:a,groupRect:{x:a.x,y:this.props.layerOffset,width:a.width+(i-o),height:he},isEndHidden:this.env.model.getters.isColHidden(e,s)}}}class jU extends t.Component{static template="o-spreadsheet-HeaderGroupContainer";static props={dimension:String,layers:Array};static components={RowGroup:qU,ColGroup:ZU,MenuPopover:fR};menu=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});getLayerOffset(e){return e*he}onContextMenu(e){const t=this.env.model.getters.getActiveSheetId(),s={x:e.clientX,y:e.clientY},o=mM(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?qU:ZU}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",aR(s)}get frozenPaneContainerStyle(){const e={};return"COL"===this.props.dimension?e.width=`${this.frozenPaneContainerSize}px`:e.height=`${this.frozenPaneContainerSize}px`,aR(e)}get frozenPaneContainerSize(){if(!this.hasFrozenPane)return 0;const e=this.env.model.getters.getMainViewportCoordinates();return"COL"===this.props.dimension?oe+e.x:se+e.y}}class YU 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=dR();getTitle(){const e=this.props.panelContent;return"function"==typeof e.title?e.title(this.env,this.props.panelProps):e.title}get pinInfoMessage(){return Go("Pin this panel to allow to open another side panel beside it.")}}class XU extends t.Component{static template="o-spreadsheet-SidePanels";static props={};static components={SidePanel:YU};sidePanelStore;spreadsheetRect=dR();setup(){this.sidePanelStore=rh(wk),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;ax((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:Sk.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:Sk.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?aR({width:`${this.sidePanelStore.secondaryPanel.size}px`}):""},{key:this.sidePanelStore.mainPanelKey,props:this.mainPanelProps,style:this.sidePanelStore.mainPanel?aR({width:`${this.sidePanelStore.mainPanel.size}px`}):""}].filter((e=>e.key&&e.props))}}class KU extends t.Component{static template="o-spreadsheet-RibbonMenu";static props={onClose:Function};static components={Menu:lR};rootItems=FU.getMenuItems();menuRef=t.useRef("menu");state=t.useState({menuItems:this.rootItems,title:Go("Menu Bar"),parentState:void 0});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}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.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 aR({height:`${this.props.height}px`})}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.props.onClose()}get backTitle(){return this.state.parentState?Go("Go to previous menu"):Go("Close menu bar")}}class JU extends t.Component{static components={Composer:ZR,BottomBar:BU,Ripple:kU,RibbonMenu:KU};static template="o-spreadsheet-SmallBottomBar";static props={onClick:Function};composerFocusStore;composerStore;composerInterface;composerRef=t.useRef("bottombarComposer");menuState=t.useState({isOpen:!1});setup(){this.composerFocusStore=rh(fh);const e=rh(HM);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}get rect(){return this.composerRef.el?Gy(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:()=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"}),isDefaultFocus:!1,inputStyle:aR({height:"inactive"===this.focus?"26px":"fit-content","max-height":"130px"}),showAssistant:!eI()}}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 QU extends t.Component{static template="o-spreadsheet-TopBarComposer";static props={};static components={Composer:ZR};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=rh(fh);const e=rh(HM);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}get composerStyle(){const e={padding:"5px 0px 5px 8px","max-height":"300px","line-height":"24px"};return e.height="inactive"===this.focus?"34px":"fit-content",aR(e)}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}}class eH{mutators=["closeDropdowns","openDropdown"];_currentDropdown=null;closeDropdowns(){this._currentDropdown=null}openDropdown(e){this._currentDropdown=e}get currentDropdown(){return this._currentDropdown}}function tH(){const e=t.useComponent(),s=rh(eH);return t.onWillUnmount((()=>{e===s.currentDropdown&&s.closeDropdowns()})),{closeDropdowns:()=>s.closeDropdowns(),openDropdown:()=>{s.openDropdown(e)},get isActive(){return s.currentDropdown===e}}}const sH=[[["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 oH 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:EN,Popover:uR};BORDER_POSITIONS=sH;lineStyleButtonRef=t.useRef("lineStyleButton");borderStyles=E;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 iH 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:oH};topBarToolStore;borderEditorButtonRef=t.useRef("borderEditorButton");state=t.useState({currentColor:Se,currentStyle:be,currentPosition:void 0});setup(){this.topBarToolStore=tH(),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 nH extends t.Component{static template="o-spreadsheet-PaintFormatButton";static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=rh(JM)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}}class rH extends t.Component{static template="o-spreadsheet-TableDropdownButton";static components={TableStylesPopover:pk,ActionButton:wN};static props={class:{type:String,optional:!0}};topBarToolStore;state=t.useState({popoverProps:void 0});setup(){this.topBarToolStore=tH()}onStylePicked(e){const t=this.env.model.getters.getActiveSheetId(),s={...this.tableConfig,styleId:e};s_(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()?Go("Edit table"):Go("Insert table"),icon:e=>e.model.getters.getFirstTableInSelection()?"o-spreadsheet-Icon.EDIT_TABLE":"o-spreadsheet-Icon.PAINT_TABLE"}}get tableConfig(){return{...Qx,numberOfHeaders:1,bandedRows:!0}}}class aH extends t.Component{static components={ColorPickerWidget:EN};static props={class:String,style:String,icon:String,title:String};static template="o-spreadsheet-ColorEditor";topBarToolStore;state=t.useState({isOpen:!1});setup(){this.topBarToolStore=tH()}get currentColor(){return this.env.model.getters.getCurrentStyle()[this.props.style]||("textColor"===this.props.style?"#000000":"#ffffff")}setColor(e){i_(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 lH extends t.Component{static template="o-spreadsheet-DropdownAction";static components={ActionButton:wN,Popover:uR};static props={parentAction:Object,childActions:Array,class:String,childClass:String};topBarToolStore;actionRef=t.useRef("actionRef");setup(){this.topBarToolStore=tH()}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 cH extends t.Component{static components={FontSizeEditor:RN};static props={class:String};static template="o-spreadsheet-TopBarFontSizeEditor";topBarToolStore;setup(){this.topBarToolStore=tH()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||fe}setFontSize(e){i_(this.env,{fontSize:e})}onToggle(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}}class hH extends t.Component{static template="o-spreadsheet-NumberFormatsTool";static components={MenuPopover:fR,ActionButton:wN};static props={class:String};formatNumberMenuItemSpec=_U;topBarToolStore;buttonRef=t.useRef("buttonRef");state=t.useState({anchorRect:{x:0,y:0,width:0,height:0},menuItems:[]});setup(){this.topBarToolStore=tH()}toggleMenu(){if(this.isActive)this.topBarToolStore.closeDropdowns();else{const e=i(this.formatNumberMenuItemSpec);this.state.menuItems=e.children(this.env).sort(((e,t)=>e.sequence-t.sequence)),this.state.anchorRect=Gy(this.buttonRef.el),this.topBarToolStore.openDropdown()}}get isActive(){return this.topBarToolStore.isActive}}const dH=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)}};dH.add("edit").addChild("edit",{component:wN,props:{action:aF,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("edit",{component:wN,props:{action:lF,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("edit",{component:nH,props:{class:"o-hoverable-button o-toolbar-button o-mobile-disabled"},sequence:3}).addChild("edit",{component:wN,props:{action:aM,class:"o-hoverable-button o-toolbar-button"},sequence:4}).add("numberFormat").addChild("numberFormat",{component:wN,props:{action:fP,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("numberFormat",{component:wN,props:{action:HP,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("numberFormat",{component:wN,props:{action:UP,class:"o-hoverable-button o-toolbar-button"},sequence:3}).addChild("numberFormat",{component:hH,props:{class:"o-menu-item-button o-hoverable-button o-toolbar-button"},sequence:4}).add("fontSize").addChild("fontSize",{component:cH,props:{class:"o-hoverable-button o-toolbar-button"},sequence:3}).add("textStyle").addChild("textStyle",{component:wN,props:{action:zP,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("textStyle",{component:wN,props:{action:BP,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("textStyle",{component:wN,props:{action:WP,class:"o-hoverable-button o-toolbar-button"},sequence:3}).addChild("textStyle",{component:aH,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button",style:"textColor",icon:"o-spreadsheet-Icon.TEXT_COLOR",title:Go("Text Color")},sequence:4}).add("cellStyle").addChild("cellStyle",{component:aH,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button",style:"fillColor",icon:"o-spreadsheet-Icon.FILL_COLOR",title:Go("Fill Color")},sequence:1}).addChild("cellStyle",{component:iH,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:2}).addChild("cellStyle",{component:wN,props:{action:xF,class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:3}).add("alignment").addChild("alignment",{component:lH,props:{parentAction:ZP,childActions:[jP,YP,XP],class:"o-hoverable-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:1}).addChild("alignment",{component:lH,props:{parentAction:KP,childActions:[JP,QP,eM],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:2}).addChild("alignment",{component:lH,props:{parentAction:sM,childActions:[oM,iM,nM],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:3}).add("misc").addChild("misc",{component:rH,props:{class:"o-toolbar-button o-hoverable-button o-menu-item-button o-mobile-disabled"},sequence:1}).addChild("misc",{component:wN,props:{action:lP,class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:2});class uH extends t.Component{static template="o-spreadsheet-TopBar";static props={onClick:Function,dropdownMaxHeight:Number};static components={MenuPopover:fR,TopBarComposer:QU,Popover:uR};toolsCategories=dH.getCategories();state=t.useState({menuState:{isOpen:!1,anchorRect:null,menuItems:[]},invisibleToolsCategories:[],toolsPopoverState:{isOpen:!1}});isSelectingMenu=!1;openedEl=null;menus=[];toolbarMenuRegistry=dH;formatNumberMenuItemSpec=_U;isntToolbarMenu=!1;composerFocusStore;fingerprints;topBarToolStore;toolBarContainerRef=t.useRef("toolBarContainer");toolbarRef=t.useRef("toolBar");moreToolsContainerRef=t.useRef("moreToolsContainer");moreToolsButtonRef=t.useRef("moreToolsButton");spreadsheetRect=dR();setup(){this.composerFocusStore=rh(fh),this.fingerprints=rh(y_),this.topBarToolStore=rh(eH),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 OU.getAllOrdered().filter((e=>!e.isVisible||e.isVisible(this.env)))}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||fe}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=Gy(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=FU.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){i_(this.env,{[e]:t}),this.onClick()}setFontSize(e){i_(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?Gy(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 gH{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({[a.PlainText]:this.getBlob(e,a.PlainText),[a.Html]:this.getBlob(e,a.Html)})]))}catch(e){}}else await this.writeText(e[a.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:{[a.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(Yt.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 pH 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:uH,Grid:xk,BottomBar:BU,SmallBottomBar:JU,SidePanels:XU,SpreadsheetDashboard:WU,HeaderGroupContainer:jU,FullScreenFigure:Dk};sidePanel;spreadsheetRef=t.useRef("spreadsheet");spreadsheetRect=dR();_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||yk}px`:"auto";return e["grid-template-columns"]=`auto ${t}`,aR(e)}setup(){if(!("isSmall"in this.env)){const e=function(){const e=dR();return{get isSmall(){return e.width<768}}}();t.useSubEnv({get isSmall(){return e.isSmall}})}const e=nh();e.inject(dh,this.model);const s=this.env;e.get(Ck).setSmallThreshhold((()=>s.isSmall)),this.notificationStore=rh(KR),this.composerFocusStore=rh(fh),this.sidePanel=rh(wk);const o=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:o?new MU(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 gH(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:tI}),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 vh.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:Go("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=he*this.rowLayers.length,t=he*this.colLayers.length;return aR({"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-re,0),height:Math.max(o-re,0)}}}class mH{transportService;constructor(e){this.transportService=e}async sendMessage(e){"CLIENT_JOINED"!==e.type&&"CLIENT_LEFT"!==e.type&&"CLIENT_MOVED"!==e.type||this.transportService.sendMessage(e)}onNewMessage(e,t){this.transportService.onNewMessage(e,t)}leave(e){this.transportService.leave(e)}}function fH(e){return xU.get(e.type)(e)}class vH{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(const s of this.operations){if(s.id===e)return e;if(s.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const s=this.buildTransformation.with(e.data),{before:o,operation:i,after:n}=this.locateOperation(t);this.operations=[...o,i,e,...n.map((e=>e.transformed(s)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new vH(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:s}=this.locateOperation(e);this.operations=t.concat([s])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class bH{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new SH(this.id,ft((()=>e(this.data))))}}class SH{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new SH(this.id,this.lazyData.map(e))}}class CH{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new CH(function*(e,t){for(const s of e)if(yield s,s.operation.id===t)return}(this.operations,e))}stopBefore(e){return new CH(function*(e,t){for(const s of e){if(s.operation.id===t)return;yield s}}(this.operations,e))}startAfter(e){return new CH(function*(e,t){let s=!0;for(const o of e)s||(yield o),o.operation.id===t&&(s=!1)}(this.operations,e))}}class yH{buildTransformation;branches;branchingOperationIds=new Map;constructor(e,t){this.buildTransformation=e,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new CH(et(this._execution(e),this._execution(e)))}revertedExecution(e){return new CH(et(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){const s=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),s&&this.insertPrevious(e,t,s)}insertOperationAfter(e,t,s){e.insert(t,s),this.updateNextWith(e,t,s),this.insertPrevious(e,t,s)}undo(e,t){const s=this.buildTransformation.without(t.data),o=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const i=e.fork(t.id);o&&this.branchingOperationIds.set(i,o),this.insertBranchAfter(e,i),this.transform(i,s)}redo(e){const t=this.nextBranch(e);if(!t)return;const s=this.nextBranch(t);this.removeBranchFromTree(t);const o=this.branchingOperationIds.get(t);o?this.branchingOperationIds.set(e,o):this.branchingOperationIds.delete(e),s&&this.rebaseUp(s)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const s of this.revertedExecution(e))if(s.operation.id===t)return s;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:s}=this.findPreviousBranchingOperation(e);if(!t||!s)return;const o=this.buildTransformation.without(s.data),i=t.fork(s.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(o);const n=this.nextBranch(i);n&&this.rebaseUp(n)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const s=this.branches.findIndex((t=>t===e));this.branches.splice(s+1,0,t)}updateNextWith(e,t,s){const o=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(o&&i)if(e.getFirstOperationAmong(s,o)===o){const n=this.addToNextBranch(e,i,o,t,s);this.updateNextWith(i,n,s)}else{const e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,s,o,i){let n=o;return i===s?(n=this.getTransformedOperation(e,s,o),t.prepend(n)):t.contains(i)?(n=this.getTransformedOperation(e,s,o),t.insert(n,i)):t.append(o),n}getTransformedOperation(e,t,s){const o=e.getOperation(t),i=this.buildTransformation.without(o.data);return s.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const s=this.nextBranch(e);s&&this.transform(s,t)}insertPrevious(e,t,s){const{previousBranch:o,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!o||!i)return;const n=this.buildTransformation.with(i.data),r=e.fork(s);r.transform(n),o.cutAfter(s),o.appendBranch(r);const a=t.transformed(n);this.insertPrevious(o,a,s)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const s=this.branchingOperationIds.get(t);return s?{previousBranch:t,branchingOperation:t.getOperation(s)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let s=!!t;const o=e.getOperations();for(let i=o.length-1;i>=0;i--){const n=o[i];n.id===t&&(s=!1),s||(yield{operation:n,branch:e,isCancelled:!this.shouldExecute(e,n)})}const i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class IH{HEAD_BRANCH;HEAD_OPERATION;tree;applyOperation;revertOperation;buildEmpty;buildTransformation;constructor(e){this.applyOperation=e.applyOperation,this.revertOperation=e.revertOperation,this.buildEmpty=e.buildEmpty,this.buildTransformation=e.buildTransformation,this.HEAD_BRANCH=new vH(this.buildTransformation),this.tree=new yH(this.buildTransformation,this.HEAD_BRANCH);const t=e.initialOperationId,s=new bH(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,s),this.HEAD_OPERATION=s}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const s=new bH(e,t),o=this.tree.getLastBranch();this.tree.insertOperationLast(o,s),this.HEAD_BRANCH=o,this.HEAD_OPERATION=s}insert(e,t,s){const o=new bH(e,t);this.revertTo(s),this.tree.insertOperationAfter(this.HEAD_BRANCH,o,s),this.fastForward()}undo(e,t,s){const{branch:o,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(o,i),this.fastForward(),this.insert(t,this.buildEmpty(t),s)}redo(e,t,s){const{branch:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(o),this.fastForward(),this.insert(t,this.buildEmpty(t),s)}rebase(e){const t=this.get(e),s=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);const o=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,o);for(const{operation:e}of s)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:s,isCancelled:o}of e)o||this.revertOperation(s.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:s,isCancelled:o}of e)o||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=s}}function wH(e){return new IH({initialOperationId:e.initialRevisionId,applyOperation:t=>{const s=t.commands.slice(),{changes:o}=e.recordChanges((()=>{for(const t of s)e.dispatch(t)}));t.setChanges(o)},revertOperation:e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){EH(t.changes[e])}}([e]),buildEmpty:e=>new JV(e,"empty",[]),buildTransformation:{with:e=>t=>new JV(t.id,t.clientId,XV(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new JV(t.id,t.clientId,XV(t.commands,e.commands.map(fH).flat()),t.rootCommand,void 0,t.timestamp)}})}function EH(e){const t=e.target,s=e.key,o=e.before;void 0===o?delete t[s]:t[s]=o}class RH{observers=new Map;defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.set(e,{owner:e,callbacks:t})}capture(e,t){if(this.observers.get(e))throw new Error("You are already subscribed forever");this.mainSubscription?.owner&&this.mainSubscription.owner!==e&&this.mainSubscription.callbacks.release?.(),this.mainSubscription={owner:e,callbacks:t}}release(e){this.mainSubscription?.owner!==e||this.observers.get(e)||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){this.mainSubscription!==this.defaultSubscription&&(this.mainSubscription?.callbacks.release?.(),this.mainSubscription=this.defaultSubscription)}isListening(e){return this.mainSubscription?.owner===e}send(e){this.mainSubscription?.callbacks.handleEvent(e),this.observers.forEach((t=>t.callbacks.handleEvent(e)))}}class xH{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new RH,this.anchor={cell:{col:0,row:0},zone:Us({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,s){this.stream.capture(e,s),this.anchor=t}registerAsDefault(e,t,s){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,s),this.defaultAnchor=t,this.capture(e,t,s)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}modifyAnchor(e,t,s){const o=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(o,e.zone)},this.processEvent({options:s,anchor:e,mode:t})}selectZone(e,t={scrollIntoView:!0}){return this.modifyAnchor(e,"overrideSelection",t)}selectCell(e,t){const s=Us({col:e,row:t});return this.selectZone({zone:s,cell:{col:e,row:t}},{scrollIntoView:!0})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new v("InvalidSelectionStep");const{col:s,row:o}=this.getNextAvailablePosition(e,t);return this.selectCell(s,o)}setAnchorCorner(e,t){const s=this.getters.getActiveSheetId(),{col:o,row:i}=this.anchor.cell,n={left:Math.min(o,e),top:Math.min(i,t),right:Math.max(o,e),bottom:Math.max(i,t)},r={zone:this.getters.expandZone(s,n),cell:{col:o,row:i}};return this.processEvent({mode:"updateAnchor",anchor:r,options:{scrollIntoView:!1}})}addCellToSelection(e,t){const s=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:s,col:e,row:t}));const o=this.getters.expandZone(s,Us({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:o,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new v("InvalidSelectionStep");const s=this.getters.getActiveSheetId(),o=this.anchor,{col:i,row:n}=o.cell,{left:r,right:a,top:l,bottom:c}=o.zone,h=this.getStartingPosition(e),[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return v.Success;let g=o.zone;const p=e=>{e=Ls(e);const{left:t,right:o,top:i,bottom:n}=this.getters.expandZone(s,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(s)-1,o),top:Math.max(0,i),bottom:Math.min(this.getters.getNumberRows(s)-1,n)}},{cell:m,zone:f}=this.getReferenceAnchor(),{col:b,row:S}=m;let C=0;for(;null!==g;){if(C++,d<0){const e=this.getNextAvailableCol(d,a-(C-1),S);g=f.right<=a-C?p({top:l,left:r,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,r+(C-1),S);g=r+C<=f.left?p({top:l,left:e,bottom:c,right:a}):null}if(u<0){const e=this.getNextAvailableRow(u,b,c-(C-1));g=f.bottom<=c-C?p({top:l,left:r,bottom:e,right:a}):null}if(u>0){const e=this.getNextAvailableRow(u,b,l+(C-1));g=l+C<=f.top?p({top:e,left:r,bottom:c,right:a}):null}if(g=g?Ls(g):g,g&&!xs(g,o.zone))return this.processEvent({options:{scrollIntoView:!0},mode:"updateAnchor",anchor:{zone:g,cell:{col:i,row:n}}})}g=p(Es({top:n,bottom:n,left:i,right:i},Ls({top:this.getNextAvailableRow(u,b,l),left:this.getNextAvailableCol(d,r,S),bottom:this.getNextAvailableRow(u,b,c),right:this.getNextAvailableCol(d,a,S)})));const y={zone:g,cell:{col:i,row:n}};return this.processEvent({anchor:y,mode:"updateAnchor",options:{scrollIntoView:!0}})}selectColumn(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.getNumberRows(s)-1;let i={left:e,right:e,top:0,bottom:o};const n=this.getters.findFirstVisibleColRowIndex(s,"ROW");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=e,a=n;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),i=Es(i,{left:r,right:r,top:n,bottom:o})}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:r,row:a}},mode:t})}selectRow(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.getNumberCols(s)-1;let i={top:e,bottom:e,left:0,right:o};const n=this.getters.findFirstVisibleColRowIndex(s,"COL");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=n,a=e;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),i=Es(i,{left:n,right:o,top:a,bottom:a})}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:r,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(xs(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:Us(t.cell)},"updateAnchor",{scrollIntoView:!1});const s=this.getters.getContiguousZone(e,t.zone);return St(s,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:s},"updateAnchor",{scrollIntoView:!1})}selectTableAroundSelection(){const e=this.getters.getActiveSheetId(),t=this.getters.getContiguousZone(e,this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:t},"updateAnchor",{scrollIntoView:!1})}selectAll(){const e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({mode:"overrideSelection",anchor:{zone:t,cell:this.anchor.cell},options:{scrollIntoView:!1}})}isListening(e){return this.stream.isListening(e)}processEvent(e){const t={...e,previousAnchor:qe(this.anchor)},s=this.checkEventAnchorZone(t);return"Success"!==s?new v(s):(this.anchor=t.anchor,this.stream.send(t),v.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:s}=e;if(!Ds(t.col,t.row,s))return"InvalidAnchorZone";const{left:o,right:i,top:n,bottom:r}=s,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",o,i);return void 0===this.getters.findVisibleHeader(a,"ROW",n,r)||void 0===l?"SelectionOutOfBound":"Success"}checkAnchorZoneOrThrow(e){if("InvalidAnchorZone"===this.checkAnchorZone(e))throw new Error("The provided anchor is invalid. The cell must be part of the zone.")}getNextAvailablePosition(e,t=1){const{col:s,row:o}=this.anchor.cell,i=this.deltaToTarget({col:s,row:o},e,t);return{col:this.getNextAvailableCol(i[0],s,o),row:this.getNextAvailableRow(i[1],s,o)}}getNextAvailableCol(e,t,s){const o=this.getters.getActiveSheetId(),i={col:t,row:s};return this.getNextAvailableHeader(e,"COL",t,i,(e=>this.getters.isInSameMerge(o,t,s,e,s)))}getNextAvailableRow(e,t,s){const o=this.getters.getActiveSheetId(),i={col:t,row:s};return this.getNextAvailableHeader(e,"ROW",s,i,(e=>this.getters.isInSameMerge(o,t,s,t,e)))}getNextAvailableHeader(e,t,s,o,i){const n=this.getters.getActiveSheetId();if(0===e)return s;const r=Math.sign(e);let a=s+e;for(;i(a);)a+=r;for(;this.getters.isHeaderHidden(n,t,a);)a+=r;return a<0||a>this.getters.getNumberHeaders(n,t)-1?this.getters.isHeaderHidden(n,t,s)?this.getNextAvailableHeader(-r,t,s,o,i):s:a}getReferenceAnchor(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:s,right:o,top:i,bottom:n}=t.zone,{col:r,row:a}=t.cell,l=this.getters.isColHidden(e,r)&&this.getters.findVisibleHeader(e,"COL",s,o)||r,c=this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",i,n)||a;return{cell:{col:l,row:c},zone:this.getters.expandZone(e,{left:l,right:l,top:c,bottom:c})}}deltaToTarget(e,t,s){switch(t){case"up":return"end"!==s?[0,-s]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==s?[0,s]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==s?[-s,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==s?[s,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:s}=this.getPosition();const o=this.anchor.zone;switch(e){case"down":case"up":s=s===o.top?o.bottom:o.top;break;case"left":case"right":t=t===o.right?o.left:o.right}return{col:t,row:s}}getEndOfCluster(e,t,s){const o=this.getters.getActiveSheetId();let i=e;const n=this.getNextCellPosition(e,t,s),r=this.isCellSkippableInCluster({...i,sheetId:o})||this.isCellSkippableInCluster({...n,sheetId:o})?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(i,t,s);if(i.col===e.col&&i.row===e.row)break;const n=this.isCellSkippableInCluster({...e,sheetId:o});if("endOfCluster"===r&&n)break;if("nextCluster"===r&&!n){i=e;break}i=e}return"cols"===t?i.col:i.row}getNextCellPosition(e,t,s){const o={...e};return o["cols"===t?"col":"row"]="cols"===t?this.getNextAvailableCol(s,o.col,o.row):this.getNextAvailableRow(s,o.col,o.row),{col:o.col,row:o.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){const t=this.getters.getMainCellPosition(e),s=this.getters.getEvaluatedCell(t);return s.type===r.empty||s.type===r.text&&""===s.value}}function TH(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class AH{changes;commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop();let s=e[0];const o=e.at(-1),i=e.length-2;for(let t=1;t<=i;t++){const o=e[t];if(void 0===s[o]){const i=e[t+1];s[o]=TH(i)}s=s[o]}s[o]!==t&&(this.changes?.push({key:o,target:s,before:s[o]}),void 0===t?delete s[o]:s[o]=t)}}const DH=17781237,_H=17781238,FH=88853993,OH=88853994;function PH(e,t,s){const o=[["xmlns:r",Oh],["xmlns:a",Th],["xmlns:c",Ah]],i=MH({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let n=qE``;if(e.data.title?.text){const t=sI(NC(e.data.backgroundColor)),s=e.data.title.fontSize??J;n=qE`
30
- <c:title>
31
- ${LH(e.data.title.text,t,s,e.data.title)}
32
- <c:overlay val="0" />
33
- </c:title>
34
- `}let r=qE``;switch(e.data.type){case"bar":r=function(e){const t=e.horizontal?"bar":"col",s=e.dataSets.map((e=>e.backgroundColor??"")),o=new Oo(e.dataSets.length,s),i=[],n=[];for(const[t,s]of Object.entries(e.dataSets)){const r=sI(o.next()),a=MH({backgroundColor:r,line:{color:r}}),l=qE`
35
- <c:ser>
36
- <c:idx val="${t}"/>
37
- <c:order val="${t}"/>
38
- ${VH(s.trend,r)}
39
- ${HH(s.label)}
40
- ${a}
41
- ${e.labelRange?qE`<c:cat>${GH(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
42
- <c:val> <!-- x-coordinate values -->
43
- ${WH(s.range)}
44
- </c:val>
45
- </c:ser>
46
- `;s.rightYAxis?n.push(l):i.push(l)}const r=e.stacked?"stacked":"clustered",a=e.stacked?100:-20;return qE`
47
- ${i.length?qE`
48
- <c:barChart>
49
- <c:barDir val="${t}"/>
50
- <c:grouping val="${r}"/>
51
- <c:overlap val="${a}"/>
52
- <c:gapWidth val="70"/>
53
- <!-- each data marker in the series does not have a different color -->
54
- <c:varyColors val="0"/>
55
- ${$E(i)}
56
- <c:axId val="${DH}" />
57
- <c:axId val="${FH}" />
58
- </c:barChart>
59
- ${"col"===t?BH("b","c:catAx",DH,FH,e.axesDesign?.x?.title,e.fontColor):BH("b","c:catAx",DH,FH,e.axesDesign?.y?.title,e.fontColor,void 0,"maxMin")}
60
- ${"col"===t?BH("l","c:valAx",FH,DH,e.axesDesign?.y?.title,e.fontColor):BH("l","c:valAx",FH,DH,e.axesDesign?.x?.title,e.fontColor,void 0,void 0,"max")}
61
- `:""}
62
- ${n.length?qE`
63
- <c:barChart>
64
- <c:barDir val="col"/>
65
- <c:grouping val="${r}"/>
66
- <c:overlap val="${a}"/>
67
- <c:gapWidth val="70"/>
68
- <!-- each data marker in the series does not have a different color -->
69
- <c:varyColors val="0"/>
70
- ${$E(n)}
71
- <c:axId val="${DH+1}" />
72
- <c:axId val="${FH+1}" />
73
- </c:barChart>
74
- ${BH("b","c:catAx",DH+1,FH+1,e.axesDesign?.x?.title,e.fontColor,i.length?1:0)}
75
- ${BH("r","c:valAx",FH+1,DH+1,e.axesDesign?.y1?.title,e.fontColor)}
76
- `:""}`}(e.data);break;case"combo":r=function(e){const t=e.dataSets,s=t.map((e=>e.backgroundColor??"")),o=new Oo(t.length,s);let i=t[0];const n=sI(o.next()),r=i.rightYAxis??!1,a=qE`
77
- <c:ser>
78
- <c:idx val="0"/>
79
- <c:order val="0"/>
80
- ${VH(i.trend,n)}
81
- ${HH(i.label)}
82
- ${MH({backgroundColor:n,line:{color:n}})}
83
- ${e.labelRange?qE`<c:cat>${GH(e.labelRange)}</c:cat>`:""}
84
- <!-- x-coordinate values -->
85
- <c:val>
86
- ${WH(i.range)}
87
- </c:val>
88
- </c:ser>
89
- `,l=[],c=[];for(let s=1;s<t.length;s++){i=t[s];const n=sI(o.next()),r=MH({backgroundColor:n,line:{color:n}}),a=qE`
90
- <c:ser>
91
- <c:idx val="${s}"/>
92
- <c:order val="${s}"/>
93
- <c:smooth val="0"/>
94
- <c:marker>
95
- <c:symbol val="circle" />
96
- <c:size val="5"/>
97
- ${r}
98
- </c:marker>
99
- ${VH(i.trend,n)}
100
- ${HH(i.label)}
101
- ${r}
102
- ${e.labelRange?qE`<c:cat>${GH(e.labelRange)}</c:cat>`:""}
103
- <!-- x-coordinate values -->
104
- <c:val>
105
- ${WH(i.range)}
106
- </c:val>
107
- </c:ser>
108
- `;i.rightYAxis?c.push(a):l.push(a)}const h=e.stacked?100:-20;return qE`
109
- <c:barChart>
110
- <c:barDir val="col"/>
111
- <c:grouping val="clustered"/>
112
- <c:overlap val="${h}"/>
113
- <c:gapWidth val="70"/>
114
- <!-- each data marker in the series does not have a different color -->
115
- <c:varyColors val="0"/>
116
- ${a}
117
- <c:axId val="${r?_H:DH}" />
118
- <c:axId val="${r?OH:FH}" />
119
- </c:barChart>
120
- ${l.length?qE`
121
- <c:lineChart>
122
- <c:grouping val="standard"/>
123
- <!-- each data marker in the series does not have a different color -->
124
- <c:varyColors val="0"/>
125
- ${$E(l)}
126
- <c:axId val="${DH}" />
127
- <c:axId val="${FH}" />
128
- </c:lineChart>
129
- `:""}
130
- ${c.length?qE`
131
- <c:lineChart>
132
- <c:grouping val="standard"/>
133
- <!-- each data marker in the series does not have a different color -->
134
- <c:varyColors val="0"/>
135
- ${$E(c)}
136
- <c:axId val="${_H}" />
137
- <c:axId val="${OH}" />
138
- </c:lineChart>
139
- `:""}
140
- ${!r||l.length?qE`
141
- ${BH("b","c:catAx",DH,FH,e.axesDesign?.x?.title,e.fontColor,0)}
142
- ${BH("l","c:valAx",FH,DH,e.axesDesign?.y?.title,e.fontColor)}
143
- `:""}
144
- ${r||c.length?qE`
145
- ${BH("b","c:catAx",_H,OH,e.axesDesign?.x?.title,e.fontColor,l.length||!r?1:0)}
146
- ${BH("r","c:valAx",OH,_H,e.axesDesign?.y1?.title,e.fontColor)}
147
- `:""}
148
- `}(e.data);break;case"pyramid":r=function(e){const t=e.dataSets,s=t.map((e=>e.backgroundColor??"")),o=new Oo(t.length,s),i=t[0],n=t[1],r=sI(o.next()),a=sI(o.next()),{maxValue:l,majorUnit:c}=function(e){const t=3,s=((e,t)=>{let s=Math.ceil(e);for(;s%t!=0;)s++;return s})(e,t),o=s/t;return{maxValue:s,majorUnit:o}}(e.maxValue),h=e.labelRange?qE`<c:cat>${GH(e.labelRange)}</c:cat>`:"",d=qE`
149
- <c:ser>
150
- <c:idx val="0"/>
151
- <c:order val="0"/>
152
- <c:invertIfNegative val="0" />
153
- ${HH(i.label)}
154
- ${MH({backgroundColor:r,line:{color:r}})}
155
- ${h}
156
- <!-- x-coordinate values -->
157
- <c:val>
158
- ${WH(i.range)}
159
- </c:val>
160
- </c:ser>
161
- `,u=qE`
162
- <c:ser>
163
- <c:idx val="1"/>
164
- <c:order val="1"/>
165
- <c:invertIfNegative val="0" />
166
- ${HH(n.label)}
167
- ${MH({backgroundColor:a,line:{color:a}})}
168
- ${e.labelRange?qE`<c:cat>${GH(e.labelRange)}</c:cat>`:""}
169
- <!-- x-coordinate values -->
170
- <c:val>
171
- ${WH(n.range)}
172
- </c:val>
173
- </c:ser>
174
- `;return qE`
175
- <c:barChart>
176
- <c:barDir val="bar"/>
177
- <c:grouping val="clustered"/>
178
- <c:varyColors val="0" />
179
- ${d}
180
- <c:gapWidth val="50" />
181
- <c:axId val="${DH}" />
182
- <c:axId val="${FH}" />
183
- </c:barChart>
184
- <c:barChart>
185
- <c:barDir val="bar"/>
186
- <c:grouping val="clustered"/>
187
- <c:varyColors val="0" />
188
- ${u}
189
- <c:gapWidth val="50" />
190
- <c:axId val="${_H}" />
191
- <c:axId val="${OH}" />
192
- </c:barChart>
193
- ${BH("r","c:catAx",DH,FH,e.axesDesign?.y?.title,e.fontColor,0,"maxMin","autoZero","high")}
194
- ${BH("b","c:valAx",FH,DH,e.axesDesign?.x?.title,e.fontColor,0,"maxMin","max","nextTo",l,c,"#0;#0")}
195
- ${BH("t","c:valAx",OH,_H,void 0,e.fontColor,1)}
196
- ${BH("l","c:catAx",_H,OH,void 0,e.fontColor,1,"maxMin")}
197
- `}(e.data);break;case"line":r=function(e){const t=e.dataSets.map((e=>e.backgroundColor??"")),s=new Oo(e.dataSets.length,t),o=[],i=[];for(const[t,n]of Object.entries(e.dataSets)){const r=sI(s.next()),a=MH({line:{width:2.5,style:"solid",color:r}}),l=qE`
198
- <c:ser>
199
- <c:idx val="${t}"/>
200
- <c:order val="${t}"/>
201
- <c:smooth val="0"/>
202
- <c:marker>
203
- <c:symbol val="circle" />
204
- <c:size val="5"/>
205
- ${MH({backgroundColor:r,line:{color:r}})}
206
- </c:marker>
207
- ${VH(n.trend,r)}
208
- ${HH(n.label)}
209
- ${a}
210
- ${e.labelRange?qE`<c:cat>${GH(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
211
- <c:val> <!-- x-coordinate values -->
212
- ${WH(n.range)}
213
- </c:val>
214
- </c:ser>
215
- `;n.rightYAxis?i.push(l):o.push(l)}const n=e.stacked?"stacked":"standard";return qE`
216
- ${o.length?qE`
217
- <c:lineChart>
218
- <c:grouping val="${n}"/>
219
- <!-- each data marker in the series does not have a different color -->
220
- <c:varyColors val="0"/>
221
- ${$E(o)}
222
- <c:axId val="${DH}" />
223
- <c:axId val="${FH}" />
224
- </c:lineChart>
225
- ${BH("b","c:catAx",DH,FH,e.axesDesign?.x?.title,e.fontColor)}
226
- ${BH("l","c:valAx",FH,DH,e.axesDesign?.y?.title,e.fontColor)}
227
- `:""}
228
- ${i.length?qE`
229
- <c:lineChart>
230
- <c:grouping val="${n}"/>
231
- <!-- each data marker in the series does not have a different color -->
232
- <c:varyColors val="0"/>
233
- ${$E(i)}
234
- <c:axId val="${DH+1}" />
235
- <c:axId val="${FH+1}" />
236
- </c:lineChart>
237
- ${BH("b","c:catAx",DH+1,FH+1,e.axesDesign?.x?.title,e.fontColor,o.length?1:0)}
238
- ${BH("r","c:valAx",FH+1,DH+1,e.axesDesign?.y1?.title,e.fontColor)}
239
- `:""}
240
- `}(e.data);break;case"scatter":r=function(e){const t=e.dataSets.map((e=>e.backgroundColor??"")),s=new Oo(e.dataSets.length,t),o=[],i=[];for(const[t,n]of Object.entries(e.dataSets)){const r=sI(s.next()),a=qE`
241
- <c:ser>
242
- <c:idx val="${t}"/>
243
- <c:order val="${t}"/>
244
- <c:smooth val="0"/>
245
- <c:spPr>
246
- <a:ln w="19050" cap="rnd">
247
- <a:noFill/>
248
- <a:round/>
249
- </a:ln>
250
- <a:effectLst/>
251
- </c:spPr>
252
- <c:marker>
253
- <c:symbol val="circle" />
254
- <c:size val="5"/>
255
- ${MH({backgroundColor:r,line:{color:r}})}
256
- </c:marker>
257
- ${VH(n.trend,r)}
258
- ${HH(n.label)}
259
- ${e.labelRange?qE`<c:xVal> <!-- x-coordinate values -->
260
- ${WH(e.labelRange)}
261
- </c:xVal>`:""}
262
- <c:yVal> <!-- y-coordinate values -->
263
- ${WH(n.range)}
264
- </c:yVal>
265
- </c:ser>
266
- `;n.rightYAxis?i.push(a):o.push(a)}return qE`
267
- ${o.length?qE`
268
- <c:scatterChart>
269
- <!-- each data marker in the series does not have a different color -->
270
- <c:varyColors val="0"/>
271
- <c:scatterStyle val="lineMarker"/>
272
- ${$E(o)}
273
- <c:axId val="${DH}" />
274
- <c:axId val="${FH}" />
275
- </c:scatterChart>
276
- ${BH("b","c:valAx",DH,FH,e.axesDesign?.x?.title,e.fontColor)}
277
- ${BH("l","c:valAx",FH,DH,e.axesDesign?.y?.title,e.fontColor)}
278
- `:""}
279
- ${i.length?qE`
280
- <c:scatterChart>
281
- <!-- each data marker in the series does not have a different color -->
282
- <c:varyColors val="0"/>
283
- <c:scatterStyle val="lineMarker"/>
284
- ${$E(i)}
285
- <c:axId val="${DH+1}" />
286
- <c:axId val="${FH+1}" />
287
- </c:scatterChart>
288
- ${BH("b","c:valAx",DH+1,FH+1,e.axesDesign?.x?.title,e.fontColor,o.length?1:0)}
289
- ${BH("r","c:valAx",FH+1,DH+1,e.axesDesign?.y1?.title,e.fontColor)}
290
- `:""}`}(e.data);break;case"pie":r=function(e,t,s){const o=kt(e.dataSets.map((e=>UA(e.range,t,s)))),i=new Oo(o),n=Je(0,o).map((()=>sI(i.next()))),r=[];for(const[o,i]of Object.entries(e.dataSets).reverse()){const a=UA(i.range,t,s),l=[];for(const e of Je(0,a)){const t=MH({backgroundColor:n[e],line:{color:"FFFFFF",width:1.5}});l.push(qE`
291
- <c:dPt>
292
- <c:idx val="${e}"/>
293
- ${t}
294
- </c:dPt>
295
- `)}r.push(qE`
296
- <c:ser>
297
- <c:idx val="${o}"/>
298
- <c:order val="${o}"/>
299
- ${HH(i.label)}
300
- ${$E(l)}
301
- ${zH({showLeaderLines:!0})}
302
- ${e.labelRange?qE`<c:cat>${GH(e.labelRange)}</c:cat>`:""}
303
- <c:val>
304
- ${WH(i.range)}
305
- </c:val>
306
- </c:ser>
307
- `)}return qE`
308
- <c:doughnutChart>
309
- <c:varyColors val="1" />
310
- <c:holeSize val="${e.pieHolePercentage??(e.isDoughnut?Hh:0)}" />
311
- ${zH()}
312
- ${$E(r)}
313
- </c:doughnutChart>
314
- `}(e.data,t,s);break;case"radar":r=function(e){const t=e.dataSets.map((e=>e.backgroundColor??"")),s=new Oo(e.dataSets.length,t),o=[];for(const[t,i]of Object.entries(e.dataSets)){const n=sI(s.next()),r=MH({line:{width:2.5,style:"solid",color:n}}),a=qE`
315
- <c:ser>
316
- <c:idx val="${t}"/>
317
- <c:order val="${t}"/>
318
- <c:smooth val="0"/>
319
- <c:marker>
320
- <c:symbol val="circle" />
321
- <c:size val="5"/>
322
- ${MH({backgroundColor:n,line:{color:n}})}
323
- </c:marker>
324
- ${HH(i.label)}
325
- ${r}
326
- ${e.labelRange?qE`<c:cat>${GH(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
327
- <c:val> <!-- x-coordinate values -->
328
- ${WH(i.range)}
329
- </c:val>
330
- </c:ser>
331
- `;o.push(a)}return qE`
332
- ${qE`
333
- <c:radarChart>
334
- <c:radarStyle val="marker"/>
335
- <c:varyColors val="0"/>
336
- ${$E(o)}
337
- <c:axId val="${DH}" />
338
- <c:axId val="${FH}" />
339
- </c:radarChart>
340
- ${BH("b","c:catAx",DH,FH,e.axesDesign?.x?.title,e.fontColor)}
341
- ${BH("l","c:valAx",FH,DH,e.axesDesign?.y?.title,e.fontColor)}
342
- `}
343
- `}(e.data)}let a="none";switch(e.data.legendPosition){case"bottom":a="b";break;case"left":a="l";break;case"right":a="r";break;case"top":a="t"}const l=e.data.fontColor,c=qE`
344
- <c:chartSpace ${zE(o)}>
345
- <c:roundedCorners val="0" />
346
- <!-- <manualLayout/> to manually position the chart in the figure container -->
347
- ${i}
348
- <c:chart>
349
- ${n}
350
- <c:autoTitleDeleted val="0" />
351
- <c:plotArea>
352
- <!-- how the chart element is placed on the chart -->
353
- <c:layout />
354
- ${r}
355
- ${MH({backgroundColor:e.data.backgroundColor})}
356
- </c:plotArea>
357
- ${"none"!==a?function(e,t){return qE`
358
- <c:legend>
359
- <c:legendPos val="${e}"/>
360
- <c:overlay val="0"/>
361
- ${kH(10,t)}
362
- </c:legend>
363
- `}(a,l):""}
364
- </c:chart>
365
- </c:chartSpace>
366
- `;return BE(c)}function MH(e){return qE`
367
- <c:spPr>
368
- ${e.backgroundColor?NH(e.backgroundColor):""}
369
- ${e.line?function(e){const t=[["cmpd","sng"]];e.width&&t.push(["w",VA(e.width)]);const s=e.style?qE`<a:prstDash val="${e.style}"/>`:"";return qE`
370
- <a:ln ${zE(t)}>
371
- ${NH(e.color)}
372
- ${s}
373
- </a:ln>
374
- `}(e.line):""}
375
- </c:spPr>
376
- `}function NH(e){return qE`
377
- <a:solidFill>
378
- <a:srgbClr val="${e}"/>
379
- </a:solidFill>
380
- `}function LH(e,t="000000",s=J,o={}){return qE`
381
- <c:tx>
382
- <c:rich>
383
- <a:bodyPr />
384
- <a:lstStyle />
385
- <a:p>
386
- <a:pPr lvl="0">
387
- <a:defRPr b="${o?.bold?1:0}" i="${o?.italic?1:0}">
388
- ${NH(t)}
389
- <a:latin typeface="+mn-lt"/>
390
- </a:defRPr>
391
- </a:pPr>
392
- <a:r> <!-- Runs -->
393
- <a:rPr b="${o?.bold?1:0}" i="${o?.italic?1:0}" sz="${100*s}"/>
394
- <a:t>${e}</a:t>
395
- </a:r>
396
- </a:p>
397
- </c:rich>
398
- </c:tx>
399
- `}function kH(e=12,t="000000",s=!1,o=!1){return qE`
400
- <c:txPr>
401
- <a:bodyPr/>
402
- <a:lstStyle/>
403
- <a:p>
404
- <a:pPr lvl="0">
405
- <a:defRPr ${zE([["b",s?"1":"0"],["i",o?"1":"0"],["sz",100*e]])}>
406
- ${NH(t)}
407
- <a:latin typeface="+mn-lt"/>
408
- </a:defRPr>
409
- </a:pPr>
410
- </a:p>
411
- </c:txPr>
412
- `}function VH(e,t){if(!e)return qE``;const{type:s,order:o,window:i}=e,n=[];switch(s){case"poly":o&&o>1?(n.push(qE`<c:trendlineType val="poly" />`),n.push(qE`<c:order val="${o}" />`)):n.push(qE`<c:trendlineType val="linear" />`);break;case"movingAvg":n.push(qE`<c:trendlineType val="movingAvg" />`),i&&n.push(qE`<c:period val="${i}" />`);break;default:n.push(qE`<c:trendlineType val="${s}" />`)}return qE`
413
- <c:trendline>
414
- ${function(e,t){if(!e)return qE``;const s=[["val",e.color?sI(e.color).slice(-6):UH(t)]];return qE`
415
- <c:spPr>
416
- <a:ln w="19050" cap="rnd">
417
- <a:solidFill>
418
- <a:srgbClr ${zE(s)}/>
419
- </a:solidFill>
420
- <a:prstDash val="sysDot" />
421
- </a:ln>
422
- <a:effectLst />
423
- </c:spPr>
424
- <c:dispRSqr val="0" />
425
- <c:dispEq val="0" />
426
- `}(e,t)}
427
- ${$E(n)}
428
- </c:trendline>
429
- `}function UH(e){return sI(Co(e,.5))}function HH(e){return e?"text"in e&&e.text?qE`
430
- <c:tx><c:v>${e.text}</c:v></c:tx>
431
- `:"reference"in e&&e.reference?qE`
432
- <c:tx>
433
- ${GH(e.reference)}
434
- </c:tx>
435
- `:qE``:qE``}function zH({showLeaderLines:e}={showLeaderLines:!1}){return qE`
436
- <dLbls>
437
- <c:showLegendKey val="0"/>
438
- <c:showVal val="0"/>
439
- <c:showCatName val="0"/>
440
- <c:showSerName val="0"/>
441
- <c:showPercent val="0"/>
442
- <c:showBubbleSize val="0"/>
443
- <c:showLeaderLines val="${e?"1":"0"}"/>
444
- </dLbls>
445
- `}function BH(e,t,s,o,i,n,r=0,a="minMax",l,c="nextTo",h,d,u="General"){const g=i?.color?sI(i.color):n,p=i?.fontSize??Q;return qE`
446
- <${t}>
447
- <c:axId val="${s}"/>
448
- <c:crossAx val="${o}"/> <!-- reference to the other axe of the chart -->
449
- <c:crosses val="${l||("b"===e||"l"===e?"min":"max")}"/>
450
- <c:auto val="1"/>
451
- ${"c:valAx"===t?qE`<c:crossBetween val="between" />`:""}
452
- <c:delete val="${r}"/> <!-- by default, axis are not displayed -->
453
- <c:scaling>
454
- <c:orientation val="${a}" />
455
- ${h?qE`<c:max val="${h}" />`:""}
456
- ${h?qE`<c:min val="${-h}" />`:""}
457
- </c:scaling>
458
- ${d?qE`<c:majorUnit val="${d}" />`:""}
459
- <c:axPos val="${e}" />
460
- <c:tickLblPos val="${c}" />
461
- ${function(e="B7B7B7"){return qE`
462
- <c:majorGridlines>
463
- ${MH({line:{color:e}})}
464
- </c:majorGridlines>
465
- `}()}
466
- <c:majorTickMark val="out" />
467
- <c:minorTickMark val="none" />
468
- <c:numFmt formatCode="${u}" sourceLinked="${"General"===u?"1":"0"}" />
469
- <c:title>
470
- ${LH(i?.text??"",g,p,i)}
471
- </c:title>
472
- ${kH(10,n)}
473
- </${t}>
474
- <!-- <tickLblPos/> omitted -->
475
- `}function GH(e){return qE`
476
- <c:strRef>
477
- <c:f>${e}</c:f>
478
- </c:strRef>
479
- `}function WH(e){return qE`
480
- <c:numRef>
481
- <c:f>${e}</c:f>
482
- <c:numCache />
483
- </c:numRef>
484
- `}function $H(e,t,s){if(!e)return{attrs:[],node:qE``};const o=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n";default:return}}(t);if(void 0===o)return{attrs:[],node:qE``};var i;return{attrs:[["cm","1"],["t",o]],node:qE`<f t="array" ref="${s}">${ZH(e)}</f><v>${(i=t)===Mi.InvalidReference?"#REF!":i}</v>`}}function qH(e,t,s=!1){let o=e;const i=[],n=o.trim().toUpperCase();return!s&&["TRUE","FALSE"].includes(n)?(o="TRUE"===n?"1":"0",i.push(["t","b"])):!s&&_i(o,w)||(o=MA(e,t),i.push(["t","s"])),{attrs:i,node:qE`<v>${o}</v>`}}function ZH(e){let t;"="===e[0]&&(e=e.slice(1));try{t=vv(e)}catch(t){return e}return t=Sv(t,"STRING",jH),t=Sv(t,"FUNCALL",(e=>e=function(e){const t=e.value.toUpperCase(),s=e.args,o=zh[t];if(o){const i=JS.content[t].args.filter((e=>!e.optional)),n=i.length-e.args.length;if(n)for(let t=e.args.length;t<i.length;t++){const e=o[t-n];s.push({type:e.type,value:e.value,tokenEndIndex:0,tokenStartIndex:0})}}return{...e,args:s}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:Bh.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})))),t=Sv(t,"REFERENCE",(e=>e.value===Mi.InvalidReference?{...e,value:"#REF!"}:e)),t?LM(t):e}function jH(e){const t=e.value.replace(new RegExp('"',"g"),""),s=mi(t,w);if(s){const o=[];return(ri.test(t)||ai.test(t))&&o.push("yyyy-mm-dd"),di.test(t)&&o.push("hh:mm:ss"),{...e,value:or(s.value,{format:o.join(" "),locale:w})}}return{...e,value:e.value.replace(/\\"/g,'""')}}function YH(e,t){const s=[];for(const o of t)switch(o.rule.type){case"CellIsRule":s.push(XH(o,o.rule,e));break;case"ColorScaleRule":s.push(JH(o,o.rule));break;case"IconSetRule":s.push(QH(o,o.rule));break;case"DataBarRule":s.push(KH(o,o.rule));break;default:console.warn(`Conditional formatting ${o.rule.type} not implemented`)}return s}function XH(e,t,s){const o=ez(e),i=TA(t.operator);o.push(...function(e){const t=TA(e.operator);switch(e.operator){case"containsText":case"notContainsText":case"beginsWithText":case"endsWithText":return[["type",t],["text",e.values[0]]];case"isEmpty":case"isNotEmpty":return[["type",t]];case"isEqual":case"isNotEqual":case"isGreaterThan":case"isGreaterOrEqualTo":case"isLessThan":case"isLessOrEqualTo":case"isBetween":case"isNotBetween":return[["type","cellIs"]];case"customFormula":return[["type","expression"]]}}(t)),i.length&&o.push(["operator",i]);const n=function(e,t){const s=e[0].split(":")[0],o=t.values;switch(t.operator){case"containsText":return[`NOT(ISERROR(SEARCH("${o[0]}",${s})))`];case"notContainsText":return[`ISERROR(SEARCH("${o[0]}",${s}))`];case"beginsWithText":return[`LEFT(${s},LEN("${o[0]}"))="${o[0]}"`];case"endsWithText":return[`RIGHT(${s},LEN("${o[0]}"))="${o[0]}"`];case"isEmpty":return[`LEN(TRIM(${s}))=0`];case"isNotEmpty":return[`LEN(TRIM(${s}))>0`];case"isEqual":case"isNotEqual":case"isGreaterThan":case"isGreaterOrEqualTo":case"isLessThan":case"isLessOrEqualTo":return[o[0]];case"customFormula":return o[0].startsWith("=")?[o[0].slice(1)]:[o[0]];case"isBetween":case"isNotBetween":return[o[0],o[1]]}}(e.ranges,t).map((e=>qE`<formula>${e}</formula>`)),r={font:{color:{rgb:t.style.textColor},bold:t.style.bold,italic:t.style.italic,strike:t.style.strikethrough,underline:t.style.underline}};return t.style.fillColor&&(r.fill={fgColor:{rgb:t.style.fillColor}}),o.push(["dxfId",MA(r,s)]),qE`
485
- <conditionalFormatting sqref="${e.ranges.join(" ")}">
486
- <cfRule ${zE(o)}>
487
- ${$E(n)}
488
- </cfRule>
489
- </conditionalFormatting>
490
- `}function KH(e,t){const s=ez(e);return s.push(["type","dataBar"]),qE`
491
- <conditionalFormatting sqref="${e.ranges.join(" ")}">
492
- <cfRule ${zE(s)}>
493
- <dataBar>
494
- <cfvo type="min" val="0"/>
495
- <cfvo type="max" val="100"/>
496
- <color rgb="${sI(io(t.color))}"/>
497
- </dataBar>
498
- </cfRule>
499
- </conditionalFormatting>
500
- `}function JH(e,t){const s=ez(e);s.push(["type","colorScale"]);const o=[];for(const i of e.ranges){const e=[],n=[];let r=!0;for(const s of["minimum","midpoint","maximum"]){const o=t[s];o&&("formula"!==o.type?(e.push(oz(o,s)),n.push([["rgb",sI(io(o.color))]])):r=!1)}if(!r){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const a=e.map((e=>qE`<cfvo ${zE(e)}/>`)),l=n.map((e=>qE`<color ${zE(e)}/>`));o.push(qE`
501
- <conditionalFormatting sqref="${i}">
502
- <cfRule ${zE(s)}>
503
- <colorScale>
504
- ${$E(a)}
505
- ${$E(l)}
506
- </colorScale>
507
- </cfRule>
508
- </conditionalFormatting>
509
- `)}return $E(o)}function QH(e,t){const s=ez(e);s.push(["type","iconSet"]);const o=[];for(const n of e.ranges){const e=[[["type","percent"],["val",0]]];let r=!0;for(const s of["lowerInflectionPoint","upperInflectionPoint"]){if("formula"===t[s].type){r=!1;continue}const o=t[s];e.push([...oz(o,s),["gte","ge"===o.operator?"1":"0"]])}if(!r){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const a=e.map((e=>qE`<cfvo ${zE(e)} />`)),l=[["iconSet",(i=t.icons,Rh[sz(i)])]];tz(t.icons)&&l.push(["reverse","1"]),o.push(qE`
510
- <conditionalFormatting sqref="${n}">
511
- <cfRule ${zE(s)}>
512
- <iconSet ${zE(l)}>
513
- ${$E(a)}
514
- </iconSet>
515
- </cfRule>
516
- </conditionalFormatting>
517
- `)}var i;return $E(o)}function ez(e){return[["priority",1],["stopIfTrue",e.stopIfTrue?1:0]]}function tz(e){const t=_T[sz(e)];return e.upper===t.bad&&e.lower===t.good}function sz(e){return Object.keys(_T).find((t=>Object.values(_T[t]).includes(e.upper)))||"dots"}function oz(e,t){const s=function(e,t){switch(e){case"value":return"minimum"===t?"min":"max";case"number":return"num";case"percentage":return"percent";default:return e}}(e.type,t),o=[["type",s]];if("min"!==s&&"max"!==s){let t=e.value;if("formula"===s)try{t=ZH(e.value)}catch(s){t=e.value}o.push(["val",t])}return o}function iz(e){const t=e.length;if(0===t)return[];const s=[new kE(`<dataValidations count="${t}">`)];for(const t of e)switch(t.criterion.type){case"dateIs":case"dateIsBefore":case"dateIsOnOrBefore":case"dateIsAfter":case"dateIsOnOrAfter":case"dateIsBetween":case"dateIsNotBetween":s.push(nz(t));break;case"isEqual":case"isNotEqual":case"isGreaterThan":case"isGreaterOrEqualTo":case"isLessThan":case"isLessOrEqualTo":case"isBetween":case"isNotBetween":s.push(rz(t));break;case"isValueInRange":case"isValueInList":s.push(az(t));break;case"customFormula":s.push(lz(t));break;default:console.warn(`Data validation ${t.criterion.type} is not supported in xlsx.`)}return s.push(new kE("</dataValidations>")),s}function nz(e){const t=e.criterion,s=ZH(t.values[0]),o=t.values[1]?ZH(t.values[1]):void 0,i=function(e){return Object.keys(rA).find((t=>rA[t]===e))}(e.criterion.type),n=cz(e);return n.push(["type","date"],["operator",i]),o?qE`
518
- <dataValidation ${zE(n)}>
519
- <formula1>${Yi(s,w)}</formula1>
520
- <formula2>${Yi(o,w)}</formula2>
521
- </dataValidation>
522
- `:qE`
523
- <dataValidation ${zE(n)}>
524
- <formula1>${Yi(s,w)}</formula1>
525
- </dataValidation>
526
- `}function rz(e){const t=e.criterion,s=ZH(t.values[0]),o=t.values[1]?ZH(t.values[1]):void 0,i=function(e){return Object.keys(nA).find((t=>nA[t]===e))}(e.criterion.type),n=cz(e);return n.push(["type","decimal"],["operator",i]),o?qE`
527
- <dataValidation ${zE(n)}>
528
- <formula1>${s}</formula1>
529
- <formula2>${o}</formula2>
530
- </dataValidation>
531
- `:qE`
532
- <dataValidation ${zE(n)}>
533
- <formula1>${s}</formula1>
534
- </dataValidation>
535
- `}function az(e){const t=e.criterion,s="isValueInRange"===e.criterion.type?ZH(t.values[0]):`"${t.values.join(",")}"`,o=cz(e);return o.push(["type","list"]),qE`
536
- <dataValidation ${zE(o)}>
537
- <formula1>${s}</formula1>
538
- </dataValidation>
539
- `}function lz(e){const t=ZH(e.criterion.values[0]),s=cz(e);return s.push(["type","custom"]),qE`
540
- <dataValidation ${zE(s)}>
541
- <formula1>${t}</formula1>
542
- </dataValidation>
543
- `}function cz(e){return[["allowBlank","1"],["showInputMessage","1"],["showErrorMessage","1"],["errorStyle",e.isBlocking?"":"warning"],["sqref",e.ranges.join(" ")]]}function hz(e,t,s,o){const i=[["xmlns:xdr",xh.drawing],["xmlns:r",Oh],["xmlns:a",Th],["xmlns:c",Ah]],n=[];for(const[i,r]of Object.entries(s))switch(r?.tag){case"chart":n.push(gz(r,t,e[i],o));break;case"image":n.push(pz(r,t,e[i]))}return BE(qE`
544
- <xdr:wsDr ${zE(i)}>
545
- ${$E(n)}
546
- </xdr:wsDr>
547
- `)}function dz(e,t){const{col:s,row:o,offset:i,width:n,height:r}=e,{x:a,y:l}=i,c=Object.values(t.rows),{index:h,offset:d}=uz(c,o,l),{index:u,offset:g}=uz(c,o,l+r),p=Object.values(t.cols),{index:m,offset:f}=uz(p,s,a),{index:v,offset:b}=uz(p,s,a+n);return{from:{col:m,colOff:f,row:h,rowOff:d},to:{col:v,colOff:b,row:u,rowOff:g}}}function uz(e,t,s){let o=0;for(const[i,n]of e.slice(t).entries()){if(o<=s&&s<o+n.size)return{index:t+i,offset:VA(s-o+ye)};i<e.length-1&&(o+=n.size)}return{index:e.length-1,offset:VA(s-o+ye)}}function gz(e,t,s,o){const{from:i,to:n}=dz(e,t),r=NA(e.id,o),a=[["id",r],["name",`Chart ${r}`],["title","Chart"]];return qE`
548
- <xdr:twoCellAnchor>
549
- <xdr:from>
550
- <xdr:col>${i.col}</xdr:col>
551
- <xdr:colOff>${i.colOff}</xdr:colOff>
552
- <xdr:row>${i.row}</xdr:row>
553
- <xdr:rowOff>${i.rowOff}</xdr:rowOff>
554
- </xdr:from>
555
- <xdr:to>
556
- <xdr:col>${n.col}</xdr:col>
557
- <xdr:colOff>${n.colOff}</xdr:colOff>
558
- <xdr:row>${n.row}</xdr:row>
559
- <xdr:rowOff>${n.rowOff}</xdr:rowOff>
560
- </xdr:to>
561
- <xdr:graphicFrame>
562
- <xdr:nvGraphicFramePr>
563
- <xdr:cNvPr ${zE(a)} />
564
- <xdr:cNvGraphicFramePr />
565
- </xdr:nvGraphicFramePr>
566
- <xdr:xfrm>
567
- <a:off x="0" y="0"/>
568
- <a:ext cx="0" cy="0"/>
569
- </xdr:xfrm>
570
- <a:graphic>
571
- <a:graphicData uri="${Ah}">
572
- <c:chart r:id="${s}" />
573
- </a:graphicData>
574
- </a:graphic>
575
- </xdr:graphicFrame>
576
- <xdr:clientData fLocksWithSheet="0"/>
577
- </xdr:twoCellAnchor>
578
- `}function pz(e,t,s){const{from:o,to:i}=dz(e,t),n=kA(e.id),r=[["id",n],["name",`Image ${n}`],["title","Image"]],a=VA(e.width),l=VA(e.height);return qE`
579
- <xdr:twoCellAnchor editAs="oneCell">
580
- <xdr:from>
581
- <xdr:col>${o.col}</xdr:col>
582
- <xdr:colOff>${o.colOff}</xdr:colOff>
583
- <xdr:row>${o.row}</xdr:row>
584
- <xdr:rowOff>${o.rowOff}</xdr:rowOff>
585
- </xdr:from>
586
- <xdr:to>
587
- <xdr:col>${i.col}</xdr:col>
588
- <xdr:colOff>${i.colOff}</xdr:colOff>
589
- <xdr:row>${i.row}</xdr:row>
590
- <xdr:rowOff>${i.rowOff}</xdr:rowOff>
591
- </xdr:to>
592
- <xdr:pic>
593
- <xdr:nvPicPr>
594
- <xdr:cNvPr ${zE(r)}/>
595
- <xdr:cNvPicPr preferRelativeResize="0"/>
596
- </xdr:nvPicPr>
597
- <xdr:blipFill>
598
- <a:blip cstate="print" r:embed="${s}"/>
599
- <a:stretch>
600
- <a:fillRect/>
601
- </a:stretch>
602
- </xdr:blipFill>
603
- <xdr:spPr>
604
- <a:xfrm>
605
- <a:ext cx="${a}" cy="${l}" />
606
- </a:xfrm>
607
- <a:prstGeom prst="rect">
608
- <a:avLst/>
609
- </a:prstGeom>
610
- <a:noFill/>
611
- </xdr:spPr>
612
- </xdr:pic>
613
- <xdr:clientData fLocksWithSheet="0"/>
614
- </xdr:twoCellAnchor>
615
- `}function mz(e){return gt(e)?qE``:qE`
616
- <font>
617
- ${e.bold?qE`<b />`:""}
618
- ${e.italic?qE`<i />`:""}
619
- ${e.underline?qE`<u />`:""}
620
- ${e.strike?qE`<strike />`:""}
621
- ${e.size?qE`<sz val="${e.size}" />`:""}
622
- ${e.color&&e.color.rgb?qE`<color rgb="${sI(e.color.rgb)}" />`:""}
623
- ${e.name?qE`<name val="${e.name}" />`:""}
624
- </font>
625
- `}function fz(e){return e?zE([["style",e.style]]):qE``}function vz(e){return e?qE`
626
- <color ${zE([["rgb",sI(e.color.rgb)]])}/>
627
- `:qE``}function bz(e,t,s){const o=qE`
628
- <table ${zE([["id",t],["name",`Table${t}`],["displayName",`Table${t}`],["ref",e.range],["headerRowCount",e.config.numberOfHeaders],["totalsRowCount",e.config.totalRow?1:0],["xmlns",xh.table],["xmlns:xr",xh.revision],["xmlns:xr3",xh.revision3],["xmlns:mc",xh.markupCompatibility]])}>
629
- ${e.config.hasFilters?function(e){const t=[["ref",e.range]];return qE`
630
- <autoFilter ${zE(t)}>
631
- ${$E(function(e){const t=[];for(const s of e.filters){const e=qE`
632
- <filterColumn ${zE([["colId",s.colId]])}>
633
- ${Sz(s)}
634
- </filterColumn>
635
- `;t.push(e)}return t}(e))}
636
- </autoFilter>
637
- `}(e):""}
638
- ${function(e,t){const s=ms(e.range),o=[];for(const i of Je(0,Fs(s).numberOfCols)){const n=as(s.left+i,s.top),r=[["id",i+1],["name",t.cells[n]||`col${i}`]];if(e.config.totalRow){const e=as(s.left+i,s.bottom),o=t.cells[e];o?.startsWith("=")&&r.push(["totalsRowFunction","custom"])}o.push(qE`<tableColumn ${zE(r)}/>`)}return qE`
639
- <tableColumns ${zE([["count",o.length]])}>
640
- ${$E(o)}
641
- </tableColumns>
642
- `}(e,s)}
643
- ${function(e){const t=[["name",e.config.styleId],["showFirstColumn",e.config.firstColumn?1:0],["showLastColumn",e.config.lastColumn?1:0],["showRowStripes",e.config.bandedRows?1:0],["showColumnStripes",e.config.bandedColumns?1:0]];return qE`<tableStyleInfo ${zE(t)}/>`}(e)}
644
- </table>
645
- `;return BE(o)}function Sz(e){const t=e.displayedValues.map((e=>qE`<filter ${zE([["val",e]])}/>`));return qE`
646
- <filters ${zE(e.displayBlanks?[["blank",1]]:[])}>
647
- ${$E(t)}
648
- </filters>
649
- `}function Cz(e){if(!Object.values(e).length)return qE``;const t=[];for(const[s,o]of Object.entries(e)){const e=[["min",parseInt(s)+1],["max",parseInt(s)+1],["width",DA(o.size||ie)],["customWidth",1],["hidden",o.isHidden?1:0]];o.outlineLevel&&e.push(["outlineLevel",o.outlineLevel]),o.collapsed&&e.push(["collapsed",1]),t.push(qE`
650
- <col ${zE(e)}/>
651
- `)}return qE`
652
- <cols>
653
- ${$E(t)}
654
- </cols>
655
- `}function yz(e,t,s){const o=[],i=new C_($r(s.id,s.styles)),n=new C_($r(s.id,s.borders)),r=new C_($r(s.id,s.formats));for(let a=0;a<s.rowNumber;a++){const l=[["r",a+1]],c=s.rows[a]||{};c.size&&c.size!==ne&&l.push(["ht",AA(c.size)],["customHeight",1]),c.isHidden&&l.push(["hidden",1]),c.outlineLevel&&l.push(["outlineLevel",c.outlineLevel]),c.collapsed&&l.push(["collapsed",1]);const h=[];for(let o=0;o<s.colNumber;o++){const l=as(o,a),c=s.cells[l],d=s.cellValues[l],u={sheetId:s.id,col:o,row:a},g=i.get(u),p=r.get(u),m=n.get(u);if(c||g||p||m||void 0!==d){const i=[["r",l]],n=FA(e,_A(t,c,g,p,m));n&&i.push(["s",n]);let r=[],u=qE``;if(c?.startsWith("=")&&void 0!==d){const e=$H(c,d,s.formulaSpillRanges[l]??l);if(!e)continue;({attrs:r,node:u}=e)}else if(c&&it(c)){const{label:t}=at(c);({attrs:r,node:u}=qH(t,e.sharedStrings))}else if(c&&""!==c){const i=Iz(o,a,s),n=wz(o,a,s),l=!(!p||!_r(t.formats[p]));({attrs:r,node:u}=qH(c,e.sharedStrings,i||n||l))}i.push(...r),h.push(qE`<c ${zE(i)}>
656
- ${u}
657
- </c>`)}}(h.length||c.size!==ne||c.isHidden||c.outlineLevel||c.collapsed)&&o.push(qE`
658
- <row ${zE(l)}>
659
- ${$E(h)}
660
- </row>
661
- `)}return qE`
662
- <sheetData>
663
- ${$E(o)}
664
- </sheetData>
665
- `}function Iz(e,t,s){return s.tables.some((s=>{const o=ms(s.range),i={...o,bottom:o.top};return Ds(e,t,i)}))}function wz(e,t,s){return s.tables.some((s=>{if(!s.config.totalRow)return!1;const o=ms(s.range),i={...o,top:o.bottom};return Ds(e,t,i)}))}function Ez(e,t,s){const o=t.sheets[s].cells,i=[];for(const n in o){const r=o[n];if(r&&it(r)){const{label:o,url:a}=at(r);if(ct(a)){const e=dt(a),s=t.sheets.find((t=>t.id===e)),r=[["display",o],["location",s?`${s.name}!A1`:Mi.InvalidReference],["ref",n]];i.push(qE`
666
- <hyperlink ${zE(r)}/>
667
- `)}else{const t=[["r:id",OA(e.relsFiles,`xl/worksheets/_rels/sheet${s}.xml.rels`,{target:$o(a),type:_h.hyperlink,targetMode:"External"})],["ref",n]];i.push(qE`
668
- <hyperlink ${zE(t)}/>
669
- `)}}}return i.length?qE`
670
- <hyperlinks>
671
- ${$E(i)}
672
- </hyperlinks>
673
- `:qE``}function Rz(e){if(e.length){const t=e.map((e=>qE`<mergeCell ref="${e}" />`));return qE`
674
- <mergeCells count="${e.length}">
675
- ${$E(t)}
676
- </mergeCells>
677
- `}return qE``}function xz(e){const t=e.panes;let s=qE``;if(t&&(t.xSplit||t.ySplit)){const e=as(t.xSplit,t.ySplit),o=t.xSplit?qE`xSplit="${t.xSplit}"`:"",i=t.ySplit?qE`ySplit="${t.ySplit}"`:"",n=t.xSplit?qE`<selection pane="topRight"/>`:"",r=t.ySplit?qE`<selection pane="bottomLeft"/>`:"",a=t.xSplit&&t.ySplit?qE`<selection pane="bottomRight"/>`:"";s=qE`
678
- <pane
679
- ${o}
680
- ${i}
681
- topLeftCell="${e}"
682
- activePane="${t.xSplit?t.ySplit?"bottomRight":"topRight":"bottomLeft"}"
683
- state="frozen"/>
684
- ${n}
685
- ${r}
686
- ${a}
687
- `}return qE`
688
- <sheetViews>
689
- <sheetView ${zE([["showGridLines",e.areGridLinesVisible?1:0],["workbookViewId",0]])}>
690
- ${s}
691
- </sheetView>
692
- </sheetViews>
693
- `}function Tz(e){return e.color?qE`
694
- <sheetPr>
695
- <tabColor ${zE([["rgb",sI(e.color)]])} />
696
- </sheetPr>
697
- `:""}function Az(e){const t=[],s=function(e){const t=[{},...Object.values(e.borders).map((e=>({left:GE(e.left),right:GE(e.right),bottom:GE(e.bottom),top:GE(e.top)})))];return{relsFiles:[],sharedStrings:[],chartIds:[],imageIds:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,alignment:{}}],fonts:[{size:fe,family:2,color:{rgb:"000000"},name:"Arial"}],fills:[{reservedAttribute:"none"},{reservedAttribute:"gray125"}],borders:t,numFmts:[],dxfs:[]}}(e=function(e){for(const t of e.sheets)t.tables=t.tables.filter((e=>Fs(ms(e.range)).numberOfRows>1));return e}(e=function(e){const t={},s=[];for(const o of e.sheets){let e=o.name.slice(0,31);e=Bt(e,s,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),s.push(e),e!==o.name&&(t[o.name]=e,o.name=e)}if(!Object.keys(t).length)return e;const o=Object.keys(t).sort(((e,t)=>t.length-e.length));let i=JSON.stringify(e);for(const e of o){const s=new RegExp(`'?${$e(e)}'?!`,"g");i=i.replaceAll(s,(s=>{const o=t[e];return s.replace(e,o)}))}return JSON.parse(i)}(e)));return t.push(function(e,t){const s=[["xmlns",xh.workbook],["xmlns:r",Oh]],o=[];for(const[s,i]of Object.entries(e.sheets)){const e=[["state",i.isVisible?"visible":"hidden"],["name",i.name],["sheetId",parseInt(s)+1],["r:id",`rId${parseInt(s)+1}`]];o.push(qE`
698
- <sheet ${zE(e)} />
699
- `),OA(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:_h.sheet,target:`worksheets/sheet${s}.xml`})}return UE(BE(qE`
700
- <workbook ${zE(s)}>
701
- <sheets>
702
- ${$E(o)}
703
- </sheets>
704
- </workbook>
705
- `),"xl/workbook.xml","workbook")}(e,s)),t.push(...function(e,t){const s=[];let o=1;for(const[i,n]of Object.entries(e.sheets)){const r=[["xmlns",xh.worksheet],["xmlns:r",Oh]],a=[["defaultRowHeight",AA(ne)],["defaultColWidth",DA(ie)]],l=Dz(n,i,o,t,s);o+=n.tables.length;let c=qE``;const h=[];for(const o of n.charts){const n=NA(o.id,t),r=OA(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../charts/chart${n}.xml`,type:_h.chart});h.push(r),s.push(UE(PH(o,i,e),`xl/charts/chart${n}.xml`,"chart"))}for(const e of n.images){const o=e.data.mimetype;if(void 0===o)continue;const n=oA[o];if(void 0===n)continue;const r=`image${kA(e.id)}.${n}`,a=OA(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../media/${r}`,type:_h.image});h.push(a),s.push({path:`xl/media/${r}`,imageSrc:e.data.path})}const d=[...n.charts,...n.images];if(d.length){const e=OA(t.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:`../drawings/drawing${i}.xml`,type:_h.drawing});s.push(UE(hz(h,n,d,t),`xl/drawings/drawing${i}.xml`,"drawing")),c=qE`<drawing r:id="${e}" />`}const u=qE`
706
- <worksheet ${zE(r)}>
707
- ${Tz(n)}
708
- ${xz(n)}
709
- <sheetFormatPr ${zE(a)} />
710
- ${Cz(n.cols)}
711
- ${yz(t,e,n)}
712
- ${Rz(n.merges)}
713
- ${$E(YH(t.dxfs,n.conditionalFormats))}
714
- ${$E(iz(n.dataValidationRules))}
715
- ${Ez(t,e,i)}
716
- ${c}
717
- ${l}
718
- </worksheet>
719
- `;s.push(UE(BE(u),`xl/worksheets/sheet${i}.xml`,"sheet"))}const i=qE`
720
- <metadata xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:xda="http://schemas.microsoft.com/office/spreadsheetml/2017/dynamicarray">
721
- <metadataTypes count="1">
722
- <metadataType name="XLDAPR" minSupportedVersion="120000" copy="1" pasteAll="1"
723
- pasteValues="1" merge="1" splitFirst="1" rowColShift="1" clearFormats="1"
724
- clearComments="1" assign="1" coerce="1" cellMeta="1" />
725
- </metadataTypes>
726
- <futureMetadata name="XLDAPR" count="1">
727
- <bk>
728
- <extLst>
729
- <ext uri="{${Fh}}">
730
- <xda:dynamicArrayProperties fDynamic="1" fCollapsed="0" />
731
- </ext>
732
- </extLst>
733
- </bk>
734
- </futureMetadata>
735
- <cellMetadata count="1">
736
- <bk>
737
- <rc t="1" v="0" />
738
- </bk>
739
- </cellMetadata>
740
- </metadata>
741
- `;return s.push(UE(BE(i),"xl/metadata.xml","metadata")),OA(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:_h.sharedStrings,target:"sharedStrings.xml"}),OA(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:_h.styles,target:"styles.xml"}),OA(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:_h.metadata,target:"metadata.xml"}),s}(e,s)),t.push(function(e){const t=qE`
742
- <styleSheet ${zE([["xmlns",xh.styleSheet],["xmlns:r",Oh]])}>
743
- ${function(e){const t=[];for(const[s,o]of Object.entries(e)){const e=[["numFmtId",parseInt(s)+Uh],["formatCode",o.format]];t.push(qE`
744
- <numFmt ${zE(e)}/>
745
- `)}return qE`
746
- <numFmts count="${e.length}">
747
- ${$E(t)}
748
- </numFmts>
749
- `}(e.numFmts)}
750
- ${s=e.fonts,qE`
751
- <fonts count="${s.length}">
752
- ${$E(Object.values(s).map(mz))}
753
- </fonts>
754
- `}
755
- ${function(e){const t=[];for(const s of Object.values(e))void 0!==s.reservedAttribute?t.push(qE`
756
- <fill>
757
- <patternFill patternType="${s.reservedAttribute}" />
758
- </fill>
759
- `):t.push(qE`
760
- <fill>
761
- <patternFill patternType="solid">
762
- <fgColor rgb="${sI(s.fgColor.rgb)}" />
763
- <bgColor indexed="64" />
764
- </patternFill>
765
- </fill>
766
- `);return qE`
767
- <fills count="${e.length}">
768
- ${$E(t)}
769
- </fills>
770
- `}(e.fills)}
771
- ${function(e){const t=[];for(const s of Object.values(e))t.push(qE`
772
- <border>
773
- <left ${fz(s.left)}>
774
- ${vz(s.left)}
775
- </left>
776
- <right ${fz(s.right)}>
777
- ${vz(s.right)}
778
- </right>
779
- <top ${fz(s.top)}>
780
- ${vz(s.top)}
781
- </top>
782
- <bottom ${fz(s.bottom)}>
783
- ${vz(s.bottom)}
784
- </bottom>
785
- <diagonal ${fz(s.diagonal)}>
786
- ${vz(s.diagonal)}
787
- </diagonal>
788
- </border>
789
- `);return qE`
790
- <borders count="${e.length}">
791
- ${$E(t)}
792
- </borders>
793
- `}(e.borders)}
794
- ${function(e){const t=[];for(const s of e){const e=[["numFmtId",s.numFmtId],["fillId",s.fillId],["fontId",s.fontId],["borderId",s.borderId]],o=[];s.alignment&&s.alignment.vertical&&o.push(["vertical",s.alignment.vertical]),s.alignment&&s.alignment.horizontal&&o.push(["horizontal",s.alignment.horizontal]),s.alignment&&s.alignment.wrapText&&o.push(["wrapText","1"]),o.length>0?(e.push(["applyAlignment","1"]),t.push(qE`<xf ${zE(e)}><alignment ${zE(o)} /></xf> `)):t.push(qE`<xf ${zE(e)} />`)}return qE`
795
- <cellXfs count="${e.length}">
796
- ${$E(t)}
797
- </cellXfs>
798
- `}(e.styles)}
799
- ${function(e){const t=[];for(const s of e){let e=qE``;s.font&&(e=mz(s.font));let o=qE``;s.fill&&(o=qE`
800
- <fill>
801
- <patternFill>
802
- <bgColor rgb="${sI(s.fill.fgColor.rgb)}" />
803
- </patternFill>
804
- </fill>
805
- `),t.push(qE`
806
- <dxf>
807
- ${e}
808
- ${o}
809
- </dxf>
810
- `)}return qE`
811
- <dxfs count="${e.length}">
812
- ${$E(t)}
813
- </dxfs>
814
- `}(e.dxfs)}
815
- </styleSheet>
816
- `;var s;return UE(BE(t),"xl/styles.xml","styles")}(s)),t.push(function(e){const t=[["xmlns",xh.sst],["count",e.length],["uniqueCount",e.length]],s=e.map((e=>e.trim()!==e?qE`<si><t xml:space="preserve">${e}</t></si>`:qE`<si><t>${e}</t></si>`));return UE(BE(qE`
817
- <sst ${zE(t)}>
818
- ${$E(s)}
819
- </sst>
820
- `),"xl/sharedStrings.xml","sharedStrings")}(s.sharedStrings)),t.push(...function(e){const t=[];for(const s of e){const e=[];for(const t of s.rels){const s=[["Id",t.id],["Target",t.target],["Type",t.type]];t.targetMode&&s.push(["TargetMode",t.targetMode]),e.push(qE`
821
- <Relationship ${zE(s)} />
822
- `)}const o=qE`
823
- <Relationships xmlns="${xh.Relationships}">
824
- ${$E(e)}
825
- </Relationships>
826
- `;t.push(UE(BE(o),s.path))}return t}(s.relsFiles)),t.push(function(e){const t=[],s=Object.entries(oA).map((([e,t])=>function(e,t){return qE`
827
- <Default Extension="${e}" ContentType="${t}" />
828
- `}(t,e)));for(const s of e)"contentType"in s&&s.contentType&&t.push(WE("/"+s.path,Dh[s.contentType]));const o=[["Extension","rels"],["ContentType","application/vnd.openxmlformats-package.relationships+xml"]],i=[["Extension","xml"],["ContentType","application/xml"]];return UE(BE(qE`
829
- <Types xmlns="${xh.Types}">
830
- ${$E(Object.values(s))}
831
- <Default ${zE(o)} />
832
- <Default ${zE(i)} />
833
- ${$E(t)}
834
- </Types>
835
- `),"[Content_Types].xml")}(t)),t.push(function(){const e=[["Id","rId1"],["Type",_h.document],["Target","xl/workbook.xml"]];return UE(BE(qE`
836
- <Relationships xmlns="${xh.Relationships}">
837
- <Relationship ${zE(e)} />
838
- </Relationships>
839
- `),"_rels/.rels")}()),{name:"my_spreadsheet.xlsx",files:t}}function Dz(e,t,s,o,i){let n=s;if(!e.tables.length)return new kE("");const r=`xl/worksheets/_rels/sheet${t}.xml.rels`,a=[];for(const t of e.tables){const s=OA(o.relsFiles,r,{target:`../tables/table${n}.xml`,type:_h.table});i.push(UE(bz(t,n,e),`xl/tables/table${n}.xml`,"table")),a.push(qE`<tablePart r:id="${s}" />`),n++}return qE`
840
- <tableParts count="${e.tables.length}">
841
- ${$E(a)}
842
- </tableParts>
843
- `}var _z;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(_z||(_z={}));function Fz(e,t={}){const s=qe(t);return s.type=e,s}const Oz={},Pz={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:se,HEADER_WIDTH:oe,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:ie,DEFAULT_CELL_HEIGHT:ne,SCROLLBAR_WIDTH:re},Mz={autoCompleteProviders:Xh,autofillModifiersRegistry:DV,autofillRulesRegistry:_V,cellMenuRegistry:eP,colMenuRegistry:uM,errorTypes:Ni,linkMenuRegistry:zx,functionRegistry:JS,featurePluginRegistry:yU,iconsOnCellRegistry:wV,statefulUIPluginRegistry:IU,coreViewsPluginRegistry:wU,corePluginRegistry:CU,rowMenuRegistry:bM,sidePanelRegistry:Sk,figureRegistry:yR,chartSidePanelComponentRegistry:fL,chartComponentRegistry:TE,chartRegistry:xE,chartSubtypeRegistry:DE,topbarMenuRegistry:FU,topbarComponentRegistry:OU,clickableCellRegistry:EU,otRegistry:UV,inverseCommandRegistry:xU,urlRegistry:qo,cellPopoverRegistry:ER,numberFormatMenuRegistry:AU,repeatLocalCommandTransformRegistry:gU,repeatCommandTransformRegistry:uU,clipboardHandlersRegistries:Jc,pivotRegistry:HO,pivotTimeAdapterRegistry:hc,pivotSidePanelRegistry:nk,pivotNormalizationValueRegistry:zc,supportedPivotPositionalFormulaRegistry:Tk,pivotToFunctionValueRegistry:Bc,migrationStepRegistry:UD,chartJsExtensionRegistry:vh},Nz={arg:qh,isEvaluationError:qi,toBoolean:nn,toJsDate:rn,toNumber:Yi,toString:tn,toNormalizedPivotValue:kc,toFunctionPivotValue:Uc,toXC:as,toZone:ms,toUnboundedZone:ps,toCartesian:rs,numberToLetters:Xt,lettersToNumber:Kt,UuidGenerator:Xa,formatValue:or,createCurrencyFormat:br,ColorGenerator:Oo,computeTextWidth:La,createEmptyWorkbookData:XD,createEmptySheet:YD,createEmptyExcelSheet:KD,rgbaToHex:uo,colorToRGBA:go,positionToZone:Us,isDefined:ut,isMatrix:R,lazy:ft,genericRepeat:pU,createAction:i,createActions:s,transformRangeData:eh,deepEquals:St,overlap:As,union:Es,isInside:Ds,deepCopy:qe,expandZoneOnInsertion:Cs,reduceZoneOnDeletion:ws,unquote:je,getMaxObjectId:Dc,getFunctionsFromTokens:bC,getFirstPivotFunction:tk,getNumberOfPivotFunctions:sk,parseDimension:Oc,isDateOrDatetimeField:Pc,makeFieldProposal:QL,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:qs,getPivotHighlights:HL,pivotTimeAdapter:dc,UNDO_REDO_PIVOT_COMMANDS:TV,createPivotFormula:Lc,areDomainArgsFieldsValid:Nc,splitReference:na,sanitizeSheetName:Xe,getUniqueText:Bt,isNumber:_i,isDateTime:gi,createCustomFields:Zc},Lz={isMarkdownLink:it,parseMarkdownLink:at,markdownLink:rt,openLink:Ko,urlRepresentation:Xo},kz={Checkbox:Rx,Section:hx,RoundColorPicker:dx,ChartDataSeries:DN,ChartErrorSection:_N,ChartLabelRange:FN,ChartTitle:NN,ChartPanel:SL,ChartFigure:SR,ChartJsComponent:Iy,ClickableCellSortIcon:Ak,ZoomableChartJsComponent:Yw,Grid:xk,GridOverlay:sN,ScorecardChart:ky,GaugeChartComponent:tE,LineConfigPanel:sL,BarConfigPanel:PN,PieChartDesignPanel:nL,GenericChartConfigPanel:ON,ChartWithAxisDesignPanel:WN,GenericZoomableChartDesignPanel:qN,LineChartDesignPanel:oL,GaugeChartConfigPanel:YN,GaugeChartDesignPanel:XN,ScorecardChartConfigPanel:aL,ScorecardChartDesignPanel:lL,GeoChartDesignPanel:eL,RadarChartDesignPanel:rL,WaterfallChartDesignPanel:mL,ComboChartDesignPanel:ZN,FunnelChartDesignPanel:jN,SunburstChartDesignPanel:cL,TreeMapChartDesignPanel:pL,ChartTypePicker:vL,FigureComponent:IR,MenuPopover:fR,Popover:uR,SelectionInput:Sx,ValidationMessages:jM,AddDimensionButton:WL,PivotDimensionGranularity:qL,PivotDimensionOrder:ZL,PivotDimension:$L,PivotLayoutConfigurator:XL,PivotHTMLRenderer:_k,PivotDeferUpdate:zL,PivotTitleSection:KL,CogWheelMenu:TN,TextInput:IN,SidePanelCollapsible:DR,RadioSelection:kN,GeoChartRegionSelectSection:KN,ChartDashboardMenu:vR,FullScreenFigure:Dk},Vz={useDragAndDropListItems:ux,useHighlights:IL,useHighlightsOnHover:yL},Uz={useStoreProvider:nh,DependencyContainer:sh,CellPopoverStore:RR,ComposerFocusStore:fh,CellComposerStore:HM,FindAndReplaceStore:ML,HighlightStore:XR,DelayedHoveredCellStore:wR,HoveredTableStore:QM,ModelStore:dh,NotificationStore:KR,RendererStore:gh,SelectionInputStore:bx,SpreadsheetStore:ph,useStore:rh,useLocalStore:ah,SidePanelStore:wk,PivotSidePanelStore:ok,PivotMeasureDisplayPanelStore:VL,ClientFocusStore:CM,GridRenderer:hN};const Hz={DEFAULT_LOCALE:w,HIGHLIGHT_COLOR:A,PIVOT_TABLE_CONFIG:ke,ChartTerms:eb,FIGURE_ID_SPLITTER:we,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2},zz={...ME,...Bw};e.AbstractCellClipboardHandler=Ja,e.AbstractChart=wy,e.AbstractFigureClipboardHandler=Qa,e.CellErrorType=Mi,e.ClientDisconnectedError=QV,e.CorePlugin=Fk,e.CoreViewPlugin=Uk,e.DispatchResult=v,e.EvaluationError=Li,e.LocalTransportService=PU,e.Model=class extends th{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},s={},o=[],i=new Xa,n=!1){const r=performance.now();console.debug("##### Model creation #####"),super(),Ho===Vo&&zo===Uo&&(zo=()=>!0),o=ZD(e,o);const a=WD(e,n);this.state=new AH,this.uuidGenerator=i,this.config=this.setupConfig(s),this.session=this.setupSession(a.revisionId),this.coreGetters={},this.range=new kk(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 xH(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 CU.getAll())this.setupCorePlugin(e,a);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(o);for(const e of wU.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(const e of IU.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(const e of yU.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(),s.snapshotRequested||e["[Content_Types].xml"]&&!this.getters.isReadonly()){const e=performance.now();console.debug("Snapshot requested"),this.session.snapshot(this.exportData()),this.garbageCollectExternalResources(),console.debug("Snapshot taken in",performance.now()-e,"ms")}t.markRaw(this),console.debug("Model created in",performance.now()-r,"ms"),console.debug("######")}joinSession(){this.session.join(this.config.client)}async leaveSession(){const e=this.getters.isReadonly()?void 0:ft((()=>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 eU(wH({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:Go("Anonymous").toString()},s=e.transportService||new PU,o="readonly"===e.mode||"dashboard"===e.mode;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:o?new mH(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(I));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){const t=f(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some((e=>"Success"!==e))?new v(t.flat()):v.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(Fz(e,t));dispatch=(e,t)=>{const s=Fz(e,t),o=this.status;if(this.getters.isReadonly()&&(i=s,!p.has(i.type)))return new v("Readonly");var i;if(!this.session.canApplyOptimisticUpdate())return new v("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();f(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(f(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(f(s))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,s)}return v.Success};dispatchFromCorePlugin=(e,t)=>{const s=Fz(e,t),o=this.status;this.status=2;const i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,s),this.status=o,v.Success};dispatchToHandlers(e,t){const s=f(t);for(const o of e)!s&&o instanceof Fk||o.beforeHandle(t);for(const o of e)!s&&o instanceof Fk||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=XD();for(const t of this.handlers)t instanceof Fk&&t.export(e);return e.revisionId=this.session.getRevisionId()||Ce,e=qe(e),e}updateMode(e){this.config.mode=e,this.trigger("update")}exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={...XD(),sheets:[KD(GD,"Sheet1")]};for(const t of this.handlers)t instanceof Ed&&t.exportForExcel(e);return e=qe(e),Az(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.PivotRuntimeDefinition=xO,e.Registry=n,e.Revision=JV,e.SPREADSHEET_DIMENSIONS=Pz,e.Spreadsheet=pH,e.SpreadsheetPivotTable=AO,e.UIPlugin=Rd,e.__info__=Oz,e.addFunction=function e(t,s){return JS.add(t,s),{addFunction:(t,s)=>e(t,s)}},e.addRenderingLayer=function(e,t){if(Wt[e])throw new Error(`Layer ${e} already exists`);Wt[e]=t},e.astToFormula=LM,e.chartHelpers=zz,e.compile=gC,e.compileTokens=pC,e.components=kz,e.constants=Hz,e.convertAstNodes=Sv,e.coreTypes=m,e.findCellInNewZone=Vs,e.functionCache=uC,e.getCaretDownSvg=ST,e.getCaretUpSvg=CT,e.helpers=Nz,e.hooks=Vz,e.invalidateCFEvaluationCommands=d,e.invalidateChartEvaluationCommands=c,e.invalidateDependenciesCommands=h,e.invalidateEvaluationCommands=l,e.iterateAstNodes=Cv,e.links=Lz,e.load=WD,e.parse=vv,e.parseTokens=bv,e.readonlyAllowedCommands=p,e.registries=Mz,e.setDefaultSheetViewSize=function(e){Pe=e},e.setTranslationMethod=function(e,t=(()=>!0)){Ho=e,zo=t},e.stores=Uz,e.tokenColors=Ge,e.tokenize=sl,Oz.version="19.1.0-alpha.4",Oz.date="2025-10-07T10:03:20.917Z",Oz.hash="b7cfed8"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);