@odoo/o-spreadsheet 19.0.35 → 19.0.36

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.
@@ -2,7 +2,7 @@
2
2
  `):``}function Gt(e){let 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 Kt(e){let t=new Map,n=e.name?e.name+` (memoized)`:`memoized`;return{[n](...n){return t.has(n[0])||t.set(n[0],e(...n)),t.get(n[0])}}[n]}function qt(e,t){let n=new Set(t),r=[];for(let t=0;t<e.length;t++)n.has(t)||r.push(e[t]);return r}function Jt(e,t,n){return e.slice(0,n).concat(t).concat(e.slice(n))}function Yt(e,t,n){let r=[...e];return r[n]=t,r}function Xt(e){return e.split(`
3
3
  `).map(e=>e.replace(/\s+/g,` `).trim()).join(`
4
4
  `)}function Zt(e,t,n){return t>n?Zt(e,n,t):e>=t&&e<=n}function Qt(e,t){let n=ut(e),r=t.matchCase?``:`i`;return t.exactMatch&&(n=`^${n}$`),RegExp(n,r)}function $t(e){let t=e.length;if(t<1e5)return Math.max(...e);let n=-1/0;for(;t--;)n=e[t]>n?e[t]:n;return n}function en(e){let t=e.length;if(t<1e5)return Math.min(...e);let n=1/0;for(;t--;)n=e[t]<n?e[t]:n;return n}var tn=class{text;currentIndex=0;current;constructor(e){this.text=e,this.current=e[0]}shift(){let 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 nn(e,t=e=>e){let n=new Set;return e.filter(e=>{let r=t(e);return n.has(r)?!1:(n.add(r),!0)})}function rn(e){let t={};for(let n in e)for(let r in e[n])t[r]||(t[r]={}),t[r][n]=e[n][r];return t}function an(e,t,n={}){let r=n.compute??((e,t)=>`${e} (${t})`),i=n.computeFirstOne??!1,a=n.start??1,o=i?r(e,a):e;for(;t.includes(o);)o=r(e,a++);return o}function on(e){return e.startsWith(`=`)||e.startsWith(`+`)}function sn(e){return{bold:e.bold,italic:e.italic,fontSize:e.fontSize,textColor:e.color,align:e.align}}let cn=/rgba?\(|\s+|\)/gi,ln=/^#([A-F\d]{2}){3,4}$/,un=[`#eb6d00`,`#0074d9`,`#ad8e00`,`#169ed4`,`#b10dc9`,`#00a82d`,`#00a3a3`,`#f012be`,`#3d9970`,`#111111`,`#62A300`,`#ff4136`,`#949494`,`#85144b`,`#001f3f`];function dn(e,t=1){let n=t===1?``:Math.round(t*255).toString(16).padStart(2,`0`);return pn(e.toString(16).padStart(6,`0`))+n}function fn(e){return typeof e==`number`?e:Number.parseInt(pn(e).slice(1,7),16)}function pn(e){let t=e;if(e.startsWith(`rgb`)?t=yn(e):(t=e.replace(`#`,``).toUpperCase(),(t.length===3||t.length===4)&&(t=t.split(``).reduce((e,t)=>e+t+t,``)),t=`#${t}`),!ln.test(t))throw Error(`invalid color input: ${e}`);return t}function mn(e){try{return pn(e),!0}catch{return!1}}function hn(e){try{return wn(e),!0}catch{return!1}}let gn=e=>e>=0&&e<=255;function _n(e,t,n,r=1){if(!gn(e)||!gn(t)||!gn(n)||r<0||r>1)throw Error(`Invalid RGBA values ${[e,t,n,r]}`);return{a:r,b:n,g:t,r:e}}function vn(e){let{r:t,g:n,b:r}=xn(e);t/=255,n/=255,r/=255;let i=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4,a=i(t),o=i(n),s=i(r);return .2126*a+.7152*o+.0722*s}function yn(e){let t=e.replace(cn,``).split(`,`),n=255;if(t.length!==3&&t.length!==4)throw Error(`invalid color`);if(t.length===4){let e=parseFloat(t.pop()||`1`);if(isNaN(e))throw Error(`invalid alpha value`);n=Math.round(e*255)}let r=t.map(e=>parseInt(e,10));return n!==255&&r.push(n),`#`+Mt(r.map(e=>e.toString(16).padStart(2,`0`))).toUpperCase()}function bn(e){let t=e.r.toString(16),n=e.g.toString(16),r=e.b.toString(16),i=Math.round(e.a*255).toString(16);return t.length===1&&(t=`0`+t),n.length===1&&(n=`0`+n),r.length===1&&(r=`0`+r),i.length===1&&(i=`0`+i),i===`ff`&&(i=``),(`#`+t+n+r+i).toUpperCase()}function xn(e){e=pn(e);let t,n,r,i;if(e.length===7)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=255;else if(e.length===9)t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16),i=parseInt(e[7]+e[8],16);else throw Error(`Invalid color`);return i=+(i/255).toFixed(3),{a:i,r:t,g:n,b:r}}function Sn(e){e={...e},e.s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,n=t*(1-Math.abs(e.h/60%2-1)),r=e.l-t/2,i=0,a=0,o=0;return 0<=e.h&&e.h<60?(i=t,a=n,o=0):60<=e.h&&e.h<120?(i=n,a=t,o=0):120<=e.h&&e.h<180?(i=0,a=t,o=n):180<=e.h&&e.h<240?(i=0,a=n,o=t):240<=e.h&&e.h<300?(i=n,a=0,o=t):300<=e.h&&e.h<360&&(i=t,a=0,o=n),i=Math.round((i+r)*255),a=Math.round((a+r)*255),o=Math.round((o+r)*255),{a:e.a,r:i,g:a,b:o}}function Cn(e){let t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s=0,c=0,l=0;return s=o===0?0:a===t?(n-r)/o%6:a===n?(r-t)/o+2:(t-n)/o+4,s=Math.round(s*60),s<0&&(s+=360),l=(a+i)/2,c=o===0?0:o/(1-Math.abs(2*l-1)),c=+(c*100).toFixed(1),l=+(l*100).toFixed(1),{a:e.a,h:s,s:c,l}}function wn(e){return bn(Sn(e))}function Tn(e){return Cn(xn(e))}function En(e,t){let n=xn(t),r=xn(e),i=n.a+r.a*(1-n.a);return bn({r:Math.round((n.r*n.a+r.r*r.a*(1-n.a))/i),g:Math.round((n.g*n.a+r.g*r.a*(1-n.a))/i),b:Math.round((n.b*n.a+r.b*r.a*(1-n.a))/i),a:i})}function Dn(e){return xn(typeof e==`number`?dn(e):e)}function On(e,t,n=0){if(!(mn(e)&&mn(t)))return!1;let r=xn(e),i=xn(t);return r.a===i.a?Math.sqrt(((r.r-i.r)/255)**2+((r.g-i.g)/255)**2+((r.b-i.b)/255)**2)<=n:!1}function kn(e,t){return t===1?pn(e).slice(0,7):bn({...xn(e),a:t})}function An(e,t){let n=Tn(e);return t===1?`#fff`:(n.l=t*(100-n.l)+n.l,wn(n))}function jn(e,t){let n=Tn(e);return t===1?`#000`:(n.s=Math.min(100,t*n.s+n.s),n.l-=t*n.l,wn(n))}function Mn(e){return vn(e)<.6?An(e,.9):jn(e,.75)}let Nn=[`#4EA7F2`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#FFD86D`],Pn=[`#4EA7F2`,`#3188E6`,`#43C5B1`,`#00A78D`,`#EA6175`,`#CE4257`,`#F4A261`,`#F48935`,`#8481DD`,`#5752D1`,`#FFD86D`,`#FFBC2C`],Fn=[`#4EA7F2`,`#3188E6`,`#056BD9`,`#A76DBC`,`#7F4295`,`#6D2387`,`#EA6175`,`#CE4257`,`#982738`,`#43C5B1`,`#00A78D`,`#0E8270`,`#F4A261`,`#F48935`,`#BE5D10`,`#8481DD`,`#5752D1`,`#3A3580`,`#A4A8B6`,`#7E8290`,`#545B70`,`#FFD86D`,`#FFBC2C`,`#C08A16`],In=`#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`.split(`.`),Ln=[`#4EA7F2`,`#43C5B1`,`#EA6175`,`#F4A261`,`#8481DD`,`#FFD86D`,`#3188E6`,`#00A78D`,`#CE4257`,`#F48935`,`#5752D1`,`#FFBC2C`],Rn=[`#4EA7F2`,`#A76DBC`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#A4A8B6`,`#FFD86D`,`#3188E6`,`#7F4295`,`#CE4257`,`#00A78D`,`#F48935`,`#5752D1`,`#7E8290`,`#FFBC2C`,`#056BD9`,`#6D2387`,`#982738`,`#0E8270`,`#BE5D10`,`#3A3580`,`#545B70`,`#C08A16`],zn=`#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`.split(`.`);function Bn(e,t){return t[e%t.length]}function Vn(e){return e<=6?Nn:e<=12?Pn:e<=24?Fn:In}function Hn(e){return e<=6?Nn:e<=12?Ln:e<=24?Rn:zn}var Un=class{preferredColors;currentColorIndex=0;palette;constructor(e,t=[]){this.preferredColors=t,this.palette=Vn(e).filter(e=>!t.includes(e))}next(){return this.preferredColors?.[this.currentColorIndex]?this.preferredColors[this.currentColorIndex++]:Bn(this.currentColorIndex++,this.palette)}},Wn=class extends Un{constructor(e,t=[]){super(e,t),this.palette=Hn(e).filter(e=>!t.includes(e))}},Gn=class{availableColors;colors={};constructor(e=12){this.availableColors=new Wn(e)}get(e){return this.colors[e]||(this.colors[e]=this.availableColors.next()),this.colors[e]}};function Kn(e){if(e.length<2)throw Error(`Color scale must have at least 2 points`);let t=[...e.sort((e,t)=>e.value-t.value)],n=[];for(let e=1;e<t.length;e++){let r=Dn(t[e-1].color).a,i=Dn(t[e].color).a,a=fn(t[e-1].color),o=fn(t[e].color);n.push({min:t[e-1].value,max:t[e].value,minColor:a,maxColor:o,minColorAlpha:r,maxColorAlpha:i,colorDiff:qn(t[e-1].value,t[e].value,a,o)})}return e=>{if(e<n[0].min)return dn(n[0].minColor,n[0].minColorAlpha);for(let t of n)if(e>=t.min&&e<=t.max)return dn(Jn(e,t.min,t.minColor,t.colorDiff),t.maxColorAlpha);return dn(n[n.length-1].maxColor,n[n.length-1].maxColorAlpha)}}function qn(e,t,n,r){let i=t-e,a=(n>>16)%256-(r>>16)%256,o=(n>>8)%256-(r>>8)%256,s=n%256-r%256;return[a/i,o/i,s/i]}function Jn(e,t,n,r){let[i,a,o]=r,s=Math.round((n>>16)%256-i*(e-t)),c=Math.round((n>>8)%256-a*(e-t)),l=Math.round(n%256-o*(e-t));return s<<16|c<<8|l}function Yn(e){if(e<0)throw Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Yn(Math.floor(e/26)-1)+Yn(e%26)}function Xn(e){let t=0,n=e.length;for(let r=0;r<n;r++){let n=Zn(e[r]);t=t*26+n}return t-1}function Zn(e){let t=e.charCodeAt(0);return t>=65&&t<=90?t-64:t-96}function Qn(e){return e>=`A`&&e<=`Z`||e>=`a`&&e<=`z`}function $n(e){return e>=`0`&&e<=`9`}let er=Xn(`ZZZ`);function tr(e){for(;e.current===` `;)e.advanceBy(1)}function nr(e){if(e.current===`$`&&e.advanceBy(1),!e.current||!Qn(e.current))return-1;let t=0;for(;e.current&&Qn(e.current);)t=t*26+Zn(e.shift());return t}function rr(e){if(e.current===`$`&&e.advanceBy(1),!e.current||!$n(e.current))return-1;let t=0;for(;e.current&&$n(e.current);)t=t*10+Number(e.shift());return t}function ir(e){let t=new tn(e);tr(t);let n=nr(t);if(n===-1||!t.current)throw Error(`Invalid cell description: ${e}`);let r=rr(t);tr(t);let i=n-1,a=r-1;if(!t.isOver()||i>er||a>9999998)throw Error(`Invalid cell description: ${e}`);return{col:i,row:a}}function T(e,t,n={colFixed:!1,rowFixed:!1}){return(n.colFixed?`$`:``)+Yn(e)+(n.rowFixed?`$`:``)+String(t+1)}let ar=e=>e,or=()=>!1,sr=ar,cr=or;function lr(e,...t){if(t.length===1&&typeof t[0]==`object`&&!(t[0]instanceof String)){let n=t[0];e=e.replace(/\%\(([^\)]+)\)s/g,(e,t)=>n[t])}else t.length>0&&(e=e.replace(/\%s/g,()=>t.shift()));return e}function ur(e,t=()=>!0){sr=e,cr=t}function dr(){sr===ar&&cr===or&&(cr=()=>!0)}let E=function(e,...t){return cr()?lr(sr(e),...t):new fr(e,t)};var fr=class extends String{values;constructor(e,t){super(e),this.values=t}valueOf(){let e=super.valueOf();return cr()?lr(sr(e),...this.values):lr(e,...this.values)}toString(){return this.valueOf()}};function pr(e){return`sheetId`in e}function mr(e){return`dimension`in e&&`sheetId`in e&&`elements`in e}function hr(e){return`target`in e&&`sheetId`in e}function gr(e){return`ranges`in e}function _r(e){return`col`in e&&`row`in e&&`sheetId`in e}function vr(e){return`sheetId`in e&&`zone`in e}let yr=new Set([`RENAME_SHEET`,`DELETE_SHEET`,`CREATE_SHEET`,`DUPLICATE_SHEET`,`ADD_COLUMNS_ROWS`,`REMOVE_COLUMNS_ROWS`,`UNDO`,`REDO`,`ADD_MERGE`,`REMOVE_MERGE`,`UPDATE_LOCALE`,`ADD_PIVOT`,`UPDATE_PIVOT`,`INSERT_PIVOT`,`RENAME_PIVOT`,`REMOVE_PIVOT`,`DUPLICATE_PIVOT`]),br=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`]),xr=new Set([`MOVE_RANGES`]),Sr=new Set([`EVALUATE_CELLS`,`ADD_CONDITIONAL_FORMAT`,`REMOVE_CONDITIONAL_FORMAT`,`CHANGE_CONDITIONAL_FORMAT_PRIORITY`]),Cr=new Set([`AUTOFILL_CELL`,`SET_BORDER`,`SET_ZONE_BORDERS`,`SET_BORDERS_ON_TARGET`]),wr=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`]),Tr=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`]),Er=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`.split(`.`));function Dr(e){return Er.has(e.type)}function Or(e){return Tr.has(e.type)}var kr=class{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>e!==`Success`)}static get Success(){return Ar}get isSuccessful(){return this.reasons.length===0}isCancelledBecause(e){return this.reasons.includes(e)}};let Ar=new kr,jr=function(e){return e.Success=`Success`,e.CancelledForUnknownReason=`CancelledForUnknownReason`,e.WillRemoveExistingMerge=`WillRemoveExistingMerge`,e.CannotMoveTableHeader=`CannotMoveTableHeader`,e.MergeIsDestructive=`MergeIsDestructive`,e.CellIsMerged=`CellIsMerged`,e.InvalidTarget=`InvalidTarget`,e.EmptyUndoStack=`EmptyUndoStack`,e.EmptyRedoStack=`EmptyRedoStack`,e.NotEnoughElements=`NotEnoughElements`,e.NotEnoughSheets=`NotEnoughSheets`,e.MissingSheetName=`MissingSheetName`,e.UnchangedSheetName=`UnchangedSheetName`,e.DuplicatedSheetName=`DuplicatedSheetName`,e.DuplicatedSheetId=`DuplicatedSheetId`,e.ForbiddenCharactersInSheetName=`ForbiddenCharactersInSheetName`,e.WrongSheetMove=`WrongSheetMove`,e.WrongSheetPosition=`WrongSheetPosition`,e.InvalidAnchorZone=`InvalidAnchorZone`,e.SelectionOutOfBound=`SelectionOutOfBound`,e.TargetOutOfSheet=`TargetOutOfSheet`,e.WrongCutSelection=`WrongCutSelection`,e.WrongPasteSelection=`WrongPasteSelection`,e.WrongPasteOption=`WrongPasteOption`,e.WrongFigurePasteOption=`WrongFigurePasteOption`,e.EmptyClipboard=`EmptyClipboard`,e.EmptyRange=`EmptyRange`,e.InvalidRange=`InvalidRange`,e.InvalidZones=`InvalidZones`,e.InvalidSheetId=`InvalidSheetId`,e.InvalidCellId=`InvalidCellId`,e.InvalidFigureId=`InvalidFigureId`,e.InputAlreadyFocused=`InputAlreadyFocused`,e.MaximumRangesReached=`MaximumRangesReached`,e.MinimumRangesReached=`MinimumRangesReached`,e.InvalidChartDefinition=`InvalidChartDefinition`,e.InvalidDataSet=`InvalidDataSet`,e.InvalidLabelRange=`InvalidLabelRange`,e.InvalidScorecardKeyValue=`InvalidScorecardKeyValue`,e.InvalidScorecardBaseline=`InvalidScorecardBaseline`,e.InvalidGaugeDataRange=`InvalidGaugeDataRange`,e.EmptyGaugeRangeMin=`EmptyGaugeRangeMin`,e.GaugeRangeMinNaN=`GaugeRangeMinNaN`,e.EmptyGaugeRangeMax=`EmptyGaugeRangeMax`,e.GaugeRangeMaxNaN=`GaugeRangeMaxNaN`,e.GaugeLowerInflectionPointNaN=`GaugeLowerInflectionPointNaN`,e.GaugeUpperInflectionPointNaN=`GaugeUpperInflectionPointNaN`,e.InvalidAutofillSelection=`InvalidAutofillSelection`,e.MinBiggerThanMax=`MinBiggerThanMax`,e.LowerBiggerThanUpper=`LowerBiggerThanUpper`,e.MidBiggerThanMax=`MidBiggerThanMax`,e.MinBiggerThanMid=`MinBiggerThanMid`,e.FirstArgMissing=`FirstArgMissing`,e.SecondArgMissing=`SecondArgMissing`,e.MinNaN=`MinNaN`,e.MidNaN=`MidNaN`,e.MaxNaN=`MaxNaN`,e.ValueUpperInflectionNaN=`ValueUpperInflectionNaN`,e.ValueLowerInflectionNaN=`ValueLowerInflectionNaN`,e.MinInvalidFormula=`MinInvalidFormula`,e.MidInvalidFormula=`MidInvalidFormula`,e.MaxInvalidFormula=`MaxInvalidFormula`,e.ValueUpperInvalidFormula=`ValueUpperInvalidFormula`,e.ValueLowerInvalidFormula=`ValueLowerInvalidFormula`,e.InvalidSortAnchor=`InvalidSortAnchor`,e.InvalidSortZone=`InvalidSortZone`,e.SortZoneWithArrayFormulas=`SortZoneWithArrayFormulas`,e.WaitingSessionConfirmation=`WaitingSessionConfirmation`,e.MergeOverlap=`MergeOverlap`,e.TooManyHiddenElements=`TooManyHiddenElements`,e.Readonly=`Readonly`,e.InvalidViewportSize=`InvalidViewportSize`,e.InvalidScrollingDirection=`InvalidScrollingDirection`,e.ViewportScrollLimitsReached=`ViewportScrollLimitsReached`,e.FigureDoesNotExist=`FigureDoesNotExist`,e.InvalidConditionalFormatId=`InvalidConditionalFormatId`,e.InvalidConditionalFormatType=`InvalidConditionalFormatType`,e.InvalidCellPopover=`InvalidCellPopover`,e.EmptyTarget=`EmptyTarget`,e.InvalidFreezeQuantity=`InvalidFreezeQuantity`,e.FrozenPaneOverlap=`FrozenPaneOverlap`,e.ValuesNotChanged=`ValuesNotChanged`,e.InvalidFilterZone=`InvalidFilterZone`,e.TableNotFound=`TableNotFound`,e.TableOverlap=`TableOverlap`,e.InvalidTableConfig=`InvalidTableConfig`,e.InvalidTableStyle=`InvalidTableStyle`,e.FilterNotFound=`FilterNotFound`,e.MergeInTable=`MergeInTable`,e.NonContinuousTargets=`NonContinuousTargets`,e.DuplicatedFigureId=`DuplicatedFigureId`,e.InvalidSelectionStep=`InvalidSelectionStep`,e.DuplicatedChartId=`DuplicatedChartId`,e.ChartDoesNotExist=`ChartDoesNotExist`,e.InvalidHeaderIndex=`InvalidHeaderIndex`,e.InvalidQuantity=`InvalidQuantity`,e.MoreThanOneColumnSelected=`MoreThanOneColumnSelected`,e.EmptySplitSeparator=`EmptySplitSeparator`,e.SplitWillOverwriteContent=`SplitWillOverwriteContent`,e.NoSplitSeparatorInSelection=`NoSplitSeparatorInSelection`,e.NoActiveSheet=`NoActiveSheet`,e.InvalidLocale=`InvalidLocale`,e.MoreThanOneRangeSelected=`MoreThanOneRangeSelected`,e.NoColumnsProvided=`NoColumnsProvided`,e.ColumnsNotIncludedInZone=`ColumnsNotIncludedInZone`,e.DuplicatesColumnsSelected=`DuplicatesColumnsSelected`,e.InvalidHeaderGroupStartEnd=`InvalidHeaderGroupStartEnd`,e.HeaderGroupAlreadyExists=`HeaderGroupAlreadyExists`,e.UnknownHeaderGroup=`UnknownHeaderGroup`,e.UnknownDataValidationRule=`UnknownDataValidationRule`,e.UnknownDataValidationCriterionType=`UnknownDataValidationCriterionType`,e.InvalidDataValidationCriterionValue=`InvalidDataValidationCriterionValue`,e.InvalidNumberOfCriterionValues=`InvalidNumberOfCriterionValues`,e.InvalidCopyPasteSelection=`InvalidCopyPasteSelection`,e.NoChanges=`NoChanges`,e.InvalidInputId=`InvalidInputId`,e.SheetIsHidden=`SheetIsHidden`,e.InvalidTableResize=`InvalidTableResize`,e.PivotIdNotFound=`PivotIdNotFound`,e.PivotInError=`PivotInError`,e.EmptyName=`EmptyName`,e.ValueCellIsInvalidFormula=`ValueCellIsInvalidFormula`,e.InvalidDefinition=`InvalidDefinition`,e.InvalidColor=`InvalidColor`,e.InvalidPivotDataSet=`InvalidPivotDataSet`,e.InvalidPivotCustomField=`InvalidPivotCustomField`,e.MissingFigureArguments=`MissingFigureArguments`,e.InvalidCarouselItem=`InvalidCarouselItem`,e}({}),Mr=new Set([`containsText`,`notContainsText`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`beginsWithText`,`endsWithText`,`isNotEmpty`,`isEmpty`,`isNotEqual`,`isEqual`,`customFormula`]),Nr=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`]),Pr=[{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:`;`}],D=Pr[0],Fr=[`thin`,`medium`,`thick`,`dashed`,`dotted`];function Ir(e){return Array.isArray(e)&&Array.isArray(e[0])}let Lr={Background:0,Highlights:1,Clipboard:2,Chart:4,Autofill:5,Selection:6,Headers:100},Rr=Kt(()=>Object.keys(Lr).sort((e,t)=>Lr[e]-Lr[t]));function zr(e,t){if(Lr[e])throw Error(`Layer ${e} already exists`);Lr[e]=t}let Br=[`containsText`,`notContainsText`,`isEqualText`,`isEmpty`,`isNotEmpty`,`beginsWithText`,`endsWithText`],Vr=[`isEqual`,`isNotEqual`,`isGreaterThan`,`isGreaterOrEqualTo`,`isLessThan`,`isLessOrEqualTo`,`isBetween`,`isNotBetween`,`isEmpty`,`isNotEmpty`],Hr=[`dateIs`,`dateIsBefore`,`dateIsOnOrBefore`,`dateIsAfter`,`dateIsOnOrAfter`,`dateIsBetween`,`dateIsNotBetween`,`isEmpty`,`isNotEmpty`];function Ur(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}let Wr=new g;function Gr(e,t){return e=Ur(e),{url:e,label:t||e,isExternal:!0,isUrlEditable:!0}}Wr.add(`sheet_URL`,{match:e=>Et(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){let n=Ot(e);return t.tryGetSheetName(n)||E(`Invalid sheet`)},open(e,t){let n=Ot(e);t.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:n}).isCancelledBecause(`SheetIsHidden`)&&t.notifyUser({type:`warning`,sticky:!1,text:E(`Cannot open the link because the linked sheet is hidden.`)})},sequence:0});let Kr={createLink:Gr,match:e=>St(e),open:e=>window.open(e,`_blank`),urlRepresentation:e=>e,sequence:0};function qr(e){return Wr.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||Kr}function Jr(e,t){return qr(e.url).urlRepresentation(e.url,t)}function Yr(e,t,n){qr(e.url).open(e.url,t,n)}function Xr(e){if(typeof e==`string`){if(xt(e)){let{label:t,url:n}=wt(e);return qr(n).createLink(n,t)}else if(St(e))return Gr(e)}}var O=class e{jsDate;constructor(e,t,n,r=0,i=0,a=0){this.jsDate=new Date(Date.UTC(e,t,n,r,i,a,0))}static fromTimestamp(t){let n=new Date(t);return new e(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds())}static now(){let t=new Date;return new e(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.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(){let e=new Date(this.jsDate.getTime()),t=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-t);let n=new Date(Date.UTC(e.getUTCFullYear(),0,1));return Math.ceil(((e.getTime()-n.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)}};let Zr=new O(1899,11,30),Qr=1440*60*1e3,$r=2e3,ei=O.now().getFullYear(),ti=O.now().getMonth(),ni=O.fromTimestamp(0).getTime()-Zr.getTime(),ri=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,ii=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,ai=Ut.join(``),oi=RegExp(`\/|-|${Ut.join(`|`)}`),si=RegExp(`^(\\d{1,4})[\/${ai}\-](\\d{1,4})([\/${ai}\-](\\d{1,4}))?$`),ci=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function li(e,t){switch(typeof e){case`number`:return e;case`string`:return ui(e,t)?fi(e,t)?.value:!e||isNaN(Number(e))?void 0:Number(e);default:return}}function ui(e,t){return fi(e,t)!==null}let di=new Map;function fi(e,t){return di.has(t)||di.set(t,new Map),di.get(t).has(e)||di.get(t).set(e,pi(e,t)),di.get(t).get(e)}function pi(e,t){e=e.trim();let n=null,r=e.match(ci);if(r){if(n=xi(r[0]),n===null)return null;e=e.replace(r[0],``).trim()}let i=null,a=mi(e,t);if(a){let t=a.dateString.match(oi)[0];if(i=gi(a,t),i===null)return null;e=e.replace(a.dateString,``).trim()}return e!==``||!(i||n)?null:i&&i.jsDate&&n&&n.jsDate?{value:i.value+n.value,format:i.format+` `+(n.format===`hhhh:mm:ss`?`hh:mm:ss`:n.format),jsDate:new O(i.jsDate.getFullYear()+n.jsDate.getFullYear()-1899,i.jsDate.getMonth()+n.jsDate.getMonth()-11,i.jsDate.getDate()+n.jsDate.getDate()-30,i.jsDate.getHours()+n.jsDate.getHours(),i.jsDate.getMinutes()+n.jsDate.getMinutes(),i.jsDate.getSeconds()+n.jsDate.getSeconds())}:i||n}function mi(e,t){let n=e.match(si);if(!n)return null;let[,r,i,,a]=n;if(r.length>2&&a&&a.length>2)return null;if(r.length>2)return{year:r,month:i,day:a,dateString:e,type:`ymd`};let o=hi(t);return a?a.length>2?o===`mdy`?{month:r,day:i,year:a,dateString:e,type:`mdy`}:{day:r,month:i,year:a,dateString:e,type:`dmy`}:o===`mdy`?{month:r,day:i,year:a,dateString:e,type:`mdy`}:o===`ymd`?{year:r,month:i,day:a,dateString:e,type:`ymd`}:o===`dmy`?{day:r,month:i,year:a,dateString:e,type:`dmy`}:null:i.length>2?{month:r,year:i,day:void 0,dateString:e,type:o}:o===`dmy`?{day:r,month:i,year:a,dateString:e,type:`dmy`}:{month:r,day:i,year:a,dateString:e,type:`mdy`}}function hi(e){switch(e.dateFormat[0]){case`d`:return`dmy`;case`m`:return`mdy`;case`y`:return`ymd`}throw Error(`Invalid date format in locale`)}function gi(e,t){let{year:n,month:r,day:i}=e,a=yi(r),o=bi(i),s=vi(n);if(s===null||a===null||o===null)return null;let c=r?.length===2&&a+1<10||i?.length===2&&o<10,l=n?.length!==2,u=new O(s,a,o);if(u.getMonth()!==a||u.getDate()!==o)return null;let d=u.getTime()-Zr.getTime(),f=_i(e,t,c,l);return{value:Math.round(d/Qr),format:f,jsDate:u}}function _i(e,t,n,r){let i=e.year?r?`yyyy`:`yy`:void 0,a=e.month?n?`mm`:`m`:void 0,o=e.day?n?`dd`:`d`:void 0;switch(e.type){case`mdy`:return[a,o,i].filter(C).join(t);case`ymd`:return[i,a,o].filter(C).join(t);case`dmy`:return[o,a,i].filter(C).join(t)}}function vi(e){if(!e)return ei;let t=Number(e);switch(e.length){case 1:return $r+t;case 2:return $r+($r+t>ei+10?-100:0)+t;case 3:case 4:return t}return null}function yi(e){if(!e)return ti;let t=Number(e);return t>=1&&t<=12?t-1:null}function bi(e){if(!e)return 1;let t=Number(e);return t>=0&&t<=31?t:null}function xi(e){if(e=e.trim(),ci.test(e)){let t=/AM/i.test(e),n=/PM/i.test(e),r=(t||n?e.substring(0,e.length-2).trim():e).split(/:/),i=r.length>=2,a=r.length===3,o=Number(r[0]),s=i?Number(r[1]):0,c=a?Number(r[2]):0,l=a?`hh:mm:ss`:`hh:mm`;if(t||n)l+=` a`;else if(!i)return null;o>=12&&t?o-=12:o<12&&n&&(o+=12),s+=Math.floor(c/60),c%=60,o+=Math.floor(s/60),s%=60,o>=24&&(l=`hhhh:mm:ss`);let u=new O(1899,11,30,o,s,c);return{value:o/24+s/1440+c/86400,format:l,jsDate:u}}return null}function Si(e){let t=Math.trunc(e),n=O.fromTimestamp(t*Qr-ni),r=e-t;r=r<0?1+r:r;let i=Math.round(r*24),a=Math.round((r-i/24)*24*60),o=Math.round((r-i/24-a/24/60)*24*60*60);return n.setHours(i),n.setMinutes(a),n.setSeconds(o),n}function Ci(e){return Math.round(wi(e))}function wi(e){return(e.getTime()-Zr.getTime())/Qr}function Ti(e){return new O(e.getFullYear(),e.getMonth()+1,0).getDate()}function Ei(e){return Ti(e)===e.getDate()}function Di(e,t,n){let r=e.getFullYear(),i=e.getMonth(),a=e.getDate(),o=new O(r,i+t,1);return n&&a===Ti(e)||a>Ti(o)?o.setDate(Ti(o)):o.setDate(a),o}function Oi(e){let t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function ki(e,t,n){if(e===t)return 0;if(e>t){let n=t;t=e,e=n}let r=Si(e),i=Si(t),a=r.getDate(),o=i.getDate(),s=r.getMonth(),c=i.getMonth(),l=r.getFullYear(),u=i.getFullYear(),d=0,f=0;switch(n){case 0:a===31&&(a=30),a===30&&o===31&&(o=30),s===1&&a===(Oi(l)?29:28)&&(a=30,c===1&&o===(Oi(u)?29:28)&&(o=30)),d=l+(s*30+a)/360,f=u+(c*30+o)/360;break;case 1:let n=365,r=l===u,i=l+1===u;if(!r&&!i||!r&&s<c||!r&&s===c&&a<o){let e=0,t=0;for(let n=l;n<=u;n++)e++,t+=Oi(n)?366:365;n=t/e}else r?Oi(l)&&(n=366):(Oi(l)&&s<2&&(n=366),Oi(u)&&(c>1||c===1&&o===29)&&(n=366));d=e/n,f=t/n;break;case 2:d=e/360,f=t/360;break;case 3:d=e/365,f=t/365;break;case 4:a===31&&(a=30),o===31&&(o=30),d=l+(s*30+a)/360,f=u+(c*30+o)/360;break}return f-d}function Ai(e,t){let n=(t.getFullYear()-e.getFullYear())*12+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?n-1:n}function ji(e,t){let n=e.getTime(),r=t.getTime();return Math.floor((r-n)/Qr)}function Mi(e,t){let n=t.getFullYear()-e.getFullYear(),r=e.getMonth(),i=t.getMonth(),a=e.getDate(),o=t.getDate();return i>r||i===r&&o>=a?n:n-1}function Ni(e,t){return ki(e,t,1)<1}function Pi(e,t){return Math.trunc(e)===Math.trunc(t)}function Fi(e,t,n){return t>n?Fi(e,n,t):(e=Math.trunc(e),t=Math.trunc(t),n=Math.trunc(n),e>=t&&e<=n)}function Ii(e,t){return Math.trunc(e)<Math.trunc(t)}function Li(e,t){return Math.trunc(e)<=Math.trunc(t)}function Ri(e,t){return Math.trunc(e)>Math.trunc(t)}function zi(e,t){return Math.trunc(e)>=Math.trunc(t)}let Bi=Kt(function(e){return e=ut(e),RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:e(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),Vi=Kt(function(e){let t=ut(e.decimalSeparator),n=`(?:\\d+(?:${ut(e.thousandsSeparator||``)}\\d{3,})*(?:${t}\\d*)?)`,r=`(?:${t}\\d+)`,i=`(?:\\s*`+n+`|`+r+`)(?:e(?:\\+|-)?\\d+)?(?:\\s*%)?`,a=`(?:\\s*-)?`,o=`(?:\\s*[\\$€])?`,s=`^(?:(?:`+[a+o+i,a+i+o,o+a+i].join(`)|(?:`)+`))$`;return new RegExp(s,`i`)});function Hi(e,t){return e?Vi(t).test(e.trim()):!1}let Ui=Kt(function(e){return RegExp(`[\$€${ut(e.thousandsSeparator||``)}]`,`g`)});function Wi(e,t){e=e.replace(Ui(t),``),t.decimalSeparator!==`.`&&(e=e.replace(t.decimalSeparator,`.`));let n=Number(e);return isNaN(n)&&e.includes(`%`)&&(n=Number(e.split(`%`)[0]),!isNaN(n))?n/100:n}function Gi(e,t,n){let r=[...e].sort((e,t)=>e-t),i=(r.length+(n?-1:1))*t;if(n||i--,Number.isInteger(i))return r[i];let a=Math.ceil(i),o=Math.floor(i);return r[a]*(i-o)+r[o]*(a-i)}let k={NotAvailable:`#N/A`,InvalidReference:`#REF`,BadExpression:`#BAD_EXPR`,CircularDependency:`#CYCLE`,UnknownFunction:`#NAME?`,DivisionByZero:`#DIV/0!`,SpilledBlocked:`#SPILL!`,GenericError:`#ERROR`,NullError:`#NULL!`},Ki=new Set(Object.values(k));var A=class{message;value;constructor(e=E(`Error`),t=k.GenericError){this.message=e,this.value=t,this.message=e.toString()}},qi=class extends A{constructor(e=E(`Invalid expression`)){super(e,k.BadExpression)}},Ji=class extends A{constructor(e=E(`Circular reference`)){super(e,k.CircularDependency)}},Yi=class extends A{constructor(e=E(`Invalid reference`)){super(e,k.InvalidReference)}},Xi=class extends A{constructor(e=E(`Data not available`)){super(e,k.NotAvailable)}},Zi=class extends A{constructor(e=E(`Unknown function`)){super(e,k.UnknownFunction)}},Qi=class extends A{errorOriginPosition;constructor(e=E(`Spill range is not empty`),t){super(e,k.SpilledBlocked),this.errorOriginPosition=t}},$i=class extends A{constructor(e=E(`Division by zero`)){super(e,k.DivisionByZero)}};let ea=[`number`,`string`,`boolean`,`undefined`];function ta(e){if(e!==void 0)return Ir(e)?e[0][0]?.format:e.format}function j(e){return typeof e==`string`&&Ki.has(e)}function na(e){return{value:k.NotAvailable,message:E(`Did not find value '%s' in [[FUNCTION_NAME]] evaluation.`,N(e))}}let ra=e=>E(`The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.`,e),ia=(e,t,n)=>E(`The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.`,e.toString(),t.toString(),n.toString()),aa=(e,t)=>E(`The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.`,t,e.map(e=>`'${e}'`).join(`, `));function M(e,t){let n=ma(e);switch(typeof n){case`number`:return n;case`boolean`:return+!!n;case`string`:if(Hi(n,t)||n===``)return Wi(n,t);let e=fi(n,t);if(e)return e.value;throw new A(ra(n));default:return 0}}function oa(e,t){try{return M(e,t)}catch{return}}function sa(e,t){return I(e).map(e=>e.map(e=>{if(typeof e.value!=`number`){let n=``;throw typeof e==`object`?n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got an empty value.`,t):typeof e==`string`?n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got a string.`,t):typeof e==`boolean`&&(n=E(`Function [[FUNCTION_NAME]] expects number values for %s, but got a boolean.`,t)),new A(n)}return e.value}))}function ca(e,t){let n=ma(e);if(n===``)throw new A(ra(n));return M(n,t)}function la(e,t){return Math.trunc(M(e,t))}function ua(e,t){return Math.trunc(ca(e,t))}function N(e){let t=ma(e);switch(typeof t){case`string`:return t;case`number`:return t.toString();case`boolean`:return t?`TRUE`:`FALSE`;default:return``}}let da=Kt(function(e){return e.toLowerCase().normalize(`NFD`).replace(/[\u0300-\u036f]/g,``)}),fa=e=>E(`The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a boolean.`,e);function P(e){let t=ma(e);switch(typeof t){case`boolean`:return t;case`string`:if(t){let e=t.toUpperCase();if(e===`TRUE`)return!0;if(e===`FALSE`)return!1;throw new A(fa(t))}else return!1;case`number`:return!!t;default:return!1}}function pa(e){let t=ma(e);if(t===``)throw new A(fa(t));return P(t)}function F(e,t){return Si(M(ma(e),t))}function ma(e){if(typeof e==`object`&&e&&`value`in e){if(j(e.value))throw e;return e.value}if(j(e))throw new A(``,e);return e}function ha(e,t,n){for(let r of e)if(Ir(r)){let e=r.length,n=r[0].length;for(let i=0;i<n;i++)for(let n=0;n<e;n++)t(r[n][i])}else n(r)}function ga(e,t){ha(e,e=>{if(j(e.value))throw e;t(e)},e=>{if(j(e?.value))throw e;t(e)})}function _a(e,t,n){ha(e,e=>{if(typeof e?.value==`number`&&t(e),j(e?.value))throw e},e=>{t({value:ca(e,n),format:e?.format})})}function va(e,t,n,r,i=`rowFirst`){let a=r;for(let r of e)if(Ir(r)){let e=r.length,n=r[0].length;if(i===`rowFirst`)for(let i=0;i<n;i++)for(let n=0;n<e;n++)a=t(a,r[n][i]);else for(let i=0;i<e;i++)for(let e=0;e<n;e++)a=t(a,r[i][e])}else a=n(a,r);return a}function ya(e,t,n,r=`rowFirst`){return va(e,t,t,n,r)}function ba(e,t,n,r){return va(e,(e,n)=>{let r=n?.value;if(typeof r==`number`)return t(e,r);if(j(r))throw n;return e},(e,n)=>t(e,ca(n,r)),n)}function xa(e,t,n,r){return va(e,(e,n)=>{let i=n?.value;if(i!=null){if(typeof i==`number`)return t(e,i);if(typeof i==`boolean`)return t(e,M(i,r));if(j(i))throw n;return t(e,0)}return e},(e,n)=>t(e,M(n,r)),n)}function Sa(e,t,n){let r=Array(e);for(let i=0;i<e;i++){r[i]=Array(t);for(let e=0;e<t;e++)r[i][e]=n(i,e)}return r}function Ca(e,t){return e.length===0?[]:Sa(e.length,e[0].length,(n,r)=>t(e[n][r]))}function wa(e,t){let n=e.length,r=e[0]?.length??0;for(let i=0;i<n;i++)for(let n=0;n<r;n++)t(e[i][n])}function Ta(e){return e.length?Sa(e[0].length,e.length,(t,n)=>e[n][t]):[]}function Ea(e,t,n=void 0){let r=1,i=1,a=1/0,o=1/0,s;for(let e=0;e<t.length;e++){let c=t[e];if(Ir(c)&&(n===void 0||n[e])){let n=c.length,l=c[0].length;n!==1||l!==1?(s??=Array(t.length),n!==1&&l!==1?(s[e]=`matrix`,r=Math.max(r,n),i=Math.max(i,l),a=Math.min(a,n),o=Math.min(o,l)):n===1?l!==1&&(s[e]=`vertical`,i=Math.max(i,l),o=Math.min(o,l)):(s[e]=`horizontal`,r=Math.max(r,n),a=Math.min(a,n))):t[e]=c[0][0]}}if(r===1&&i===1)return e(...t);let c=(e,n)=>t.map((t,r)=>{switch(s?.[r]){case`matrix`:return t[e][n];case`horizontal`:return t[e][0];case`vertical`:return t[0][n];case void 0:return t}});return Sa(r,i,(t,n)=>{if(t>a-1||n>o-1)return new Xi(E(`Array arguments to [[FUNCTION_NAME]] are of different size.`));let r=e(...c(t,n));return Ir(r)?r[0][0]:r})}function Da(e,t,n){for(let r of e)if(Ir(r)){let e=r.length,n=r[0].length;for(let i=0;i<n;i++)for(let n=0;n<e;n++)if(!t(r[n][i]??void 0))return}else if(!n(r))return}function Oa(e,t){return Da(e,e=>{let n=e?.value;if(typeof n==`boolean`)return t(n);if(typeof n==`number`)return t(!!n);if(j(n))throw e;return!0},e=>e!==void 0&&e.value!==null?t(pa(e)):!0)}function ka(e,t){let n,r,i=e.substring(0,2);return i===`<=`||i===`>=`||i===`<>`?(n=i,r=e.substring(2)):(i=e.substring(0,1),i===`<`||i===`>`||i===`=`?(n=i,r=e.substring(1)):(n=`=`,r=e)),Hi(r,t)||ui(r,t)?r=M(r,t):(r===`TRUE`||r===`FALSE`)&&(r=P(r)),{operator:n,operand:r}}let Aa=Kt(function(e){if(e===`*`)return/.+/;let t=``,n=``;for(let r of e)r===`?`&&n!==`~`?t+=`.`:r===`*`&&n!==`~`?t+=`.*`:((r===`*`||r===`?`)&&(t=t.slice(0,-1)),[`^`,`.`,`[`,`]`,`$`,`(`,`)`,`*`,`+`,`?`,`|`,`{`,`}`,`\\`].includes(r)&&(t+=`\\`),t+=r),n=r;return RegExp(`^`+t+`$`,`i`)});function ja(e=``,t,n){let{operator:r,operand:i}=t;if(i===void 0||e===null||i===null)return!1;if(typeof i==`number`&&r===`=`)return typeof e==`string`&&(Hi(e,n)||ui(e,n))?M(e,n)===i:e===i;if(r===`<>`||r===`=`){let t;return t=typeof e==typeof i?e===``&&i===``?!0:typeof e==`string`&&typeof i==`string`?Aa(i).test(e):e===i:!1,r===`=`?t:!t}if(typeof e==typeof i)switch(r){case`<`:return e<i;case`>`:return e>i;case`<=`:return e<=i;case`>=`:return e>=i}return!1}function Ma(e,t,n,r=!1){let i=e.length;if(i%2==1)throw new A(E(`Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs.`));let a=I(e[0]),o=a.length,s=a[0].length,c=[];for(let t=0;t<i-1;t+=2){let i=I(e[t]);if(i.length!==o||i[0].length!==s)throw new A(E(`Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension`));let a=ka(N(e[t+1]),n);r&&typeof a.operand==`string`&&(a.operand+=`*`),c.push(a)}for(let r=0;r<o;r++)for(let a=0;a<s;a++){let o=!0;for(let t=0;t<i-1;t+=2){let i=I(e[t])[r][a].value,s=c[t/2];if(o=ja(i??void 0,s,n),!o)break}o&&t(r,a)}}function Na(e,t,n,r,i,a){if(t===void 0||t.value===null)return-1;if(j(t.value))throw t;let o=Ia(t.value),s=typeof o,c,l,u=0,d=i-1,f,p,m,h,g=r===`desc`?t=>Ia(a(e,i-t-1)):t=>Ia(a(e,t));for(;d-u>=0;){for(f=Math.floor((u+d)/2),p=f,m=g(p),h=typeof m;u<p&&s!==h;)p--,m=g(p),h=typeof m;if(h!==s||m==null){u=f+1;continue}n===`strict`&&m===o?(c=m,l=p):n===`nextSmaller`&&m<=o?(c==null||c<m||c===m&&l<p)&&(c=m,l=p):n===`nextGreater`&&m>=o&&(c===void 0||c>m||c===m&&l<p)&&(c=m,l=p),m>o||n===`strict`&&m===o?d=p-1:u=f+1}return l===void 0?-1:r===`desc`?i-l-1:l}function Pa(e,t,n,r,i,a,o=!1){if(t===void 0||t.value===null)return-1;if(j(t.value))throw t;let s=Ia(t.value),c=o?(e,t)=>Ia(i(e,r-t-1)):(e,t)=>Ia(i(e,t)),l=n!==`wildcard`||typeof s!=`string`||!(s.includes(`*`)||s.includes(`?`));if(a&&l){let t=o?`reverseSearch`:`forwardSearch`,i=a[t].get(e);if(i===void 0){i=new Map;for(let t=0;t<r;t++){let n=c(e,t)??null;i.has(n)||i.set(n,t)}a[t].set(e,i)}if(i.has(s)){let e=i.get(s);return o?r-e-1:e}if(n===`strict`||n===`wildcard`)return-1}let u=Fa(e,s,n,r,c);return o&&u!==-1?r-u-1:u}function Fa(e,t,n,r,i){let a=n=>i(e,n)===t;if(n===`wildcard`&&typeof t==`string`&&(t.includes(`*`)||t.includes(`?`))){let n=Aa(t);a=t=>{let r=i(e,t);return typeof r==`string`?n.test(r):!1}}let o,s=-1;n===`nextSmaller`&&(a=n=>{let r=i(e,n);return(!o&&La(t,r)>=0||La(t,r)>=0&&La(r,o)>0)&&(o=r,s=n),r===t}),n===`nextGreater`&&(a=n=>{let r=i(e,n);return(!o&&La(t,r)<=0||La(t,r)<=0&&La(r,o)<0)&&(o=r,s=n),r===t});for(let e=0;e<r;e++)if(a(e))return e;return s}function Ia(e){return typeof e==`string`?da(e):e}function La(e,t){let n=ea.indexOf(typeof e)-ea.indexOf(typeof t);return n===0&&(typeof e==`string`&&typeof t==`string`?n=e.localeCompare(t):typeof e==`number`&&typeof t==`number`?n=e-t:typeof e==`boolean`&&typeof t==`boolean`&&(n=Number(e)-Number(t))),n}function I(e){return e===void 0?[[]]:Ir(e)?e:[[e]]}function Ra(e,t){return ya(e,(e,n)=>(e.push(t(n)),e),[],`rowFirst`)}function za(e){if(e===void 0)return!1;let{value:t}=e;return!(t===null||t===``)}let Ba=E(`[[FUNCTION_NAME]] has no valid input data.`);function Va(e){return E(`[[FUNCTION_NAME]] expects the provided values of %(argName)s to be a non-empty matrix.`,{argName:e})}function Ha(e){let t=new tn(e),n=[],r=[];for(n.push(r);!t.isOver();){if(t.current===`;`){r=[],n.push(r),t.shift();continue}let e=Xa(t)||Ua(t)||Ga(t)||Ka(t)||Ja(t)||Ya(t)||Qa(t)||qa(t)||$a(t);if(!e)throw Error(`Unknown token at `+t.remaining());r.push(e)}return n}function Ua(e){let t;if(e.current===`"`?(e.shift(),t=`"`):e.currentStartsWith(`[$`)&&(e.advanceBy(2),t=`]`),!t)return null;let n=``;for(;e.current&&e.current!==t;)n+=e.shift();if(e.current===t)e.shift();else throw Error(`Unterminated string in format`);return{type:`STRING`,value:n}}let Wa=new Set(`$+-/():!^&~{}<>= `);function Ga(e){if(e.current===`\\`){e.shift();let t=e.shift();if(!t)throw Error(`Unexpected end of format string`);return{type:`CHAR`,value:t}}return Wa.has(e.current)?{type:`CHAR`,value:e.shift()}:null}function Ka(e){return e.current===`,`?(e.shift(),{type:`THOUSANDS_SEPARATOR`,value:`,`}):null}function qa(e){return e.current===`@`?(e.shift(),{type:`TEXT_PLACEHOLDER`,value:`@`}):null}function Ja(e){return e.current===`.`?(e.shift(),{type:`DECIMAL_POINT`,value:`.`}):null}function Ya(e){return e.current===`%`?(e.shift(),{type:`PERCENT`,value:`%`}):null}function Xa(e){if(e.current===`0`||e.current===`#`){let t=e.current;return e.shift(),{type:`DIGIT`,value:t}}return null}let Za=new Set(`dmqyhsa`);function Qa(e){if(!Za.has(e.current))return null;let t=e.current,n=``;for(;e.current===t;)n+=e.shift();return{type:`DATE_PART`,value:n}}function $a(e){if(e.current!==`*`)return null;e.shift();let t=e.shift();if(!t)throw Error(`Unexpected end of format string`);return{type:`REPEATED_CHAR`,value:t}}let eo={};function to(e){let t=eo[e];return t===void 0&&(t=no(e),eo[e]=t),t}function no(e){let t=Ha(e);for(let e of t){let t=e.filter(e=>e.type===`REPEATED_CHAR`);for(let e of t.slice(1))e.type=`CHAR`}let n=so(t[0])||oo(t[0])||co(t[0]);if(!n)throw Error(`Invalid first format part of: `+e);if(t.length>1&&n.type===`text`)throw Error(`The first format in a multi-part format must be a number format: `+e);let r=so(t[1])||oo(t[1]);if(t[1]?.length&&!r)throw Error(`Invalid second format part of: `+e);let i=so(t[2])||oo(t[2]);if(t[2]?.length&&!i)throw Error(`Invalid third format part of: `+e);let a=co(t[3]);if(t[3]?.length&&!a)throw Error(`Invalid fourth format part of: `+e);return{positive:n,negative:r,zero:i,text:a}}function ro(e){return e.every(e=>e.type===`DATE_PART`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function io(e){return e.every(e=>e.type===`DIGIT`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`PERCENT`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function ao(e){return e.every(e=>e.type===`STRING`||e.type===`TEXT_PLACEHOLDER`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function oo(e){if(!e||!io(e))return;let t=[],n,r=t,i=0,a=0,o=e.findLastIndex(e=>e.type===`DIGIT`),s=!1,c=0;for(let l=0;l<e.length;l++){let u=e[l];switch(u.type){case`DIGIT`:r===t?r.push(u):c<20&&(r.push(u),c++);break;case`DECIMAL_POINT`:if(r===t)n=[],r=n;else throw Error(`Multiple decimal points in a number format`);break;case`REPEATED_CHAR`:case`CHAR`:case`STRING`:r.push(u);break;case`PERCENT`:i++,r.push(u);break;case`THOUSANDS_SEPARATOR`:l-1===o?(a+=1,o++,r.push(u)):e[l+1]?.type===`DIGIT`&&e[l-1]?.type===`DIGIT`?(r===t&&(s=!0),r.push(u)):r.push({type:`CHAR`,value:`,`});break}}return{type:`number`,integerPart:t,decimalPart:n,percentSymbols:i,thousandsSeparator:s,magnitude:a}}function so(e){let t=e&&ro(e)?{type:`date`,tokens:e}:void 0;if(t){if(t.tokens.length&&t.tokens.every(e=>e.type===`DATE_PART`&&e.value===`a`))throw Error(`Invalid date format`);return{type:`date`,tokens:lo(t.tokens.map(e=>e.type===`THOUSANDS_SEPARATOR`||e.type===`DECIMAL_POINT`?{type:`CHAR`,value:e.value}:e))}}}function co(e){return e&&ao(e)?{type:`text`,tokens:e}:void 0}function lo(e){let t=e.filter(e=>e.type===`DATE_PART`);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}function uo(e){return[fo(e.positive),fo(e.negative),fo(e.zero),fo(e.text)].filter(C).join(`;`)}function fo(e){if(!e)return;let t=``,n=e.type===`number`?po(e):e.tokens;for(let e of n)switch(e.type){case`STRING`:t+=`[$${e.value}]`;break;case`CHAR`:t+=mo(e.value)?`\\${e.value}`:e.value;break;case`REPEATED_CHAR`:t+=`*`+e.value;break;case`DATE_PART`:t+=e.value===`MM`?`mm`:e.value;break;default:t+=e.value}return t}function po(e){let t=[...e.integerPart];return e.decimalPart&&(t.push({type:`DECIMAL_POINT`,value:`.`}),t.push(...e.decimalPart)),t}function mo(e){return!Wa.has(e)}let ho=`REPEATED_CHAR_PLACEHOLDER_`,go={0:E(`January`),1:E(`February`),2:E(`March`),3:E(`April`),4:E(`May`),5:E(`June`),6:E(`July`),7:E(`August`),8:E(`September`),9:E(`October`),10:E(`November`),11:E(`December`)},_o={0:E(`Sunday`),1:E(`Monday`),2:E(`Tuesday`),3:E(`Wednesday`),4:E(`Thursday`),5:E(`Friday`),6:E(`Saturday`)};function vo(e,t,n,r=!1){return r?Wo({value:e,format:t},n):L(e,{format:t,locale:n})}function L(e,{format:t,locale:n,formatWidth:r}){switch(typeof e==`boolean`&&(e=e?`TRUE`:`FALSE`),typeof e){case`string`:{if(e.includes(`\\"`)&&(e=e.replaceAll(/\\"/g,`"`)),!t)return e;let n=to(t),i=n.text||n.positive;return!i||i.type!==`text`?e:yo(e,i,r)}case`number`:t||=Fo(e);let i=to(t);if(i.positive.type===`text`)return yo(e.toString(),i.positive,r);let a=i.positive;if(e<0&&i.negative?(a=i.negative,e=-e):e===0&&i.zero&&(a=i.zero),a.type===`date`)return bo(Mo(e,a),r);let o=e<0,s=bo(xo(Math.abs(e),a,n),r);return o?`-`+s:s;case`object`:return``}}function yo(e,t,n){let r=``;for(let n of t.tokens)switch(n.type){case`TEXT_PLACEHOLDER`:r+=e;break;case`CHAR`:case`STRING`:r+=n.value;break;case`REPEATED_CHAR`:r+=ho+n.value;break}return bo(r,n)}function bo(e,t){let n=e.indexOf(ho);if(n===-1)return e;let r=e.slice(0,n),i=e.slice(n+26+1),a=e[n+26];function o(){if(!t)return{timesToRepeat:0,padding:``};let e=t.measureText(r+i),n=t.measureText(a),o=t.availableWidth-e;if(o<=0)return{timesToRepeat:0,padding:``};let s=Math.floor(o/n),c=o-s*n,l=t.measureText(` `);return{timesToRepeat:s,padding:` `.repeat(Math.floor(c/l))}}let{timesToRepeat:s,padding:c}=o();return r+a.repeat(s)+c+i}function xo(e,t,n){if(e===1/0)return`∞`+(t.percentSymbols?`%`:``);let r=t.percentSymbols*2-t.magnitude*3;e*=10**r;let i=0;t.decimalPart!==void 0&&(i=t.decimalPart.filter(e=>e.type===`DIGIT`).length);let{integerDigits:a,decimalDigits:o}=To(Math.abs(e),i),s=So(a,t,t.thousandsSeparator?n.thousandsSeparator:void 0);return t.decimalPart!==void 0&&(s+=n.decimalSeparator+Co(o||``,t)),s}function So(e,t,n){let r=t.integerPart;r.some(e=>e.type===`DIGIT`)||(r=[...r,{type:`DIGIT`,value:`#`}]),e===`0`&&(e=``);let i=``,a=r.findIndex(e=>e.type===`DIGIT`),o=e.length-1;function s(t,r){if(r===`0`&&(t||=`0`),!t)return;let a=e.length-1-o;i=n&&a>0&&a%3==0?t+n+i:t+i}for(let t=r.length-1;t>=0;t--){let n=r[t];switch(n.type){case`DIGIT`:let r=e[o];if(s(r,n.value),o--,a===t)for(;o>=0;)s(e[o],`0`),o--;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:i=ho+n.value+i;break;default:i=n.value+i;break}}return i}function Co(e,t){if(!t.decimalPart)return``;let n=``,r=0;for(let i of t.decimalPart)switch(i.type){case`DIGIT`:let t=i.value===`#`?e[r]||``:e[r]||`0`;n+=t,r++;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:n+=ho+i.value;break;default:n+=i.value;break}return n}let wo=[];function To(e,t=20){let n=e.toString();if(n.includes(`e`))return ko(e,t);if(Number.isInteger(e))return{integerDigits:n,decimalDigits:void 0};let r=n.indexOf(`.`),i=n.substring(0,r),a=n.substring(r+1);if(t===0)return Number(a[0])>=5&&(i=(Number(i)+1).toString()),{integerDigits:i,decimalDigits:void 0};if(a.length>t){let{integerDigits:e,decimalDigits:n}=Oo(a,t);a=n,e!==`0`&&(i=(Number(i)+Number(e)).toString())}return{integerDigits:i,decimalDigits:Eo(a||``)}}function Eo(e){let t=e.length-1;for(;t>=0&&e[t]===`0`;)t--;return e.slice(0,t+1)||void 0}let Do=/^0+/;function Oo(e,t){let n=`0`,r=e,i=e.slice(0,t);if(Number(e[t])<5)return{integerDigits:n,decimalDigits:i};let a=i.match(Do)?.[0]||``,o=(Number(i)+1).toString(),s=i.slice(a.length),c=o.length>s.length;return c&&!a?(n=`1`,r=void 0):r=c?a.slice(0,-1)+o:a+o,{integerDigits:n,decimalDigits:r}}function ko(e,t=20){let n=wo[t];n||(n=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:t,useGrouping:!1}),wo[t]=n);let[r,i]=n.format(e).split(`.`);return{integerDigits:r,decimalDigits:i}}function Ao(e,t){let{integerDigits:n,decimalDigits:r}=To(e,20);return r?n+t+r:n}let jo=Kt(function(e){if(!e)return!1;try{return to(e).positive.type===`date`}catch{return!1}});function Mo(e,t){let n=Si(e);if(isNaN(n.getTime()))return e.toString();let r=t.tokens.some(e=>e.type===`DATE_PART`&&e.value===`a`),i=``;for(let e of t.tokens)switch(e.type){case`DATE_PART`:i+=No(n,e.value,r);break;case`REPEATED_CHAR`:i+=ho+e.value;break;default:i+=e.value;break}return i}function No(e,t,n){switch(t){case`d`:return e.getDate();case`dd`:return e.getDate().toString().padStart(2,`0`);case`ddd`:return _o[e.getDay()].slice(0,3);case`dddd`:return _o[e.getDay()].toString();case`m`:return e.getMonth()+1;case`mm`:return String(e.getMonth()+1).padStart(2,`0`);case`mmm`:return go[e.getMonth()].slice(0,3);case`mmmm`:return go[e.getMonth()].toString();case`mmmmm`:return go[e.getMonth()].slice(0,1);case`qq`:return E(`Q%(quarter)s`,{quarter:e.getQuarter()}).toString();case`qqqq`:return E(`Quarter %(quarter)s`,{quarter:e.getQuarter()}).toString();case`yy`:let r=String(e.getFullYear()).replace(`-`,``).padStart(2,`0`);return r.slice(r.length-2);case`yyyy`:return String(e.getFullYear()).replace(`-`,``).padStart(4,`0`);case`hhhh`:return Math.floor((e.getTime()-Zr.getTime())/(3600*1e3)).toString();case`hh`:let i=e.getHours();return n&&(i=i===0?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 Error(`invalid date format token: ${t}`)}}let Po=Kt(function(e){return RegExp(`[0-9]+${ut(e.decimalSeparator)}[0-9]`)});function Fo(e){let{integerDigits:t,decimalDigits:n}=To(e);if(!n)return`0`;let r=t.replace(`-`,``).length;if(r+2>11)return`0`;let i=11-r-1;return{decimalDigits:n}=To(e,Math.min(i,n.length)),n?`0.`+`0`.repeat(n.length):`0`}function Io(e,t){if(ui(e,t))return fi(e,t).format}function Lo(e){let t=e.includes(`.`)?`0.00`:`0`,n=e.match(/[\$€]/);if(n){let r=e.match(/[\d]/),i=`[$`+n.values().next().value+`]`;return r.index<n.index?`#,##`+t+i:i+`#,##`+t}if(e.includes(`%`))return t+`%`}function Ro(e){let t=e.decimalPlaces??2,n=e.position??`before`,r=e.code??``,i=e.symbol??``,a=`#,##0`+(t?`.`+`0`.repeat(t):``),o=`${r} ${i}`.trim();return n===`after`&&r&&(o=` `+o),Vo(o,n,a)}function zo(e){let t=e.decimalPlaces??2,n=e.position??`before`,r=e.code??``,i=e.symbol??``,a=`#,##0`+(t?`.`+`0`.repeat(t):``),o=`${r} ${i}`.trim();return n===`after`&&r&&(o=` `+o),[Bo(o,n,` ${a} `),Bo(o,n,`(${a})`),Bo(o,n,` - `)].join(`;`)}function Bo(e,t,n){let r=`[$${e}]`;return t===`before`?r+`* `+n:n+`* `+r}function Vo(e,t,n){let r=`[$${e}]`;return t===`before`?r+n:n+r}function Ho(e){let t=to(e);return uo({positive:Uo(t.positive),negative:t.negative?Uo(t.negative):void 0,zero:t.zero?Uo(t.zero):void 0,text:t.text})}function Uo(e){if(e.type!==`number`||!e.decimalPart)return e;let t=e.decimalPart.filter(e=>e.type!==`DIGIT`);return{...e,decimalPart:void 0,integerPart:[...e.integerPart,...t]}}function Wo({value:e,format:t},n){let r=oa(e,n);if(r===void 0)return``;let i=t;if(Math.abs(r)<1e3){let e=r%1!=0;i=!t&&e?`0.####`:t}else i=Go({value:e,format:t},void 0,n);return L(e,{format:i,locale:n})}function Go(e,t,n){let r=0;try{r=Math.abs(M(e?.value,n))}catch{return``}let i=e?.format;if(t!==void 0)switch(t?.value){case`k`:return Ko(i,1,`k`,n);case`m`:return Ko(i,2,`m`,n);case`b`:return Ko(i,3,`b`,n);default:throw new A(E(`The formatting unit should be 'k', 'm' or 'b'.`))}return r<1e5?Ko(i,0,``,n):r<1e8?Ko(i,1,`k`,n):r<1e11?Ko(i,2,`m`,n):Ko(i,3,`b`,n)}function Ko(e,t,n,r){let i=to(e||`#,##0`);return uo({positive:qo(i.positive,t,n),negative:i.negative?qo(i.negative,t,n):void 0,zero:i.zero?qo(i.zero,t,n):void 0,text:i.text})}function qo(e,t,n){if(e.type!==`number`)return e;let r=Uo(e),i={type:`STRING`,value:n},a=[...r.integerPart],o=a.findLastIndex(e=>e.type===`DIGIT`);if(o===-1)throw Error(`Cannot create a large number format from a format with no digit.`);for(;a[o+1]?.type===`THOUSANDS_SEPARATOR`;)a=qt(a,[o+1]);let s=a[o+1];a=s?.type===`STRING`&&[`m`,`k`,`b`].includes(s.value)?Yt(a,i,o+1):Jt(a,[i],o+1),t>0&&(a=Jt(a,Array(t).fill({type:`THOUSANDS_SEPARATOR`,value:`,`}),o+1));let c=r.percentSymbols-a.filter(e=>e.type===`PERCENT`).length;return a.push(...Array(c).fill({type:`PERCENT`,value:`%`})),{...r,integerPart:a,magnitude:t}}function Jo(e,t){let n=to(e);return uo(to(uo({positive:Yo(n.positive,t),negative:n.negative?Yo(n.negative,t):void 0,zero:n.zero?Yo(n.zero,t):void 0,text:n.text})))}function Yo(e,t){return e.type===`number`?t>0?Zo(e,t):Xo(e,Math.abs(t)):e}function Xo(e,t){let n=e.decimalPart;if(!n)return e;let r=[],i=0;for(let e=n.length-1;e>=0&&!(i>=Math.abs(t));e--)n[e].type===`DIGIT`&&(i++,r.push(e));return n=qt(n,r),n.some(e=>e.type===`DIGIT`)?{...e,decimalPart:n}:{...e,decimalPart:void 0,integerPart:[...e.integerPart,...n]}}function Zo(e,t){let n=e.integerPart,r=e.decimalPart;if(!r){let e=n.findLastIndex(e=>e.type===`DIGIT`);r=n.slice(e+1),n=n.slice(0,e+1)}let i=S(0,t).map(()=>({type:`DIGIT`,value:`0`})),a=r.findLastIndex(e=>e.type===`DIGIT`);return r=a===-1?[...i,...r]:Jt(r,i,a+1),{...e,decimalPart:r,integerPart:n}}function Qo(e){let t=to(e);for(let e of[t.positive,t.negative,t.zero])if(e&&e.type===`date`&&e.tokens.some(e=>e.type===`DATE_PART`&&e.value.includes(`q`)))return!1;return!0}function $o(e){if(!e)return!1;try{return to(e).positive.type===`text`}catch{return!1}}function es(e,t,n){return ns({value:$o(t.format)&&e.parsedValue!==null?e.content:e.parsedValue,format:t.format,origin:n},t.locale)}function ts(e,t){if(e.startsWith(`=`))throw Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);if(e===``)return null;if(e.includes(`
5
- `))return e;if(Hi(e,D))return Wi(e,D);let n=fi(e,t);return n?n.value:vt(e)?e.toUpperCase()===`TRUE`:e}function ns(e,t=D,n,r){let i=Xr(e.value);if(!i)return us(rs(e,t,n),e.origin??r);let a=ts(i.label,t);return us({...rs({value:a,format:e.format||(typeof a==`number`?Io(i.label,t)||Lo(i.label):void 0)},t,n),link:i},e.origin??r)}function rs(e,t,n){let{value:r,format:i,message:a,errorOriginPosition:o}=e;i=n?.format||i;let s=L(r,{format:i,locale:t});return j(r)?ls(r,a,o):r===null?os(i):$o(i)?is(N(r),i,s):typeof r==`number`?jo(i||``)?ss(r,i,s):as(r,i,s):typeof r==`boolean`?cs(r,i,s):is(r,i,s)}function is(e,t,n){return{value:e,format:t,formattedValue:n,type:`text`,isAutoSummable:!0,defaultAlign:`left`}}function as(e,t,n){return{value:e||0,format:t,formattedValue:n,type:`number`,isAutoSummable:!0,defaultAlign:`right`}}let os=Kt(function(e){return{value:null,format:e,formattedValue:``,type:`empty`,isAutoSummable:!0,defaultAlign:`left`}});function ss(e,t,n){return{value:e,format:t,formattedValue:n,type:`number`,isAutoSummable:!1,defaultAlign:`right`}}function cs(e,t,n){return{value:e,format:t,formattedValue:n,type:`boolean`,isAutoSummable:!1,defaultAlign:`center`}}function ls(e,t,n){return{value:e,formattedValue:e,message:t,type:`error`,isAutoSummable:!1,defaultAlign:`center`,errorOriginPosition:n}}function us(e,t){return e.value===null||`origin`in e||(e.origin=t),e}function ds(e){let t=O.now();switch(e){case`today`:return Math.floor(wi(t));case`yesterday`:return t.setDate(t.getDate()-1),Math.floor(wi(t));case`tomorrow`:return t.setDate(t.getDate()+1),Math.floor(wi(t));case`lastWeek`:return t.setDate(t.getDate()-6),Math.floor(wi(t));case`lastMonth`:{let e=t.getMonth()===0?11:t.getMonth()-1,n=new O(t.getFullYear(),e,1);return t.getDate()>Ti(n)?t.setDate(1):(t.setDate(t.getDate()+1),t.setMonth(t.getMonth()-1)),Math.floor(wi(t))}case`lastYear`:return t.getMonth()===1&&t.getDate()===29?(t.setDate(28),t.setFullYear(t.getFullYear()-1)):(t.setDate(t.getDate()+1),t.setFullYear(t.getFullYear()-1)),Math.floor(wi(t))}}function fs(e,t){return`dateValue`in e&&e.dateValue!==`exactDate`?[ds(e.dateValue)]:e.values.map(e=>li(e,t))}function ps(e,t){return e.map(e=>{if(e.startsWith(`=`))return e;let n=ts(e,t);return typeof n==`number`?L(n,{format:t.dateFormat,locale:t}):``})}function ms(e,t=[]){if(e.length<=1&&t.length===0)return e;let n=[0],r=new Map([[0,[]]]);return hs(n,r,e,!1),hs(n,r,t,!0),bs(n,r)}function hs(e,t,n,r=!1){for(let i of n){let n=i.left,a=i.right===void 0?void 0:i.right+1,o=_s(e,t,n,!0,0),s=_s(e,t,a,!1,o);for(let n=o;n<=s;n++)vs(t.get(e[n]),i,r);ys(e,t,o,s)}}function gs(e,t,n){let r=n.left,i=n.right,a=xs(e,r,0),o=i===void 0?e.length-1:xs(e,i,a),s=n.top,c=n.bottom===void 0?void 0:n.bottom+1;for(let n=a;n<=o;n++){let r=t.get(e[n]),i=xs(r,s,0);if(i===-1||i%2!=0)return!1;let a=c===void 0?r.length:Ss(r,c,0);if(i+1!==a)return!1}return!0}function _s(e,t,n,r,i){if(n===void 0)return e.length-1;let a=xs(e,n,i);return n===e[a]?r?a:a-1:(e.splice(a+1,0,n),t.set(n,[...t.get(e[a])]),r?a+1:a)}function vs(e,t,n=!1){let r=t.top,i=t.bottom===void 0?void 0:t.bottom+1,a=[],o=xs(e,r,0,!1);if((o%2!=0&&!n||o%2==0&&n)&&a.push(r),i===void 0){e.splice(o+1),e.push(...a);return}let s=Ss(e,i,0,!1);(s%2==0&&!n||s%2!=0&&n)&&a.push(i);let c=s-o-1,l=a.length,u=o+1;u===e.length-1&&c===1&&l===1?e[u]=a[0]??a[1]:e.splice(u,c,...a)}function ys(e,t,n,r){let i=n-1==-1?0:n-1,a=r===e.length-1?r:r+1;for(let n=a;n>i;n--)Lt(t.get(e[n]),t.get(e[n-1]))&&(t.delete(e[n]),e.splice(n,1))}function bs(e,t){let n=[],r=[];for(let i=0;i<e.length;i++){let a=e[i],o=t.get(a);if(!o||o.length===0){n.push(...r),r=[];continue}let s=e[i+1];s!==void 0&&s--;let c=[];for(let e=0;e<o.length;e+=2){let t=o[e],n=o[e+1];n!==void 0&&n--;let i={top:t,left:a,bottom:n,right:s};(n===void 0&&t!==0||s===void 0&&a!==0)&&(i.hasHeader=!0);let l=!1;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.top===i.top&&t.bottom===i.bottom){t.right=i.right,r.splice(e,1),c.push(t),l=!0;break}}l||c.push(i)}n.push(...r),r=c}return n.push(...r),n}function xs(e,t,n=0,r=!0){let i=e.length-1,a=-1;for(;n<=i;){let o=n+(i-n>>1);if(e[o]===t&&r)return o;e[o]<t?(a=o,n=o+1):i=o-1}return a}function Ss(e,t,n=0,r=!0){let i=e.length-1,a=e.length;for(;n<=i;){let o=n+(i-n>>1);if(e[o]===t&&r)return o;e[o]>t?(a=o,i=o-1):n=o+1}return a}function Cs(e){let t=new tn(e);tr(t);let n=e.indexOf(`!`);n!==-1&&t.advanceBy(n+1);let r=nr(t),i=rr(t),a,o,s,c,l=!1,u=!1,d=!1;if(i===-1?(s=c=r-1,a=o=0,l=!0):r===-1?(a=o=i-1,s=c=0,u=!0):(s=c=r-1,a=o=i-1,d=!0),tr(t),t.current===`:`){t.advanceBy(1),tr(t);let e=nr(t),n=rr(t);n===-1?(c=e-1,l=!0):e===-1?(o=n-1,u=!0):(c=e-1,o=n-1,a=l?o:a,s=u?c:s,d=!0)}let f={top:a,left:s,bottom:l?void 0:o,right:u?void 0:c};return d&&=u||l,d&&(f.hasHeader=d),f}function ws(e){let t=Js(Cs(e)),n=t.bottom,r=t.right;if(n!==void 0&&n>9999998||r!==void 0&&r>er)throw Error(`Range string out of bounds: ${e}`);if(n===void 0&&r===void 0)throw Error(`Wrong zone xc. The zone cannot be at the same time a full column and a full row`);return t}function Ts(e){let t=ws(e);if(t.bottom===void 0||t.right===void 0)throw Error(`This does not support unbounded ranges`);return t}function Es(e){return Os(ws(e))}function Ds(e){try{return Es(e)}catch{return!1}}function Os(e){let{bottom:t,top:n,left:r,right:i}=e;return t!==void 0&&isNaN(t)||isNaN(n)||isNaN(r)||i!==void 0&&isNaN(i)?!1:ks(e)&&e.top>=0&&e.left>=0}function ks(e){return(e.bottom===void 0||e.bottom>=e.top&&e.bottom>=0)&&(e.right===void 0||e.right>=e.left&&e.right>=0)}function As(e){let{top:t,bottom:n,left:r,right:i}=e,a=`hasHeader`in e?e.hasHeader:!1,o=t===n&&r===i;if(n===void 0&&i!==void 0)return t===0&&!a?`${Yn(r)}:${Yn(i)}`:`${T(r,t)}:${Yn(i)}`;if(i===void 0&&n!==void 0)return r===0&&!a?`${t+1}:${n+1}`:`${T(r,t)}:${n+1}`;if(n!==void 0&&i!==void 0)return o?T(r,t):`${T(r,t)}:${T(i,n)}`;throw Error(`Bad zone format`)}function js(e,t,n,r,i){let a=t===`left`?`columns`:`rows`,o=r===`before`?n-1:n,s=e[t===`left`?`right`:`bottom`];return e[t]<=o&&s&&s>o?Ys(e,a,`RESIZE`,i):o<e[t]?Ys(e,a,`MOVE`,i):{...e}}function Ms(e,t,n,r,i){let a=t===`left`?`columns`:`rows`,o=r===`before`?n-1:n,s=t===`left`?`right`:`bottom`;return e[t]<=o&&e[s]>o?Ys(e,a,`RESIZE`,i):o<e[t]?Ys(e,a,`MOVE`,i):{...e}}function Ns(e,t,n){let r=t===`left`?`right`:`bottom`,i=e[t],a=e[r];for(let o of n.sort((e,t)=>t-e))e[t]>o&&(i--,a--),e[t]<o&&e[r]>=o&&a--;return{...e,[t]:i,[r]:a}}function Ps(e,t,n){let r=t===`left`?`right`:`bottom`,i=e[t],a=e[r],o=e[r];for(let r of n.sort((e,t)=>t-e))e[t]>r&&(i--,a!==void 0&&a--),o!==void 0&&a!==void 0&&e[t]<=r&&o>=r&&a--;if(!(a!==void 0&&i>a))return{...e,[t]:i,[r]:a}}function Fs(...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 Is(...e){return{top:Math.min(...e.map(e=>e.top)),left:Math.min(...e.map(e=>e.left)),bottom:e.some(e=>e.bottom===void 0)?void 0:Math.max(...e.map(e=>e.bottom)),right:e.some(e=>e.right===void 0)?void 0:Math.max(...e.map(e=>e.right))}}function Ls(e,t){if(zs(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:Math.min(e.bottom,t.bottom),right:Math.min(e.right,t.right)}}function Rs(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function zs(e,t){return!(e.bottom<t.top||t.bottom<e.top||e.right<t.left||t.right<e.left)}function Bs(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++)if(zs(e[t],e[n]))return!0;return!1}function Vs(e,t,n){let{left:r,right:i,top:a,bottom:o}=n;return e>=r&&e<=i&&t>=a&&t<=o}function Hs(e,t){return e.left>=t.left&&e.right<=t.right&&e.top>=t.top&&e.bottom<=t.bottom}function Us(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function Ws(e){let{numberOfCols:t,numberOfRows:n}=Us(e);return t===1||n===1}function Gs(e){let{top:t,left:n,bottom:r,right:i}=e;if(nc(e)===1)return[];let a={top:t+1,bottom:r,left:n,right:n};if(i===n)return[a];let o={top:t,bottom:r,left:n+1,right:i};return t===r?[o]:[a,o]}function Ks(e){let t=[],{left:n,right:r,top:i,bottom:a}=Js(e);for(let e of S(n,r+1))for(let n of S(i,a+1))t.push({col:e,row:n});return t}function qs(e,t){let n=[],{left:r,right:i,top:a,bottom:o}=Js(t);for(let t of S(r,i+1))for(let r of S(a,o+1))n.push({sheetId:e,col:t,row:r});return n}function Js(e){return e.right!==void 0&&e.left>e.right&&(e={...e,left:e.right,right:e.left}),e.bottom!==void 0&&e.top>e.bottom&&(e={...e,top:e.bottom,bottom:e.top}),e}function Ys(e,t,n,r){let i=t===`both`?r[0]:t===`columns`?r:0,a=t===`both`?r[1]:t===`rows`?r:0,o=`hasHeader`in e?e.hasHeader:!1,s;s=tc(e)&&!o?t!==`rows`:ec(e)&&!o?t!==`columns`:!0;let c={...e};return s&&n===`MOVE`&&(c.left+=i,c.top+=a),c.right!==void 0&&(c.right+=i),c.bottom!==void 0&&(c.bottom+=a),c}function Xs(e){return e.reverse().filter((e,t,n)=>t===n.findIndex(t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)).reverse()}function Zs(e){return e.reduce((e,t)=>{let n=e.length;for(let r=0;r<n;r++)if(zs(e[r],t))return e[r]=Fs(e[r],t),e;return e[n]=t,e},[])}function Qs(e,t){let n,r,{left:i,right:a,top:o,bottom:s}=e,{left:c,right:l,top:u,bottom:d}=t;return n=c===i?l===a?c:l:c,r=u===o?d===s?u:d:u,{col:n,row:r}}function R(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function $s(e){return{...e,right:e.left,bottom:e.top}}function ec(e){return e.right===void 0}function tc(e){return e.bottom===void 0}function nc(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function rc(e,t,n){return e.left<t&&t<=e.right||e.top<n&&n<=e.bottom}function ic(e,t,n){return e.some(e=>rc(e,t,n))}function ac(e,t){let{left:n,top:r,bottom:i,right:a}=e;if(a!==void 0&&i!==void 0)return e;if(i===void 0&&a!==void 0)return{right:a,top:r,left:n,bottom:t.numberOfRows-1};if(a===void 0&&i!==void 0)return{bottom:i,left:n,top:r,right:t.numberOfCols-1};throw Error(`Bad zone format`)}function oc(e){return e.length<2?!0:ms(e).length===1}function sc(e){let t=new Set;for(let n of ms(e))for(let e of S(n.left,n.right+1))t.add(e);return t}function cc(e){let t=new Map;for(let n of e)for(let e=n.left;e<=n.right;e++){let r=t.get(e);r?(r.top=Math.min(r.top,n.top),r.bottom=Math.max(r.bottom,n.bottom)):t.set(e,{left:e,right:e,top:n.top,bottom:n.bottom})}return Array.from(t.values())}function lc(e){let t=new Set;for(let n of ms(e))for(let e of S(n.top,n.bottom+1))t.add(e);return t}function uc(e,t){return e.right+1===t.left||e.left===t.right+1?e.top<=t.bottom&&e.top>=t.top||t.top<=e.bottom&&t.top>=e.top:e.bottom+1===t.top||e.top===t.bottom+1?e.left<=t.right&&e.left>=t.left||t.left<=e.right&&t.left>=e.left:!1}function dc(e){let t=[...e],n=!0;for(;n;){n=!1;for(let e=0;e<t.length;e++){let r=t[e],i=t.findIndex((t,n)=>e!==n&&(uc(t,r)||zs(t,r)));if(i!==-1){t[e]=Fs(t[i],r),t.splice(i,1),n=!0;break}}}return t}let fc=new WeakMap,pc=new WeakMap;function mc(e,t){fc.has(t)||(fc.set(t,new Map),pc.set(t,0));let n=fc.get(t),r=_c(e);if(n.has(r)){let i=n.get(r);return t[i]=e,i}let i=pc.get(t)+1;return n.set(r,i),pc.set(t,i),t[i]=e,i}function hc(e){let t={};for(let n in e){let r=ms(e[n].map(R));for(let e of r)t[As(e)]=Number(n)}return t}function*gc(e,t){for(let n in t){let r=Ts(n),i=t[n];for(let t=r.top;t<=r.bottom;t++)for(let n=r.left;n<=r.right;n++)yield[{sheetId:e,col:n,row:t},i]}}function _c(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(typeof e!=`object`)return String(e);if(Array.isArray(e)){let t=e.length,n=`[`;for(let r=0;r<t;r++)r>0&&(n+=`,`),n+=_c(e[r]);return n+`]`}let t=Object.keys(e).sort(),n=`{`;for(let r of t)e[r]!==void 0&&(n+=`"${r}":${_c(e[r])},`);return n+=`}`,n}function vc(e){return 20+120*Math.exp(-.035*(e-1))}let yc=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,`i`),bc=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,`i`),xc=new RegExp(/^\$?([A-Z]{1,3})+$/,`i`),Sc=new RegExp(/^\$?([0-9]{1,7})+$/,`i`),Cc=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,`i`),wc=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,`i`),Tc=RegExp(`^\\s*('.+'!|[^']+!)?(`+[yc.source,`(\\$?[A-Z]{1,3})?\\$?[0-9]{1,7}\\s*:\\s*(\\$?[A-Z]{1,3})?\\$?[0-9]{1,7}\\s*`,`\\$?[A-Z]{1,3}(\\$?[0-9]{1,7})?\\s*:\\s*\\$?[A-Z]{1,3}(\\$?[0-9]{1,7})?\\s*`].join(`|`)+`)$`,`i`);function Ec(e){return Cc.test(e)}function Dc(e){return wc.test(e)}function Oc(e){return xc.test(e)}function kc(e){return Sc.test(e)}function Ac(e){return bc.test(e)}function jc(e){if(!e.includes(`!`))return{xc:e};let t=e.split(`!`),n=t.pop();return{sheetName:ft(t.join(`!`))||void 0,xc:n}}function Mc(e,t){return e===void 0?t:`${mt(e)}!${t}`}function Nc(e,t){let n=e.zone,r=ac(n,t(e.sheetId)),i=e.parts;return e.parts.length===1&&nc(r)>1?i=[e.parts[0],e.parts[0]]:e.parts.length===2&&nc(r)===1&&(i=[e.parts[0]]),{unboundedZone:n,zone:r,parts:i,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function Pc(e,t){let n=e.xc,{xc:r,sheetName:i}=jc(n),a=ws(r);return Nc({zone:a,parts:Hc(r,a),sheetId:e.sheetId,prefixSheet:!!i,invalidSheetName:e.invalidSheetName},t)}function Fc(e){let t={left:-1,top:-1,right:-1,bottom:-1};return{sheetId:``,zone:t,unboundedZone:t,parts:[],invalidXc:e,prefixSheet:!1}}function Ic(e){return tc(e.unboundedZone)}function Lc(e){return ec(e.unboundedZone)}function Rc(e,t,n,r={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||e.zone.left<0||e.zone.top<0)return k.InvalidReference;let i=e.sheetId!==t||e.invalidSheetName||e.prefixSheet,a=``;if(i&&(a=e.invalidSheetName?mt(e.invalidSheetName):mt(n(e.sheetId))),i&&!a)return k.InvalidReference;let o=$c(e,0,r);return e.parts&&e.parts.length===2&&(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)&&(o+=`:`,o+=$c(e,1,r)),`${i?a+`!`:``}${o}`}function zc(e,t,n){let r=n.sheetId===e?t:n.sheetId;return{...n,sheetId:r}}function Bc(e,t,n){if(!n)return;let r=e.getRangeFromSheetXC(t,n);return r.invalidSheetName||r.invalidXc?void 0:r}function Vc(e){let t=[];for(let n of e)for(let e of Ks(n.zone))t.push({...e,sheetId:n.sheetId});return t}function Hc(e,t){let n=e.split(`:`).map(e=>{let t=Dc(e);return{colFixed:t?!1:e.startsWith(`$`),rowFixed:t?e.startsWith(`$`):e.includes(`$`,1)}}),r=t.bottom===void 0,i=t.right===void 0;return r&&(n[0].rowFixed=n[0].rowFixed||n[1].rowFixed,n[1].rowFixed=n[0].rowFixed||n[1].rowFixed),i&&(n[0].colFixed=n[0].colFixed||n[1].colFixed,n[1].colFixed=n[0].colFixed||n[1].colFixed),n}function Uc(e){let t={left:e.col,top:e.row,right:e.col,bottom:e.row};return{sheetId:e.sheetId,zone:t}}function Wc(e){if(ks(e.zone))return e;let t={...e.unboundedZone},n={...e.zone},r=e.parts;if(t.right!==void 0&&t.right<t.left){let e=t.right;t.right=t.left,t.left=e,n.right=n.left,n.left=e,r=[{colFixed:r[1]?.colFixed||!1,rowFixed:r[0]?.rowFixed||!1},{colFixed:r[0]?.colFixed||!1,rowFixed:r[1]?.rowFixed||!1}]}if(t.bottom!==void 0&&t.bottom<t.top){let e=t.bottom;t.bottom=t.top,t.top=e,n.bottom=n.top,n.top=e,r=[{colFixed:r[0]?.colFixed||!1,rowFixed:r[1]?.rowFixed||!1},{colFixed:r[1]?.colFixed||!1,rowFixed:r[0]?.rowFixed||!1}]}return{unboundedZone:t,zone:n,parts:r,invalidXc:e.invalidXc,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function Gc(e){return Kc.get(e.type)?.(e)}let Kc=new class extends g{add(e,t){return super.add(e,t),this}get(e){return this.content[e]}};Kc.add(`REMOVE_COLUMNS_ROWS`,e=>({applyChange:qc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`ADD_COLUMNS_ROWS`,e=>({applyChange:Jc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`DELETE_SHEET`,e=>({applyChange:Yc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`RENAME_SHEET`,e=>({applyChange:Xc(e),sheetId:e.sheetId,sheetName:{old:e.oldName,current:e.newName}})).add(`MOVE_RANGES`,e=>({applyChange:Zc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}));function qc(e){let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`,i=[...e.elements];i.sort((e,t)=>t-e);let a=gt(i);return i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`,range:i};let o=i,s=`NONE`;for(let e of a){let a=en(e),c=$t(e);if(i.zone[t]<=a&&a<=i.zone[n]){let e=Math.min(i.zone[n],c)-a+1;s=`RESIZE`,o=Qc(o,r,s,-e)}else if(i.zone[t]>=a&&i.zone[n]<=c)s=`REMOVE`,o=Fc(k.InvalidReference);else if(i.zone[t]<=c&&i.zone[n]>=c){let e=c-i.zone[t]+1;s=`RESIZE`,o=Qc(o,r,s,-e),o=Qc(o,r,`MOVE`,-(i.zone[t]-a))}else a<i.zone[t]&&(s=`MOVE`,o=Qc(o,r,s,-(c-a+1)))}return{changeType:s,range:o}}}function Jc(e){let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`;return i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`,range:i};if(e.position===`after`){if(i.zone[t]<=e.base&&e.base<i.zone[n])return{changeType:`RESIZE`,range:Qc(i,r,`RESIZE`,e.quantity)};if(e.base<i.zone[t])return{changeType:`MOVE`,range:Qc(i,r,`MOVE`,e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[n])return{changeType:`RESIZE`,range:Qc(i,r,`RESIZE`,e.quantity)};if(e.base<=i.zone[t])return{changeType:`MOVE`,range:Qc(i,r,`MOVE`,e.quantity)}}return{changeType:`NONE`,range:i}}}function Yc(e){return t=>{if(t.sheetId!==e.sheetId&&t.invalidSheetName!==e.sheetName)return{changeType:`NONE`,range:t};let n=e.sheetName;return t={...Fc(k.InvalidReference),invalidSheetName:n},{changeType:`REMOVE`,range:t}}}function Xc(e){return t=>{if(t.sheetId===e.sheetId)return{changeType:`CHANGE`,range:t};if(e.newName&&t.invalidSheetName===e.newName){let n=e.sheetId;return{changeType:`CHANGE`,range:{...t,sheetId:n,invalidSheetName:void 0}}}if(e.oldName&&t.invalidSheetName===e.oldName){let n=e.sheetId;return{changeType:`CHANGE`,range:{...t,sheetId:n,invalidSheetName:void 0}}}return{changeType:`NONE`,range:t}}}function Zc(e){let t=e.target[0];return n=>{if(n.sheetId!==e.sheetId||!Hs(n.zone,t))return{changeType:`NONE`,range:n};let r=e.targetSheetId,i=Qc(n,`both`,`MOVE`,[e.col-t.left,e.row-t.top]),a=e.sheetId===r?i.prefixSheet:!0;return{changeType:`MOVE`,range:{...i,sheetId:r,prefixSheet:a}}}}function Qc(e,t,n,r){return{...e,unboundedZone:Ys(e.unboundedZone,t,n,r),zone:Ys(e.zone,t,n,r)}}function $c(e,t,n={useBoundedReference:!1,useFixedReference:!1}){let r=e.parts[t]?.colFixed||n.useFixedReference?`$`:``,i=Yn(t===0?e.zone.left:e.zone.right),a=e.parts[t]?.rowFixed||n.useFixedReference?`$`:``,o=String(t===0?e.zone.top+1:e.zone.bottom+1),s=``;return s=tc(e.unboundedZone)&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:r+i:ec(e.unboundedZone)&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:a+o:r+i+a+o,s}function el(e,t){e=e.toLocaleLowerCase(),t=t.toLocaleLowerCase();let n=0,r=0,i=t.length,a=0;for(let o=0;o<i;o++)t[o]===e[a]?(a++,r+=100+r-o/200):r=0,n+=r;return a===e.length?n:0}function tl(e,t,n){let r=[];return t.forEach(t=>{let i=el(e,n(t));i>0&&r.push({score:i,elem:t})}),r.sort((e,t)=>t.score-e.score),r.map(e=>e.elem)}function nl(e){let t=[];for(let n=0;n<e;n++)t.push({cells:{}});return t}function rl(e,t,n){return n.map(n=>n>=e?n+t:n)}function il(e,t){return e=[...e].sort((e,t)=>t-e),t.map(t=>{for(let n of e)if(t>n)t--;else if(t===n)return;return t}).filter(C)}function al(e,t=`Sheet`){let n=1,r=`${t}${n}`;for(;e.includes(r);)r=`${t}${n}`,n++;return r}function ol(e,t){let n=1,r=E(`Copy of %s`,e),i=r.toString();for(;t.includes(i);)i=`${r} (${n})`,n++;return i}let sl=Kt(function(e){return ft(e.trim().toUpperCase())});function cl(e,t){return e===void 0||t===void 0?!1:sl(e)===sl(t)}function ll(e,t=1){return t*(e+4)-4}function ul(e,t,n,r){if(!t||!t.isFormula&&!t.content)return 23;let i=``;try{if(!t.isFormula){let e={format:t.format,locale:n};i=L(ts(t.content,n),e)}}catch{i=k.GenericError}return dl(e,i,t.style,r)}function dl(e,t,n,r){let i=Cl(e,t,n,n?.wrapping===`wrap`?r-8:void 0).length;return ll(xl(n),i)+6}function fl(e,t=!1,n=!1){return`${n?`italic`:``} ${t?`bold`:``} ${e}px ${He}`}let pl={};function ml(e,t,n,r=`pt`){return hl(e,t,bl(n,r))}function hl(e,t,n){if(pl[n]||(pl[n]={}),pl[n][t]===void 0){let r=e.font;e.font=n,pl[n][t]=e.measureText(t).width,e.font=r}return pl[n][t]}let gl={};function _l(e,t,n,r=`pt`){let i=bl(n,r);e.save(),e.font=i;let a=vl(e,t);return e.restore(),a}function vl(e,t){let n=e.font;if(gl[n]||(gl[n]={}),gl[n][t]===void 0){let r=e.measureText(t),i=r.width,a=r.fontBoundingBoxAscent+r.fontBoundingBoxDescent;gl[n][t]={width:i,height:a}}return gl[n][t]}function yl(e){return Math.round(e*96/72)}function bl(e,t=`pt`){return`${e.italic?`italic `:``}${e.bold?`bold`:`400`} ${(t===`pt`?xl(e):e.fontSize)??Ve}px ${He}`}function xl(e){return yl(e?.fontSize||Ve)}function Sl(e,t,n,r){if(ml(e,t,r)<=n)return[t];let i=[],a=``;for(let o of t)ml(e,a+o,r)>n?(i.push(a),a=o):a+=o;return i.push(a),i}function Cl(e,t,n,r){n||={},xt(t)&&(t=wt(t).label);let i=[],a=t.includes(`
5
+ `))return e;if(Hi(e,D))return Wi(e,D);let n=fi(e,t);return n?n.value:vt(e)?e.toUpperCase()===`TRUE`:e}function ns(e,t=D,n,r){let i=Xr(e.value);if(!i)return us(rs(e,t,n),e.origin??r);let a=ts(i.label,t);return us({...rs({value:a,format:e.format||(typeof a==`number`?Io(i.label,t)||Lo(i.label):void 0)},t,n),link:i},e.origin??r)}function rs(e,t,n){let{value:r,format:i,message:a,errorOriginPosition:o}=e;i=n?.format||i;let s=L(r,{format:i,locale:t});return j(r)?ls(r,a,o):r===null?os(i):$o(i)?is(N(r),i,s):typeof r==`number`?jo(i||``)?ss(r,i,s):as(r,i,s):typeof r==`boolean`?cs(r,i,s):is(r,i,s)}function is(e,t,n){return{value:e,format:t,formattedValue:n,type:`text`,isAutoSummable:!0,defaultAlign:`left`}}function as(e,t,n){return{value:e||0,format:t,formattedValue:n,type:`number`,isAutoSummable:!0,defaultAlign:`right`}}let os=Kt(function(e){return{value:null,format:e,formattedValue:``,type:`empty`,isAutoSummable:!0,defaultAlign:`left`}});function ss(e,t,n){return{value:e,format:t,formattedValue:n,type:`number`,isAutoSummable:!1,defaultAlign:`right`}}function cs(e,t,n){return{value:e,format:t,formattedValue:n,type:`boolean`,isAutoSummable:!1,defaultAlign:`center`}}function ls(e,t,n){return{value:e,formattedValue:e,message:t,type:`error`,isAutoSummable:!1,defaultAlign:`center`,errorOriginPosition:n}}function us(e,t){return e.value===null||`origin`in e||(e.origin=t),e}function ds(e){let t=O.now();switch(e){case`today`:return Math.floor(wi(t));case`yesterday`:return t.setDate(t.getDate()-1),Math.floor(wi(t));case`tomorrow`:return t.setDate(t.getDate()+1),Math.floor(wi(t));case`lastWeek`:return t.setDate(t.getDate()-6),Math.floor(wi(t));case`lastMonth`:{let e=t.getMonth()===0?11:t.getMonth()-1,n=new O(t.getFullYear(),e,1);return t.getDate()>Ti(n)?t.setDate(1):(t.setDate(t.getDate()+1),t.setMonth(t.getMonth()-1)),Math.floor(wi(t))}case`lastYear`:return t.getMonth()===1&&t.getDate()===29?(t.setDate(28),t.setFullYear(t.getFullYear()-1)):(t.setDate(t.getDate()+1),t.setFullYear(t.getFullYear()-1)),Math.floor(wi(t))}}function fs(e,t){return`dateValue`in e&&e.dateValue!==`exactDate`?[ds(e.dateValue)]:e.values.map(e=>li(e,t))}function ps(e,t){return e.map(e=>{if(e.startsWith(`=`))return e;let n=ts(e,t);return typeof n==`number`?L(n,{format:t.dateFormat,locale:t}):``})}function ms(e,t=[]){if(e.length<=1&&t.length===0)return e;let n=[0],r=new Map([[0,[]]]);return hs(n,r,e,!1),hs(n,r,t,!0),bs(n,r)}function hs(e,t,n,r=!1){for(let i of n){let n=i.left,a=i.right===void 0?void 0:i.right+1,o=_s(e,t,n,!0,0),s=_s(e,t,a,!1,o);for(let n=o;n<=s;n++)vs(t.get(e[n]),i,r);ys(e,t,o,s)}}function gs(e,t,n){let r=n.left,i=n.right,a=xs(e,r,0),o=i===void 0?e.length-1:xs(e,i,a),s=n.top,c=n.bottom===void 0?void 0:n.bottom+1;for(let n=a;n<=o;n++){let r=t.get(e[n]),i=xs(r,s,0);if(i===-1||i%2!=0)return!1;let a=c===void 0?r.length:Ss(r,c,0);if(i+1!==a)return!1}return!0}function _s(e,t,n,r,i){if(n===void 0)return e.length-1;let a=xs(e,n,i);return n===e[a]?r?a:a-1:(e.splice(a+1,0,n),t.set(n,[...t.get(e[a])]),r?a+1:a)}function vs(e,t,n=!1){let r=t.top,i=t.bottom===void 0?void 0:t.bottom+1,a=[],o=xs(e,r,0,!1);if((o%2!=0&&!n||o%2==0&&n)&&a.push(r),i===void 0){e.splice(o+1),e.push(...a);return}let s=Ss(e,i,0,!1);(s%2==0&&!n||s%2!=0&&n)&&a.push(i);let c=s-o-1,l=a.length,u=o+1;u===e.length-1&&c===1&&l===1?e[u]=a[0]??a[1]:e.splice(u,c,...a)}function ys(e,t,n,r){let i=n-1==-1?0:n-1,a=r===e.length-1?r:r+1;for(let n=a;n>i;n--)Lt(t.get(e[n]),t.get(e[n-1]))&&(t.delete(e[n]),e.splice(n,1))}function bs(e,t){let n=[],r=[];for(let i=0;i<e.length;i++){let a=e[i],o=t.get(a);if(!o||o.length===0){n.push(...r),r=[];continue}let s=e[i+1];s!==void 0&&s--;let c=[];for(let e=0;e<o.length;e+=2){let t=o[e],n=o[e+1];n!==void 0&&n--;let i={top:t,left:a,bottom:n,right:s};(n===void 0&&t!==0||s===void 0&&a!==0)&&(i.hasHeader=!0);let l=!1;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.top===i.top&&t.bottom===i.bottom){t.right=i.right,r.splice(e,1),c.push(t),l=!0;break}}l||c.push(i)}n.push(...r),r=c}return n.push(...r),n}function xs(e,t,n=0,r=!0){let i=e.length-1,a=-1;for(;n<=i;){let o=n+(i-n>>1);if(e[o]===t&&r)return o;e[o]<t?(a=o,n=o+1):i=o-1}return a}function Ss(e,t,n=0,r=!0){let i=e.length-1,a=e.length;for(;n<=i;){let o=n+(i-n>>1);if(e[o]===t&&r)return o;e[o]>t?(a=o,i=o-1):n=o+1}return a}function Cs(e){let t=new tn(e);tr(t);let n=e.indexOf(`!`);n!==-1&&t.advanceBy(n+1);let r=nr(t),i=rr(t),a,o,s,c,l=!1,u=!1,d=!1;if(i===-1?(s=c=r-1,a=o=0,l=!0):r===-1?(a=o=i-1,s=c=0,u=!0):(s=c=r-1,a=o=i-1,d=!0),tr(t),t.current===`:`){t.advanceBy(1),tr(t);let e=nr(t),n=rr(t);n===-1?(c=e-1,l=!0):e===-1?(o=n-1,u=!0):(c=e-1,o=n-1,a=l?o:a,s=u?c:s,d=!0)}let f={top:a,left:s,bottom:l?void 0:o,right:u?void 0:c};return d&&=u||l,d&&(f.hasHeader=d),f}function ws(e){let t=Js(Cs(e)),n=t.bottom,r=t.right;if(n!==void 0&&n>9999998||r!==void 0&&r>er)throw Error(`Range string out of bounds: ${e}`);if(n===void 0&&r===void 0)throw Error(`Wrong zone xc. The zone cannot be at the same time a full column and a full row`);return t}function Ts(e){let t=ws(e);if(t.bottom===void 0||t.right===void 0)throw Error(`This does not support unbounded ranges`);return t}function Es(e){return Os(ws(e))}function Ds(e){try{return Es(e)}catch{return!1}}function Os(e){let{bottom:t,top:n,left:r,right:i}=e;return t!==void 0&&isNaN(t)||isNaN(n)||isNaN(r)||i!==void 0&&isNaN(i)?!1:ks(e)&&e.top>=0&&e.left>=0}function ks(e){return(e.bottom===void 0||e.bottom>=e.top&&e.bottom>=0)&&(e.right===void 0||e.right>=e.left&&e.right>=0)}function As(e){let{top:t,bottom:n,left:r,right:i}=e,a=`hasHeader`in e?e.hasHeader:!1,o=t===n&&r===i;if(n===void 0&&i!==void 0)return t===0&&!a?`${Yn(r)}:${Yn(i)}`:`${T(r,t)}:${Yn(i)}`;if(i===void 0&&n!==void 0)return r===0&&!a?`${t+1}:${n+1}`:`${T(r,t)}:${n+1}`;if(n!==void 0&&i!==void 0)return o?T(r,t):`${T(r,t)}:${T(i,n)}`;throw Error(`Bad zone format`)}function js(e,t,n,r,i){let a=t===`left`?`columns`:`rows`,o=r===`before`?n-1:n,s=e[t===`left`?`right`:`bottom`];return e[t]<=o&&s&&s>o?Ys(e,a,`RESIZE`,i):o<e[t]?Ys(e,a,`MOVE`,i):{...e}}function Ms(e,t,n,r,i){let a=t===`left`?`columns`:`rows`,o=r===`before`?n-1:n,s=t===`left`?`right`:`bottom`;return e[t]<=o&&e[s]>o?Ys(e,a,`RESIZE`,i):o<e[t]?Ys(e,a,`MOVE`,i):{...e}}function Ns(e,t,n){let r=t===`left`?`right`:`bottom`,i=e[t],a=e[r];for(let o of n.sort((e,t)=>t-e))e[t]>o&&(i--,a--),e[t]<o&&e[r]>=o&&a--;return{...e,[t]:i,[r]:a}}function Ps(e,t,n){let r=t===`left`?`right`:`bottom`,i=e[t],a=e[r],o=e[r];for(let r of n.sort((e,t)=>t-e))e[t]>r&&(i--,a!==void 0&&a--),o!==void 0&&a!==void 0&&e[t]<=r&&o>=r&&a--;if(!(a!==void 0&&i>a))return{...e,[t]:i,[r]:a}}function Fs(...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 Is(...e){return{top:Math.min(...e.map(e=>e.top)),left:Math.min(...e.map(e=>e.left)),bottom:e.some(e=>e.bottom===void 0)?void 0:Math.max(...e.map(e=>e.bottom)),right:e.some(e=>e.right===void 0)?void 0:Math.max(...e.map(e=>e.right))}}function Ls(e,t){if(zs(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:Math.min(e.bottom,t.bottom),right:Math.min(e.right,t.right)}}function Rs(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function zs(e,t){return!(e.bottom<t.top||t.bottom<e.top||e.right<t.left||t.right<e.left)}function Bs(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++)if(zs(e[t],e[n]))return!0;return!1}function Vs(e,t,n){let{left:r,right:i,top:a,bottom:o}=n;return e>=r&&e<=i&&t>=a&&t<=o}function Hs(e,t){return e.left>=t.left&&e.right<=t.right&&e.top>=t.top&&e.bottom<=t.bottom}function Us(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function Ws(e){let{numberOfCols:t,numberOfRows:n}=Us(e);return t===1||n===1}function Gs(e){let{top:t,left:n,bottom:r,right:i}=e;if(nc(e)===1)return[];let a={top:t+1,bottom:r,left:n,right:n};if(i===n)return[a];let o={top:t,bottom:r,left:n+1,right:i};return t===r?[o]:[a,o]}function Ks(e){let t=[],{left:n,right:r,top:i,bottom:a}=Js(e);for(let e of S(n,r+1))for(let n of S(i,a+1))t.push({col:e,row:n});return t}function qs(e,t){let n=[],{left:r,right:i,top:a,bottom:o}=Js(t);for(let t of S(r,i+1))for(let r of S(a,o+1))n.push({sheetId:e,col:t,row:r});return n}function Js(e){return e.right!==void 0&&e.left>e.right&&(e={...e,left:e.right,right:e.left}),e.bottom!==void 0&&e.top>e.bottom&&(e={...e,top:e.bottom,bottom:e.top}),e}function Ys(e,t,n,r){let i=t===`both`?r[0]:t===`columns`?r:0,a=t===`both`?r[1]:t===`rows`?r:0,o=`hasHeader`in e?e.hasHeader:!1,s;s=tc(e)&&!o?t!==`rows`:ec(e)&&!o?t!==`columns`:!0;let c={...e};return s&&n===`MOVE`&&(c.left+=i,c.top+=a),c.right!==void 0&&(c.right+=i),c.bottom!==void 0&&(c.bottom+=a),c}function Xs(e){return e.reverse().filter((e,t,n)=>t===n.findIndex(t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)).reverse()}function Zs(e){return e.reduce((e,t)=>{let n=e.length;for(let r=0;r<n;r++)if(zs(e[r],t))return e[r]=Fs(e[r],t),e;return e[n]=t,e},[])}function Qs(e,t){let n,r,{left:i,right:a,top:o,bottom:s}=e,{left:c,right:l,top:u,bottom:d}=t;return n=c===i?l===a?c:l:c,r=u===o?d===s?u:d:u,{col:n,row:r}}function R(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function $s(e){return{...e,right:e.left,bottom:e.top}}function ec(e){return e.right===void 0}function tc(e){return e.bottom===void 0}function nc(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function rc(e,t,n){return e.left<t&&t<=e.right||e.top<n&&n<=e.bottom}function ic(e,t,n){return e.some(e=>rc(e,t,n))}function ac(e,t){let{left:n,top:r,bottom:i,right:a}=e;if(a!==void 0&&i!==void 0)return e;if(i===void 0&&a!==void 0)return{right:a,top:r,left:n,bottom:t.numberOfRows-1};if(a===void 0&&i!==void 0)return{bottom:i,left:n,top:r,right:t.numberOfCols-1};throw Error(`Bad zone format`)}function oc(e){return e.length<2?!0:ms(e).length===1}function sc(e){let t=new Set;for(let n of ms(e))for(let e of S(n.left,n.right+1))t.add(e);return t}function cc(e){let t=new Map;for(let n of e)for(let e=n.left;e<=n.right;e++){let r=t.get(e);r?(r.top=Math.min(r.top,n.top),r.bottom=Math.max(r.bottom,n.bottom)):t.set(e,{left:e,right:e,top:n.top,bottom:n.bottom})}return Array.from(t.values())}function lc(e){let t=new Set;for(let n of ms(e))for(let e of S(n.top,n.bottom+1))t.add(e);return t}function uc(e,t){return e.right+1===t.left||e.left===t.right+1?e.top<=t.bottom&&e.top>=t.top||t.top<=e.bottom&&t.top>=e.top:e.bottom+1===t.top||e.top===t.bottom+1?e.left<=t.right&&e.left>=t.left||t.left<=e.right&&t.left>=e.left:!1}function dc(e){let t=[...e],n=!0;for(;n;){n=!1;for(let e=0;e<t.length;e++){let r=t[e],i=t.findIndex((t,n)=>e!==n&&(uc(t,r)||zs(t,r)));if(i!==-1){t[e]=Fs(t[i],r),t.splice(i,1),n=!0;break}}}return t}let fc=new WeakMap,pc=new WeakMap;function mc(e,t){fc.has(t)||(fc.set(t,new Map),pc.set(t,0));let n=fc.get(t),r=_c(e);if(n.has(r)){let i=n.get(r);return t[i]=e,i}let i=pc.get(t)+1;return n.set(r,i),pc.set(t,i),t[i]=e,i}function hc(e){let t={};for(let n in e){let r=ms(e[n].map(R));for(let e of r)t[As(e)]=Number(n)}return t}function*gc(e,t){for(let n in t){let r=Ts(n),i=t[n];for(let t=r.top;t<=r.bottom;t++)for(let n=r.left;n<=r.right;n++)yield[{sheetId:e,col:n,row:t},i]}}function _c(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(typeof e!=`object`)return String(e);if(Array.isArray(e)){let t=e.length,n=`[`;for(let r=0;r<t;r++)r>0&&(n+=`,`),n+=_c(e[r]);return n+`]`}let t=Object.keys(e).sort(),n=`{`;for(let r of t)e[r]!==void 0&&(n+=`"${r}":${_c(e[r])},`);return n+=`}`,n}function vc(e){return 20+120*Math.exp(-.035*(e-1))}let yc=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,`i`),bc=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,`i`),xc=new RegExp(/^\$?([A-Z]{1,3})+$/,`i`),Sc=new RegExp(/^\$?([0-9]{1,7})+$/,`i`),Cc=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,`i`),wc=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,`i`),Tc=RegExp(`^\\s*('.+'!|[^']+!)?(`+[yc.source,`(\\$?[A-Z]{1,3})?\\$?[0-9]{1,7}\\s*:\\s*(\\$?[A-Z]{1,3})?\\$?[0-9]{1,7}\\s*`,`\\$?[A-Z]{1,3}(\\$?[0-9]{1,7})?\\s*:\\s*\\$?[A-Z]{1,3}(\\$?[0-9]{1,7})?\\s*`].join(`|`)+`)$`,`i`);function Ec(e){return Cc.test(e)}function Dc(e){return wc.test(e)}function Oc(e){return xc.test(e)}function kc(e){return Sc.test(e)}function Ac(e){return bc.test(e)}function jc(e){if(!e.includes(`!`))return{xc:e};let t=e.split(`!`),n=t.pop();return{sheetName:ft(t.join(`!`))||void 0,xc:n}}function Mc(e,t){return e===void 0?t:`${mt(e)}!${t}`}function Nc(e,t){let n=e.zone,r=ac(n,t(e.sheetId)),i=e.parts;return e.parts.length===1&&nc(r)>1?i=[e.parts[0],e.parts[0]]:e.parts.length===2&&nc(r)===1&&(i=[e.parts[0]]),{unboundedZone:n,zone:r,parts:i,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function Pc(e,t){let n=e.xc,{xc:r,sheetName:i}=jc(n),a=ws(r);return Nc({zone:a,parts:Hc(r,a),sheetId:e.sheetId,prefixSheet:!!i,invalidSheetName:e.invalidSheetName},t)}function Fc(e){let t={left:-1,top:-1,right:-1,bottom:-1};return{sheetId:``,zone:t,unboundedZone:t,parts:[],invalidXc:e,prefixSheet:!1}}function Ic(e){return tc(e.unboundedZone)}function Lc(e){return ec(e.unboundedZone)}function Rc(e,t,n,r={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||e.zone.left<0||e.zone.top<0)return k.InvalidReference;let i=e.sheetId!==t||e.invalidSheetName||e.prefixSheet,a=``;if(i&&(a=e.invalidSheetName?mt(e.invalidSheetName):mt(n(e.sheetId))),i&&!a)return k.InvalidReference;let o=$c(e,0,r);return e.parts&&e.parts.length===2&&(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)&&(o+=`:`,o+=$c(e,1,r)),`${i?a+`!`:``}${o}`}function zc(e,t,n){let r=n.sheetId===e?t:n.sheetId;return{...n,sheetId:r}}function Bc(e,t,n){if(!n)return;let r=e.getRangeFromSheetXC(t,n);return r.invalidSheetName||r.invalidXc?void 0:r}function Vc(e){let t=[];for(let n of e)for(let e of Ks(n.zone))t.push({...e,sheetId:n.sheetId});return t}function Hc(e,t){let n=e.split(`:`).map(e=>{let t=Dc(e);return{colFixed:t?!1:e.startsWith(`$`),rowFixed:t?e.startsWith(`$`):e.includes(`$`,1)}}),r=t.bottom===void 0,i=t.right===void 0;return r&&(n[0].rowFixed=n[0].rowFixed||n[1].rowFixed,n[1].rowFixed=n[0].rowFixed||n[1].rowFixed),i&&(n[0].colFixed=n[0].colFixed||n[1].colFixed,n[1].colFixed=n[0].colFixed||n[1].colFixed),n}function Uc(e){let t={left:e.col,top:e.row,right:e.col,bottom:e.row};return{sheetId:e.sheetId,zone:t}}function Wc(e){if(ks(e.zone))return e;let t={...e.unboundedZone},n={...e.zone},r=e.parts;if(t.right!==void 0&&t.right<t.left){let e=t.right;t.right=t.left,t.left=e,n.right=n.left,n.left=e,r=[{colFixed:r[1]?.colFixed||!1,rowFixed:r[0]?.rowFixed||!1},{colFixed:r[0]?.colFixed||!1,rowFixed:r[1]?.rowFixed||!1}]}if(t.bottom!==void 0&&t.bottom<t.top){let e=t.bottom;t.bottom=t.top,t.top=e,n.bottom=n.top,n.top=e,r=[{colFixed:r[0]?.colFixed||!1,rowFixed:r[1]?.rowFixed||!1},{colFixed:r[1]?.colFixed||!1,rowFixed:r[0]?.rowFixed||!1}]}return{unboundedZone:t,zone:n,parts:r,invalidXc:e.invalidXc,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function Gc(e){return Kc.get(e.type)?.(e)}let Kc=new class extends g{add(e,t){return super.add(e,t),this}get(e){return this.content[e]}};Kc.add(`REMOVE_COLUMNS_ROWS`,e=>({applyChange:qc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`ADD_COLUMNS_ROWS`,e=>({applyChange:Jc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`DELETE_SHEET`,e=>({applyChange:Yc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`RENAME_SHEET`,e=>({applyChange:Xc(e),sheetId:e.sheetId,sheetName:{old:e.oldName,current:e.newName}})).add(`MOVE_RANGES`,e=>({applyChange:Zc(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}));function qc(e){let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`,i=[...e.elements];i.sort((e,t)=>t-e);let a=gt(i);return i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`,range:i};let o=i,s=`NONE`;for(let e of a){let a=en(e),c=$t(e);if(i.zone[t]<=a&&a<=i.zone[n]){let e=Math.min(i.zone[n],c)-a+1;s=`RESIZE`,o=Qc(o,r,s,-e)}else if(i.zone[t]>=a&&i.zone[n]<=c)s=`REMOVE`,o=Fc(k.InvalidReference);else if(i.zone[t]<=c&&i.zone[n]>=c){let e=c-i.zone[t]+1;s=`RESIZE`,o=Qc(o,r,s,-e),o=Qc(o,r,`MOVE`,-(i.zone[t]-a))}else a<i.zone[t]&&(s=`MOVE`,o=Qc(o,r,s,-(c-a+1)))}return{changeType:s,range:o}}}function Jc(e){let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`;return i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`,range:i};let a=i.unboundedZone[n]===void 0;if(a&&!i.unboundedZone.hasHeader)return{changeType:`RESIZE`,range:Qc(i,r,`RESIZE`,e.quantity)};if(e.position===`after`){if(i.zone[t]<=e.base&&(e.base<i.zone[n]||a))return{changeType:`RESIZE`,range:Qc(i,r,`RESIZE`,e.quantity)};if(e.base<i.zone[t])return{changeType:`MOVE`,range:Qc(i,r,`MOVE`,e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[n])return{changeType:`RESIZE`,range:Qc(i,r,`RESIZE`,e.quantity)};if(e.base<=i.zone[t])return{changeType:`MOVE`,range:Qc(i,r,`MOVE`,e.quantity)}}return{changeType:`NONE`,range:i}}}function Yc(e){return t=>{if(t.sheetId!==e.sheetId&&t.invalidSheetName!==e.sheetName)return{changeType:`NONE`,range:t};let n=e.sheetName;return t={...Fc(k.InvalidReference),invalidSheetName:n},{changeType:`REMOVE`,range:t}}}function Xc(e){return t=>{if(t.sheetId===e.sheetId)return{changeType:`CHANGE`,range:t};if(e.newName&&t.invalidSheetName===e.newName){let n=e.sheetId;return{changeType:`CHANGE`,range:{...t,sheetId:n,invalidSheetName:void 0}}}if(e.oldName&&t.invalidSheetName===e.oldName){let n=e.sheetId;return{changeType:`CHANGE`,range:{...t,sheetId:n,invalidSheetName:void 0}}}return{changeType:`NONE`,range:t}}}function Zc(e){let t=e.target[0];return n=>{if(n.sheetId!==e.sheetId||!Hs(n.zone,t))return{changeType:`NONE`,range:n};let r=e.targetSheetId,i=Qc(n,`both`,`MOVE`,[e.col-t.left,e.row-t.top]),a=e.sheetId===r?i.prefixSheet:!0;return{changeType:`MOVE`,range:{...i,sheetId:r,prefixSheet:a}}}}function Qc(e,t,n,r){return{...e,unboundedZone:Ys(e.unboundedZone,t,n,r),zone:Ys(e.zone,t,n,r)}}function $c(e,t,n={useBoundedReference:!1,useFixedReference:!1}){let r=e.parts[t]?.colFixed||n.useFixedReference?`$`:``,i=Yn(t===0?e.zone.left:e.zone.right),a=e.parts[t]?.rowFixed||n.useFixedReference?`$`:``,o=String(t===0?e.zone.top+1:e.zone.bottom+1),s=``;return s=tc(e.unboundedZone)&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:r+i:ec(e.unboundedZone)&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:a+o:r+i+a+o,s}function el(e,t){e=e.toLocaleLowerCase(),t=t.toLocaleLowerCase();let n=0,r=0,i=t.length,a=0;for(let o=0;o<i;o++)t[o]===e[a]?(a++,r+=100+r-o/200):r=0,n+=r;return a===e.length?n:0}function tl(e,t,n){let r=[];return t.forEach(t=>{let i=el(e,n(t));i>0&&r.push({score:i,elem:t})}),r.sort((e,t)=>t.score-e.score),r.map(e=>e.elem)}function nl(e){let t=[];for(let n=0;n<e;n++)t.push({cells:{}});return t}function rl(e,t,n){return n.map(n=>n>=e?n+t:n)}function il(e,t){return e=[...e].sort((e,t)=>t-e),t.map(t=>{for(let n of e)if(t>n)t--;else if(t===n)return;return t}).filter(C)}function al(e,t=`Sheet`){let n=1,r=`${t}${n}`;for(;e.includes(r);)r=`${t}${n}`,n++;return r}function ol(e,t){let n=1,r=E(`Copy of %s`,e),i=r.toString();for(;t.includes(i);)i=`${r} (${n})`,n++;return i}let sl=Kt(function(e){return ft(e.trim().toUpperCase())});function cl(e,t){return e===void 0||t===void 0?!1:sl(e)===sl(t)}function ll(e,t=1){return t*(e+4)-4}function ul(e,t,n,r){if(!t||!t.isFormula&&!t.content)return 23;let i=``;try{if(!t.isFormula){let e={format:t.format,locale:n};i=L(ts(t.content,n),e)}}catch{i=k.GenericError}return dl(e,i,t.style,r)}function dl(e,t,n,r){let i=Cl(e,t,n,n?.wrapping===`wrap`?r-8:void 0).length;return ll(xl(n),i)+6}function fl(e,t=!1,n=!1){return`${n?`italic`:``} ${t?`bold`:``} ${e}px ${He}`}let pl={};function ml(e,t,n,r=`pt`){return hl(e,t,bl(n,r))}function hl(e,t,n){if(pl[n]||(pl[n]={}),pl[n][t]===void 0){let r=e.font;e.font=n,pl[n][t]=e.measureText(t).width,e.font=r}return pl[n][t]}let gl={};function _l(e,t,n,r=`pt`){let i=bl(n,r);e.save(),e.font=i;let a=vl(e,t);return e.restore(),a}function vl(e,t){let n=e.font;if(gl[n]||(gl[n]={}),gl[n][t]===void 0){let r=e.measureText(t),i=r.width,a=r.fontBoundingBoxAscent+r.fontBoundingBoxDescent;gl[n][t]={width:i,height:a}}return gl[n][t]}function yl(e){return Math.round(e*96/72)}function bl(e,t=`pt`){return`${e.italic?`italic `:``}${e.bold?`bold`:`400`} ${(t===`pt`?xl(e):e.fontSize)??Ve}px ${He}`}function xl(e){return yl(e?.fontSize||Ve)}function Sl(e,t,n,r){if(ml(e,t,r)<=n)return[t];let i=[],a=``;for(let o of t)ml(e,a+o,r)>n?(i.push(a),a=o):a+=o;return i.push(a),i}function Cl(e,t,n,r){n||={},xt(t)&&(t=wt(t).label);let i=[],a=t.includes(`
6
6
  `)?t.split(`
7
7
  `):[t];for(let t of a){let a=t.includes(` `)?t.split(` `):[t];if(!r){i.push(t);continue}let o=``,s=r;for(let t of a){let a=Sl(e,t,r,n),c=a.pop(),l=ml(e,c,n);if(a.length)o!==``&&(i.push(o),o=``,s=r),a.forEach(e=>{i.push(e)}),o=c,s=r-l;else{let t=o===``?c:` `+c,a=ml(e,t,n);a<=s?(o+=t,s-=a):(i.push(o),o=c,s=r-l)}}o!==``&&i.push(o)}return i}function wl(e,t,n,r=.25){let i=1;if(n(i)>e)return i;if(n(t)<e)return t;let a=(i+t)/2,o=n(a),s=0;for(;Math.abs(o-e)>r&&s<20;)o>=e?t=(i+t)/2:i=(i+t)/2,a=(i+t)/2,o=n(a),s++;return a}function Tl(e){return e?e.toLowerCase():``}let El=/([0-9\.]*)px/;function Dl(e){return Number(e.match(El)?.[1])}function Ol(e,t,n){let r=hl(e,t,e.font);if(r<=n)return t;let i=hl(e,`…`,e.font);if(r<=i)return t;let a=t.length;for(;r>=n-i&&a-- >0;)t=t.substring(0,a),r=hl(e,t,e.font);return t+`…`}function kl(e,t,n,r=!1,i=!1,a=Dl(e.font)/10){if(e.fillText(t,n.x,n.y),!r&&!i)return;let o=e.measureText(t),s=o.width,c=o.actualBoundingBoxAscent+o.actualBoundingBoxDescent,l=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent,{x:u,y:d}=n,f=d,p=d;switch(e.textAlign){case`center`:u-=s/2;break;case`right`:u-=s;break}switch(e.textBaseline){case`top`:p+=l-2*a,f+=l/2-a;break;case`middle`:p+=l/2-a;break;case`alphabetic`:p+=2*a,f-=3*a;break;case`bottom`:p=d,f-=c/2-a/2;break}r&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,p),e.lineTo(u+s,p),e.stroke()),i&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+s,f),e.stroke())}function Al(e,t,n,r,i=`pt`){if(ml(e,n,r,i)<=t)return n;let a=ml(e,`...`,r,i);if(a>=t)return``;let o=1,s=n.length,c;for(;o<=s;){let l=Math.floor((o+s)/2);c=ml(e,n.slice(0,l),r,i),c+a>t?s=l-1:o=l+1}let l=n.slice(0,Math.max(0,o-1));return l?l+`...`:``}var jl=class{smallUuid(){return window.crypto?`10000000-1000`.replace(/[01]/g,e=>{let t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)}):`xxxxxxxx-xxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}uuidv4(){return window.crypto?`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>{let 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){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}};let Ml=[`image/avif`,`image/bmp`,`image/gif`,`image/vnd.microsoft.icon`,`image/jpeg`,`image/png`,`image/tiff`,`image/webp`];function Nl(e,t){let n=new Set(t.map(e=>e.left)),r=new Set(t.map(e=>e.right)),i=new Set(t.map(e=>e.top)),a=new Set(t.map(e=>e.bottom)),o=i.size===1&&a.size===1||n.size===1&&r.size===1?Zs(t):[t[t.length-1]],s=o.map(e=>Ks(e)).flat();return{sheetId:e,zones:t,clippedZones:o,columnsIndexes:[...new Set(s.map(e=>e.col))].sort((e,t)=>e-t),rowsIndexes:[...new Set(s.map(e=>e.row))].sort((e,t)=>e-t)}}function Pl(e,t,n){let r=Math.max(e.right-t+1,e.left),i=Math.max(e.bottom-n+1,e.top),a=[];for(let o=e.left;o<=r;o+=t)for(let r=e.top;r<=i;r+=n)a.push({left:o,top:r,bottom:r+n-1,right:o+t-1});return a}function Fl(e,t){if(!t.length||!t[0].length)return e;let n=t[0].length,r=t.length;return e.map(e=>Pl(e,n,r)).flat()}function Il(e){let t;e[`text/html`]&&(t=Ll(new DOMParser().parseFromString(e[`text/html`],`text/html`)));let n=e[`text/plain`]||``,r;if(!n.trim()){for(let t of Ml)if(e[t]){r=e[t];break}}return{text:n,data:t,imageBlob:r}}function Ll(e){if([...e.documentElement.attributes].some(e=>e.value.includes(`microsoft`)))return;let t=e.querySelector(`div`)?.getAttribute(`data-osheet-clipboard`);return t&&JSON.parse(t)}let Rl=(e,t,n,r)=>{e.forEach(({handlerName:e,handler:i})=>{let a=t[e];a&&i.paste(n,a,r)})};function zl(e,t,n,r,i){let a,o=[],s={sheetId:e,zones:t};for(let{handlerName:c,handler:l}of r){let r=n[c];if(!r)continue;let u=l.getPasteTarget(e,t,r,i);u.figureId&&(s.figureId=u.figureId);for(let e of u.zones){if(o.push(e),a===void 0){a=e;continue}a=Fs(a,e)}}return{target:s,zone:a,selectedZones:o}}let Bl=(e,t,n)=>{let r={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:r,zone:Fs(...n)},{scrollIntoView:!1})};var Vl=class{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,n=`copyPaste`){}paste(e,t,n){}isPasteAllowed(e,t,n,r){return`Success`}isCutAllowed(e){return`Success`}getPasteTarget(e,t,n,r){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}},Hl=class extends Vl{copy(e,t,n=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of Fl(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of ms(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++)this.pasteZone(e,t,a,n,r)}pasteZone(e,t,n,r,i){}},Ul=class extends Hl{queuedBordersToAdd={};copy(e){let t=e.sheetId;if(e.zones.length===0)return;let{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getCellBorder(r))}i.push(n)}return{borders:i}}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(!n.isCutOperation)this.pasteFromCopy(r,i,t.borders);else{let{left:e,top:n}=i[0];this.pasteZone(r,e,n,t.borders)}this.executeQueuedChanges(r)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteBorder(o,a)}}pasteBorder(e,t){let n={...this.getters.getCellBorder(t),...e},r=JSON.stringify(n);this.queuedBordersToAdd[r]||(this.queuedBordersToAdd[r]=[]),this.queuedBordersToAdd[r].push(R(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=ms(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}},Wl=class extends Vl{copy(e){}},Gl=class extends Wl{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`carousel`)return;let r={...n},i=this.getters.getCarousel(e.figureId),a={};for(let e of i.items)if(e.type===`chart`){let n=this.getters.getChart(e.chartId);if(!n)throw Error(`No chart for the given id: ${e.chartId}`);a[e.chartId]=n.copyInSheetId(t)}return{figureId:e.figureId,copiedFigure:r,copiedCarousel:i,copiedCharts:a,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:new jl().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=this.getters.getMaxAnchorOffset(a,s,o),{left:l,top:u}=r[0],d={x:0,y:0};l>c.col&&(l=c.col,d.x=c.offset.x),u>c.row&&(u=c.row,d.y=c.offset.y),this.dispatch(`CREATE_CAROUSEL`,{figureId:i,sheetId:a,definition:{items:[]},col:l,row:u,offset:d,size:{height:s,width:o}});let f=new jl,p=b(t.copiedCarousel.items);for(let e of p){if(e.type!==`chart`)continue;let n=t.copiedCharts[e.chartId],r=f.smallUuid(),o=n.copyInSheetId(a).getDefinition();this.dispatch(`CREATE_CHART`,{figureId:i,chartId:r,sheetId:a,definition:o}),e.chartId=r}this.dispatch(`UPDATE_CAROUSEL`,{sheetId:a,figureId:i,definition:{...t.copiedCarousel,items:p}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}};let Kl=[`%`],ql=`+,-,*,/,:,=,<>,>=,>,<=,<,^,&`.split(`,`).concat(Kl);function Jl(e,t=D){e=Wt(e);let n=new tn(e),r=[],i=Vt.test(e)?ou:su;for(;!n.isOver();){let e=cu(n)||i(n)||Ql(n,t)||Zl(n)||$l(n)||nu(n)||Yl(n)||lu(n)||tu(n,t)||au(n);e||={type:`UNKNOWN`,value:n.shift()},r.push(e)}return r}function Yl(e){return e.current===`?`?(e.shift(),{type:`DEBUGGER`,value:`?`}):null}let Xl={"(":{type:`LEFT_PAREN`,value:`(`},")":{type:`RIGHT_PAREN`,value:`)`}};function Zl(e){return e.current===`(`||e.current===`)`?Xl[e.shift()]:null}function Ql(e,t){return e.current===t.formulaArgSeparator?{type:`ARG_SEPARATOR`,value:e.shift()}:null}function $l(e){for(let t of ql)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:`OPERATOR`,value:t};return null}let eu=new Set(`0123456789`);function tu(e,t){if(!eu.has(e.current)&&e.current!==t.decimalSeparator)return null;let n=e.remaining().match(Bi(t.decimalSeparator));return n?(e.advanceBy(n[0].length),{type:`NUMBER`,value:n[0]}):null}function nu(e){if(e.current===`"`){let t=e.shift(),n=t;for(;e.current&&(e.current!==t||n[n.length-1]===`\\`);)n+=e.shift();return e.current===`"`&&(n+=e.shift()),{type:`STRING`,value:n}}return null}let ru=/\p{L}|\p{N}|_|\.|!|\$/u,iu=new Set(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$`);function au(e){let t=``;if(e.current===`'`){let n=e.shift();for(t+=n;e.current;)if(n=e.shift(),t+=n,n===`'`)if(e.current&&e.current===`'`)n=e.shift(),t+=n;else break;if(n!==`'`)return{type:`UNKNOWN`,value:t}}for(;e.current&&(iu.has(e.current)||e.current.match(ru));)t+=e.shift();if(t.length){let e=t;return Tc.test(e)?{type:`REFERENCE`,value:e}:{type:`SYMBOL`,value:e}}return null}function ou(e){let t=``;for(;e.current===` `||e.current&&e.current.match(Vt);)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function su(e){let t=``;for(;e.current===` `;)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function cu(e){let t=0;for(;e.current===`
8
8
  `;)t++,e.shift();return t?{type:`SPACE`,value:`
@@ -13,7 +13,7 @@ Did you forget to inject your store instance?
13
13
  const stores = useStoreProvider();
14
14
  stores.inject(MyMetaStore, storeInstance);
15
15
  `)}}return t}var ff=class{get;disposeCallbacks=[];constructor(e){this.get=e}onDispose(e){this.disposeCallbacks.push(e)}dispose(){this.disposeCallbacks.forEach(e=>e())}};function pf(){let e=(0,t.useEnv)();if(e.__spreadsheet_stores__ instanceof lf)return e.__spreadsheet_stores__;let n=new lf;return(0,t.useSubEnv)({__spreadsheet_stores__:n,getStore:e=>gf(n.get(e),()=>n.trigger(`store-updated`))}),(0,t.onWillUnmount)(()=>n.dispose()),n}function z(e){let n=_f((0,t.useEnv)());return hf(n,n.get(e))}function mf(e,...n){let r=_f((0,t.useEnv)()),i=r.instantiate(e,...n);return(0,t.onWillUnmount)(()=>i.dispose()),hf(r,i)}function hf(e,n){let r=(0,t.useComponent)();return gf(n,()=>{(0,t.status)(r)===`mounted`&&e.trigger(`store-updated`)})}function gf(e,t){return new Proxy(e,{get(n,r,i){let a=n,o=Reflect.get(n,r,a);return e.mutators?.includes(r)?new Proxy(o,{apply(e,n,r){Reflect.apply(e,a,r)!==`noStateChange`&&t()}}):o}})}function _f(e){let t=e.__spreadsheet_stores__;if(!(t instanceof lf))throw Error(`No store provider found. Did you forget to call useStoreProvider()?`);return t}let vf=df(`Model`);var yf=class{mutators=[`register`,`unRegister`,`draw`,`startAnimation`,`stopAnimation`];renderers={};model;context=void 0;animationFrameId=null;registeredAnimations=new Set;constructor(e){this.model=e(vf)}register(e){if(e.renderingLayers.length)for(let t of e.renderingLayers)this.renderers[t]||(this.renderers[t]=[]),this.renderers[t].push(e)}unRegister(e){for(let t of Object.keys(this.renderers))this.renderers[t]=this.renderers[t].filter(t=>t!==e)}drawLayer(e,t,n){let r=this.renderers[t];if(r)for(let i of r)e.ctx.save(),i.drawLayer(e,t,n),e.ctx.restore();return`noStateChange`}draw(e,t){if(e||=this.context,!e)throw Error(`Rendering context is not defined`);this.context=e;for(let n of Rr())this.model.drawLayer(e,n),this.drawLayer(e,n,t);return`noStateChange`}startAnimation(e){if(this.registeredAnimations.add(e),!this.animationFrameId){let e=t=>{this.animationFrameId=requestAnimationFrame(e),this.draw(void 0,t)};this.animationFrameId=requestAnimationFrame(e)}return`noStateChange`}stopAnimation(e){return this.registeredAnimations.delete(e),this.registeredAnimations.size===0&&this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),`noStateChange`}dispose(){this.animationFrameId&&=(cancelAnimationFrame(this.animationFrameId),null)}},bf=class extends ff{model=this.get(vf);getters=this.model.getters;renderer=this.get(yf);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,n){}};let xf={id:`void-composer`,get editionMode(){return`inactive`},startEdition:()=>{throw Error(`No composer is registered`)},stopEdition:()=>{throw Error(`No composer is registered`)},setCurrentContent:()=>{throw Error(`No composer is registered`)}};var Sf=class extends bf{mutators=[`focusComposer`,`focusActiveComposer`];activeComposer=xf;_focusMode=`inactive`;get focusMode(){return this.activeComposer.editionMode===`inactive`?`inactive`:this._focusMode}focusComposer(e,t){if(this.activeComposer=e,this.getters.isReadonly())return`noStateChange`;this._focusMode=t.focusMode||`contentFocus`,this._focusMode!==`inactive`&&this.setComposerContent(t)}focusActiveComposer(e){if(this.getters.isReadonly())return`noStateChange`;if(!this.activeComposer)throw Error(`No composer is registered`);this._focusMode=e.focusMode||`contentFocus`,this._focusMode!==`inactive`&&this.setComposerContent(e)}setComposerContent({content:e,selection:t}){this.activeComposer.editionMode===`inactive`?this.activeComposer.startEdition(e,t):e&&this.activeComposer.setCurrentContent(e,t)}};let Cf={},wf=0;function B(e,...t){let n=`__sheet__${wf++}`;return Ef(n,String.raw(e,...t)),Df(n),n}function Tf(e){let t=e.split(/(\{|\}|;)/).map(e=>e.trim()),n=[],r=[],i=[];function a(e,t){let r=[];for(let i of n[e]){let o=t&&t+` `+i||i;o.includes(`&`)&&(o=i.replace(/&/g,t||``)),e<n.length-1&&(o=a(e+1,o)),r.push(o)}return r.join(`, `)}function o(){i.length&&(r.push(a(0)+` {`),r.push(...i),r.push(`}`),i=[])}for(;t.length;){let e=t.shift();e===`}`?(o(),n.pop()):(t[0]===`{`&&(o(),n.push(e.split(/\s*,\s*/)),t.shift()),t[0]===`;`&&i.push(` `+e+`;`))}return r.join(`
16
- `)}function Ef(e,t){let n=document.createElement(`style`);n.textContent=Tf(t),Cf[e]=n}function Df(e){let t=Cf[e];t.setAttribute(`component`,e),document.head.appendChild(t)}function Of({strikethrough:e,underline:t}){return!e&&!t?`none`:`${e?`line-through`:``} ${t?`underline`:``}`}function kf(e){let t=Af(e);return e&&e.fillColor&&(t.background=e.fillColor),t}function Af(e){let 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 n=e.strikethrough?`line-through`:``;n=e.underline?n+` underline`:n,t[`text-decoration`]=n}return e.textColor&&(t.color=e.textColor),t}function V(e){let t=``;for(let n in e)e[n]&&(t+=`${n}:${e[n]}; `);return t}function jf(e){let 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}}let Mf=new g;function Nf(){return!!window.Chart.registry.plugins.get(`chartShowValuesPlugin`)}function Pf(){if(!(!window.Chart||Nf()))for(let e of Mf.getAll())e.register(window.Chart)}function Ff(){if(window.Chart)for(let e of Mf.getAll())e.unregister(window.Chart)}var If=class extends bf{mutators=[`disableAnimationForChart`,`enableAnimationForChart`];animationPlayed={};disableAnimationForChart(e,t){return this.animationPlayed[e]=t,`noStateChange`}enableAnimationForChart(e){return this.animationPlayed[e]=void 0,`noStateChange`}};function Lf(){return class extends window.Chart.BarController{static id=`funnel`;static defaults={...window.Chart?.BarController.defaults,dataElementType:`funnel`,animation:{duration:e=>e.type===`data`?1e3*(e.raw[1]/Math.max(...e.dataset.data.map(e=>e[1]))):1e3}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);for(let i=t;i<t+n;i++){let t=e[i];this.updateElement(t,i,{nextElement:e[i+1]},r)}}}}function Rf(){return class extends window.Chart.BarElement{static id=`funnel`;draw(e){e.save();let{x:t,y:n,height:r,nextElement:i,base:a,options:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=zf(this),c=(s-(i?zf(i):0))/2,l=Math.min(t,a),u=n-r/2;e.fillStyle=o.backgroundColor,e.beginPath(),e.moveTo(l,u),e.lineTo(l+s,u),e.lineTo(l+s-c,u+r),e.lineTo(l+c,u+r),e.closePath(),e.fill(),o.borderWidth&&(e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,e.stroke()),e.restore()}inRange(e,t){let{x:n,y:r,height:i,nextElement:a,base:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=zf(this),c=a?zf(a):0,l=Math.min(n,o),u=r-i/2;if(t<u||t>u+i)return!1;let d=(s-c)/2,f=l+d*(t-u)/i,p=l+s-d*(t-u)/i;return!(e<f||e>p)}}}function zf(e){let{x:t,base:n}=e.getProps([`x`,`base`]);return Math.max(t,n)-Math.min(t,n)}let Bf=function(e){if(!e.length)return{x:0,y:0};let{x:t,y:n,base:r,width:i,height:a}=e[0].element.getProps([`x`,`y`,`width`,`height`,`base`]),o=Math.min(t,r),s=n-a/2;return{x:o+i*2/3,y:s+a/2}},Vf=`000000`,Hf={arrows:`3Arrows`,smiley:`3Symbols`,dots:`3TrafficLights1`},Uf={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`},Wf=`http://schemas.openxmlformats.org/drawingml/2006/main`,Gf=`http://schemas.openxmlformats.org/drawingml/2006/chart`,Kf={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`},qf={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`},Jf=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,Yf=.75,Xf=.143,Zf=8.43,Qf=12.75,$f={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}]},ep=`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`.split(`,`),tp=/(.*?)\((.*?)\)(.*)/,np=[`ANY`,`BOOLEAN`,`DATE`,`NUMBER`,`STRING`,`RANGE`,`RANGE<BOOLEAN>`,`RANGE<DATE>`,`RANGE<NUMBER>`,`RANGE<STRING>`,`META`,`RANGE<META>`];function H(e,t=``,n){return rp(e,t,n)}function rp(e,t,n){let r=e.match(tp),i=r[1].trim();if(!i)throw Error(`Function argument definition is missing a name: '${e}'.`);let a=[],o=!1,s=!1,c;for(let e of r[2].split(`,`)){let t=e.trim().toUpperCase(),n=np.find(e=>t===e);n?a.push(n):t===`RANGE<ANY>`?a.push(`RANGE`):t===`OPTIONAL`?o=!0:t===`REPEATING`?s=!0:t.startsWith(`DEFAULT=`)&&(c=e.trim().slice(8))}let l={name:i,description:t,type:a};return(a.includes(`ANY`)||a.includes(`RANGE`))&&(l.acceptErrors=!0),o&&(l.optional=!0),s&&(l.repeating=!0),c!==void 0&&(l.default=!0,l.defaultValue=c),a.some(e=>e.startsWith(`RANGE`))&&(l.acceptMatrix=!0),a.every(e=>e.startsWith(`RANGE`))&&(l.acceptMatrixOnly=!0),n&&n.length>0&&(l.proposalValues=n),l}function ip(e,t){let n=0,r=0,i=0,a=0;for(let e of t.args)n++,!e.optional&&!e.repeating&&!e.default&&r++,e.repeating&&i++,(e.optional||e.default)&&a++;let o=t;return o.minArgRequired=r,o.maxArgPossible=i?1/0:n,o.nbrArgRepeating=i,o.nbrArgOptional=a,o.hidden=t.hidden||!1,o.name=e,o}let ap={};function op(e,t){let n=e.name;return ap[n]?.[t]||(ap[n]||(ap[n]={}),ap[n][t]||(ap[n][t]=sp(e,t)),ap[n][t])}function sp(e,t){let n={},r=e.nbrArgRepeating?Math.floor((t-e.minArgRequired)/e.nbrArgRepeating):0,i=e.nbrArgRepeating*r,a=t-e.minArgRequired-i,o=0,s=0;for(let t=0;t<e.args.length;t++){let i=e.args[t];if(i.optional||i.default){s<a&&(n[o]=t,o++),s++;continue}if(i.repeating){for(let i=0;i<r;i++)for(let r=0;r<e.nbrArgRepeating;r++)n[o]=t+r,o++;t+=e.nbrArgRepeating-1;continue}n[o]=t,o++}return e=>n[e]}let cp=[`META`,`RANGE<META>`];function lp(e){if(e.nbrArgRepeating&&e.nbrArgOptional>=e.nbrArgRepeating)throw Error(`Function ${e.name} has more optional arguments than repeatable ones.`);let t=!1,n=!1;for(let r of e.args){if(r.type.some(e=>cp.includes(e))&&r.type.some(e=>!cp.includes(e)))throw Error(`Function ${e.name} has a mix of META and non-META types in the same argument: ${r.type}.`);if(r.repeating){if(!n&&t)throw Error(`Function ${e.name} has non-consecutive repeating arguments. All repeating arguments must be declared consecutively.`);t=!0,n=!0}else n=!1}}let up=new g;var dp=l({ARRAY_CONSTRAIN:()=>fp,CHOOSECOLS:()=>pp,CHOOSEROWS:()=>mp,EXPAND:()=>hp,FLATTEN:()=>gp,FREQUENCY:()=>_p,HSTACK:()=>vp,MDETERM:()=>yp,MINVERSE:()=>bp,MMULT:()=>xp,SUMPRODUCT:()=>Sp,SUMX2MY2:()=>wp,SUMX2PY2:()=>Tp,SUMXMY2:()=>Ep,TOCOL:()=>kp,TOROW:()=>Ap,TRANSPOSE:()=>jp,VSTACK:()=>Mp,WRAPCOLS:()=>Np,WRAPROWS:()=>Pp});let fp={description:E(`Returns a result array constrained to a specific width and height.`),args:[H(`input_range (any, range<any>)`,E(`The range to constrain.`)),H(`rows (number)`,E(`The number of rows in the constrained array.`)),H(`columns (number)`,E(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=I(e),i=la(t?.value,this.locale),a=la(n?.value,this.locale);if(i<=0)return new A(E(`The rows argument (%s) must be strictly positive.`,i.toString()));if(a<=0)return new A(E(`The columns argument (%s) must be strictly positive.`,a.toString()));let o=Math.min(i,r[0].length);return Sa(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},pp={description:E(`Creates a new array from the selected columns in the existing range.`),args:[H(`array (any, range<any>)`,E(`The array that contains the columns to be returned.`)),H(`col_num (number, range<number>)`,E(`The first column index of the columns to be returned.`)),H(`col_num2 (number, range<number>, repeating)`,E(`The columns indexes of the columns to be returned.`))],compute:function(e,...t){let n=I(e),r=Ra(t,e=>la(e?.value,this.locale)),i=r.filter(e=>e===0||n.length<Math.abs(e));if(i.length!==0)return new A(E(`The columns arguments must be between -%s and %s (got %s), excluding 0.`,n.length.toString(),n.length.toString(),i.join(`,`)));let a=Array(r.length);for(let e=0;e<r.length;e++)r[e]>0?a[e]=n[r[e]-1]:a[e]=n[n.length+r[e]];return a},isExported:!0},mp={description:E(`Creates a new array from the selected rows in the existing range.`),args:[H(`array (any, range<any>)`,E(`The array that contains the rows to be returned.`)),H(`row_num (number, range<number>)`,E(`The first row index of the rows to be returned.`)),H(`row_num2 (number, range<number>, repeating)`,E(`The rows indexes of the rows to be returned.`))],compute:function(e,...t){let n=I(e),r=Ra(t,e=>la(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?Sa(i,r.length,(e,t)=>r[t]>0?n[e][r[t]-1]:n[e][n[e].length+r[t]]):new A(E(`The rows arguments must be between -%s and %s (got %s), excluding 0.`,n[0].length.toString(),n[0].length.toString(),a.join(`,`)))},isExported:!0},hp={description:E(`Expands or pads an array to specified row and column dimensions.`),args:[H(`array (any, range<any>)`,E(`The array to expand.`)),H(`rows (number)`,E(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),H(`columns (number, optional)`,E(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),H(`pad_with (any, default=0)`,E(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=I(e),a=la(t?.value,this.locale),o=n===void 0?i.length:la(n.value,this.locale);return a<i[0].length?new A(E(`The rows arguments (%s) must be greater or equal than the number of rows of the array.`,a.toString())):o<i.length?new A(E(`The columns arguments (%s) must be greater or equal than the number of columns of the array.`,o.toString())):Sa(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},gp={description:E(`Flattens all the values from one or more ranges into a single column.`),args:[H(`range (any, range<any>)`,E(`The first range to flatten.`)),H(`range2 (any, range<any>, repeating)`,E(`Additional ranges to flatten.`))],compute:function(...e){return[Ra(e,e=>e===void 0?{value:``}:e)]},isExported:!1},_p={description:E(`Calculates the frequency distribution of a range.`),args:[H(`data (range<number>)`,E(`The array of ranges containing the values to be counted.`)),H(`classes (number, range<number>)`,E(`The range containing the set of classes.`))],compute:function(e,t){let n=Ra([e],e=>e.value).filter(e=>typeof e==`number`),r=Ra([t],e=>e.value).filter(e=>typeof e==`number`).map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);r.push({initialIndex:r.length,value:1/0,count:0});let i=n.sort((e,t)=>e-t),a=0;for(let e of i){for(;e>r[a].value&&a<r.length-1;)a++;r[a].count++}return[r.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},vp={description:E(`Appends ranges horizontally and in sequence to return a larger array.`),args:[H(`range1 (any, range<any>)`,E(`The first range to be appended.`)),H(`range2 (any, range<any>, repeating)`,E(`Additional ranges to add to range1.`))],compute:function(...e){let t=Math.max(...e.map(e=>e?.[0]?.length??0)),n=[];for(let r of e){let e=I(r);for(let r=0;r<e.length;r++){let i=Array(t).fill({value:null});for(let t=0;t<e[r].length;t++)i[t]=e[r][t];n.push(i)}}return n},isExported:!0},yp={description:E(`Returns the matrix determinant of a square matrix.`),args:[H(`square_matrix (number, range<number>)`,E(`An range with an equal number of rows and columns representing a matrix whose determinant will be calculated.`))],compute:function(e){let t=sa(e,`square_matrix`);return Iu(t)?zu(t).determinant:new A(E(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},bp={description:E(`Returns the multiplicative inverse of a square matrix.`),args:[H(`square_matrix (number, range<number>)`,E(`An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated.`))],compute:function(e){let t=sa(e,`square_matrix`);if(!Iu(t))return new A(E(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=zu(t);return n||new A(E(`The matrix is not invertible.`))},isExported:!0},xp={description:E(`Calculates the matrix product of two matrices.`),args:[H(`matrix1 (number, range<number>)`,E(`The first matrix in the matrix multiplication operation.`)),H(`matrix2 (number, range<number>)`,E(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=sa(e,`matrix1`),r=sa(t,`matrix2`);return n.length===0||r.length===0?new A(E(`The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.`)):n.length===r[0].length?Vu(n,r):new A(E(`In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).`,n.length.toString(),r[0].length.toString()))},isExported:!0},Sp={description:E(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[H(`range1 (number, range<number>)`,E(`The first range whose entries will be multiplied with corresponding entries in the other ranges.`)),H(`range2 (number, range<number>, repeating)`,E(`The other range whose entries will be multiplied with corresponding entries in the other ranges.`))],compute:function(...e){if(!Fu(...e))return new A(E(`All the ranges must have the same dimensions.`));let t=e.map(I),n=0;for(let e=0;e<t[0].length;e++)for(let r=0;r<t[0][e].length;r++){if(!t.every(t=>typeof t[e][r].value==`number`))continue;let i=1;for(let n of t)i*=M(n[e][r],this.locale);n+=i}return n},isExported:!0};function Cp(e,t,n){if(!Fu(e,t))return new A(E(`The arguments array_x and array_y must have the same dimensions.`));let r=I(e),i=I(t),a=!1,o=0;for(let e in r)for(let t in r[e]){let s=r[e][t].value,c=i[e][t].value;typeof s!=`number`||typeof c!=`number`||(a=!0,o+=n(s,c))}return a?o:new A(E(`The arguments array_x and array_y must contain at least one pair of numbers.`))}let wp={description:E(`Calculates the sum of the difference of the squares of the values in two array.`),args:[H(`array_x (number, range<number>)`,E(`The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.`)),H(`array_y (number, range<number>)`,E(`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 Cp(e,t,(e,t)=>e**2-t**2)},isExported:!0},Tp={description:E(`Calculates the sum of the sum of the squares of the values in two array.`),args:[H(`array_x (number, range<number>)`,E(`The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.`)),H(`array_y (number, range<number>)`,E(`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 Cp(e,t,(e,t)=>e**2+t**2)},isExported:!0},Ep={description:E(`Calculates the sum of squares of the differences of values in two array.`),args:[H(`array_x (number, range<number>)`,E(`The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.`)),H(`array_y (number, range<number>)`,E(`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 Cp(e,t,(e,t)=>(e-t)**2)},isExported:!0},Dp=[H(`array (any, range<any>)`,E(`The array which will be transformed.`)),H(`ignore (number, default=0)`,E(`Whether to ignore certain types of values. By default, no values are ignored.`),[{value:0,label:E(`Keep all values (default)`)},{value:1,label:E(`Ignore blanks`)},{value:2,label:E(`Ignore errors`)},{value:3,label:E(`Ignore blanks and errors`)}]),H(`scan_by_column (number, default=false)`,E(`Scan the array by column. By default, the array is scanned by row.`),[{value:!1,label:E(`Scan by row (default)`)},{value:!0,label:E(`Scan by column`)}])];function Op(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!j(e.value);if(t===3)return e=>e.value!==null&&!j(e.value);throw new A(E(`Argument ignore must be between 0 and 3`))}let kp={description:E(`Transforms a range of cells into a single column.`),args:Dp,compute:function(e,t={value:0},n={value:!1}){let r=I(e),i=M(t.value,this.locale),a=(P(n.value)?r:Ta(r)).flat().filter(Op(i));return a.length===0?new Xi(E(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},Ap={description:E(`Transforms a range of cells into a single row.`),args:Dp,compute:function(e,t={value:0},n={value:!1}){let r=I(e),i=M(t.value,this.locale),a=(P(n.value)?r:Ta(r)).flat().filter(Op(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Xi(E(`No results for the given arguments of TOROW.`)):a},isExported:!0},jp={description:E(`Transposes the rows and columns of a range.`),args:[H(`range (any, range<any>)`,E(`The range to be transposed.`))],compute:function(e){let t=I(e),n=t[0].length,r=t.length;return Sa(n,r,(e,n)=>t[n][e])},isExported:!0},Mp={description:E(`Appends ranges vertically and in sequence to return a larger array.`),args:[H(`range1 (any, range<any>)`,E(`The first range to be appended.`)),H(`range2 (any, range<any>, repeating)`,E(`Additional ranges to add to range1.`))],compute:function(...e){let t=Math.max(...e.map(e=>I(e).length)),n=e.reduce((e,t)=>e+I(t)[0].length,0),r=Array(t).fill([]).map(()=>Array(n).fill({value:0})),i=0;for(let t of e){let e=I(t);for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)r[t][i+n]=e[t][n];i+=e[0].length}return r},isExported:!0},Np={description:E(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[H(`range (any, range<any>)`,E(`The range to wrap.`)),H(`wrap_count (number)`,E(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),H(`pad_with (any, default=0)`,E(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=I(e),i=la(t?.value,this.locale);if(!Pu(r))return new A(E(`Argument range must be a single row or column.`));let a=r.flat();return Sa(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},Pp={description:E(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[H(`range (any, range<any>)`,E(`The range to wrap.`)),H(`wrap_count (number)`,E(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),H(`pad_with (any, default=0)`,E(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=I(e),i=la(t?.value,this.locale);if(!Pu(r))return new A(E(`Argument range must be a single row or column.`));let a=r.flat();return Sa(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0};var Fp=l({FORMAT_LARGE_NUMBER:()=>Ip});let Ip={description:E(`Apply a large number format`),args:[H(`value (number)`,E(`The number.`)),H(`unit (string, optional)`,E(`The formatting unit. Use 'k', 'm', or 'b' to force the unit`),[{value:`k`,label:E(`Thousand`)},{value:`m`,label:E(`Million`)},{value:`b`,label:E(`Billion`)}])],compute:function(e,t){return{value:M(e,this.locale),format:Go(e,t,this.locale)}}};var Lp=class{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return`Success`}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==`Success`);if(r.length)return r}return`Success`}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},Rp=class extends Lp{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:n,canDispatch:r,uiActions:i,selection:a}){super(t),this.getters=e,this.ui=i,this.selection=a,this.dispatch=n,this.canDispatch=r}drawLayer(e,t){}},zp=class extends Rp{subtotalCells=new Set;handle(e){switch(e.type){case`START`:this.subtotalCells.clear();for(let e of this.getters.getSheetIds()){let t=this.getters.getCells(e);for(let e in t){let n=t[e];Bp(n)&&this.subtotalCells.add(n.id)}}break;case`UPDATE_CELL`:{if(!(`content`in e))return;let t=this.getters.getCell(e);if(!t)return;Bp(t)?this.subtotalCells.add(t.id):this.subtotalCells.delete(t.id);break}}wr.has(e.type)&&this.dispatch(`EVALUATE_CELLS`,{cellIds:Array.from(this.subtotalCells)})}};function Bp(e){return e.isFormula&&e.compiledFormula.tokens.some(e=>e.type===`SYMBOL`&&e.value.toUpperCase()===`SUBTOTAL`)}var Vp=l({ABS:()=>Up,ACOS:()=>Wp,ACOSH:()=>Gp,ACOT:()=>Kp,ACOTH:()=>qp,ASIN:()=>Jp,ASINH:()=>Yp,ATAN:()=>Xp,ATAN2:()=>Zp,ATANH:()=>Qp,CEILING:()=>$p,CEILING_MATH:()=>tm,CEILING_PRECISE:()=>nm,COS:()=>rm,COSH:()=>im,COT:()=>am,COTH:()=>om,COUNTBLANK:()=>sm,COUNTIF:()=>cm,COUNTIFS:()=>lm,COUNTUNIQUE:()=>um,COUNTUNIQUEIFS:()=>dm,CSC:()=>fm,CSCH:()=>pm,DECIMAL:()=>mm,DEGREES:()=>hm,EXP:()=>gm,FLOOR:()=>_m,FLOOR_MATH:()=>ym,FLOOR_PRECISE:()=>bm,INT:()=>nh,ISEVEN:()=>xm,ISODD:()=>Cm,ISO_CEILING:()=>Sm,LN:()=>wm,LOG:()=>Tm,MOD:()=>Dm,MUNIT:()=>Om,ODD:()=>km,PI:()=>Am,POWER:()=>jm,PRODUCT:()=>Mm,RAND:()=>Nm,RANDARRAY:()=>Pm,RANDBETWEEN:()=>Fm,ROUND:()=>Im,ROUNDDOWN:()=>Lm,ROUNDUP:()=>Rm,SEC:()=>zm,SECH:()=>Bm,SEQUENCE:()=>Vm,SIN:()=>Hm,SINH:()=>Um,SQRT:()=>Wm,SUBTOTAL:()=>Jm,SUM:()=>Ym,SUMIF:()=>Xm,SUMIFS:()=>Zm,TAN:()=>Qm,TANH:()=>$m,TRUNC:()=>th});let Hp=/^-?[a-z0-9]+$/i,Up={description:E(`Absolute value of a number.`),args:[H(`value (number)`,E(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(M(e,this.locale))},isExported:!0},Wp={description:E(`Inverse cosine of a value, in radians.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)>1?new A(E(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.acos(t)},isExported:!0},Gp={description:E(`Inverse hyperbolic cosine of a number.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.`))],compute:function(e){let t=M(e,this.locale);return t<1?new A(E(`The value (%s) must be greater than or equal to 1.`,t)):Math.acosh(t)},isExported:!0},Kp={description:E(`Inverse cotangent of a value.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=M(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},qp={description:E(`Inverse hyperbolic cotangent of a value.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)<=1?new A(E(`The value (%s) cannot be between -1 and 1 inclusive.`,t)):Math.log((t+1)/(t-1))/2},isExported:!0},Jp={description:E(`Inverse sine of a value, in radians.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)>1?new A(E(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.asin(t)},isExported:!0},Yp={description:E(`Inverse hyperbolic sine of a number.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(M(e,this.locale))},isExported:!0},Xp={description:E(`Inverse tangent of a value, in radians.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(M(e,this.locale))},isExported:!0},Zp={description:E(`Angle from the X axis to a point (x,y), in radians.`),args:[H(`x (number)`,E(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),H(`y (number)`,E(`The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`))],compute:function(e,t){let n=M(e,this.locale),r=M(t,this.locale);return n===0&&r===0?new $i(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},Qp={description:E(`Inverse hyperbolic tangent of a number.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)>=1?new A(E(`The value (%s) must be between -1 and 1 exclusive.`,t)):Math.atanh(t)},isExported:!0},$p={description:E(`Rounds number up to nearest multiple of factor.`),args:[H(`value (number)`,E(`The value to round up to the nearest integer multiple of factor.`)),H(`factor (number, default=1)`,E(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=M(e,this.locale),r=M(t,this.locale);return r<0&&n>0?new A(E(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.ceil(n/r)*r:0,format:e?.format}},isExported:!0};function em(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.ceil(e/t)*t:n===0?-Math.floor(Math.abs(e)/t)*t:-Math.ceil(Math.abs(e)/t)*t)}let tm={description:E(`Rounds number up to nearest multiple of factor.`),args:[H(`number (number)`,E(`The value to round up to the nearest integer multiple of significance.`)),H(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),H(`mode (number, default=0)`,E(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.`))],compute:function(e,t={value:1},n={value:0}){let r=M(t,this.locale);return{value:em(M(e,this.locale),r,M(n,this.locale)),format:e?.format}},isExported:!0},nm={description:E(`Rounds number up to nearest multiple of factor.`),args:[H(`number (number)`,E(`The value to round up to the nearest integer multiple of significance.`)),H(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=M(t,this.locale);return{value:em(M(e,this.locale),n),format:e?.format}},isExported:!0},rm={description:E(`Cosine of an angle provided in radians.`),args:[H(`angle (number)`,E(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(M(e,this.locale))},isExported:!0},im={description:E(`Hyperbolic cosine of any real number.`),args:[H(`value (number)`,E(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(M(e,this.locale))},isExported:!0},am={description:E(`Cotangent of an angle provided in radians.`),args:[H(`angle (number)`,E(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=M(e,this.locale);return t===0?new $i(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},om={description:E(`Hyperbolic cotangent of any real number.`),args:[H(`value (number)`,E(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=M(e,this.locale);return t===0?new $i(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},sm={description:E(`Number of empty values.`),args:[H(`value1 (any, range)`,E(`The first value or range in which to count the number of blanks.`)),H(`value2 (any, range, repeating)`,E(`Additional values or ranges in which to count the number of blanks.`))],compute:function(...e){return ya(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},cm={description:E(`A conditional count across a range.`),args:[H(`range (range)`,E(`The range that is tested against criterion.`)),H(`criterion (string)`,E(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return Ma(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},lm={description:E(`Count values depending on multiple criteria.`),args:[H(`criteria_range1 (range)`,E(`The range to check against criterion1.`)),H(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1.`)),H(`criteria_range2 (any, range, repeating)`,E(`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.`)),H(`criterion2 (string, repeating)`,E(`Additional criteria to check.`))],compute:function(...e){let t=0;return Ma(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},um={description:E(`Counts number of unique values in a range.`),args:[H(`value1 (any, range)`,E(`The first value or range to consider for uniqueness.`)),H(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider for uniqueness.`))],compute:function(...e){return ju(e)}},dm={description:E(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[H(`range (range)`,E(`The range of cells from which the number of unique values will be counted.`)),H(`criteria_range1 (range)`,E(`The range of cells over which to evaluate criterion1.`)),H(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.`)),H(`criteria_range2 (any, range, repeating)`,E(`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.`)),H(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=new Set;return Ma(t,(t,r)=>{let i=e[t]?.[r];za(i)&&n.add(i.value)},this.locale),n.size}},fm={description:E(`Cosecant of an angle provided in radians.`),args:[H(`angle (number)`,E(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=M(e,this.locale);return t===0?new $i(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},pm={description:E(`Hyperbolic cosecant of any real number.`),args:[H(`value (number)`,E(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=M(e,this.locale);return t===0?new $i(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},mm={description:E(`Converts from another base to decimal.`),args:[H(`value (string)`,E(`The number to convert.`)),H(`base (number)`,E(`The base to convert the value from.`))],compute:function(e,t){let n=M(t,this.locale);if(n=Math.floor(n),2>n||n>36)return new A(E(`The base (%s) must be between 2 and 36 inclusive.`,n));let r=N(e);if(r===``)return 0;if(!Hp.test(r))return new A(E(`The value (%s) must be a valid base %s representation.`,r,n));let i=parseInt(r,n);return isNaN(i)?new A(E(`The value (%s) must be a valid base %s representation.`,r,n)):i},isExported:!0},hm={description:E(`Converts an angle value in radians to degrees.`),args:[H(`angle (number)`,E(`The angle to convert from radians to degrees.`))],compute:function(e){return M(e,this.locale)*180/Math.PI},isExported:!0},gm={description:E(`Euler's number, e (~2.718) raised to a power.`),args:[H(`value (number)`,E(`The exponent to raise e.`))],compute:function(e){return Math.exp(M(e,this.locale))},isExported:!0},_m={description:E(`Rounds number down to nearest multiple of factor.`),args:[H(`value (number)`,E(`The value to round down to the nearest integer multiple of factor.`)),H(`factor (number, default=1)`,E(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=M(e,this.locale),r=M(t,this.locale);return r<0&&n>0?new A(E(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.floor(n/r)*r:0,format:e?.format}},isExported:!0};function vm(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.floor(e/t)*t:n===0?-Math.ceil(Math.abs(e)/t)*t:-Math.floor(Math.abs(e)/t)*t)}let ym={description:E(`Rounds number down to nearest multiple of factor.`),args:[H(`number (number)`,E(`The value to round down to the nearest integer multiple of significance.`)),H(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),H(`mode (number, default=0)`,E(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.`))],compute:function(e,t={value:1},n={value:0}){let r=M(t,this.locale);return{value:vm(M(e,this.locale),r,M(n,this.locale)),format:e?.format}},isExported:!0},bm={description:E(`Rounds number down to nearest multiple of factor.`),args:[H(`number (number)`,E(`The value to round down to the nearest integer multiple of significance.`)),H(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=M(t,this.locale);return{value:vm(M(e,this.locale),n),format:e?.format}},isExported:!0},xm={description:E(`Whether the provided value is even.`),args:[H(`value (number)`,E(`The value to be verified as even.`))],compute:function(e){let t=ca(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},Sm={description:E(`Rounds number up to nearest multiple of factor.`),args:[H(`number (number)`,E(`The value to round up to the nearest integer multiple of significance.`)),H(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:em(M(e,this.locale),M(t,this.locale)),format:e?.format}},isExported:!0},Cm={description:E(`Whether the provided value is even.`),args:[H(`value (number)`,E(`The value to be verified as even.`))],compute:function(e){let t=ca(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},wm={description:E(`The logarithm of a number, base e (euler's number).`),args:[H(`value (number)`,E(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=M(e,this.locale);return t<=0?new A(E(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},Tm={description:E(`The logarithm of a number, for a given base.`),args:[H(`value (number)`,E(`The value for which to calculate the logarithm.`)),H(`base (number, default=10)`,E(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=M(e,this.locale),r=M(t,this.locale);return n<=0?new A(E(`The value (%s) must be strictly positive.`,n)):r<=0?new A(E(`The base (%s) must be strictly positive.`,r)):r===1?new A(E(`The base must be different from 1.`)):Math.log10(n)/Math.log10(r)},isExported:!0};function Em(e,t){Nu(t,E(`The divisor must be different from 0.`));let n=e%t;return n>0&&t<0||n<0&&t>0?n+t:n}let Dm={description:E(`Modulo (remainder) operator.`),args:[H(`dividend (number)`,E(`The number to be divided to find the remainder.`)),H(`divisor (number)`,E(`The number to divide by.`))],compute:function(e,t){let n=M(t,this.locale);return{value:Em(M(e,this.locale),n),format:e?.format}},isExported:!0},Om={description:E(`Returns a n x n unit matrix, where n is the input dimension.`),args:[H(`dimension (number)`,E(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=la(e,this.locale);return t<1?new A(E(`The argument dimension must be positive`)):Ru(t)},isExported:!0},km={description:E(`Rounds a number up to the nearest odd integer.`),args:[H(`value (number)`,E(`The value to round to the next greatest odd number.`))],compute:function(e){let t=M(e,this.locale),n=Math.ceil(Math.abs(t));return n=n&1?n:n+1,{value:t<0?-n:n,format:e?.format}},isExported:!0},Am={description:E(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},jm={description:E(`A number raised to a power.`),args:[H(`base (number)`,E(`The number to raise to the exponent power.`)),H(`exponent (number)`,E(`The exponent to raise base to.`))],compute:function(e,t){let n=M(e,this.locale),r=M(t,this.locale);return n<0&&!Number.isInteger(r)?new A(E(`The exponent (%s) must be an integer when the base is negative.`,r)):{value:n**+r,format:e?.format}},isExported:!0},Mm={description:E(`Result of multiplying a series of numbers together.`),args:[H(`factor1 (number, range<number>)`,E(`The first number or range to calculate for the product.`)),H(`factor2 (number, range<number>, repeating)`,E(`More numbers or ranges to calculate for the product.`))],compute:function(...e){let t=0,n=1;for(let r of e)if(Ir(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),j(e))return r}else r!==void 0&&r.value!==null&&(n*=ca(r,this.locale),t+=1);return{value:t===0?0:n,format:ta(e[0])}},isExported:!0},Nm={description:E(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},Pm={description:E(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[H(`rows (number, default=1)`,E(`The number of rows to be returned.`)),H(`columns (number, default=1)`,E(`The number of columns to be returned.`)),H(`min (number, default=0)`,E(`The minimum number you would like returned.`)),H(`max (number, default=1)`,E(`The maximum number you would like returned.`)),H(`whole_number (boolean, default=FALSE)`,E(`Return a whole number or a decimal value.`),[{value:!1,label:E(`Decimal (default)`)},{value:!0,label:E(`Integer`)}])],compute:function(e={value:1},t={value:1},n={value:0},r={value:1},i={value:!1}){let a=la(t,this.locale),o=la(e,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=P(i);if(a<1)return new A(E(`The number of columns (%s) must be positive.`,a));if(o<1)return new A(E(`The number of rows (%s) must be positive.`,o));if(s>c)return new A(E(`The maximum (%s) must be greater than or equal to the minimum (%s).`,c,s));if(l&&(!Number.isInteger(s)||!Number.isInteger(c)))return new A(E(`The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.`,c.toString(),s.toString()));let u=Array(a);for(let e=0;e<a;e++){u[e]=Array(o);for(let t=0;t<o;t++)l?u[e][t]=Math.floor(Math.random()*(c-s+1)+s):u[e][t]=s+Math.random()*(c-s)}return u},isExported:!0},Fm={description:E(`Random integer between two values, inclusive.`),args:[H(`low (number)`,E(`The low end of the random range.`)),H(`high (number)`,E(`The high end of the random range.`))],compute:function(e,t){let n=M(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=M(t,this.locale);return Number.isInteger(r)||(r=Math.floor(r)),n>r?new A(E(`The high (%s) must be greater than or equal to the low (%s).`,r,n)):{value:n+Math.ceil((r-n+1)*Math.random())-1,format:e?.format}},isExported:!0},Im={description:E(`Rounds a number according to standard rules.`),args:[H(`value (number)`,E(`The value to round to places number of places.`)),H(`places (number, default=0)`,E(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=M(e,this.locale),r=M(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.round(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.round(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},Lm={description:E(`Rounds down a number.`),args:[H(`value (number)`,E(`The value to round to places number of places, always rounding down.`)),H(`places (number, default=0)`,E(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=M(e,this.locale),r=M(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.floor(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.floor(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},Rm={description:E(`Rounds up a number.`),args:[H(`value (number)`,E(`The value to round to places number of places, always rounding up.`)),H(`places (number, default=0)`,E(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=M(e,this.locale),r=M(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.ceil(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.ceil(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},zm={description:E(`Secant of an angle provided in radians.`),args:[H(`angle (number)`,E(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(M(e,this.locale))},isExported:!0},Bm={description:E(`Hyperbolic secant of any real number.`),args:[H(`value (number)`,E(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(M(e,this.locale))},isExported:!0},Vm={description:E(`Returns a sequence of numbers.`),args:[H(`rows (number)`,E(`The number of rows to return`)),H(`columns (number, optional, default=1)`,E(`The number of columns to return`)),H(`start (number, optional, default=1)`,E(`The first number in the sequence`)),H(`step (number, optional, default=1)`,E(`The amount to increment each value in the sequence`))],compute:function(e,t={value:1},n={value:1},r={value:1}){let i=M(n,this.locale),a=M(r,this.locale),o=la(e,this.locale),s=la(t,this.locale);return s<1?new A(E(`The number of columns (%s) must be positive.`,s)):o<1?new A(E(`The number of rows (%s) must be positive.`,o)):Sa(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},Hm={description:E(`Sine of an angle provided in radians.`),args:[H(`angle (number)`,E(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(M(e,this.locale))},isExported:!0},Um={description:E(`Hyperbolic sine of any real number.`),args:[H(`value (number)`,E(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(M(e,this.locale))},isExported:!0},Wm={description:E(`Positive square root of a positive number.`),args:[H(`value (number)`,E(`The number for which to calculate the positive square root.`))],compute:function(e){let t=M(e,this.locale);return t<0?new A(E(`The value (%s) must be positive or null.`,t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},Gm={1:`AVERAGE`,2:`COUNT`,3:`COUNTA`,4:`MAX`,5:`MIN`,6:`PRODUCT`,7:`STDEV`,8:`STDEVP`,9:`SUM`,10:`VAR`,11:`VARP`},Km=Object.entries(Gm).map(([e,t])=>({value:parseInt(e),label:E(`%s (include manually-hidden rows)`,t)})),qm=Object.entries(Gm).map(([e,t])=>({value:parseInt(e)+100,label:E(`%s (exclude manually-hidden rows)`,t)})),Jm={description:E(`Returns a subtotal for a vertical range of cells using a specified aggregation function.`),args:[H(`function_code (number)`,E(`The function to use in subtotal aggregation.`),[...Km,...qm]),H(`ref1 (meta, range<meta>)`,E(`The range or reference for which you want the subtotal.`)),H(`ref2 (meta, range<meta>, repeating)`,E(`Additional ranges or references for which you want the subtotal.`))],compute:function(e,...t){let n=la(e,this.locale),r=!0;if(n>100&&(n-=100,r=!1),n<1||n>11)return new A(E(`The function code (%s) must be between 1 to 11 or 101 to 111.`,n));let i=[];for(let e of t){let t=e[0][0],n=jc(t.value).sheetName,a=n?this.getters.getSheetIdByName(n):this.__originSheetId;if(!a)continue;let{top:o,left:s}=Ts(t.value),c=s+e.length-1,l=o+e[0].length-1;for(let e=o;e<=l;e++)if(!this.getters.isRowFiltered(a,e)&&!(!r&&this.getters.isRowHiddenByUser(a,e)))for(let t=s;t<=c;t++){let n=this.getters.getCorrespondingFormulaCell({sheetId:a,col:t,row:e});(!n||!Bp(n))&&i.push(this.getters.getEvaluatedCell({sheetId:a,col:t,row:e}))}}return this[Gm[n]].apply(this,[[i]])},isExported:!0},Ym={description:E(`Sum of a series of numbers and/or cells.`),args:[H(`value1 (number, range<number>)`,E(`The first number or range to add together.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional numbers or ranges to add to value1.`))],compute:function(...e){let t=e[0];return{value:Au(e,this.locale),format:ta(t)}},isExported:!0},Xm={description:E(`A conditional sum across a range.`),args:[H(`criteria_range (range)`,E(`The range which is tested against criterion.`)),H(`criterion (string)`,E(`The pattern or test to apply to range.`)),H(`sum_range (range, default=criteria_range)`,E(`The range to be summed, if different from range.`))],compute:function(e,t,n){n===void 0&&(n=e);let r=0;return Ma([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},Zm={description:E(`Sums a range depending on multiple criteria.`),args:[H(`sum_range (range)`,E(`The range to sum.`)),H(`criteria_range1 (range)`,E(`The range to check against criterion1.`)),H(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1.`)),H(`criteria_range2 (any, range, repeating)`,E(`Additional ranges to check.`)),H(`criterion2 (string, repeating)`,E(`Additional criteria to check.`))],compute:function(e,...t){let n=0;return Ma(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},Qm={description:E(`Tangent of an angle provided in radians.`),args:[H(`angle (number)`,E(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(M(e,this.locale))},isExported:!0},$m={description:E(`Hyperbolic tangent of any real number.`),args:[H(`value (number)`,E(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(M(e,this.locale))},isExported:!0};function eh(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let th={description:E(`Truncates a number.`),args:[H(`value (number)`,E(`The value to be truncated.`)),H(`places (number, default=0)`,E(`The number of significant digits to the right of the decimal point to retain.`))],compute:function(e,t={value:0}){return{value:eh(M(e,this.locale),M(t,this.locale)),format:e?.format}},isExported:!0},nh={description:E(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[H(`value (number)`,E(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(M(e,this.locale))},isExported:!0};var rh=l({AVEDEV:()=>ph,AVERAGE:()=>mh,AVERAGEA:()=>vh,AVERAGEIF:()=>yh,AVERAGEIFS:()=>bh,AVERAGE_WEIGHTED:()=>_h,CORREL:()=>Hh,COUNT:()=>xh,COUNTA:()=>Sh,COVAR:()=>Ch,COVARIANCE_P:()=>wh,COVARIANCE_S:()=>Th,FORECAST:()=>Eh,GROWTH:()=>Dh,INTERCEPT:()=>Oh,LARGE:()=>kh,LINEST:()=>Ah,LOGEST:()=>jh,MATTHEWS:()=>Mh,MAX:()=>Nh,MAXA:()=>Ph,MAXIFS:()=>Fh,MEDIAN:()=>Ih,MIN:()=>Lh,MINA:()=>Rh,MINIFS:()=>zh,PEARSON:()=>Vh,PERCENTILE:()=>Uh,PERCENTILE_EXC:()=>Wh,PERCENTILE_INC:()=>Gh,POLYFIT_COEFFS:()=>Kh,POLYFIT_FORECAST:()=>qh,QUARTILE:()=>Jh,QUARTILE_EXC:()=>Yh,QUARTILE_INC:()=>Xh,RANK:()=>Zh,RSQ:()=>Qh,SLOPE:()=>$h,SMALL:()=>eg,SPEARMAN:()=>tg,STDEV:()=>ng,STDEVA:()=>ag,STDEVP:()=>og,STDEVPA:()=>sg,STDEV_P:()=>rg,STDEV_S:()=>ig,STEYX:()=>cg,TREND:()=>lg,VAR:()=>ug,VARA:()=>pg,VARP:()=>mg,VARPA:()=>hg,VAR_P:()=>dg,VAR_S:()=>fg});let ih=[{value:!0,label:E(`b is calculated normally`)},{value:!1,label:E(`b is forced to 1`)}],ah=[{value:!1,label:E(`do not return additional regression statistics`)},{value:!0,label:E(`return additional regression statistics`)}],oh=[{value:1,label:E(`order 1 (Linear)`)},{value:2,label:E(`order 2 (Quadratic)`)},{value:3,label:E(`order 3 (Cubic)`)},{value:4,label:E(`order 4 (Quartic)`)},{value:5,label:E(`order 5 (Quintic)`)},{value:6,label:E(`order 6 (Sextic)`)}],sh=[{value:!0,label:E(`Compute intercept`)},{value:!1,label:E(`Force intercept to 0`)}],ch=[{value:0,label:E(`Minimum value`)},{value:1,label:E(`First quartile (25th percentile)`)},{value:2,label:E(`Median value (50th percentile)`)},{value:3,label:E(`Third quartile (75th percentile)`)},{value:4,label:E(`Maximum value`)}];function lh(e,t){let n=[],r=[],i=0,a=0;ga([e],e=>{n.push(e),i+=1}),ga([t],e=>{r.push(e),a+=1}),Mu(i===a,E(`[[FUNCTION_NAME]] has mismatched argument count %s vs %s.`,i,a));let o=[],s=[];for(let e=0;e<i;e++){let t=n[e]?.value,i=r[e]?.value;typeof t==`number`&&typeof i==`number`&&(s.push(t),o.push(i))}return{flatDataX:o,flatDataY:s}}function uh(e,t,n){let{flatDataX:r,flatDataY:i}=lh(e,t),a=i.length;Nu(a),n&&Nu(a-1);let o=0,s=0;for(let e=0;e<a;e++)o+=i[e],s+=r[e];let c=o/a,l=s/a,u=0;for(let e=0;e<a;e++)u+=(i[e]-c)*(r[e]-l);return u/(a-+!!n)}function dh(e,t,n,r){let i=0,a=n?xa:ba,o=a(e,(e,t)=>(i+=1,e+t),0,r);Nu(i),t&&Nu(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function fh(e,t,n,r){let i=M(t,r);Mu(n?0<=i&&i<=1:0<i&&i<1,E(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`));let a=[],o,s=0;return ga(e,e=>{let t=e?.value;typeof t==`number`&&(o=Na(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),Mu(s!==0,Ba),n||Mu(1/(s+1)<=i&&i<=s/(s+1),E(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),Gi(a,i,n)}let ph={description:E(`Average magnitude of deviations from mean.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){let t=0,n=ba(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new $i(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return ba(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},mh={description:E(`Numerical average value in a dataset, ignoring text.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the average value.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the average value.`))],compute:function(...e){return{value:Ku(e,this.locale),format:ta(e[0])}},isExported:!0},hh=E(`[[FUNCTION_NAME]] has mismatched range sizes.`),gh=E(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),_h={description:E(`Weighted average.`),args:[H(`values (number, range<number>)`,E(`Values to average.`)),H(`weights (number, range<number>)`,E(`Weights for each corresponding value.`)),H(`additional_values (number, range<number>, repeating)`,E(`Additional values to average.`)),H(`additional_weights (number, range<number>, repeating)`,E(`Additional weights.`))],compute:function(...e){let t=0,n=0;for(let r=0;r<e.length-1;r+=2){let i=e[r],a=e[r+1];if(!Fu(i,a))return new A(hh);if(Ir(i))for(let e=0;e<i.length;e++)for(let r=0;r<i[0].length;r++){let o=i[e][r].value,s=Ir(a)?a?.[e][r].value:M(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new A(gh);t+=o*s,n+=s;continue}if(c!==l)return new A(E(`[[FUNCTION_NAME]] expects number values.`))}else{let e=M(i,this.locale),r=Ir(a)?a?.[0][0].value:M(a,this.locale);if(typeof r==`number`){if(r<0)return new A(gh);t+=e*r,n+=r}}}return n===0?new $i(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:ta(e[0])}}},vh={description:E(`Numerical average value in a dataset.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the average value.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the average value.`))],compute:function(...e){let t=0,n=xa(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new $i(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:ta(e[0])}},isExported:!0},yh={description:E(`Average of values depending on criteria.`),args:[H(`criteria_range (number, range<number>)`,E(`The range to check against criterion.`)),H(`criterion (string)`,E(`The pattern or test to apply to criteria_range.`)),H(`average_range (number, range<number>, default=criteria_range)`,E(`The range to average. If not included, criteria_range is used for the average instead.`))],compute:function(e,t,n){let r=I(n===void 0?e:n),i=0,a=0;return Ma([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new $i(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},bh={description:E(`Average of values depending on multiple criteria.`),args:[H(`average_range (range)`,E(`The range to average.`)),H(`criteria_range1 (range)`,E(`The range to check against criterion1.`)),H(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1.`)),H(`criteria_range2 (any, range, repeating)`,E(`Additional criteria_range and criterion to check.`)),H(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=I(e),r=0,i=0;return Ma(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new $i(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},xh={description:E(`The number of numeric values in dataset.`),args:[H(`value1 (number, any, range<number>)`,E(`The first value or range to consider when counting.`)),H(`value2 (number, any, range<number>, repeating)`,E(`Additional values or ranges to consider when counting.`))],compute:function(...e){return qu(e,this.locale)},isExported:!0},Sh={description:E(`The number of values in a dataset.`),args:[H(`value1 (any, range)`,E(`The first value or range to consider when counting.`)),H(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider when counting.`))],compute:function(...e){return Ju(e)},isExported:!0},Ch={description:E(`The covariance of a dataset.`),args:[H(`data_y (any, range)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (any, range)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return uh(e,t,!1)},isExported:!0},wh={description:E(`The covariance of a dataset.`),args:[H(`data_y (any, range)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (any, range)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return uh(e,t,!1)},isExported:!0},Th={description:E(`The sample covariance of a dataset.`),args:[H(`data_y (any, range)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (any, range)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return uh(e,t,!0)},isExported:!0},Eh={description:E(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[H(`x (number, range<number>)`,E(`The value(s) on the x-axis to forecast.`)),H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t,n){let{flatDataX:r,flatDataY:i}=lh(t,n);return r.length===0||i.length===0?new Xi(Ba):id([i],[r],Ca(I(e),e=>M(e,this.locale)),!0)},isExported:!0},Dh={description:E(`Fits points to exponential growth trend.`),args:[H(`known_data_y (range<number>)`,E(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.`)),H(`known_data_x (range<number>, default={1;2;3;...})`,E(`The values of the independent variable(s) corresponding with known_data_y.`)),H(`new_data_x (any, range, default=known_data_x)`,E(`The data points to return the y values for on the ideal curve fit.`)),H(`b (boolean, default=TRUE)`,E(`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.`),ih)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new A(Va(`known_data_y`)):nd(id(rd(sa(e,`known_data_y`)),sa(t,`known_data_x`),sa(n,`new_data_y`),P(r)))}},Oh={description:E(`Compute the intercept of the linear regression.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lh(e,t);if(n.length===0||r.length===0)return new Xi(Ba);let[[],[i]]=Qu([n],[r]);return i},isExported:!0},kh={description:E(`Nth largest element from a data set.`),args:[H(`data (any, range)`,E(`Array or range containing the dataset to consider.`)),H(`n (number)`,E(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(M(t?.value,this.locale)),r=[],i,a=0;ga([e],e=>{typeof e?.value==`number`&&(i=Na(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.shift(),a--))});let o=r.shift();return o===void 0?new A(Ba):a<n?new A(E(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},Ah={description:E(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>, default={1;2;3;...})`,E(`The range representing the array or matrix of independent data.`)),H(`calculate_b (boolean, default=TRUE)`,E(`A flag specifying whether to compute the slope or not`),ih),H(`verbose (boolean, default=FALSE)`,E(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),ah)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new A(Va(`data_y`)):Qu(sa(t,`data_x`),sa(e,`data_y`),P(n),P(r))},isExported:!0},jh={description:E(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>, optional, default={1;2;3;...})`,E(`The range representing the array or matrix of independent data.`)),H(`calculate_b (boolean, default=TRUE)`,E(`A flag specifying whether to compute the slope or not`),ih),H(`verbose (boolean, default=FALSE)`,E(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),ah)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new A(Va(`data_y`));let i=Qu(sa(t,`data_x`),rd(sa(e,`data_y`)),P(n),P(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},Mh={description:E(`Compute the Matthews correlation coefficient of a dataset.`),args:[H(`data_x (range)`,E(`The range representing the array or matrix of observed data.`)),H(`data_y (range)`,E(`The range representing the array or matrix of predicted data.`))],compute:function(e,t){let n=e.flat(),r=t.flat();if(Gu(n,r),n.length===0||r.length===0)return new Xi(Ba);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=P(n[e]);t===P(r[e])?t?o++:a++:t?c++:s++}return(o*a-s*c)/Math.sqrt((o+s)*(o+c)*(a+s)*(a+c))},isExported:!1},Nh={description:E(`Maximum value in a numeric dataset.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the maximum value.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the maximum value.`))],compute:function(...e){return Yu(e,this.locale)},isExported:!0},Ph={description:E(`Maximum numeric value in a dataset.`),args:[H(`value1 (any, range)`,E(`The first value or range to consider when calculating the maximum value.`)),H(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider when calculating the maximum value.`))],compute:function(...e){let t=xa(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:ta(e[0])}},isExported:!0},Fh={description:E(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[H(`range (range)`,E(`The range of cells from which the maximum will be determined.`)),H(`criteria_range1 (range)`,E(`The range of cells over which to evaluate criterion1.`)),H(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.`)),H(`criteria_range2 (any, range, repeating)`,E(`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.`)),H(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=-1/0;return Ma(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n<i?i:n)},this.locale),n===-1/0?0:n},isExported:!0},Ih={description:E(`Median value in a numeric dataset.`),args:[H(`value1 (any, range)`,E(`The first value or range to consider when calculating the median value.`)),H(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider when calculating the median value.`))],compute:function(...e){let t=[];return _a(e,e=>{t.push(e)},this.locale),{value:fh(t,{value:.5},!0,this.locale),format:ta(t[0])}},isExported:!0},Lh={description:E(`Minimum value in a numeric dataset.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the minimum value.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the minimum value.`))],compute:function(...e){return Xu(e,this.locale)},isExported:!0},Rh={description:E(`Minimum numeric value in a dataset.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the minimum value.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the minimum value.`))],compute:function(...e){let t=xa(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:ta(e[0])}},isExported:!0},zh={description:E(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[H(`range (range)`,E(`The range of cells from which the minimum will be determined.`)),H(`criteria_range1 (range)`,E(`The range of cells over which to evaluate criterion1.`)),H(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.`)),H(`criteria_range2 (any, range, repeating)`,E(`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.`)),H(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=1/0;return Ma(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n>i?i:n)},this.locale),n===1/0?0:n},isExported:!0};function Bh(e,t){let{flatDataX:n,flatDataY:r}=lh(e,t);if(n.length===0||r.length===0)return new Xi(Ba);let i=n.length,a=0,o=0,s=0,c=0,l=0;for(let e=0;e<i;e++){let t=n[e],i=r[e];a+=t,o+=i,s+=t*i,c+=t*t,l+=i*i}return(i*s-a*o)/Math.sqrt((i*c-a*a)*(i*l-o*o))}let Vh={description:E(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return Bh(e,t)},isExported:!0},Hh=Vh,Uh={description:E(`Value at a given percentile of a dataset.`),args:[H(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),H(`percentile (number)`,E(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return Gh.compute.bind(this)(e,t)},isExported:!0},Wh={description:E(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[H(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),H(`percentile (number)`,E(`The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.`))],compute:function(e,t){return{value:fh([e],t,!1,this.locale),format:ta(e)}},isExported:!0},Gh={description:E(`Value at a given percentile of a dataset.`),args:[H(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),H(`percentile (number)`,E(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:fh([e],t,!0,this.locale),format:ta(e)}},isExported:!0},Kh={description:E(`Compute the coefficients of polynomial regression of the dataset.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`)),H(`order (number)`,E(`The order of the polynomial to fit the data, between 1 and 6.`),oh),H(`intercept (boolean, default=TRUE)`,E(`A flag specifying whether to compute the intercept or not.`),sh)],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=lh(e,t);return i.length===0||a.length===0?new Xi(Ba):$u(a,i,M(n,this.locale),P(r))},isExported:!1},qh={description:E(`Predict value by computing a polynomial regression of the dataset.`),args:[H(`x (number, range<number>)`,E(`The value(s) on the x-axis to forecast.`)),H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`)),H(`order (number)`,E(`The order of the polynomial to fit the data, between 1 and 6.`),oh),H(`intercept (boolean, default=TRUE)`,E(`A flag specifying whether to compute the intercept or not.`),sh)],compute:function(e,t,n,r,i={value:!0}){let a=M(r,this.locale),{flatDataX:o,flatDataY:s}=lh(t,n);if(o.length===0||s.length===0)return new Xi(Ba);let c=$u(s,o,a,P(i)).flat();return Ca(I(e),e=>td(c,M(e,this.locale),a))},isExported:!1},Jh={description:E(`Value nearest to a specific quartile of a dataset.`),args:[H(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),H(`quartile_number (number)`,E(`Which quartile value to return.`),ch)],compute:function(e,t){return Xh.compute.bind(this)(e,t)},isExported:!0},Yh={description:E(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[H(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),H(`quartile_number (number)`,E(`Which quartile value, exclusive of 0 and 4, to return.`),[{value:1,label:E(`First quartile (25th percentile)`)},{value:2,label:E(`Median value (50th percentile)`)},{value:3,label:E(`Third quartile (75th percentile)`)}])],compute:function(e,t){let n={value:.25*Math.trunc(M(t,this.locale))};return{value:fh([e],n,!1,this.locale),format:ta(e)}},isExported:!0},Xh={description:E(`Value nearest to a specific quartile of a dataset.`),args:[H(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),H(`quartile_number (number)`,E(`Which quartile value to return.`),ch)],compute:function(e,t){let n={value:.25*Math.trunc(M(t,this.locale))};return{value:fh([e],n,!0,this.locale),format:ta(e)}},isExported:!0},Zh={description:E(`Returns the rank of a specified value in a dataset.`),args:[H(`value (number)`,E(`The value whose rank will be determined.`)),H(`data (range)`,E(`The range containing the dataset to consider.`)),H(`is_ascending (boolean, default=FALSE)`,E(`Whether to consider the values in data in descending or ascending order.`),[{value:!1,label:E(`Descending`)},{value:!0,label:E(`Ascending`)}])],compute:function(e,t,n={value:!1}){let r=P(n),i=M(e,this.locale),a=1,o=!1;for(let e of t)for(let t of e){if(typeof t.value!=`number`)continue;let e=M(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Xi(E(`Value not found in the given data.`))},isExported:!0},Qh={description:E(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=Bh(e,t);if(n instanceof Error)throw n;return n**2},isExported:!0},$h={description:E(`Compute the slope of the linear regression.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lh(e,t);if(n.length===0||r.length===0)return new Xi(Ba);let[[i]]=Qu([n],[r]);return i},isExported:!0},eg={description:E(`Nth smallest element in a data set.`),args:[H(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),H(`n (number)`,E(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(M(t?.value,this.locale)),r=[],i,a=0;ga([e],e=>{typeof e?.value==`number`&&(i=Na(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.pop(),a--))});let o=r.pop();return o===void 0?new A(Ba):a<n?new A(E(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},tg={description:E(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lh(t,e);if(n.length===0||r.length===0)return new Xi(Ba);let i=n.length,a=n.map((e,t)=>[e,r[t]]);a.sort((e,t)=>e[0]-t[0]);for(let e=0;e<i;++e)a[e][0]=e;a.sort((e,t)=>e[1]-t[1]);let o=0;for(let e=0;e<i;++e)o+=(a[e][0]-e)**2;return 1-6*o/(i**3-i)},isExported:!1},ng={description:E(`Standard deviation.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Math.sqrt(ug.compute.bind(this)(...e))},isExported:!0},rg={description:E(`Standard deviation of entire population.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Math.sqrt(dg.compute.bind(this)(...e))},isExported:!0},ig={description:E(`Standard deviation.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Math.sqrt(fg.compute.bind(this)(...e))},isExported:!0},ag={description:E(`Standard deviation of sample (text as 0).`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Math.sqrt(pg.compute.bind(this)(...e))},isExported:!0},og={description:E(`Standard deviation of entire population.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Math.sqrt(mg.compute.bind(this)(...e))},isExported:!0},sg={description:E(`Standard deviation of entire population (text as 0).`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Math.sqrt(hg.compute.bind(this)(...e))},isExported:!0},cg={description:E(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lh(e,t);return n.length===0||r.length===0?new Xi(Ba):Qu([n],[r],!0,!0)[1][2]},isExported:!0},lg={description:E(`Fits points to linear trend derived via least-squares.`),args:[H(`known_data_y (number, range<number>)`,E(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.`)),H(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,E(`The values of the independent variable(s) corresponding with known_data_y.`)),H(`new_data_x (number, range<number>, optional, default=known_data_x)`,E(`The data points to return the y values for on the ideal curve fit.`)),H(`b (boolean, optional, default=TRUE)`,E(`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.`),ih)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new A(Va(`known_data_y`)):id(sa(e,`known_data_y`),sa(t,`known_data_x`),sa(n,`new_data_y`),P(r))}},ug={description:E(`Variance.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return dh(e,!0,!1,this.locale)},isExported:!0},dg={description:E(`Variance of entire population.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return dh(e,!1,!1,this.locale)},isExported:!0},fg={description:E(`Variance.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return dh(e,!0,!1,this.locale)},isExported:!0},pg={description:E(`Variance of sample (text as 0).`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return dh(e,!0,!0,this.locale)},isExported:!0},mg={description:E(`Variance of entire population.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return dh(e,!1,!1,this.locale)},isExported:!0},hg={description:E(`Variance of entire population (text as 0).`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return dh(e,!1,!0,this.locale)},isExported:!0};var gg=l({DAVERAGE:()=>yg,DCOUNT:()=>bg,DCOUNTA:()=>xg,DGET:()=>Sg,DMAX:()=>Cg,DMIN:()=>wg,DPRODUCT:()=>Tg,DSTDEV:()=>Eg,DSTDEVP:()=>Dg,DSUM:()=>Og,DVAR:()=>kg,DVARP:()=>Ag});function _g(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(N(e[t][0]).toUpperCase(),t);let o=t?.value;if(typeof o!=`number`&&typeof o!=`string`)throw new A(E(`The field must be a number or a string`));let s;if(typeof o==`number`){if(s=Math.trunc(o)-1,s<0||a-1<s)throw new A(E(`The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.`,{fieldValue:o.toString(),dimRowDB:a.toString()}))}else{let e=N(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new A(E(`The field (%s) must be one of %s.`,N(t),[...i.keys()].toString()))}let c=n[0].length;if(c<2)throw new A(E(`The criteria range contains %s row, it must be at least 2 rows.`,c.toString()));let l=new Set,u=e[0].length;for(let t=1;t<c;t++){let a=[],o=!0;for(let r=0;r<n.length;r++){let s=N(n[r][0]).toUpperCase(),c=i.get(s),l=n[r][t];if(l.value!==null)if(c!==void 0)a.push([e[c].slice(1,u)]),a.push(l);else{o=!1;break}}if(o)if(a.length>0)Ma(a,(e,t)=>{l.add(t)},r,!0);else{l=new Set(Array(u-1).keys());break}}let d=e[s];return[...l].map(e=>d[e+1])}let vg=[H(`database (range)`,E(`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.`)),H(`field (number, string)`,E(`Indicates which column in database contains the values to be extracted and operated on.`)),H(`criteria (range)`,E(`An array or range containing zero or more criteria to filter the database values by before operating.`))],yg={description:E(`Average of a set of values from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return mh.compute.bind(this)([r])},isExported:!0},bg={description:E(`Counts values from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return xh.compute.bind(this)([r])},isExported:!0},xg={description:E(`Counts values and text from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return Sh.compute.bind(this)([r])},isExported:!0},Sg={description:E(`Single value from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return r.length===1?r[0]:new A(E(`More than one match found in DGET evaluation.`))},isExported:!0},Cg={description:E(`Maximum of values from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return Nh.compute.bind(this)([r])},isExported:!0},wg={description:E(`Minimum of values from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return Lh.compute.bind(this)([r])},isExported:!0},Tg={description:E(`Product of values from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return Mm.compute.bind(this)([r])},isExported:!0},Eg={description:E(`Standard deviation of population sample from table.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return ng.compute.bind(this)([r])},isExported:!0},Dg={description:E(`Standard deviation of entire population from table.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return og.compute.bind(this)([r])},isExported:!0},Og={description:E(`Sum of values from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return Ym.compute.bind(this)([r])},isExported:!0},kg={description:E(`Variance of population sample from table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return ug.compute.bind(this)([r])},isExported:!0},Ag={description:E(`Variance of a population from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return mg.compute.bind(this)([r])},isExported:!0},jg=E(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),Mg=E(`There must be both positive and negative values in cashflow_amounts.`),Ng=e=>E(`The cost (%s) must be positive or null.`,e),Pg=e=>E(`The cost (%s) must be strictly positive.`,e),Fg=e=>E(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),Ig=e=>E(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),Lg=e=>E(`The depreciation factor (%s) must be strictly positive.`,e),Rg=e=>E(`The discount (%s) must be different from -1.`,e),zg=e=>E(`The discount (%s) must be strictly positive.`,e),Bg=e=>E(`The discount (%s) must be smaller than 1.`,e),Vg=e=>E(`The effective_rate (%s) must be strictly positive.`,e),Hg=e=>E(`The end_period (%s) must be positive or null.`,e),Ug=(e,t)=>E(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),Wg=e=>E(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),Gg=(e,t)=>E(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),Kg=e=>E(`The first_period (%s) must be strictly positive.`,e),qg=e=>E(`The future_value (%s) must be strictly positive.`,e),Jg=e=>E(`The investment (%s) must be strictly positive.`,e),Yg=e=>E(`The issue (%s) must be positive or null.`,e),Xg=(e,t)=>E(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),Zg=e=>E(`The last_period (%s) must be strictly positive.`,e),Qg=e=>E(`The life (%s) must be strictly positive.`,e),$g=(e,t)=>E(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),e_=e=>E(`The month (%s) must be between 1 and 12 inclusive.`,e),t_=e=>E(`The nominal_rate (%s) must be strictly positive.`,e),n_=e=>E(`The number_of_periods (%s) must be different from zero.`,e),r_=e=>E(`The number_of_periods (%s) must be strictly positive.`,e),i_=e=>E(`The period must be between 1 and number_of_periods (%s)`,e),a_=(e,t)=>E(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),o_=e=>E(`The period (%s) must be positive or null.`,e),s_=e=>E(`The periods_by_year (%s) must be strictly positive.`,e),c_=(e,t)=>E(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),l_=e=>E(`The period (%s) must be strictly positive.`,e),u_=e=>E(`The present_value (%s) must be strictly positive.`,e),d_=e=>E(`The price (%s) must be strictly positive.`,e),f_=(e,t)=>E(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),p_=e=>E(`The purchase_date (%s) must be positive or null.`,e),m_=e=>E(`The rate_guess (%s) must be strictly greater than -1.`,e),h_=e=>E(`The rate (%s) must be positive or null.`,e),g_=e=>E(`The rate (%s) must be strictly positive.`,e),__=e=>E(`The redemption (%s) must be strictly positive.`,e),v_=e=>E(`The salvage (%s) must be positive or null.`,e),y_=(e,t)=>E(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),b_=(e,t)=>E(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),x_=(e,t)=>E(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),S_=(e,t)=>E(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),C_=e=>E(`The start_period (%s) must be positive or null.`,e),w_=(e,t)=>E(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),T_=e=>E(`The unit (%s) must be strictly positive.`,e),E_=e=>E(`The yield (%s) must be positive or null.`,e);function D_(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function O_(e){return![0,1,2,3,4].includes(e)}function k_(e){return![1,2,4].includes(e)}function A_(e,t,n){let r=F(e,n),i=F(t,n),a=F(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}let j_=[{value:0,label:E(`US (NASD) 30/360`)},{value:1,label:E(`Actual/Actual`)},{value:2,label:E(`Actual/360`)},{value:3,label:E(`Actual/365`)},{value:4,label:E(`European 30/360`)}];var M_=l({DATE:()=>P_,DATEDIF:()=>F_,DATEVALUE:()=>I_,DAY:()=>L_,DAYS:()=>R_,DAYS360:()=>z_,EDATE:()=>B_,EOMONTH:()=>V_,HOUR:()=>H_,ISOWEEKNUM:()=>U_,MINUTE:()=>W_,MONTH:()=>G_,MONTH_END:()=>cv,MONTH_START:()=>sv,NETWORKDAYS:()=>K_,NETWORKDAYS_INTL:()=>Y_,NOW:()=>X_,QUARTER:()=>lv,QUARTER_END:()=>dv,QUARTER_START:()=>uv,SECOND:()=>Z_,TIME:()=>Q_,TIMEVALUE:()=>$_,TODAY:()=>ev,WEEKDAY:()=>tv,WEEKNUM:()=>nv,WORKDAY:()=>rv,WORKDAY_INTL:()=>iv,YEAR:()=>av,YEARFRAC:()=>ov,YEAR_END:()=>pv,YEAR_START:()=>fv}),N_=function(e){return e.WHOLE_YEARS=`Y`,e.WHOLE_MONTHS=`M`,e.WHOLE_DAYS=`D`,e.DAYS_WITHOUT_WHOLE_MONTHS=`MD`,e.MONTH_WITHOUT_WHOLE_YEARS=`YM`,e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR=`YD`,e}(N_||{});let P_={description:E(`Converts year/month/day into a date.`),args:[H(`year (number)`,E(`The year component of the date.`)),H(`month (number)`,E(`The month component of the date.`)),H(`day (number)`,E(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=Math.trunc(M(n,this.locale));if(r<0||r>9999)return new A(E(`The year (%s) must be between 0 and 9999 inclusive.`,r.toString()));r<1900&&(r+=1900);let o=Ci(new O(r,i-1,a));return o<0?new A(E(`The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.`)):{value:o,format:this.locale.dateFormat}},isExported:!0},F_={description:E(`Calculates the number of days, months, or years between two dates.`),args:[H(`start_date (date)`,E(`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.`)),H(`end_date (date)`,E(`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.`)),H(`unit (string)`,E(`A text abbreviation for unit of time.`),[{value:`Y`,label:E(`The number of whole years between start_date and end_date`)},{value:`M`,label:E(`The number of whole months between start_date and end_date`)},{value:`D`,label:E(`The number of days between start_date and end_date`)},{value:`MD`,label:E(`The number of days between start_date and end_date after subtracting whole months`)},{value:`YM`,label:E(`The number of whole months between start_date and end_date after subtracting whole years`)},{value:`YD`,label:E(`The number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart`)}])],compute:function(e,t,n){let r=N(n).toUpperCase();if(!Object.values(N_).includes(r))return new A(aa(Object.values(N_),N(n)));let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Si(i),s=Si(a);if(a<i)return new A(E(`start_date (%s) should be on or before end_date (%s).`,o.toLocaleDateString(),s.toLocaleDateString()));switch(r){case`Y`:return Mi(o,s);case`M`:return Ai(o,s);case`D`:return ji(o,s);case`YM`:return Ai(o,s)-Mi(o,s)*12;case`MD`:let e=s.getDate()-o.getDate();return e<0&&(e=Ti(new O(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case`YD`:{if(Ni(i,a))return ji(o,s);let e=new O(o.getFullYear(),s.getMonth(),s.getDate()),t=ji(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=ji(o,e)),t}}},isExported:!0},I_={description:E(`Converts a date string to a date value.`),args:[H(`date_string (string)`,E(`The string representing the date.`))],compute:function(e){let t=N(e),n=fi(t,this.locale);return n===null?new A(E(`The date_string (%s) cannot be parsed to date/time.`,t.toString())):Math.trunc(n.value)},isExported:!0},L_={description:E(`Day of the month that a specific date falls on.`),args:[H(`date (string)`,E(`The date from which to extract the day.`))],compute:function(e){return F(e,this.locale).getDate()},isExported:!0},R_={description:E(`Number of days between two dates.`),args:[H(`end_date (date)`,E(`The end of the date range.`)),H(`start_date (date)`,E(`The start of the date range.`))],compute:function(e,t){let n=F(e,this.locale),r=F(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/Qr)},isExported:!0},z_={description:E(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[H(`start_date (date)`,E(`The start date to consider in the calculation.`)),H(`end_date (date)`,E(`The end date to consider in the calculation.`)),H(`method (boolean, default=false)`,E(`An indicator of what day count method to use.`),[{value:!1,label:E(`U.S. NASD method (default)`)},{value:!0,label:E(`European method`)}])],compute:function(e,t,n={value:!1}){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=ki(r,i,P(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},B_={description:E(`Date a number of months before/after another date.`),args:[H(`start_date (date)`,E(`The date from which to calculate the result.`)),H(`months (number)`,E(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:Ci(Di(F(e,this.locale),Math.trunc(M(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},V_={description:E(`Last day of a month before or after a date.`),args:[H(`start_date (date)`,E(`The date from which to calculate the result.`)),H(`months (number)`,E(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=F(e,this.locale),r=Math.trunc(M(t,this.locale));return{value:Ci(new O(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},H_={description:E(`Hour component of a specific time.`),args:[H(`time (date)`,E(`The time from which to calculate the hour component.`))],compute:function(e){return F(e,this.locale).getHours()},isExported:!0},U_={description:E(`ISO week number of the year.`),args:[H(`date (date)`,E(`The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`))],compute:function(e){let t=F(e,this.locale),n=t.getFullYear(),r=1;for(;new O(n,0,r).getDay()!==4;)r+=1;let i=new O(n,0,r-3),a=31;for(;new O(n,11,a).getDay()!==4;)--a;let o=new O(n,11,a+3),s;s=i.getTime()<=t.getTime()?t.getTime()<=o.getTime()?0:1:-1;let c;switch(s){case 0:c=i;break;case 1:c=new O(n,11,a+3+1);break;case-1:let e=1;for(;new O(n-1,0,e).getDay()!==4;)e+=1;c=new O(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/Qr;return Math.floor(l/7)+1},isExported:!0},W_={description:E(`Minute component of a specific time.`),args:[H(`time (date)`,E(`The time from which to calculate the minute component.`))],compute:function(e){return F(e,this.locale).getMinutes()},isExported:!0},G_={description:E(`Month of the year a specific date falls in`),args:[H(`date (date)`,E(`The date from which to extract the month.`))],compute:function(e){return F(e,this.locale).getMonth()+1},isExported:!0},K_={description:E(`Net working days between two provided days.`),args:[H(`start_date (date)`,E(`The start date of the period from which to calculate the number of net working days.`)),H(`end_date (date)`,E(`The end date of the period from which to calculate the number of net working days.`)),H(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the date serial numbers to consider holidays.`))],compute:function(e,t,n){return Y_.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function q_(e){let t=e?.value;if(typeof t==`string`){Mu(t.length===7&&[...t].every(e=>e===`0`||e===`1`),E(`When weekend is a string (%s) it must be composed of "0" or "1".`,t));let e=[];for(let n=0;n<7;n++)t[n]===`1`&&e.push((n+1)%7);return e}if(typeof t==`number`)return Mu(1<=t&&t<=7||11<=t&&t<=17,E(`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 A(E(`The weekend must be a number or a string.`))}let J_=[{value:1,label:E(`Saturday/Sunday are weekends`)},{value:2,label:E(`Sunday/Monday are weekends`)},{value:3,label:E(`Monday/Tuesday are weekends`)},{value:4,label:E(`Tuesday/Wednesday are weekends`)},{value:5,label:E(`Wednesday/Thursday are weekends`)},{value:6,label:E(`Thursday/Friday are weekends`)},{value:7,label:E(`Friday/Saturday are weekends`)},{value:11,label:E(`Sunday is the only weekend`)},{value:12,label:E(`Monday is the only weekend`)},{value:13,label:E(`Tuesday is the only weekend`)},{value:14,label:E(`Wednesday is the only weekend`)},{value:15,label:E(`Thursday is the only weekend`)},{value:16,label:E(`Friday is the only weekend`)},{value:17,label:E(`Saturday is the only weekend`)}],Y_={description:E(`Net working days between two dates (specifying weekends).`),args:[H(`start_date (date)`,E(`The start date of the period from which to calculate the number of net working days.`)),H(`end_date (date)`,E(`The end date of the period from which to calculate the number of net working days.`)),H(`weekend (any, default=1)`,E(`A number or string representing which days of the week are considered weekends.`),J_),H(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the dates to consider as holidays.`))],compute:function(e,t,n={value:1},r){let i=F(e,this.locale),a=F(t,this.locale),o=q_(n),s=new Set;r!==void 0&&ga([r],e=>{let t=F(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=O.fromTimestamp((c?i:a).getTime()),u=O.fromTimestamp((c?a:i).getTime()),d=l.getTime(),f=u.getTime(),p=0;for(;f<=d;)!o.includes(u.getDay())&&!s.has(f)&&(p+=1),u.setDate(u.getDate()+1),f=u.getTime();return c?-p:p},isExported:!0},X_={description:E(`Current date and time as a date value.`),args:[],compute:function(){let e=O.now(),t=e.getTime()-Zr.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Qr)+n,format:Du(this.locale)}},isExported:!0},Z_={description:E(`Minute component of a specific time.`),args:[H(`time (date)`,E(`The time from which to calculate the second component.`))],compute:function(e){return F(e,this.locale).getSeconds()},isExported:!0},Q_={description:E(`Converts hour/minute/second into a time.`),args:[H(`hour (number)`,E(`The hour component of the time.`)),H(`minute (number)`,E(`The minute component of the time.`)),H(`second (number)`,E(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=Math.trunc(M(n,this.locale));return i+=Math.floor(a/60),a=a%60+(a<0?60:0),r+=Math.floor(i/60),i=i%60+(i<0?60:0),r%=24,r<0?new A(E(`The function [[FUNCTION_NAME]] result cannot be negative`)):{value:r/24+i/1440+a/(1440*60),format:this.locale.timeFormat}},isExported:!0},$_={description:E(`Converts a time string into its serial number representation.`),args:[H(`time_string (string)`,E(`The string that holds the time representation.`))],compute:function(e){let t=N(e),n=fi(t,this.locale);if(n===null)return new A(E(`The time_string (%s) cannot be parsed to date/time.`,t));let r=n.value-Math.trunc(n.value);return r<0?1+r:r},isExported:!0},ev={description:E(`Current date as a date value.`),args:[],compute:function(){let e=O.now();return{value:Ci(new O(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},tv={description:E(`Day of the week of the date provided (as number).`),args:[H(`date (date)`,E(`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.`)),H(`type (number, default=1)`,E(`A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.`),[{value:1,label:E(`Numbers 1 (Sunday) trough 7 (Saturday)`)},{value:2,label:E(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:3,label:E(`Numbers 0 (Monday) trough 6 (Sunday)`)},{value:11,label:E(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:12,label:E(`Numbers 1 (Tuesday) trough 7 (Monday)`)},{value:13,label:E(`Numbers 1 (Wednesday) trough 7 (Tuesday)`)},{value:14,label:E(`Numbers 1 (Thursday) trough 7 (Wednesday)`)},{value:15,label:E(`Numbers 1 (Friday) trough 7 (Thursday)`)},{value:16,label:E(`Numbers 1 (Saturday) trough 7 (Friday)`)},{value:17,label:E(`Numbers 1 (Sunday) trough 7 (Saturday)`)}])],compute:function(e,t={value:1}){let n=F(e,this.locale),r=Math.round(M(t,this.locale)),i=n.getDay();if(!(1<=r&&r<=3)&&!(11<=r&&r<=17))return new A(E(`The type (%s) must be between 1 and 3 or between 11 and 17.`,r));switch(r){case 1:return i+1;case 2:return i===0?7:i;case 3:return i===0?6:i-1}let a=r-10,o=(i+1-a+7)%7;return o===0?7:o},isExported:!0},nv={description:E(`Week number of the year.`),args:[H(`date (date)`,E(`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.`)),H(`type (number, default=1)`,E(`A number representing the day that a week starts on. Sunday = 1.`),[{value:1,label:E(`Sunday`)},{value:2,label:E(`Monday`)},{value:11,label:E(`Monday`)},{value:12,label:E(`Tuesday`)},{value:13,label:E(`Wednesday`)},{value:14,label:E(`Thursday`)},{value:15,label:E(`Friday`)},{value:16,label:E(`Saturday`)},{value:17,label:E(`Sunday`)},{value:21,label:E(`ISO week number (Monday as first day of the week)`)}])],compute:function(e,t={value:1}){let n=F(e,this.locale),r=Math.round(M(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(r))return new A(E(`The type (%s) is out of range.`,r.toString()));if(r===21)return U_.compute.bind(this)(e);let i;i=r===1||r===2?r-1:r-10==7?0:r-10;let a=n.getFullYear(),o=1,s=new O(a,0,o);for(;s.getDay()!==i;)o+=1,s=new O(a,0,o);let c=(n.getTime()-s.getTime())/Qr;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},rv={description:E(`Date after a number of workdays.`),args:[H(`start_date (date)`,E(`The date from which to begin counting.`)),H(`num_days (number)`,E(`The number of working days to advance from start_date. If negative, counts backwards.`)),H(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:null}){return iv.compute.bind(this)(e,t,{value:1},n)},isExported:!0},iv={description:E(`Date after a number of workdays (specifying weekends).`),args:[H(`start_date (date)`,E(`The date from which to begin counting.`)),H(`num_days (number)`,E(`The number of working days to advance from start_date. If negative, counts backwards.`)),H(`weekend (any, default=1)`,E(`A number or string representing which days of the week are considered weekends.`),J_),H(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:1},r){let i=F(e,this.locale),a=Math.trunc(M(t,this.locale));if(n.value===`1111111`)return new A(E(`The weekend must be different from '1111111'.`));let o=q_(n),s=new Set;r!==void 0&&ga([r],e=>{let t=F(e,this.locale);s.add(t.getTime())});let c=O.fromTimestamp(i.getTime()),l=c.getTime(),u=Math.sign(a),d=Math.abs(a);for(;d>0;)c.setDate(c.getDate()+u),l=c.getTime(),!o.includes(c.getDay())&&!s.has(l)&&--d;let f=l-Zr.getTime();return{value:Math.round(f/Qr),format:this.locale.dateFormat}},isExported:!0},av={description:E(`Year specified by a given date.`),args:[H(`date (date)`,E(`The date from which to extract the year.`))],compute:function(e){return F(e,this.locale).getFullYear()},isExported:!0},ov={description:E(`Exact number of years between two dates.`),args:[H(`start_date (date)`,E(`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.`)),H(`end_date (date)`,E(`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.`)),H(`day_count_convention (number, default=0)`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n={value:0}){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=Math.trunc(M(n,this.locale));return r<0?new A(E(`The start_date (%s) must be positive or null.`,r)):i<0?new A(E(`The end_date (%s) must be positive or null.`,i)):0>a||a>4?new A(E(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,a)):ki(r,i,a)}},sv={description:E(`First day of the month preceding a date.`),args:[H(`date (date)`,E(`The date from which to calculate the result.`))],compute:function(e){let t=F(e,this.locale);return{value:Ci(new O(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},cv={description:E(`Last day of the month following a date.`),args:[H(`date (date)`,E(`The date from which to calculate the result.`))],compute:function(e){return V_.compute.bind(this)(e,{value:0})}},lv={description:E(`Quarter of the year a specific date falls in`),args:[H(`date (date)`,E(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((F(e,this.locale).getMonth()+1)/3)}},uv={description:E(`First day of the quarter of the year a specific date falls in.`),args:[H(`date (date)`,E(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=lv.compute.bind(this)(e);return{value:Ci(new O(av.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},dv={description:E(`Last day of the quarter of the year a specific date falls in.`),args:[H(`date (date)`,E(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=lv.compute.bind(this)(e);return{value:Ci(new O(av.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},fv={description:E(`First day of the year a specific date falls in.`),args:[H(`date (date)`,E(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:Ci(new O(av.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},pv={description:E(`Last day of the year a specific date falls in.`),args:[H(`date (date)`,E(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:Ci(new O(av.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var mv=l({DELTA:()=>hv});let hv={description:E(`Compare two numeric values, returning 1 if they're equal.`),args:[H(`number1 (number)`,E(`The first number to compare.`)),H(`number2 (number, default=0)`,E(`The second number to compare.`))],compute:function(e,t={value:0}){return+(M(e,this.locale)===M(t,this.locale))},isExported:!0},gv=[`number`,`error`,`text`,`boolean`];function _v(e){let t=e===`asc`?1:-1;return(e,n)=>{if(e.type===`empty`)return n.type===`empty`?0:1;if(n.type===`empty`)return-1;let r=gv.indexOf(e.type)-gv.indexOf(n.type);return r===0&&(r=e.type===`text`||e.type===`error`?e.value.localeCompare(n.value):e.value-n.value),t*r}}function vv(e,t,n){let r=e.map((e,t)=>({index:t,type:e.type,value:e.value}));return(n?r.map(e=>e.type===`empty`?{...e,type:`number`,value:0}:e):r).sort(_v(t))}function yv(e,t,n,r,i){let a=r.right>r.left;if(e.model.getters.doesIntersectMerge(t,r)){a=!1;let n;for(let i=r.top;i<=r.bottom;i++){n=[];for(let a=r.left;a<=r.right;a++){let r=e.model.getters.getMerge({sheetId:t,col:a,row:i});r&&!n.includes(r.id.toString())&&n.push(r.id.toString())}if(n.length>=2){a=!0;break}}}if(a){bv(e,t,n,r,i);return}let o=e.model.getters.getContiguousZone(t,r);Rs(o,r)?bv(e,t,n,r,i):e.askConfirmation(E(`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?`),()=>bv(e,t,n,o,i),()=>bv(e,t,n,r,i))}function bv(e,t,n,r,i,a){let o=e.model.dispatch(`SORT_CELLS`,{sheetId:t,col:n.col,row:n.row,zone:r,sortDirection:i,sortOptions:a});if(o.isCancelledBecause(`InvalidSortZone`)){let{col:t,row:i}=n;e.model.selection.selectZone({cell:{col:t,row:i},zone:r}),e.raiseError(E(`Cannot sort. To sort, select only cells or only merges that have the same size.`))}if(o.isCancelledBecause(`SortZoneWithArrayFormulas`)){let{col:t,row:i}=n;e.model.selection.selectZone({cell:{col:t,row:i},zone:r}),e.raiseError(E(`Cannot sort a zone with array formulas.`))}}var xv=l({FILTER:()=>Cv,SORT:()=>wv,SORTN:()=>Tv,UNIQUE:()=>Ev});function Sv(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;Mu(n[e]!==void 0,E(`Value for parameter %s is missing in [[FUNCTION_NAME]].`,t))}let r=[],i=[],a=e.length;for(let o=0;o<n.length;o+=2){r.push(P(Hu(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(Ir(s)&&(s.length>1||s[0].length>1))Mu(s.length===1&&s[0].length===a,E(`Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.`,`sort_column${o+1}`,a,s.length,s[0].length)),i.push(s.flat().map(e=>e.value));else{let n=M(Hu(s)?.value,t);if(n<1||n>e[0].length)return e;i.push(e.map(e=>e[n-1].value))}}if(i.length===0)for(let t=0;t<e[0].length;t++)i.push(e.map(e=>e[t].value)),r.push(`asc`);let o={desc:_v(`desc`),asc:_v(`asc`)},s=S(0,e.length);return s.sort((e,t)=>{for(let[n,a]of i.entries()){let i=a[e],s=a[t],c={value:i,type:i===null?`empty`:typeof i==`string`?`text`:typeof i},l={value:s,type:s===null?`empty`:typeof s==`string`?`text`:typeof s},u=o[r[n]](c,l);if(u!==0)return u}return 0}),s.map(t=>e[t])}let Cv={description:E(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[H(`range (any, range<any>)`,E(`The data to be filtered.`)),H(`condition1 (boolean, range<boolean>)`,E(`A column or row containing true or false values corresponding to the first column or row of range.`)),H(`condition2 (boolean, range<boolean>, repeating)`,E(`Additional column or row containing true or false values.`))],compute:function(e,...t){let n=I(e),r=t.map(e=>Ca(I(e),e=>e.value));for(let e of r)if(!Pu(e))return new A(E(`The arguments condition must be a single column or row.`));if(!Fu(...t))return new A(E(`The arguments conditions must have the same dimensions.`));let i=r.map(e=>e.flat()),a=r[0].length===1?`row`:`col`;if(n=a===`row`?Ta(n):n,i.some(e=>e.length!==n.length))return new A(E(`FILTER has mismatched sizes on the range and conditions.`));let o=[];for(let e=0;e<n.length;e++){let t=n[e];i.every(t=>(typeof t[e]==`boolean`||typeof t[e]==`number`)&&t[e])&&o.push(t)}return o.length?a===`row`?Ta(o):o:new Xi(E(`No match found in FILTER evaluation`))},isExported:!1},wv={description:E(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[H(`range (range)`,E(`The data to be sorted.`)),H(`sort_column (any, range<number>, repeating)`,E(`The index of the column in range or a range outside of range containing the values by which to sort.`)),H(`is_ascending (boolean, repeating)`,E(`TRUE or FALSE indicating whether to sort sort_column in ascending order.`),[{value:!0,label:E(`Ascending`)},{value:!1,label:E(`Descending`)}])],compute:function(e,...t){return Ta(Sv(Ta(e),this.locale,...t))},isExported:!0},Tv={description:E(`Returns the first n items in a data set after performing a sort.`),args:[H(`range (range)`,E(`The data to be sorted.`)),H(`n (number)`,E(`The number of items to return.`)),H(`display_ties_mode (number, default=0)`,E(`A number representing the way to display ties.`)),H(`sort_column (number, range<number>, repeating)`,E(`The index of the column in range or a range outside of range containing the values by which to sort.`)),H(`is_ascending (boolean, repeating)`,E(`TRUE or FALSE indicating whether to sort sort_column in ascending order.`),[{value:!0,label:E(`Ascending`)},{value:!1,label:E(`Descending`)}])],compute:function(e,t,...n){let r=M(t?.value??1,this.locale),i=n.length%2==0?0:M(n[0]?.value,this.locale),a=n.length%2==0?n:n.slice(1);if(r<0)return new A(E(`Wrong value of 'n'. Expected a positive number. Got %s.`,r));if(i<0||i>3)return new A(E(`Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.`,i));let o=Sv(Ta(e),this.locale,...a),s=(e,t)=>JSON.stringify(o[e].map(e=>e.value))===JSON.stringify(o[t].map(e=>e.value));switch(i){case 0:return Ta(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return Ta(o.slice(0,e));return Ta(o);case 2:{let e=[o[0]];for(let t=1;t<o.length;t++)for(let n=0;n<t&&!s(t,n);n++)n===t-1&&e.push(o[t]);return Ta(e.slice(0,r))}case 3:{let e=[o[0]],t=1;for(let n=1;n<o.length&&(s(n,n-1)||t++,!(t>r));n++)e.push(o[n]);return Ta(e)}}},isExported:!1},Ev={description:E(`Unique rows in the provided source range.`),args:[H(`range (any, range<any>)`,E(`The data to filter by unique entries.`)),H(`by_column (boolean, default=FALSE)`,E(`Whether to filter the data by columns or by rows.`),[{value:!0,label:E(`Return unique columns`)},{value:!1,label:E(`Return unique rows`)}]),H(`exactly_once (boolean, default=FALSE)`,E(`Whether to return only entries with no duplicates.`),[{value:!0,label:E(`Return items that appear exactly once`)},{value:!1,label:E(`Return every distinct item`)}])],compute:function(e={value:``},t,n){if(!Ir(e))return[[e]];let r=P(t?.value)||!1,i=P(n?.value)||!1;r||(e=Ta(e));let a=new Map;for(let t of e){let e=JSON.stringify(t.map(e=>e.value)),n=a.get(e);n?n.count++:a.set(e,{data:t,count:1})}let o=[];for(let e of a.values())i&&e.count>1||o.push(e.data);return o.length?r?o:Ta(o):new A(E(`No unique values found`))},isExported:!0};var Dv=l({ACCRINTM:()=>Mv,AMORLINC:()=>Nv,COUPDAYBS:()=>Fv,COUPDAYS:()=>Pv,COUPDAYSNC:()=>Iv,COUPNCD:()=>Lv,COUPNUM:()=>Rv,COUPPCD:()=>zv,CUMIPMT:()=>Bv,CUMPRINC:()=>Vv,DB:()=>Hv,DDB:()=>Wv,DISC:()=>Gv,DOLLARDE:()=>Kv,DOLLARFR:()=>qv,DURATION:()=>Jv,EFFECT:()=>Yv,FV:()=>Zv,FVSCHEDULE:()=>Qv,INTRATE:()=>$v,IPMT:()=>ty,IRR:()=>ry,ISPMT:()=>iy,MDURATION:()=>ay,MIRR:()=>oy,NOMINAL:()=>sy,NPER:()=>cy,NPV:()=>uy,PDURATION:()=>dy,PMT:()=>py,PPMT:()=>hy,PRICE:()=>_y,PRICEDISC:()=>vy,PRICEMAT:()=>yy,PV:()=>gy,RATE:()=>xy,RECEIVED:()=>Sy,RRI:()=>Cy,SLN:()=>wy,SYD:()=>Ty,TBILLEQ:()=>Oy,TBILLPRICE:()=>Dy,TBILLYIELD:()=>ky,VDB:()=>Ay,XIRR:()=>jy,XNPV:()=>My,YIELD:()=>Ny,YIELDDISC:()=>Py,YIELDMAT:()=>Fy});let Ov=[{value:1,label:E(`Annual`)},{value:2,label:E(`Semi-annual`)},{value:4,label:E(`Quarterly`)}],kv=[{value:0,label:E(`End of period (default)`)},{value:1,label:E(`Beginning of period`)}],Av=[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`),Ov),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)];function jv(e,t,n,r,i=1e-10,a){let o=n,s,c,l,u=!1,d=0,f;do{if(l=e(o),isNaN(l)){Mu(d<r&&a!==void 0,E(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++,o=a(f),f=o;continue}s=o-l/t(o),c=Math.abs(s-o),o=s,u=c<i||Math.abs(l)<i,Mu(d<r,E(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let Mv={description:E(`Accrued interest of security paying at maturity.`),args:[H(`issue (date)`,E(`The date the security was initially issued.`)),H(`maturity (date)`,E(`The maturity date of the security.`)),H(`rate (number)`,E(`The annualized rate of interest.`)),H(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(r,this.locale),c=M(n,this.locale),l=Math.trunc(M(i,this.locale));if(a<0)return new A(Yg(a));if(a>=o)return new A($g(a,o));if(O_(l))return new A(Ig(l));if(s<=0)return new A(__(s));if(c<=0)return new A(g_(c));let u=ki(a,o,l);return s*c*u},isExported:!0},Nv={description:E(`Depreciation for an accounting period.`),args:[H(`cost (number)`,E(`The initial cost of the asset.`)),H(`purchase_date (date)`,E(`The date the asset was purchased.`)),H(`first_period_end (date)`,E(`The date the first period ended.`)),H(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),H(`period (number)`,E(`The single period within life for which to calculate depreciation.`)),H(`rate (number)`,E(`The deprecation rate.`)),H(`day_count_convention (number, optional)`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=M(e,this.locale),c=Math.trunc(M(t,this.locale)),l=Math.trunc(M(n,this.locale)),u=M(r,this.locale),d=M(i,this.locale),f=M(a,this.locale),p=Math.trunc(M(o,this.locale));if(s<=0)return new A(Pg(s));if(c<0)return new A(p_(c));if(u<0)return new A(v_(u));if(u>s)return new A(y_(u,s));if(d<0)return new A(o_(d));if(f<=0)return new A(g_(f));if(O_(p))return new A(Ig(p));if(c>l)return new A(f_(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=ki(c,l,p),_=c===l?h:h*g,v=s-_-h*m;return v>=u?m===0?_:h:u-v<h?h-(u-v):0},isExported:!0},Pv={description:E(`Days in coupon period containing settlement date.`),args:Av,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A($g(i,a));if(k_(o))return new A(Fg(o));if(O_(s))return new A(Ig(s));if(s===1){let i=zv.compute.bind(this)(e,t,n,r).value,a=Lv.compute.bind(this)(e,t,n,r).value;return M(a,this.locale)-M(i,this.locale)}return(s===3?365:360)/o},isExported:!0},Fv={description:E(`Days from settlement until next coupon.`),args:Av,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A($g(i,a));if(k_(o))return new A(Fg(o));if(O_(s))return new A(Ig(s));let c=zv.compute.bind(this)(e,t,n,r).value,l=M(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=ki(l,i,s);return Math.round(e*360)}let u=F(i,this.locale),d=F(l,this.locale),f=d.getFullYear(),p=u.getFullYear(),m=d.getMonth()+1,h=u.getMonth()+1,g=d.getDate(),_=u.getDate();return m===2&&h===2&&Ei(d)&&Ei(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&Ei(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},Iv={description:E(`Days from settlement until next coupon.`),args:Av,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A($g(i,a));if(k_(o))return new A(Fg(o));if(O_(s))return new A(Ig(s));let c=Lv.compute.bind(this)(e,t,n,r).value,l=M(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=ki(i,l,s);return Math.round(e*360)}let u=Fv.compute.bind(this)(e,t,n,r);return M(Pv.compute.bind(this)(e,t,n,r),this.locale)-M(u,this.locale)},isExported:!0},Lv={description:E(`Next coupon date after the settlement date.`),args:Av,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A($g(i,a));if(k_(o))return new A(Fg(o));if(O_(s))return new A(Ig(s));let c=12/o,l=Rv.compute.bind(this)(e,t,n,r);return{value:Ci(Di(F(a,this.locale),-(M(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},Rv={description:E(`Number of coupons between settlement and maturity.`),args:Av,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A($g(i,a));if(k_(o))return new A(Fg(o));if(O_(s))return new A(Ig(s));let c=1,l=a,u=12/o;for(;l>i;)l=Ci(Di(F(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},zv={description:E(`Last coupon date prior to or on the settlement date.`),args:Av,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A($g(i,a));if(k_(o))return new A(Fg(o));if(O_(s))return new A(Ig(s));let c=12/o,l=Rv.compute.bind(this)(e,t,n,r);return{value:Ci(Di(F(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},Bv={description:E(`Cumulative interest paid over a set of periods.`),args:[H(`rate (number)`,E(`The interest rate.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`present_value (number)`,E(`The current value of the annuity.`)),H(`first_period (number)`,E(`The number of the payment period to begin the cumulative calculation.`)),H(`last_period (number)`,E(`The number of the payment period to end the cumulative calculation.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r,i,a={value:0}){let o=M(r,this.locale),s=M(i,this.locale),c=M(e,this.locale),l=M(n,this.locale),u=M(t,this.locale),d=+!!P(a);if(u<=0)return new A(r_(u));if(o<=0)return new A(Kg(o));if(s<=0)return new A(Zg(s));if(o>s)return new A(Gg(o,s));if(s>u)return new A(Xg(s,u));if(c<=0)return new A(g_(c));if(l<=0)return new A(u_(l));let f=0;for(let e=o;e<=s;e++)f+=ey(c,e,u,l,0,d);return f},isExported:!0},Vv={description:E(`Cumulative principal paid over a set of periods.`),args:[H(`rate (number)`,E(`The interest rate.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`present_value (number)`,E(`The current value of the annuity.`)),H(`first_period (number)`,E(`The number of the payment period to begin the cumulative calculation.`)),H(`last_period (number)`,E(`The number of the payment period to end the cumulative calculation.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r,i,a={value:0}){let o=M(r,this.locale),s=M(i,this.locale),c=M(e,this.locale),l=M(n,this.locale),u=M(t,this.locale),d=+!!P(a);if(u<=0)return new A(r_(u));if(o<=0)return new A(Kg(o));if(s<=0)return new A(Zg(s));if(o>s)return new A(Gg(o,s));if(s>u)return new A(Xg(s,u));if(c<=0)return new A(g_(c));if(l<=0)return new A(u_(l));let f=0;for(let e=o;e<=s;e++)f+=my(c,e,u,l,0,d);return f},isExported:!0},Hv={description:E(`Depreciation via declining balance method.`),args:[H(`cost (number)`,E(`The initial cost of the asset.`)),H(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),H(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),H(`period (number)`,E(`The single period within life for which to calculate depreciation.`)),H(`month (number, optional)`,E(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=Math.trunc(M(r,this.locale)),l=i.length?Math.trunc(M(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new A(Ng(a));if(o<0)return new A(v_(o));if(c<=0)return new A(l_(c));if(s<=0)return new A(Qg(s));if(1>l||l>12)return new A(e_(l));if(c>u)return new A(a_(c,u));let d=l/12,f=1-(o/a)**(1/s);f=Math.round(f*1e3)/1e3;let p=a,m=a*(1-f*d);for(let e=1;e<c;e++)p=m,m=p*(1-f),e===s&&(m=p*(1-f*(1-d)));return{value:p-m,format:`#,##0.00`}},isExported:!0},Uv=`#,##0.00`,Wv={description:E(`Depreciation via double-declining balance method.`),args:[H(`cost (number)`,E(`The initial cost of the asset.`)),H(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),H(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),H(`period (number)`,E(`The single period within life for which to calculate depreciation.`)),H(`factor (number, default=2)`,E(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=M(i,this.locale);if(a<0)return new A(Ng(a));if(o<0)return new A(v_(o));if(c<=0)return new A(l_(c));if(s<=0)return new A(Qg(s));if(c>s)return new A(c_(c,s));if(l<=0)return new A(Lg(l));if(a===0||o>=a)return{value:0,format:Uv};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:Uv};if(c<=1)return{value:a*u,format:Uv};let d=a*(1-u)**(c-1),f=a*(1-u)**c,p=f<o?d-o:d-f;return{value:Math.max(p,0),format:Uv}},isExported:!0},Gv={description:E(`Discount rate of a security based on price.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`price (number)`,E(`The price at which the security is bought per 100 face value.`)),H(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A($g(a,o));if(O_(l))return new A(Ig(l));if(s<=0)return new A(d_(s));if(c<=0)return new A(__(c));let u=ki(a,o,l);return(c-s)/c/u},isExported:!0},Kv={description:E(`Convert a decimal fraction to decimal value.`),args:[H(`fractional_price (number)`,E(`The price quotation given using fractional decimal conventions.`)),H(`unit (number)`,E(`The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));if(r<=0)return new A(T_(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},qv={description:E(`Convert a decimal value to decimal fraction.`),args:[H(`decimal_price (number)`,E(`The price quotation given as a decimal value.`)),H(`unit (number)`,E(`The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));if(r<=0)return new A(T_(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},Jv={description:E(`Number of periods for an investment to reach a value.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`rate (number)`,E(`The annualized rate of interest.`)),H(`yield (number)`,E(`The expected annual yield of the security.`)),H(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`),Ov),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(M(e,this.locale)),s=Math.trunc(M(t,this.locale)),c=M(n,this.locale),l=M(r,this.locale),u=Math.trunc(M(i,this.locale)),d=Math.trunc(M(a,this.locale));if(o>=s)return new A($g(o,s));if(k_(u))return new A(Fg(u));if(O_(d))return new A(Ig(d));if(c<0)return new A(h_(c));if(l<0)return new A(E_(l));let f=ki(o,s,d),p=f-Math.trunc(f)||1/u,m=Math.ceil(f*u),h=c/u,g=l/u,_=0,v=0;for(let e=1;e<=m;e++){let t=(h+ +(e===m))/(1+g)**e;v+=(p+(e-1)/u)*t,_+=t}return _===0?0:v/_},isExported:!0},Yv={description:E(`Annual effective interest rate.`),args:[H(`nominal_rate (number)`,E(`The nominal interest rate per year.`)),H(`periods_per_year (number)`,E(`The number of compounding periods per year.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));return n<=0?new A(t_(n)):r<=0?new A(s_(r)):(1+n/r)**+r-1},isExported:!0};function Xv(e,t,n,r,i){return e===0?-(r+n*t):-r*(1+e)**t-n*(1+e*i)*((1+e)**t-1)/e}let Zv={description:E(`Future value of an annuity investment.`),args:[H(`rate (number)`,E(`The interest rate.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`payment_amount (number)`,E(`The amount per period to be paid.`)),H(`present_value (number, default=0)`,E(`The current value of the annuity.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:Xv(M(e,this.locale),M(t,this.locale),M(n,this.locale),M(r,this.locale),+!!P(i)),format:`#,##0.00`}},isExported:!0},Qv={description:E(`Future value of principal from series of rates.`),args:[H(`principal (number)`,E(`The amount of initial capital or value to compound against.`)),H(`rate_schedule (number, range<number>)`,E(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=M(e,this.locale);return ya([t],(e,t)=>e*(1+M(t,this.locale)),n)},isExported:!0},$v={description:E(`Calculates effective interest rate.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`investment (number)`,E(`The amount invested in the security.`)),H(`redemption (number)`,E(`The amount to be received at maturity.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(r,this.locale),c=M(n,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A($g(a,o));if(c<=0)return new A(Jg(c));if(s<=0)return new A(__(s));if(O_(l))return new A(Ig(l));let u=ki(a,o,l);return(s-c)/c/u},isExported:!0};function ey(e,t,n,r,i,a){return fy(e,n,r,i,a)-my(e,t,n,r,i,a)}let ty={description:E(`Payment on the principal of an investment.`),args:[H(`rate (number)`,E(`The annualized rate of interest.`)),H(`period (number)`,E(`The amortization period, in terms of number of periods.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`present_value (number)`,E(`The current value of the annuity.`)),H(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:ey(M(e,this.locale),M(t,this.locale),M(n,this.locale),M(r,this.locale),M(i,this.locale),+!!P(a)),format:`#,##0.00`}},isExported:!0},ny=.1,ry={description:E(`Internal rate of return given periodic cashflows.`),args:[H(`cashflow_amounts (number, range<number>)`,E(`An array or range containing the income or payments associated with the investment.`)),H(`rate_guess (number, default=${ny})`,E(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:ny}){let n=M(t,this.locale);if(n<=-1)return new A(m_(n));let r=!1,i=!1,a=[];if(_a([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new A(Mg);let o=a.shift();function s(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*e**(r-i)),t*e**r)}function c(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*(r-i)*e**(r-i-1)),t*r*e**(r-1))}function l(e){return s(e,o,a)}function u(e){return c(e,o,a)}return{value:jv(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},iy={description:E(`Returns the interest paid at a particular period of an investment.`),args:[H(`rate (number)`,E(`The interest rate.`)),H(`period (number)`,E(`The period for which you want to view the interest payment.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`present_value (number)`,E(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=M(e,this.locale),a=M(t,this.locale),o=M(n,this.locale),s=M(r,this.locale);return o===0?new A(n_(o)):-1*(s-a/o*s)*i},isExported:!0},ay={description:E(`Modified Macaulay duration.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`rate (number)`,E(`The annualized rate of interest.`)),H(`yield (number)`,E(`The expected annual yield of the security.`)),H(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`),Ov),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=Jv.compute.bind(this)(e,t,n,r,i,a),s=M(r,this.locale),c=Math.trunc(M(i,this.locale));return M(o,this.locale)/(1+s/c)},isExported:!0},oy={description:E(`Modified internal rate of return.`),args:[H(`cashflow_amounts (range<number>)`,E(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),H(`financing_rate (number)`,E(`The interest rate paid on funds invested.`)),H(`reinvestment_return_rate (number)`,E(`The return (as a percentage) earned on reinvestment of income received from the investment.`))],compute:function(e,t,n){let r=M(t,this.locale),i=M(n,this.locale),a=Ta(e).flat().filter(e=>e.value!==null).map(e=>M(e,this.locale)),o=a.length,s=0,c=0;for(let e of S(0,o)){let t=a[e];t>=0?s+=t*(i+1)**(o-e-1):c+=t/(r+1)**e}if(c===0||s===0)return new A(Mg);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},sy={description:E(`Annual nominal interest rate.`),args:[H(`effective_rate (number)`,E(`The effective interest rate per year.`)),H(`periods_per_year (number)`,E(`The number of compounding periods per year.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));return n<=0?new A(Vg(n)):r<=0?new A(s_(r)):((n+1)**(1/r)-1)*r},isExported:!0},cy={description:E(`Number of payment periods for an investment.`),args:[H(`rate (number)`,E(`The interest rate.`)),H(`payment_amount (number)`,E(`The amount of each payment made.`)),H(`present_value (number)`,E(`The current value of the annuity.`)),H(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=+!!P(i);if(a===0)return-(c+s)/o;let u=o*(1+a*l)/a;return Math.log((u-c)/(s+u))/Math.log(1+a)},isExported:!0};function ly(e,t,n,r){let i=0;return ba(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let uy={description:E(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[H(`discount (number)`,E(`The discount rate of the investment over one period.`)),H(`cashflow1 (number, range<number>)`,E(`The first future cash flow.`)),H(`cashflow2 (number, range<number>, repeating)`,E(`Additional future cash flows.`))],compute:function(e,...t){let n=M(e,this.locale);return n===-1?new A(Rg(n)):{value:ly(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},dy={description:E(`Computes the number of periods needed for an investment to reach a value.`),args:[H(`rate (number)`,E(`The rate at which the investment grows each period.`)),H(`present_value (number)`,E(`The investment's current value.`)),H(`future_value (number)`,E(`The investment's desired future value.`))],compute:function(e,t,n){let r=M(e,this.locale),i=M(t,this.locale),a=M(n,this.locale);return r<=0?new A(g_(r)):i<=0?new A(u_(i)):a<=0?new A(qg(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function fy(e,t,n,r,i){if(t<=0)throw new A(r_(t));if(e===0)return-(r+n)/t;let a=-(n*(1+e)**t+r);return a=a*e/((1+e*i)*((1+e)**t-1)),a}let py={description:E(`Periodic payment for an annuity investment.`),args:[H(`rate (number)`,E(`The annualized rate of interest.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`present_value (number)`,E(`The current value of the annuity.`)),H(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r={value:0},i={value:0}){let a=M(t,this.locale),o=M(e,this.locale),s=+!!P(i),c=M(r,this.locale);return{value:fy(o,a,M(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function my(e,t,n,r,i,a){if(n<=0)throw new A(r_(n));if(t<=0||t>n)throw new A(i_(n));let o=fy(e,n,r,i,a);return a===1&&t===1?o:o+-Xv(e,a===0?t-1:t-2,o,r+o*a,0)*e}let hy={description:E(`Payment on the principal of an investment.`),args:[H(`rate (number)`,E(`The annualized rate of interest.`)),H(`period (number)`,E(`The amortization period, in terms of number of periods.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`present_value (number)`,E(`The current value of the annuity.`)),H(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=M(n,this.locale),s=M(e,this.locale),c=M(t,this.locale),l=+!!P(a),u=M(i,this.locale);return{value:my(s,c,o,M(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},gy={description:E(`Present value of an annuity investment.`),args:[H(`rate (number)`,E(`The interest rate.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`payment_amount (number)`,E(`The amount per period to be paid.`)),H(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=+!!P(i);return{value:a?-(s*(1+a*l)*((1+a)**o-1)/a+c)/(1+a)**o:-(c+s*o),format:`#,##0.00`}},isExported:!0},_y={description:E(`Price of a security paying periodic interest.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`rate (number)`,E(`The annualized rate of interest.`)),H(`yield (number)`,E(`The expected annual yield of the security.`)),H(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),H(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`),Ov),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(M(e,this.locale)),c=Math.trunc(M(t,this.locale)),l=M(n,this.locale),u=M(r,this.locale),d=M(i,this.locale),f=Math.trunc(M(a,this.locale)),p=Math.trunc(M(o,this.locale));if(s>=c)return new A($g(s,c));if(k_(f))return new A(Fg(f));if(O_(p))return new A(Ig(p));if(l<0)return new A(h_(l));if(u<0)return new A(E_(u));if(d<=0)return new A(__(d));let m=ki(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=1+u/f,v=100*l/f;if(h===1)return(v+d)/(g*u/f+1)-v*(1-g);let y=0;for(let e=1;e<=h;e++)y+=v/_**(e-1+g);return d/_**(h-1+g)+y-v*(1-g)},isExported:!0},vy={description:E(`Price of a discount security.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`discount (number)`,E(`The discount rate of the security at time of purchase.`)),H(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A($g(a,o));if(O_(l))return new A(Ig(l));if(s<=0)return new A(zg(s));if(c<=0)return new A(__(c));let u=ki(a,o,l);return c-s*c*u},isExported:!0},yy={description:E(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`issue (date)`,E(`The date the security was initially issued.`)),H(`rate (number)`,E(`The annualized rate of interest.`)),H(`yield (number)`,E(`The expected annual yield of the security.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(M(e,this.locale)),s=Math.trunc(M(t,this.locale)),c=Math.trunc(M(n,this.locale)),l=M(r,this.locale),u=M(i,this.locale),d=Math.trunc(M(a,this.locale));if(o<=c)return new A(S_(o,c));if(o>=s)return new A($g(o,s));if(O_(d))return new A(Ig(d));if(l<0)return new A(h_(l));if(u<0)return new A(E_(u));let f=ki(o,s,d),p=ki(o,c,d),m=100+ki(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},by=.1,xy={description:E(`Interest rate of an annuity investment.`),args:[H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`payment_per_period (number)`,E(`The amount per period to be paid.`)),H(`present_value (number)`,E(`The current value of the annuity.`)),H(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv),H(`rate_guess (number, default=${by})`,E(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:by}){let o=M(e,this.locale),s=M(t,this.locale),c=+!!P(i),l=M(a,this.locale)||by,u=M(r,this.locale),d=M(n,this.locale);return o<=0?new A(r_(o)):D_([s,d,u])?l<=-1?new A(m_(l)):(u-=s*c,d+=s*c,{value:jv(e=>{let t=(1+e)**+o,n=(t-1)/e;return u+d*t+s*n},e=>{let t=(1+e)**(o-1),n=((1+e)**+o-1)/e,r=o*t/e-n/e;return d*o*t+s*r},l,40,1e-5),format:`0%`}):new A(E(`There must be both positive and negative values in [payment_amount, present_value, future_value].`))},isExported:!0},Sy={description:E(`Amount received at maturity for a security.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`investment (number)`,E(`The amount invested (irrespective of face value of each security).`)),H(`discount (number)`,E(`The discount rate of the security invested in.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));return a>=o?new A($g(a,o)):O_(l)?new A(Ig(l)):s<=0?new A(Jg(s)):c<=0?new A(zg(c)):s/(1-c*ki(a,o,l))},isExported:!0},Cy={description:E(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[H(`number_of_periods (number)`,E(`The number of periods.`)),H(`present_value (number)`,E(`The present value of the investment.`)),H(`future_value (number)`,E(`The future value of the investment.`))],compute:function(e,t,n){let r=M(e,this.locale),i=M(t,this.locale),a=M(n,this.locale);return r<=0?new A(r_(r)):(a/i)**(1/r)-1},isExported:!0},wy={description:E(`Depreciation of an asset using the straight-line method.`),args:[H(`cost (number)`,E(`The initial cost of the asset.`)),H(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),H(`life (number)`,E(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=M(e,this.locale),i=M(t,this.locale),a=M(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},Ty={description:E(`Depreciation via sum of years digit method.`),args:[H(`cost (number)`,E(`The initial cost of the asset.`)),H(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),H(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),H(`period (number)`,E(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=M(e,this.locale),a=M(t,this.locale),o=M(n,this.locale),s=M(r,this.locale);if(s<=0)return new A(l_(s));if(o<=0)return new A(Qg(o));if(s>o)return new A(c_(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function Ey(e,t,n){return 100*(1-n*ki(e,t,2))}let Dy={description:E(`Price of a US Treasury bill.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`discount (number)`,E(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=M(n,this.locale);return r>=i?new A($g(r,i)):A_(r,i,this.locale)?a<=0?new A(zg(a)):a>=1?new A(Bg(a)):Ey(r,i,a):new A(x_(r,i))},isExported:!0},Oy={description:E(`Equivalent rate of return for a US Treasury bill.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`discount (number)`,E(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=M(n,this.locale);if(r>=i)return new A($g(r,i));if(!A_(r,i,this.locale))return new A(x_(r,i));if(a<=0)return new A(zg(a));if(a>=1)return new A(Bg(a));let o=R_.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=Ey(r,i,a)/100,c=o/(o===366?366:365);return(-2*c+2*Math.sqrt(c**2-(2*c-1)*(1-1/s)))/(2*c-1)},isExported:!0},ky={description:E(`The yield of a US Treasury bill based on price.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`price (number)`,E(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=M(n,this.locale);if(r>=i)return new A($g(r,i));if(!A_(r,i,this.locale))return new A(x_(r,i));if(a<=0)return new A(d_(a));let o=ki(r,i,2);return(100-a)/a*(1/o)},isExported:!0},Ay={description:E(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[H(`cost (number)`,E(`The initial cost of the asset.`)),H(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),H(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),H(`start (number)`,E(`Starting period to calculate depreciation.`)),H(`end (number)`,E(`Ending period to calculate depreciation.`)),H(`factor (number, default=2)`,E(`The number of months in the first year of depreciation.`)),H(`no_switch (number, default=false)`,E(`Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.`),[{value:!1,label:E(`Switch to straight-line depreciation`)},{value:!0,label:E(`Do not switch to straight-line depreciation`)}])],compute:function(e,t,n,r,i,a={value:2},o={value:!1}){a||=0;let s=M(e,this.locale),c=M(t,this.locale),l=M(n,this.locale),u=Math.trunc(M(r,this.locale)),d=Math.trunc(M(i,this.locale)),f=M(a,this.locale),p=P(o);if(s<0)return new A(Ng(s));if(c<0)return new A(v_(c));if(l<=0)return new A(Qg(l));if(u<0)return new A(C_(u));if(d<0)return new A(Hg(d));if(u>d)return new A(w_(u,d));if(d>l)return new A(Ug(d,l));if(f<=0)return new A(Lg(f));if(s===0)return 0;if(c>=s)return u<1?s-c:0;let m=f/l;if(m>=1)return u<1?s-c:0;let h=s,g=0,_=0,v=!1;for(let e=0;e<d;e++){if(!v||p){let t=h*m,n=l-e,r=(h-c)/n;!p&&r>t?(v=!0,g=r):g=t}let t=Math.max(h-g,c);e>=u&&(_+=h-t),h=t}return _},isExported:!0},jy={description:E(`Internal rate of return given non-periodic cash flows.`),args:[H(`cashflow_amounts (range<number>)`,E(`An range containing the income or payments associated with the investment.`)),H(`cashflow_dates (range<number>)`,E(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),H(`rate_guess (number, default=${by})`,E(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:by}){let r=M(n,this.locale);if(!Fu(e,t))return new A(jg);let i=e.flat().map(e=>M(e,this.locale)),a=t.flat().map(e=>M(e,this.locale));if(!D_(i))return new A(Mg);if(a.some(e=>e<a[0]))return new A(Wg(a[0]));if(r<=-1)return new A(m_(r));let o=new Map;for(let e of S(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e));return jv(e=>{let t=c[0];for(let n of S(1,c.length)){let r=(s[0]-s[n])/365;t+=c[n]*(1+e)**r}return t},e=>{let t=0;for(let n of S(1,c.length)){let r=(s[0]-s[n])/365;t+=r*c[n]*(1+e)**(r-1)}return t},r,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},My={description:E(`Net present value given to non-periodic cash flows..`),args:[H(`discount (number)`,E(`The discount rate of the investment over one period.`)),H(`cashflow_amounts (number, range<number>)`,E(`An range containing the income or payments associated with the investment.`)),H(`cashflow_dates (number, range<number>)`,E(`An range with dates corresponding to the cash flows in cashflow_amounts.`))],compute:function(e,t,n){let r=M(e,this.locale);if(!Fu(t,n))return new A(jg);let i=I(t).flat().map(e=>ca(e,this.locale)),a=I(n).flat().map(e=>ca(e,this.locale));if(a.some(e=>e<a[0]))return new A(Wg(a[0]));if(r<=0)return new A(g_(r));if(i.length===1)return i[0];let o=new Map;for(let e of S(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e)),l=c[0];for(let e of S(1,c.length)){let t=(s[0]-s[e])/365;l+=c[e]*(1+r)**t}return l},isExported:!0},Ny={description:E(`Annual yield of a security paying periodic interest.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`rate (number)`,E(`The annualized rate of interest.`)),H(`price (number)`,E(`The price at which the security is bought per 100 face value.`)),H(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),H(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`),Ov),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(M(e,this.locale)),c=Math.trunc(M(t,this.locale)),l=M(n,this.locale),u=M(r,this.locale),d=M(i,this.locale),f=Math.trunc(M(a,this.locale)),p=Math.trunc(M(o,this.locale));if(s>=c)return new A($g(s,c));if(k_(f))return new A(Fg(f));if(O_(p))return new A(Ig(p));if(l<0)return new A(h_(l));if(u<=0)return new A(d_(u));if(d<=0)return new A(__(d));let m=ki(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=100*l/f;if(h===1){let e=u+_*(1-g);return(d+_-e)*f*(1/g)/e}function v(e,t,n,r,i,a){let o=a-(e+i*(1-t))*r**(n-1+t);for(let e=1;e<=n;e++)o+=i*r**(e-1);return o}function y(e,t,n,r,i){let a=-(e+i*(1-t))*(n-1+t)*r**(n-2+t);for(let e=1;e<=n;e++)a+=i*(e-1)*r**(e-2);return a}function ee(e){return v(u,g,h,e,_,d)}function te(e){return y(u,g,h,e,_)}return(jv(ee,te,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},Py={description:E(`Annual yield of a discount security.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`price (number)`,E(`The price at which the security is bought per 100 face value.`)),H(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A($g(a,o));if(O_(l))return new A(Ig(l));if(s<=0)return new A(d_(s));if(c<=0)return new A(__(c));let u=ki(a,o,l);return(c/s-1)/u},isExported:!0},Fy={description:E(`Annual yield of a security paying interest at maturity.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`issue (date)`,E(`The date the security was initially issued.`)),H(`rate (number)`,E(`The annualized rate of interest.`)),H(`price (number)`,E(`The price at which the security is bought.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(M(e,this.locale)),s=Math.trunc(M(t,this.locale)),c=Math.trunc(M(n,this.locale)),l=M(r,this.locale),u=M(i,this.locale),d=Math.trunc(M(a,this.locale));if(o>=s)return new A($g(o,s));if(O_(d))return new A(Ig(d));if(o<c)return new A(b_(o,c));if(l<0)return new A(h_(l));if(u<=0)return new A(d_(u));let f=ki(c,s,d),p=ki(c,o,d),m=ki(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0},Iy=(e,t=()=>!0)=>[{goTo:e,guard:t}],Ly=(e,t=()=>!0)=>({goTo:e,guard:t}),Ry={0:{REFERENCE:Iy(2),NUMBER:Iy(4),SYMBOL:[Ly(3,e=>Ec(e.value)),Ly(4,e=>Dc(e.value))]},3:{SPACE:Iy(3),OPERATOR:Iy(5,e=>e.value===`:`)},4:{SPACE:Iy(4),OPERATOR:Iy(6,e=>e.value===`:`)},2:{SPACE:Iy(2),OPERATOR:Iy(1,e=>e.value===`:`)},1:{SPACE:Iy(1),NUMBER:Iy(7),REFERENCE:Iy(7,e=>Ac(e.value)),SYMBOL:Iy(7,e=>Oc(e.value)||kc(e.value))},5:{SPACE:Iy(5),SYMBOL:Iy(7,e=>Oc(e.value)),REFERENCE:Iy(7,e=>Ac(e.value))},6:{SPACE:Iy(6),NUMBER:Iy(7),REFERENCE:Iy(7,e=>Ac(e.value)),SYMBOL:Iy(7,e=>kc(e.value))},7:{}};function zy(e){let t=0,n=Ry[0],r=``;for(;n!==void 0;){let i=e[t++];if(!i)return null;let a=n[i.type]?.find(e=>e.guard(i)),o=a?a.goTo:void 0;switch(o){case void 0:return null;case 7:return r+=i.value,e.splice(0,t),{type:`REFERENCE`,value:r};default:n=Ry[o],r+=i.value;break}}return null}function By(e,t=D){let n=Jl(e,t),r=[];for(;n.length;)r.push(zy(n)||n.shift());return r}let Vy=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,Hy=[`-`,`+`],Uy=[`%`];var Wy=class{tokens;currentIndex=0;current;length;constructor(e){this.tokens=e,this.current=e[0],this.length=e.length}shift(){let e=this.tokens[this.currentIndex];return this.current=this.tokens[++this.currentIndex],e}get next(){return this.tokens[this.currentIndex+1]}};let Gy={"%":40,"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function Ky(e){let t=e.shift();if(!t)throw new qi;switch(t.type){case`DEBUGGER`:let n=Xy(e,1e3);return n.debug=!0,n;case`NUMBER`:return{type:`NUMBER`,value:Wi(t.value,D),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`STRING`:return{type:`STRING`,value:ct(t.value),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`INVALID_REFERENCE`:return{type:`REFERENCE`,value:k.InvalidReference,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`REFERENCE`:if(e.current?.value===`:`&&e.next?.type===`REFERENCE`){e.shift();let n=e.shift();return{type:`REFERENCE`,value:`${t.value}:${n?.value}`,tokenStartIndex:t.tokenIndex,tokenEndIndex:n.tokenIndex}}return{type:`REFERENCE`,value:t.value,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`SYMBOL`:let r=t.value;if(e.current?.type===`LEFT_PAREN`&&Vy.test(t.value)&&r===pt(r,`'`)){let{args:n,rightParen:i}=qy(e);return{type:`FUNCALL`,value:r,args:n,tokenStartIndex:t.tokenIndex,tokenEndIndex:i.tokenIndex}}let i=r.toUpperCase();return i===`TRUE`||i===`FALSE`?{type:`BOOLEAN`,value:i===`TRUE`,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:{type:`SYMBOL`,value:pt(t.value,`'`),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`LEFT_PAREN`:let a=Xy(e),o=Yy(e,`RIGHT_PAREN`,E(`Missing closing parenthesis`));return{...a,tokenStartIndex:t.tokenIndex,tokenEndIndex:o.tokenIndex};case`OPERATOR`:let s=t.value;if(Hy.includes(s)){let n=Xy(e,Gy[s]);return{type:`UNARY_OPERATION`,value:s,operand:n,tokenStartIndex:t.tokenIndex,tokenEndIndex:n.tokenEndIndex}}throw new qi(E(`Unexpected token: %s`,t.value));default:throw new qi(E(`Unexpected token: %s`,t.value))}}function qy(e){if(Yy(e,`LEFT_PAREN`,E(`Missing opening parenthesis`)),e.current?.type===`RIGHT_PAREN`)return{args:[],rightParen:Yy(e,`RIGHT_PAREN`)};let t=[];for(t.push(Jy(e));e.current?.type!==`RIGHT_PAREN`;)Yy(e,`ARG_SEPARATOR`,E(`Wrong function call`)),t.push(Jy(e));return{args:t,rightParen:Yy(e,`RIGHT_PAREN`)}}function Jy(e){let t=e.current;return t?.type===`ARG_SEPARATOR`||t?.type===`RIGHT_PAREN`?{type:`EMPTY`,value:``,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:Xy(e)}function Yy(e,t,n){let r=e.shift();if(!r||r.type!==t)throw new qi(n);return r}function Xy(e,t=0){if(e.length===0)throw new qi;let n=Ky(e);for(;e.current?.type===`OPERATOR`&&Gy[e.current.value]>t;){let t=e.shift(),r=t.value;if(Uy.includes(r))n={type:`UNARY_OPERATION`,value:r,operand:n,postfix:!0,tokenStartIndex:n.tokenStartIndex,tokenEndIndex:t.tokenIndex};else{let t=Xy(e,Gy[r]);n={type:`BIN_OPERATION`,value:r,left:n,right:t,tokenStartIndex:n.tokenStartIndex,tokenEndIndex:t.tokenEndIndex}}}return n}function Zy(e){return Qy(By(e))}function Qy(e){let t=new Wy(e.map((e,t)=>({type:e.type,value:e.value,tokenIndex:t})).filter(e=>e.type!==`SPACE`));t.current?.value===`=`&&t.shift();let n=Xy(t);if(t.current)throw new qi;return n}function $y(e,t,n){return nb(e,e=>e.type===t?n(e):e)}function eb(e){return Array.from(tb(e))}function*tb(e){switch(yield e,e.type){case`FUNCALL`:for(let t of e.args)yield*tb(t);break;case`UNARY_OPERATION`:yield*tb(e.operand);break;case`BIN_OPERATION`:yield*tb(e.left),yield*tb(e.right);break}}function nb(e,t){switch(e=t(e),e.type){case`FUNCALL`:return{...e,args:e.args.map(e=>nb(e,t))};case`UNARY_OPERATION`:return{...e,operand:nb(e.operand,t)};case`BIN_OPERATION`:return{...e,right:nb(e.right,t),left:nb(e.left,t)};default:return e}}function rb(e){let t=0;return e.map(e=>{let n=e.value.toString().length,r=Object.assign({},e,{start:t,end:t+n,length:n});return t=r.end,r})}function ib(e){let t=[],n=0;return e.map((r,i)=>{if(r.type===`LEFT_PAREN`){t.push(n+1),n=0;for(let n=i-1;n>=0;n--){if(e[n].type===`SPACE`){e[n].parenthesesCode=t.join(`:`);continue}e[n].type===`SYMBOL`&&(e[n].parenthesesCode=t.join(`:`));break}}return r.parenthesesCode=t.join(`:`),r.type===`RIGHT_PAREN`&&t.length&&(n=t.pop()),r})}function ab(e){let t=[],n=``;function r(e){if(t.length===0)return;let n=t.at(-1);if(n&&n.argsTokens){let{argsTokens:t,argPosition:r}=n;t[r]||(t[r]=[]),t[r].push({value:e.value,type:e.type})}}return e.map((e,i)=>{switch([`SPACE`,`LEFT_PAREN`].includes(e.type)||(n=``),e.type){case`SYMBOL`:r(e),n=e.value;break;case`LEFT_PAREN`:t.push({parent:n,argPosition:0,argsTokens:[],args:[]}),r(e),n=``;break;case`RIGHT_PAREN`:t.pop()?.argsTokens?.flat().forEach(r),r(e);break;case`ARG_SEPARATOR`:t.length&&t[t.length-1].argPosition++,r(e);break;default:r(e);break}if(t.length){let n=t[t.length-1];n.parent&&(e.functionContext=Object.assign({},n))}return e})}function ob(e){for(let t of e)if(t.functionContext){let{argsTokens:e,args:n}=t.functionContext;if(delete t.functionContext.argsTokens,n.length||!e)continue;e[0]?.[0]?.type===`LEFT_PAREN`&&(e[0]=e[0].slice(1));for(let t of e){let e=t;e.at(0)?.type===`ARG_SEPARATOR`&&(e=e.slice(1));try{n.push(Qy(e))}catch{n.push(void 0)}}}return e}function sb(e,t){return ob(ab(ib(rb(By(e,t)))))}function cb(e){if(e.type!==`REFERENCE`)return e;let{xc:t,sheetName:n}=jc(e.value),[r,i]=t.split(`:`),a=lb(r),o=i?`:${lb(i)}`:``;return{...e,value:Mc(n,a+o)}}function lb(e){switch(fb(e)){case`none`:e=ub(e,`colrow`);break;case`colrow`:e=ub(e,`row`);break;case`row`:e=ub(e,`col`);break;case`col`:e=ub(e,`none`);break}return e}function ub(e,t){let n;({sheetName:n,xc:e}=jc(e)),n=n?mt(n)+`!`:``,e=e.replace(/\$/g,``);let r=e.indexOf(`:`);return r>=0?`${n}${db(e.slice(0,r),t)}:${db(e.slice(r+1),t)}`:n+db(e,t)}function db(e,t){let n=e.search(/[0-9]/),r=n!==0,i=n>=0;switch(t){case`col`:return r?`$`+e:e;case`row`:return i?e.slice(0,n)+`$`+e.slice(n):e;case`colrow`:return!i||!r?`$`+e:`$`+e.slice(0,n)+`$`+e.slice(n);case`none`:return e}}function fb(e){return hb(e)?`colrow`:pb(e)?`col`:mb(e)?`row`:`none`}function pb(e){return e.startsWith(`$`)}function mb(e){return e.includes(`$`,1)}function hb(e){return e.startsWith(`$`)&&e.length>1&&e.slice(1).includes(`$`)}function gb(e,t,n){let r=(t.startsWith(`=`)?sb(t,n):[]).filter(t=>t.start<=e.start&&t.end>=e.start||t.start>=e.start&&t.start<e.end),i=r.filter(e=>e.type===`REFERENCE`);if(i.length===0)return;let a=r.map(cb).map(e=>e.value).join(``),o=r[0].start,s=r[r.length-1].end,c=t.slice(0,o)+a+t.slice(s),l=c.length-t.length,u={start:i[0].start,end:i[i.length-1].end+l};return i.length===1&&e.start===e.end&&(u.start=u.end),{content:c,selection:u}}var _b=l({CELL:()=>yb,ISBLANK:()=>Db,ISERR:()=>bb,ISERROR:()=>xb,ISFORMULA:()=>kb,ISLOGICAL:()=>Sb,ISNA:()=>Cb,ISNONTEXT:()=>wb,ISNUMBER:()=>Tb,ISTEXT:()=>Eb,NA:()=>Ob});let vb=[{value:`address`,label:E(`Returns an absolute reference as plain text of the top left cell in reference.`)},{value:`col`,label:E(`Returns the column number of the cell in reference.`)},{value:`contents`,label:E(`Returns the value contained in the top left cell in reference.`)},{value:`format`,label:E(`Returns the format of the top left cell in reference.`)},{value:`row`,label:E(`Returns the row number of the top left cell in reference.`)},{value:`type`,label:E(`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.`)}],yb={description:E(`Gets information about a cell.`),args:[H(`info_type (string)`,E(`The type of information requested.`),vb),H(`reference (meta, range<meta>)`,E(`The reference to the cell.`))],compute:function(e,t){let n=N(e).toLowerCase();if(!vb.map(e=>e.value).includes(n))return new A(E(`The info_type should be one of %s.`,vb.join(`, `)));let r=this.__originSheetId,i=t[0][0].value,{sheetName:a,xc:o}=jc(i);a=a===this.getters.getSheetName(r)?void 0:a;let s=Mc(a,ub(o,`colrow`)),c=this.getters.getRangeFromSheetXC(r,s);switch(n){case`address`:return this.getters.getRangeString(c,r);case`col`:return c.zone.left+1;case`contents`:{let e={sheetId:c.sheetId,col:c.zone.left,row:c.zone.top};return this.getters.getEvaluatedCell(e).value}case`format`:{let 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`:{let e={sheetId:c.sheetId,col:c.zone.left,row:c.zone.top},t=this.getters.getEvaluatedCell(e).type;return t===`empty`?`b`:t===`text`?`l`:`v`}}return``},isExported:!0},bb={description:E(`Whether a value is an error other than #N/A.`),args:[H(`value (any)`,E(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return j(t)&&t!==k.NotAvailable},isExported:!0},xb={description:E(`Whether a value is an error.`),args:[H(`value (any)`,E(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return j(t)},isExported:!0},Sb={description:E("Whether a value is `true` or `false`."),args:[H(`value (any)`,E(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},Cb={description:E(`Whether a value is the error #N/A.`),args:[H(`value (any)`,E(`The value to be verified as an error type.`))],compute:function(e){return e?.value===k.NotAvailable},isExported:!0},wb={description:E(`Whether a value is non-textual.`),args:[H(`value (any)`,E(`The value to be checked.`))],compute:function(e){return!Eb.compute.bind(this)(e)},isExported:!0},Tb={description:E(`Whether a value is a number.`),args:[H(`value (any)`,E(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},Eb={description:E(`Whether a value is text.`),args:[H(`value (any)`,E(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&j(e?.value)===!1},isExported:!0},Db={description:E(`Whether the referenced cell is empty`),args:[H(`value (any)`,E(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},Ob={description:E(`Returns the error value #N/A.`),args:[],compute:function(){return{value:k.NotAvailable}},isExported:!0},kb={description:E(`Checks whether there is a reference to a cell that contains a formula, and returns TRUE or FALSE.`),args:[H(`cell_reference (meta)`,E(`A reference to a cell.`))],compute:function(e){let{sheetName:t,xc:n}=jc(e.value),{col:r,row:i}=ir(n),a=(t&&this.getters.getSheetIdByName(t))??this.__originSheetId;return this.getters.getCell({sheetId:a,col:r,row:i})?.isFormula??!1},isExported:!0};var Ab=l({AND:()=>jb,FALSE:()=>Mb,IF:()=>Nb,IFERROR:()=>Pb,IFNA:()=>Fb,IFS:()=>Ib,NOT:()=>Lb,OR:()=>Rb,SWITCH:()=>zb,TRUE:()=>Bb,XOR:()=>Vb});let jb={description:E("Logical `and` operator."),args:[H(`logical_expression1 (boolean, range<boolean>)`,E(`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.`)),H(`logical_expression2 (boolean, range<boolean>, repeating)`,E(`More expressions that represent logical values.`))],compute:function(...e){let{result:t,foundBoolean:n}=Ou(e);return n?t:new A(Ba)},isExported:!0},Mb={description:E("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},Nb={description:E(`Returns value depending on logical expression.`),args:[H(`logical_expression (boolean, range<boolean>)`,E(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.`)),H(`value_if_true (any, range)`,E(`The value the function returns if logical_expression is TRUE.`)),H(`value_if_false (any, range, default=FALSE)`,E(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return Wu(e)?Ea(Nb.compute,[e,t,n]):(P(Hu(e))?t:n)??{value:0}},isExported:!0},Pb={description:E(`Value if it is not an error, otherwise 2nd argument.`),args:[H(`value (any, range)`,E(`The value to return if value itself is not an error.`)),H(`value_if_error (any, range, default="empty")`,E(`The value the function returns if value is an error.`))],compute:function(e,t){return Wu(e)?Ea(Pb.compute,[e,t]):(j(Hu(e)?.value)?t:e)??{value:0}},isExported:!0},Fb={description:E(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[H(`value (any, range)`,E(`The value to return if value itself is not #N/A an error.`)),H(`value_if_error (any, range, default="empty")`,E(`The value the function returns if value is an #N/A error.`))],compute:function(e,t){return Wu(e)?Ea(Fb.compute,[e,t]):(Hu(e)?.value===k.NotAvailable?t:e)??{value:0}},isExported:!0},Ib={description:E(`Returns a value depending on multiple logical expressions.`),args:[H(`condition1 (boolean, range<boolean>)`,E(`The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.`)),H(`value1 (any, range)`,E(`The returned value if condition1 is TRUE.`)),H(`condition2 (boolean, any, range, repeating)`,E(`Additional conditions to be evaluated if the previous ones are FALSE.`)),H(`value2 (any, range, repeating)`,E(`Additional values to be returned if their corresponding conditions are TRUE.`))],compute:function(...e){if(e.length%2!=0)return new A(E(`Wrong number of arguments. Expected an even number of arguments.`));for(;e.length>0;){if(Wu(e[0]))return Ea(Ib.compute,e);let t=P(Hu(e.shift())),n=e.shift();if(t)return n??{value:0}}return new A(E(`No match.`))},isExported:!0},Lb={description:E(`Returns opposite of provided logical value.`),args:[H(`logical_expression (boolean)`,E(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!P(e)},isExported:!0},Rb={description:E("Logical `or` operator."),args:[H(`logical_expression1 (boolean, range<boolean>)`,E(`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.`)),H(`logical_expression2 (boolean, range<boolean>, repeating)`,E(`More expressions that evaluate to logical values.`))],compute:function(...e){let{result:t,foundBoolean:n}=ku(e);return n?t:new A(Ba)},isExported:!0},zb={description:E(`Returns a value by comparing cases to an expression.`),args:[H(`expression (number, boolean, string)`,E(`The value to be checked.`)),H(`case1 (number, boolean, string)`,E(`The first case to be checked against expression.`)),H(`value1 (any)`,E(`The corresponding value to be returned if case1 matches expression.`)),H(`case2 (any, repeating)`,E(`Additional cases to try if the previous ones don't match expression.`)),H(`value2 (any, repeating)`,E(`Additional values to be returned if their corresponding cases match expression.`)),H(`default (any, default="empty")`,E(`An optional default value to be returned if none of the cases match expression.`))],compute:function(e,...t){let n=t.length%2==0?na(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&j(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},Bb={description:E("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},Vb={description:E("Logical `xor` operator."),args:[H(`logical_expression1 (boolean, range<boolean>)`,E(`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.`)),H(`logical_expression2 (boolean, range<boolean>, repeating)`,E(`More expressions that evaluate to logical values.`))],compute:function(...e){let t=!1,n=!1;return Oa(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new A(Ba)},isExported:!0},Hb={Errors:{InvalidRange:E(`The range is invalid`),FirstArgMissing:E(`The argument is missing. Please provide a value`),SecondArgMissing:E(`The second argument is missing. Please provide a value`),MinNaN:E(`The minpoint must be a number`),MidNaN:E(`The midpoint must be a number`),MaxNaN:E(`The maxpoint must be a number`),ValueUpperInflectionNaN:E(`The first value must be a number`),ValueLowerInflectionNaN:E(`The second value must be a number`),MinBiggerThanMax:E(`Minimum must be smaller then Maximum`),MinBiggerThanMid:E(`Minimum must be smaller then Midpoint`),MidBiggerThanMax:E(`Midpoint must be smaller then Maximum`),LowerBiggerThanUpper:E(`Lower inflection point must be smaller than upper inflection point`),MinInvalidFormula:E(`Invalid Minpoint formula`),MaxInvalidFormula:E(`Invalid Maxpoint formula`),MidInvalidFormula:E(`Invalid Midpoint formula`),ValueUpperInvalidFormula:E(`Invalid upper inflection point formula`),ValueLowerInvalidFormula:E(`Invalid lower inflection point formula`),EmptyRange:E(`A range needs to be defined`),ValueCellIsInvalidFormula:E(`At least one of the provided values is an invalid formula`),Unexpected:E(`The rule is invalid for an unknown reason`)},ColorScale:E(`Color scale`),IconSet:E(`Icon set`),DataBar:E(`Data bar`)},Ub={Series:E(`Series`),BackgroundColor:E(`Background color`),StackedBarChart:E(`Stacked bar chart`),StackedLineChart:E(`Stacked line chart`),StackedAreaChart:E(`Stacked area chart`),StackedColumnChart:E(`Stacked column chart`),CumulativeData:E(`Cumulative data`),TreatLabelsAsText:E(`Treat labels as text`),AggregatedChart:E(`Aggregate`),Errors:{Unexpected:E(`The chart definition is invalid for an unknown reason`),InvalidDataSet:E(`The dataset is invalid`),InvalidLabelRange:E(`Labels are invalid`),InvalidScorecardKeyValue:E(`The key value is invalid`),InvalidScorecardBaseline:E(`The baseline value is invalid`),InvalidGaugeDataRange:E(`The data range is invalid`),EmptyGaugeRangeMin:E(`A minimum range limit value is needed`),GaugeRangeMinNaN:E(`The minimum range limit value must be a number`),EmptyGaugeRangeMax:E(`A maximum range limit value is needed`),GaugeRangeMaxNaN:E(`The maximum range limit value must be a number`),GaugeLowerInflectionPointNaN:E(`The lower inflection point value must be a number`),GaugeUpperInflectionPointNaN:E(`The upper inflection point value must be a number`)},GeoChart:{ColorScales:{blues:E(`Blues`),cividis:E(`Cividis`),greens:E(`Greens`),greys:E(`Greys`),oranges:E(`Oranges`),purples:E(`Purples`),rainbow:E(`Rainbow`),reds:E(`Reds`),viridis:E(`Viridis`)}}},Wb={Custom:E(`Custom`)},Gb=E(`Merged cells are preventing this operation. Unmerge those cells and try again.`),Kb=E(`The header row of a table can't be moved.`),qb={Errors:{Unexpected:E(`Cannot split the selection for an unknown reason`),NoSplitSeparatorInSelection:E(`There is no match for the selected separator in the selection`),MoreThanOneColumnSelected:E(`Only a selection from a single column can be split`),SplitWillOverwriteContent:E(`Splitting will overwrite existing content`)}},Jb={Errors:{Unexpected:E(`Cannot remove duplicates for an unknown reason`),MoreThanOneRangeSelected:E(`Please select only one range of cells`),EmptyTarget:E(`Please select a range of cells containing values.`),NoColumnsProvided:E(`Please select at latest one column to analyze.`),WillRemoveExistingMerge:E(`This operation is not possible due to a merge. Please remove the merges first than try again.`)}},U={DateIs:{today:E(`today`),yesterday:E(`yesterday`),tomorrow:E(`tomorrow`),lastWeek:E(`in the past week`),lastMonth:E(`in the past month`),lastYear:E(`in the past year`)},DateIsBefore:{today:E(`today`),yesterday:E(`yesterday`),tomorrow:E(`tomorrow`),lastWeek:E(`one week ago`),lastMonth:E(`one month ago`),lastYear:E(`one year ago`)},CriterionError:{notEmptyValue:E(`The value must not be empty`),numberValue:E(`The value must be a number`),dateValue:E(`The value must be a date`),validRange:E(`The value must be a valid range`),validFormula:E(`The formula must be valid`)},Errors:{InvalidRange:E(`The range is invalid.`),InvalidDataValidationCriterionValue:E(`One or more of the provided criteria values are invalid. Please review and correct them.`),InvalidNumberOfCriterionValues:E(`One or more of the provided criteria values are missing.`),Unexpected:E(`The rule is invalid for an unknown reason.`)}},Yb={Errors:{Unexpected:E(`The table zone is invalid for an unknown reason`),TableOverlap:E(`You cannot create overlapping tables.`),NonContinuousTargets:E(`A table can only be created on a continuous selection.`),InvalidRange:E(`The range is invalid`),TargetOutOfSheet:E(`The range is out of the sheet`)},Checkboxes:{hasFilters:E(`Filter button`),headerRow:E(`Header row(s)`),bandedRows:E(`Banded rows`),firstColumn:E(`First column`),lastColumn:E(`Last column`),bandedColumns:E(`Banded columns`),automaticAutofill:E(`Automatically autofill formulas`),totalRow:E(`Total row`),isDynamic:E(`Auto-adjust to formula result`)},Tooltips:{filterWithoutHeader:E(`Cannot have filters without a header row`),isDynamic:E(`For tables based on array formulas only`)}},Xb={labels:{no_calculations:E(`No calculations`),"%_of_grand_total":E(`% of grand total`),"%_of_col_total":E(`% of column total`),"%_of_row_total":E(`% of row total`),"%_of":E(`% of`),"%_of_parent_row_total":E(`% of parent row total`),"%_of_parent_col_total":E(`% of parent column total`),"%_of_parent_total":E(`% of parent total`),difference_from:E(`Difference from`),"%_difference_from":E(`% difference from`),running_total:E(`Running total`),"%_running_total":E(`% Running total`),rank_asc:E(`Rank smallest to largest`),rank_desc:E(`Rank largest to smallest`),index:E(`Index`)},descriptions:{"%_of_grand_total":()=>E(`Displayed as % of grand total`),"%_of_col_total":()=>E(`Displayed as % of column total`),"%_of_row_total":()=>E(`Displayed as % of row total`),"%_of":e=>E(`Displayed as % of "%s"`,e),"%_of_parent_row_total":e=>E(`Displayed as % of parent row total of "%s"`,e),"%_of_parent_col_total":()=>E(`Displayed as % of parent column total`),"%_of_parent_total":e=>E(`Displayed as % of parent "%s" total`,e),difference_from:e=>E(`Displayed as difference from "%s"`,e),"%_difference_from":e=>E(`Displayed as % difference from "%s"`,e),running_total:e=>E(`Displayed as running total based on "%s"`,e),"%_running_total":e=>E(`Displayed as % running total based on "%s"`,e),rank_asc:e=>E(`Displayed as rank from smallest to largest based on "%s"`,e),rank_desc:e=>E(`Displayed as rank largest to smallest based on "%s"`,e),index:()=>E(`Displayed as index`)},documentation:{no_calculations:E(`Displays the value that is entered in the field.`),"%_of_grand_total":E(`Displays values as a percentage of the grand total of all the values or data points in the report.`),"%_of_col_total":E(`Displays all the values in each column or series as a percentage of the total for the column or series.`),"%_of_row_total":E(`Displays the value in each row or category as a percentage of the total for the row or category.`),"%_of":E(`Displays values as a percentage of the value of the Base item in the Base field.`),"%_of_parent_row_total":E(`Calculates values as follows:
16
+ `)}function Ef(e,t){let n=document.createElement(`style`);n.textContent=Tf(t),Cf[e]=n}function Df(e){let t=Cf[e];t.setAttribute(`component`,e),document.head.appendChild(t)}function Of({strikethrough:e,underline:t}){return!e&&!t?`none`:`${e?`line-through`:``} ${t?`underline`:``}`}function kf(e){let t=Af(e);return e&&e.fillColor&&(t.background=e.fillColor),t}function Af(e){let 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 n=e.strikethrough?`line-through`:``;n=e.underline?n+` underline`:n,t[`text-decoration`]=n}return e.textColor&&(t.color=e.textColor),t}function V(e){let t=``;for(let n in e)e[n]&&(t+=`${n}:${e[n]}; `);return t}function jf(e){let 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}}let Mf=new g;function Nf(){return!!window.Chart.registry.plugins.get(`chartShowValuesPlugin`)}function Pf(){if(!(!window.Chart||Nf()))for(let e of Mf.getAll())e.register(window.Chart)}function Ff(){if(window.Chart)for(let e of Mf.getAll())e.unregister(window.Chart)}var If=class extends bf{mutators=[`disableAnimationForChart`,`enableAnimationForChart`];animationPlayed={};disableAnimationForChart(e,t){return this.animationPlayed[e]=t,`noStateChange`}enableAnimationForChart(e){return this.animationPlayed[e]=void 0,`noStateChange`}};function Lf(){return class extends window.Chart.BarController{static id=`funnel`;static defaults={...window.Chart?.BarController.defaults,dataElementType:`funnel`,animation:{duration:e=>e.type===`data`?1e3*(e.raw[1]/Math.max(...e.dataset.data.map(e=>e[1]))):1e3}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);for(let i=t;i<t+n;i++){let t=e[i];this.updateElement(t,i,{nextElement:e[i+1]},r)}}}}function Rf(){return class extends window.Chart.BarElement{static id=`funnel`;draw(e){e.save();let{x:t,y:n,height:r,nextElement:i,base:a,options:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=zf(this),c=(s-(i?zf(i):0))/2,l=Math.min(t,a),u=n-r/2;e.fillStyle=o.backgroundColor,e.beginPath(),e.moveTo(l,u),e.lineTo(l+s,u),e.lineTo(l+s-c,u+r),e.lineTo(l+c,u+r),e.closePath(),e.fill(),o.borderWidth&&(e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,e.stroke()),e.restore()}inRange(e,t){let{x:n,y:r,height:i,nextElement:a,base:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=zf(this),c=a?zf(a):0,l=Math.min(n,o),u=r-i/2;if(t<u||t>u+i)return!1;let d=(s-c)/2,f=l+d*(t-u)/i,p=l+s-d*(t-u)/i;return!(e<f||e>p)}}}function zf(e){let{x:t,base:n}=e.getProps([`x`,`base`]);return Math.max(t,n)-Math.min(t,n)}let Bf=function(e){if(!e.length)return{x:0,y:0};let{x:t,y:n,base:r,width:i,height:a}=e[0].element.getProps([`x`,`y`,`width`,`height`,`base`]),o=Math.min(t,r),s=n-a/2;return{x:o+i*2/3,y:s+a/2}},Vf=`000000`,Hf={arrows:`3Arrows`,smiley:`3Symbols`,dots:`3TrafficLights1`},Uf={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`},Wf=`http://schemas.openxmlformats.org/drawingml/2006/main`,Gf=`http://schemas.openxmlformats.org/drawingml/2006/chart`,Kf={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`},qf={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`},Jf=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,Yf=.75,Xf=.143,Zf=8.43,Qf=12.75,$f={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}],IFERROR:[{type:`NUMBER`,value:0}]},ep=`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`.split(`,`),tp=/(.*?)\((.*?)\)(.*)/,np=[`ANY`,`BOOLEAN`,`DATE`,`NUMBER`,`STRING`,`RANGE`,`RANGE<BOOLEAN>`,`RANGE<DATE>`,`RANGE<NUMBER>`,`RANGE<STRING>`,`META`,`RANGE<META>`];function H(e,t=``,n){return rp(e,t,n)}function rp(e,t,n){let r=e.match(tp),i=r[1].trim();if(!i)throw Error(`Function argument definition is missing a name: '${e}'.`);let a=[],o=!1,s=!1,c;for(let e of r[2].split(`,`)){let t=e.trim().toUpperCase(),n=np.find(e=>t===e);n?a.push(n):t===`RANGE<ANY>`?a.push(`RANGE`):t===`OPTIONAL`?o=!0:t===`REPEATING`?s=!0:t.startsWith(`DEFAULT=`)&&(c=e.trim().slice(8))}let l={name:i,description:t,type:a};return(a.includes(`ANY`)||a.includes(`RANGE`))&&(l.acceptErrors=!0),o&&(l.optional=!0),s&&(l.repeating=!0),c!==void 0&&(l.default=!0,l.defaultValue=c),a.some(e=>e.startsWith(`RANGE`))&&(l.acceptMatrix=!0),a.every(e=>e.startsWith(`RANGE`))&&(l.acceptMatrixOnly=!0),n&&n.length>0&&(l.proposalValues=n),l}function ip(e,t){let n=0,r=0,i=0,a=0;for(let e of t.args)n++,!e.optional&&!e.repeating&&!e.default&&r++,e.repeating&&i++,(e.optional||e.default)&&a++;let o=t;return o.minArgRequired=r,o.maxArgPossible=i?1/0:n,o.nbrArgRepeating=i,o.nbrArgOptional=a,o.hidden=t.hidden||!1,o.name=e,o}let ap={};function op(e,t){let n=e.name;return ap[n]?.[t]||(ap[n]||(ap[n]={}),ap[n][t]||(ap[n][t]=sp(e,t)),ap[n][t])}function sp(e,t){let n={},r=e.nbrArgRepeating?Math.floor((t-e.minArgRequired)/e.nbrArgRepeating):0,i=e.nbrArgRepeating*r,a=t-e.minArgRequired-i,o=0,s=0;for(let t=0;t<e.args.length;t++){let i=e.args[t];if(i.optional||i.default){s<a&&(n[o]=t,o++),s++;continue}if(i.repeating){for(let i=0;i<r;i++)for(let r=0;r<e.nbrArgRepeating;r++)n[o]=t+r,o++;t+=e.nbrArgRepeating-1;continue}n[o]=t,o++}return e=>n[e]}let cp=[`META`,`RANGE<META>`];function lp(e){if(e.nbrArgRepeating&&e.nbrArgOptional>=e.nbrArgRepeating)throw Error(`Function ${e.name} has more optional arguments than repeatable ones.`);let t=!1,n=!1;for(let r of e.args){if(r.type.some(e=>cp.includes(e))&&r.type.some(e=>!cp.includes(e)))throw Error(`Function ${e.name} has a mix of META and non-META types in the same argument: ${r.type}.`);if(r.repeating){if(!n&&t)throw Error(`Function ${e.name} has non-consecutive repeating arguments. All repeating arguments must be declared consecutively.`);t=!0,n=!0}else n=!1}}let up=new g;var dp=l({ARRAY_CONSTRAIN:()=>fp,CHOOSECOLS:()=>pp,CHOOSEROWS:()=>mp,EXPAND:()=>hp,FLATTEN:()=>gp,FREQUENCY:()=>_p,HSTACK:()=>vp,MDETERM:()=>yp,MINVERSE:()=>bp,MMULT:()=>xp,SUMPRODUCT:()=>Sp,SUMX2MY2:()=>wp,SUMX2PY2:()=>Tp,SUMXMY2:()=>Ep,TOCOL:()=>kp,TOROW:()=>Ap,TRANSPOSE:()=>jp,VSTACK:()=>Mp,WRAPCOLS:()=>Np,WRAPROWS:()=>Pp});let fp={description:E(`Returns a result array constrained to a specific width and height.`),args:[H(`input_range (any, range<any>)`,E(`The range to constrain.`)),H(`rows (number)`,E(`The number of rows in the constrained array.`)),H(`columns (number)`,E(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=I(e),i=la(t?.value,this.locale),a=la(n?.value,this.locale);if(i<=0)return new A(E(`The rows argument (%s) must be strictly positive.`,i.toString()));if(a<=0)return new A(E(`The columns argument (%s) must be strictly positive.`,a.toString()));let o=Math.min(i,r[0].length);return Sa(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},pp={description:E(`Creates a new array from the selected columns in the existing range.`),args:[H(`array (any, range<any>)`,E(`The array that contains the columns to be returned.`)),H(`col_num (number, range<number>)`,E(`The first column index of the columns to be returned.`)),H(`col_num2 (number, range<number>, repeating)`,E(`The columns indexes of the columns to be returned.`))],compute:function(e,...t){let n=I(e),r=Ra(t,e=>la(e?.value,this.locale)),i=r.filter(e=>e===0||n.length<Math.abs(e));if(i.length!==0)return new A(E(`The columns arguments must be between -%s and %s (got %s), excluding 0.`,n.length.toString(),n.length.toString(),i.join(`,`)));let a=Array(r.length);for(let e=0;e<r.length;e++)r[e]>0?a[e]=n[r[e]-1]:a[e]=n[n.length+r[e]];return a},isExported:!0},mp={description:E(`Creates a new array from the selected rows in the existing range.`),args:[H(`array (any, range<any>)`,E(`The array that contains the rows to be returned.`)),H(`row_num (number, range<number>)`,E(`The first row index of the rows to be returned.`)),H(`row_num2 (number, range<number>, repeating)`,E(`The rows indexes of the rows to be returned.`))],compute:function(e,...t){let n=I(e),r=Ra(t,e=>la(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?Sa(i,r.length,(e,t)=>r[t]>0?n[e][r[t]-1]:n[e][n[e].length+r[t]]):new A(E(`The rows arguments must be between -%s and %s (got %s), excluding 0.`,n[0].length.toString(),n[0].length.toString(),a.join(`,`)))},isExported:!0},hp={description:E(`Expands or pads an array to specified row and column dimensions.`),args:[H(`array (any, range<any>)`,E(`The array to expand.`)),H(`rows (number)`,E(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),H(`columns (number, optional)`,E(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),H(`pad_with (any, default=0)`,E(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=I(e),a=la(t?.value,this.locale),o=n===void 0?i.length:la(n.value,this.locale);return a<i[0].length?new A(E(`The rows arguments (%s) must be greater or equal than the number of rows of the array.`,a.toString())):o<i.length?new A(E(`The columns arguments (%s) must be greater or equal than the number of columns of the array.`,o.toString())):Sa(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},gp={description:E(`Flattens all the values from one or more ranges into a single column.`),args:[H(`range (any, range<any>)`,E(`The first range to flatten.`)),H(`range2 (any, range<any>, repeating)`,E(`Additional ranges to flatten.`))],compute:function(...e){return[Ra(e,e=>e===void 0?{value:``}:e)]},isExported:!1},_p={description:E(`Calculates the frequency distribution of a range.`),args:[H(`data (range<number>)`,E(`The array of ranges containing the values to be counted.`)),H(`classes (number, range<number>)`,E(`The range containing the set of classes.`))],compute:function(e,t){let n=Ra([e],e=>e.value).filter(e=>typeof e==`number`),r=Ra([t],e=>e.value).filter(e=>typeof e==`number`).map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);r.push({initialIndex:r.length,value:1/0,count:0});let i=n.sort((e,t)=>e-t),a=0;for(let e of i){for(;e>r[a].value&&a<r.length-1;)a++;r[a].count++}return[r.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},vp={description:E(`Appends ranges horizontally and in sequence to return a larger array.`),args:[H(`range1 (any, range<any>)`,E(`The first range to be appended.`)),H(`range2 (any, range<any>, repeating)`,E(`Additional ranges to add to range1.`))],compute:function(...e){let t=Math.max(...e.map(e=>e?.[0]?.length??0)),n=[];for(let r of e){let e=I(r);for(let r=0;r<e.length;r++){let i=Array(t).fill({value:null});for(let t=0;t<e[r].length;t++)i[t]=e[r][t];n.push(i)}}return n},isExported:!0},yp={description:E(`Returns the matrix determinant of a square matrix.`),args:[H(`square_matrix (number, range<number>)`,E(`An range with an equal number of rows and columns representing a matrix whose determinant will be calculated.`))],compute:function(e){let t=sa(e,`square_matrix`);return Iu(t)?zu(t).determinant:new A(E(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},bp={description:E(`Returns the multiplicative inverse of a square matrix.`),args:[H(`square_matrix (number, range<number>)`,E(`An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated.`))],compute:function(e){let t=sa(e,`square_matrix`);if(!Iu(t))return new A(E(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=zu(t);return n||new A(E(`The matrix is not invertible.`))},isExported:!0},xp={description:E(`Calculates the matrix product of two matrices.`),args:[H(`matrix1 (number, range<number>)`,E(`The first matrix in the matrix multiplication operation.`)),H(`matrix2 (number, range<number>)`,E(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=sa(e,`matrix1`),r=sa(t,`matrix2`);return n.length===0||r.length===0?new A(E(`The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.`)):n.length===r[0].length?Vu(n,r):new A(E(`In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).`,n.length.toString(),r[0].length.toString()))},isExported:!0},Sp={description:E(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[H(`range1 (number, range<number>)`,E(`The first range whose entries will be multiplied with corresponding entries in the other ranges.`)),H(`range2 (number, range<number>, repeating)`,E(`The other range whose entries will be multiplied with corresponding entries in the other ranges.`))],compute:function(...e){if(!Fu(...e))return new A(E(`All the ranges must have the same dimensions.`));let t=e.map(I),n=0;for(let e=0;e<t[0].length;e++)for(let r=0;r<t[0][e].length;r++){if(!t.every(t=>typeof t[e][r].value==`number`))continue;let i=1;for(let n of t)i*=M(n[e][r],this.locale);n+=i}return n},isExported:!0};function Cp(e,t,n){if(!Fu(e,t))return new A(E(`The arguments array_x and array_y must have the same dimensions.`));let r=I(e),i=I(t),a=!1,o=0;for(let e in r)for(let t in r[e]){let s=r[e][t].value,c=i[e][t].value;typeof s!=`number`||typeof c!=`number`||(a=!0,o+=n(s,c))}return a?o:new A(E(`The arguments array_x and array_y must contain at least one pair of numbers.`))}let wp={description:E(`Calculates the sum of the difference of the squares of the values in two array.`),args:[H(`array_x (number, range<number>)`,E(`The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.`)),H(`array_y (number, range<number>)`,E(`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 Cp(e,t,(e,t)=>e**2-t**2)},isExported:!0},Tp={description:E(`Calculates the sum of the sum of the squares of the values in two array.`),args:[H(`array_x (number, range<number>)`,E(`The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.`)),H(`array_y (number, range<number>)`,E(`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 Cp(e,t,(e,t)=>e**2+t**2)},isExported:!0},Ep={description:E(`Calculates the sum of squares of the differences of values in two array.`),args:[H(`array_x (number, range<number>)`,E(`The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.`)),H(`array_y (number, range<number>)`,E(`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 Cp(e,t,(e,t)=>(e-t)**2)},isExported:!0},Dp=[H(`array (any, range<any>)`,E(`The array which will be transformed.`)),H(`ignore (number, default=0)`,E(`Whether to ignore certain types of values. By default, no values are ignored.`),[{value:0,label:E(`Keep all values (default)`)},{value:1,label:E(`Ignore blanks`)},{value:2,label:E(`Ignore errors`)},{value:3,label:E(`Ignore blanks and errors`)}]),H(`scan_by_column (number, default=false)`,E(`Scan the array by column. By default, the array is scanned by row.`),[{value:!1,label:E(`Scan by row (default)`)},{value:!0,label:E(`Scan by column`)}])];function Op(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!j(e.value);if(t===3)return e=>e.value!==null&&!j(e.value);throw new A(E(`Argument ignore must be between 0 and 3`))}let kp={description:E(`Transforms a range of cells into a single column.`),args:Dp,compute:function(e,t={value:0},n={value:!1}){let r=I(e),i=M(t.value,this.locale),a=(P(n.value)?r:Ta(r)).flat().filter(Op(i));return a.length===0?new Xi(E(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},Ap={description:E(`Transforms a range of cells into a single row.`),args:Dp,compute:function(e,t={value:0},n={value:!1}){let r=I(e),i=M(t.value,this.locale),a=(P(n.value)?r:Ta(r)).flat().filter(Op(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Xi(E(`No results for the given arguments of TOROW.`)):a},isExported:!0},jp={description:E(`Transposes the rows and columns of a range.`),args:[H(`range (any, range<any>)`,E(`The range to be transposed.`))],compute:function(e){let t=I(e),n=t[0].length,r=t.length;return Sa(n,r,(e,n)=>t[n][e])},isExported:!0},Mp={description:E(`Appends ranges vertically and in sequence to return a larger array.`),args:[H(`range1 (any, range<any>)`,E(`The first range to be appended.`)),H(`range2 (any, range<any>, repeating)`,E(`Additional ranges to add to range1.`))],compute:function(...e){let t=Math.max(...e.map(e=>I(e).length)),n=e.reduce((e,t)=>e+I(t)[0].length,0),r=Array(t).fill([]).map(()=>Array(n).fill({value:0})),i=0;for(let t of e){let e=I(t);for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)r[t][i+n]=e[t][n];i+=e[0].length}return r},isExported:!0},Np={description:E(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[H(`range (any, range<any>)`,E(`The range to wrap.`)),H(`wrap_count (number)`,E(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),H(`pad_with (any, default=0)`,E(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=I(e),i=la(t?.value,this.locale);if(!Pu(r))return new A(E(`Argument range must be a single row or column.`));let a=r.flat();return Sa(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},Pp={description:E(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[H(`range (any, range<any>)`,E(`The range to wrap.`)),H(`wrap_count (number)`,E(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),H(`pad_with (any, default=0)`,E(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=I(e),i=la(t?.value,this.locale);if(!Pu(r))return new A(E(`Argument range must be a single row or column.`));let a=r.flat();return Sa(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0};var Fp=l({FORMAT_LARGE_NUMBER:()=>Ip});let Ip={description:E(`Apply a large number format`),args:[H(`value (number)`,E(`The number.`)),H(`unit (string, optional)`,E(`The formatting unit. Use 'k', 'm', or 'b' to force the unit`),[{value:`k`,label:E(`Thousand`)},{value:`m`,label:E(`Million`)},{value:`b`,label:E(`Billion`)}])],compute:function(e,t){return{value:M(e,this.locale),format:Go(e,t,this.locale)}}};var Lp=class{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return`Success`}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==`Success`);if(r.length)return r}return`Success`}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},Rp=class extends Lp{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:n,canDispatch:r,uiActions:i,selection:a}){super(t),this.getters=e,this.ui=i,this.selection=a,this.dispatch=n,this.canDispatch=r}drawLayer(e,t){}},zp=class extends Rp{subtotalCells=new Set;handle(e){switch(e.type){case`START`:this.subtotalCells.clear();for(let e of this.getters.getSheetIds()){let t=this.getters.getCells(e);for(let e in t){let n=t[e];Bp(n)&&this.subtotalCells.add(n.id)}}break;case`UPDATE_CELL`:{if(!(`content`in e))return;let t=this.getters.getCell(e);if(!t)return;Bp(t)?this.subtotalCells.add(t.id):this.subtotalCells.delete(t.id);break}}wr.has(e.type)&&this.dispatch(`EVALUATE_CELLS`,{cellIds:Array.from(this.subtotalCells)})}};function Bp(e){return e.isFormula&&e.compiledFormula.tokens.some(e=>e.type===`SYMBOL`&&e.value.toUpperCase()===`SUBTOTAL`)}var Vp=l({ABS:()=>Up,ACOS:()=>Wp,ACOSH:()=>Gp,ACOT:()=>Kp,ACOTH:()=>qp,ASIN:()=>Jp,ASINH:()=>Yp,ATAN:()=>Xp,ATAN2:()=>Zp,ATANH:()=>Qp,CEILING:()=>$p,CEILING_MATH:()=>tm,CEILING_PRECISE:()=>nm,COS:()=>rm,COSH:()=>im,COT:()=>am,COTH:()=>om,COUNTBLANK:()=>sm,COUNTIF:()=>cm,COUNTIFS:()=>lm,COUNTUNIQUE:()=>um,COUNTUNIQUEIFS:()=>dm,CSC:()=>fm,CSCH:()=>pm,DECIMAL:()=>mm,DEGREES:()=>hm,EXP:()=>gm,FLOOR:()=>_m,FLOOR_MATH:()=>ym,FLOOR_PRECISE:()=>bm,INT:()=>nh,ISEVEN:()=>xm,ISODD:()=>Cm,ISO_CEILING:()=>Sm,LN:()=>wm,LOG:()=>Tm,MOD:()=>Dm,MUNIT:()=>Om,ODD:()=>km,PI:()=>Am,POWER:()=>jm,PRODUCT:()=>Mm,RAND:()=>Nm,RANDARRAY:()=>Pm,RANDBETWEEN:()=>Fm,ROUND:()=>Im,ROUNDDOWN:()=>Lm,ROUNDUP:()=>Rm,SEC:()=>zm,SECH:()=>Bm,SEQUENCE:()=>Vm,SIN:()=>Hm,SINH:()=>Um,SQRT:()=>Wm,SUBTOTAL:()=>Jm,SUM:()=>Ym,SUMIF:()=>Xm,SUMIFS:()=>Zm,TAN:()=>Qm,TANH:()=>$m,TRUNC:()=>th});let Hp=/^-?[a-z0-9]+$/i,Up={description:E(`Absolute value of a number.`),args:[H(`value (number)`,E(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(M(e,this.locale))},isExported:!0},Wp={description:E(`Inverse cosine of a value, in radians.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)>1?new A(E(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.acos(t)},isExported:!0},Gp={description:E(`Inverse hyperbolic cosine of a number.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.`))],compute:function(e){let t=M(e,this.locale);return t<1?new A(E(`The value (%s) must be greater than or equal to 1.`,t)):Math.acosh(t)},isExported:!0},Kp={description:E(`Inverse cotangent of a value.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=M(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},qp={description:E(`Inverse hyperbolic cotangent of a value.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)<=1?new A(E(`The value (%s) cannot be between -1 and 1 inclusive.`,t)):Math.log((t+1)/(t-1))/2},isExported:!0},Jp={description:E(`Inverse sine of a value, in radians.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)>1?new A(E(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.asin(t)},isExported:!0},Yp={description:E(`Inverse hyperbolic sine of a number.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(M(e,this.locale))},isExported:!0},Xp={description:E(`Inverse tangent of a value, in radians.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(M(e,this.locale))},isExported:!0},Zp={description:E(`Angle from the X axis to a point (x,y), in radians.`),args:[H(`x (number)`,E(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),H(`y (number)`,E(`The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`))],compute:function(e,t){let n=M(e,this.locale),r=M(t,this.locale);return n===0&&r===0?new $i(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},Qp={description:E(`Inverse hyperbolic tangent of a number.`),args:[H(`value (number)`,E(`The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.`))],compute:function(e){let t=M(e,this.locale);return Math.abs(t)>=1?new A(E(`The value (%s) must be between -1 and 1 exclusive.`,t)):Math.atanh(t)},isExported:!0},$p={description:E(`Rounds number up to nearest multiple of factor.`),args:[H(`value (number)`,E(`The value to round up to the nearest integer multiple of factor.`)),H(`factor (number, default=1)`,E(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=M(e,this.locale),r=M(t,this.locale);return r<0&&n>0?new A(E(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.ceil(n/r)*r:0,format:e?.format}},isExported:!0};function em(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.ceil(e/t)*t:n===0?-Math.floor(Math.abs(e)/t)*t:-Math.ceil(Math.abs(e)/t)*t)}let tm={description:E(`Rounds number up to nearest multiple of factor.`),args:[H(`number (number)`,E(`The value to round up to the nearest integer multiple of significance.`)),H(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),H(`mode (number, default=0)`,E(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.`))],compute:function(e,t={value:1},n={value:0}){let r=M(t,this.locale);return{value:em(M(e,this.locale),r,M(n,this.locale)),format:e?.format}},isExported:!0},nm={description:E(`Rounds number up to nearest multiple of factor.`),args:[H(`number (number)`,E(`The value to round up to the nearest integer multiple of significance.`)),H(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=M(t,this.locale);return{value:em(M(e,this.locale),n),format:e?.format}},isExported:!0},rm={description:E(`Cosine of an angle provided in radians.`),args:[H(`angle (number)`,E(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(M(e,this.locale))},isExported:!0},im={description:E(`Hyperbolic cosine of any real number.`),args:[H(`value (number)`,E(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(M(e,this.locale))},isExported:!0},am={description:E(`Cotangent of an angle provided in radians.`),args:[H(`angle (number)`,E(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=M(e,this.locale);return t===0?new $i(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},om={description:E(`Hyperbolic cotangent of any real number.`),args:[H(`value (number)`,E(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=M(e,this.locale);return t===0?new $i(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},sm={description:E(`Number of empty values.`),args:[H(`value1 (any, range)`,E(`The first value or range in which to count the number of blanks.`)),H(`value2 (any, range, repeating)`,E(`Additional values or ranges in which to count the number of blanks.`))],compute:function(...e){return ya(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},cm={description:E(`A conditional count across a range.`),args:[H(`range (range)`,E(`The range that is tested against criterion.`)),H(`criterion (string)`,E(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return Ma(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},lm={description:E(`Count values depending on multiple criteria.`),args:[H(`criteria_range1 (range)`,E(`The range to check against criterion1.`)),H(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1.`)),H(`criteria_range2 (any, range, repeating)`,E(`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.`)),H(`criterion2 (string, repeating)`,E(`Additional criteria to check.`))],compute:function(...e){let t=0;return Ma(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},um={description:E(`Counts number of unique values in a range.`),args:[H(`value1 (any, range)`,E(`The first value or range to consider for uniqueness.`)),H(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider for uniqueness.`))],compute:function(...e){return ju(e)}},dm={description:E(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[H(`range (range)`,E(`The range of cells from which the number of unique values will be counted.`)),H(`criteria_range1 (range)`,E(`The range of cells over which to evaluate criterion1.`)),H(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.`)),H(`criteria_range2 (any, range, repeating)`,E(`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.`)),H(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=new Set;return Ma(t,(t,r)=>{let i=e[t]?.[r];za(i)&&n.add(i.value)},this.locale),n.size}},fm={description:E(`Cosecant of an angle provided in radians.`),args:[H(`angle (number)`,E(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=M(e,this.locale);return t===0?new $i(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},pm={description:E(`Hyperbolic cosecant of any real number.`),args:[H(`value (number)`,E(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=M(e,this.locale);return t===0?new $i(E(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},mm={description:E(`Converts from another base to decimal.`),args:[H(`value (string)`,E(`The number to convert.`)),H(`base (number)`,E(`The base to convert the value from.`))],compute:function(e,t){let n=M(t,this.locale);if(n=Math.floor(n),2>n||n>36)return new A(E(`The base (%s) must be between 2 and 36 inclusive.`,n));let r=N(e);if(r===``)return 0;if(!Hp.test(r))return new A(E(`The value (%s) must be a valid base %s representation.`,r,n));let i=parseInt(r,n);return isNaN(i)?new A(E(`The value (%s) must be a valid base %s representation.`,r,n)):i},isExported:!0},hm={description:E(`Converts an angle value in radians to degrees.`),args:[H(`angle (number)`,E(`The angle to convert from radians to degrees.`))],compute:function(e){return M(e,this.locale)*180/Math.PI},isExported:!0},gm={description:E(`Euler's number, e (~2.718) raised to a power.`),args:[H(`value (number)`,E(`The exponent to raise e.`))],compute:function(e){return Math.exp(M(e,this.locale))},isExported:!0},_m={description:E(`Rounds number down to nearest multiple of factor.`),args:[H(`value (number)`,E(`The value to round down to the nearest integer multiple of factor.`)),H(`factor (number, default=1)`,E(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=M(e,this.locale),r=M(t,this.locale);return r<0&&n>0?new A(E(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.floor(n/r)*r:0,format:e?.format}},isExported:!0};function vm(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.floor(e/t)*t:n===0?-Math.ceil(Math.abs(e)/t)*t:-Math.floor(Math.abs(e)/t)*t)}let ym={description:E(`Rounds number down to nearest multiple of factor.`),args:[H(`number (number)`,E(`The value to round down to the nearest integer multiple of significance.`)),H(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),H(`mode (number, default=0)`,E(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.`))],compute:function(e,t={value:1},n={value:0}){let r=M(t,this.locale);return{value:vm(M(e,this.locale),r,M(n,this.locale)),format:e?.format}},isExported:!0},bm={description:E(`Rounds number down to nearest multiple of factor.`),args:[H(`number (number)`,E(`The value to round down to the nearest integer multiple of significance.`)),H(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=M(t,this.locale);return{value:vm(M(e,this.locale),n),format:e?.format}},isExported:!0},xm={description:E(`Whether the provided value is even.`),args:[H(`value (number)`,E(`The value to be verified as even.`))],compute:function(e){let t=ca(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},Sm={description:E(`Rounds number up to nearest multiple of factor.`),args:[H(`number (number)`,E(`The value to round up to the nearest integer multiple of significance.`)),H(`significance (number, default=1)`,E(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:em(M(e,this.locale),M(t,this.locale)),format:e?.format}},isExported:!0},Cm={description:E(`Whether the provided value is even.`),args:[H(`value (number)`,E(`The value to be verified as even.`))],compute:function(e){let t=ca(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},wm={description:E(`The logarithm of a number, base e (euler's number).`),args:[H(`value (number)`,E(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=M(e,this.locale);return t<=0?new A(E(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},Tm={description:E(`The logarithm of a number, for a given base.`),args:[H(`value (number)`,E(`The value for which to calculate the logarithm.`)),H(`base (number, default=10)`,E(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=M(e,this.locale),r=M(t,this.locale);return n<=0?new A(E(`The value (%s) must be strictly positive.`,n)):r<=0?new A(E(`The base (%s) must be strictly positive.`,r)):r===1?new A(E(`The base must be different from 1.`)):Math.log10(n)/Math.log10(r)},isExported:!0};function Em(e,t){Nu(t,E(`The divisor must be different from 0.`));let n=e%t;return n>0&&t<0||n<0&&t>0?n+t:n}let Dm={description:E(`Modulo (remainder) operator.`),args:[H(`dividend (number)`,E(`The number to be divided to find the remainder.`)),H(`divisor (number)`,E(`The number to divide by.`))],compute:function(e,t){let n=M(t,this.locale);return{value:Em(M(e,this.locale),n),format:e?.format}},isExported:!0},Om={description:E(`Returns a n x n unit matrix, where n is the input dimension.`),args:[H(`dimension (number)`,E(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=la(e,this.locale);return t<1?new A(E(`The argument dimension must be positive`)):Ru(t)},isExported:!0},km={description:E(`Rounds a number up to the nearest odd integer.`),args:[H(`value (number)`,E(`The value to round to the next greatest odd number.`))],compute:function(e){let t=M(e,this.locale),n=Math.ceil(Math.abs(t));return n=n&1?n:n+1,{value:t<0?-n:n,format:e?.format}},isExported:!0},Am={description:E(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},jm={description:E(`A number raised to a power.`),args:[H(`base (number)`,E(`The number to raise to the exponent power.`)),H(`exponent (number)`,E(`The exponent to raise base to.`))],compute:function(e,t){let n=M(e,this.locale),r=M(t,this.locale);return n<0&&!Number.isInteger(r)?new A(E(`The exponent (%s) must be an integer when the base is negative.`,r)):{value:n**+r,format:e?.format}},isExported:!0},Mm={description:E(`Result of multiplying a series of numbers together.`),args:[H(`factor1 (number, range<number>)`,E(`The first number or range to calculate for the product.`)),H(`factor2 (number, range<number>, repeating)`,E(`More numbers or ranges to calculate for the product.`))],compute:function(...e){let t=0,n=1;for(let r of e)if(Ir(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),j(e))return r}else r!==void 0&&r.value!==null&&(n*=ca(r,this.locale),t+=1);return{value:t===0?0:n,format:ta(e[0])}},isExported:!0},Nm={description:E(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},Pm={description:E(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[H(`rows (number, default=1)`,E(`The number of rows to be returned.`)),H(`columns (number, default=1)`,E(`The number of columns to be returned.`)),H(`min (number, default=0)`,E(`The minimum number you would like returned.`)),H(`max (number, default=1)`,E(`The maximum number you would like returned.`)),H(`whole_number (boolean, default=FALSE)`,E(`Return a whole number or a decimal value.`),[{value:!1,label:E(`Decimal (default)`)},{value:!0,label:E(`Integer`)}])],compute:function(e={value:1},t={value:1},n={value:0},r={value:1},i={value:!1}){let a=la(t,this.locale),o=la(e,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=P(i);if(a<1)return new A(E(`The number of columns (%s) must be positive.`,a));if(o<1)return new A(E(`The number of rows (%s) must be positive.`,o));if(s>c)return new A(E(`The maximum (%s) must be greater than or equal to the minimum (%s).`,c,s));if(l&&(!Number.isInteger(s)||!Number.isInteger(c)))return new A(E(`The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.`,c.toString(),s.toString()));let u=Array(a);for(let e=0;e<a;e++){u[e]=Array(o);for(let t=0;t<o;t++)l?u[e][t]=Math.floor(Math.random()*(c-s+1)+s):u[e][t]=s+Math.random()*(c-s)}return u},isExported:!0},Fm={description:E(`Random integer between two values, inclusive.`),args:[H(`low (number)`,E(`The low end of the random range.`)),H(`high (number)`,E(`The high end of the random range.`))],compute:function(e,t){let n=M(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=M(t,this.locale);return Number.isInteger(r)||(r=Math.floor(r)),n>r?new A(E(`The high (%s) must be greater than or equal to the low (%s).`,r,n)):{value:n+Math.ceil((r-n+1)*Math.random())-1,format:e?.format}},isExported:!0},Im={description:E(`Rounds a number according to standard rules.`),args:[H(`value (number)`,E(`The value to round to places number of places.`)),H(`places (number, default=0)`,E(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=M(e,this.locale),r=M(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.round(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.round(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},Lm={description:E(`Rounds down a number.`),args:[H(`value (number)`,E(`The value to round to places number of places, always rounding down.`)),H(`places (number, default=0)`,E(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=M(e,this.locale),r=M(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.floor(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.floor(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},Rm={description:E(`Rounds up a number.`),args:[H(`value (number)`,E(`The value to round to places number of places, always rounding up.`)),H(`places (number, default=0)`,E(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=M(e,this.locale),r=M(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.ceil(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.ceil(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},zm={description:E(`Secant of an angle provided in radians.`),args:[H(`angle (number)`,E(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(M(e,this.locale))},isExported:!0},Bm={description:E(`Hyperbolic secant of any real number.`),args:[H(`value (number)`,E(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(M(e,this.locale))},isExported:!0},Vm={description:E(`Returns a sequence of numbers.`),args:[H(`rows (number)`,E(`The number of rows to return`)),H(`columns (number, optional, default=1)`,E(`The number of columns to return`)),H(`start (number, optional, default=1)`,E(`The first number in the sequence`)),H(`step (number, optional, default=1)`,E(`The amount to increment each value in the sequence`))],compute:function(e,t={value:1},n={value:1},r={value:1}){let i=M(n,this.locale),a=M(r,this.locale),o=la(e,this.locale),s=la(t,this.locale);return s<1?new A(E(`The number of columns (%s) must be positive.`,s)):o<1?new A(E(`The number of rows (%s) must be positive.`,o)):Sa(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},Hm={description:E(`Sine of an angle provided in radians.`),args:[H(`angle (number)`,E(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(M(e,this.locale))},isExported:!0},Um={description:E(`Hyperbolic sine of any real number.`),args:[H(`value (number)`,E(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(M(e,this.locale))},isExported:!0},Wm={description:E(`Positive square root of a positive number.`),args:[H(`value (number)`,E(`The number for which to calculate the positive square root.`))],compute:function(e){let t=M(e,this.locale);return t<0?new A(E(`The value (%s) must be positive or null.`,t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},Gm={1:`AVERAGE`,2:`COUNT`,3:`COUNTA`,4:`MAX`,5:`MIN`,6:`PRODUCT`,7:`STDEV`,8:`STDEVP`,9:`SUM`,10:`VAR`,11:`VARP`},Km=Object.entries(Gm).map(([e,t])=>({value:parseInt(e),label:E(`%s (include manually-hidden rows)`,t)})),qm=Object.entries(Gm).map(([e,t])=>({value:parseInt(e)+100,label:E(`%s (exclude manually-hidden rows)`,t)})),Jm={description:E(`Returns a subtotal for a vertical range of cells using a specified aggregation function.`),args:[H(`function_code (number)`,E(`The function to use in subtotal aggregation.`),[...Km,...qm]),H(`ref1 (meta, range<meta>)`,E(`The range or reference for which you want the subtotal.`)),H(`ref2 (meta, range<meta>, repeating)`,E(`Additional ranges or references for which you want the subtotal.`))],compute:function(e,...t){let n=la(e,this.locale),r=!0;if(n>100&&(n-=100,r=!1),n<1||n>11)return new A(E(`The function code (%s) must be between 1 to 11 or 101 to 111.`,n));let i=[];for(let e of t){let t=e[0][0],n=jc(t.value).sheetName,a=n?this.getters.getSheetIdByName(n):this.__originSheetId;if(!a)continue;let{top:o,left:s}=Ts(t.value),c=s+e.length-1,l=o+e[0].length-1;for(let e=o;e<=l;e++)if(!this.getters.isRowFiltered(a,e)&&!(!r&&this.getters.isRowHiddenByUser(a,e)))for(let t=s;t<=c;t++){let n=this.getters.getCorrespondingFormulaCell({sheetId:a,col:t,row:e});(!n||!Bp(n))&&i.push(this.getters.getEvaluatedCell({sheetId:a,col:t,row:e}))}}return this[Gm[n]].apply(this,[[i]])},isExported:!0},Ym={description:E(`Sum of a series of numbers and/or cells.`),args:[H(`value1 (number, range<number>)`,E(`The first number or range to add together.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional numbers or ranges to add to value1.`))],compute:function(...e){let t=e[0];return{value:Au(e,this.locale),format:ta(t)}},isExported:!0},Xm={description:E(`A conditional sum across a range.`),args:[H(`criteria_range (range)`,E(`The range which is tested against criterion.`)),H(`criterion (string)`,E(`The pattern or test to apply to range.`)),H(`sum_range (range, default=criteria_range)`,E(`The range to be summed, if different from range.`))],compute:function(e,t,n){n===void 0&&(n=e);let r=0;return Ma([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},Zm={description:E(`Sums a range depending on multiple criteria.`),args:[H(`sum_range (range)`,E(`The range to sum.`)),H(`criteria_range1 (range)`,E(`The range to check against criterion1.`)),H(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1.`)),H(`criteria_range2 (any, range, repeating)`,E(`Additional ranges to check.`)),H(`criterion2 (string, repeating)`,E(`Additional criteria to check.`))],compute:function(e,...t){let n=0;return Ma(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},Qm={description:E(`Tangent of an angle provided in radians.`),args:[H(`angle (number)`,E(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(M(e,this.locale))},isExported:!0},$m={description:E(`Hyperbolic tangent of any real number.`),args:[H(`value (number)`,E(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(M(e,this.locale))},isExported:!0};function eh(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let th={description:E(`Truncates a number.`),args:[H(`value (number)`,E(`The value to be truncated.`)),H(`places (number, default=0)`,E(`The number of significant digits to the right of the decimal point to retain.`))],compute:function(e,t={value:0}){return{value:eh(M(e,this.locale),M(t,this.locale)),format:e?.format}},isExported:!0},nh={description:E(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[H(`value (number)`,E(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(M(e,this.locale))},isExported:!0};var rh=l({AVEDEV:()=>ph,AVERAGE:()=>mh,AVERAGEA:()=>vh,AVERAGEIF:()=>yh,AVERAGEIFS:()=>bh,AVERAGE_WEIGHTED:()=>_h,CORREL:()=>Hh,COUNT:()=>xh,COUNTA:()=>Sh,COVAR:()=>Ch,COVARIANCE_P:()=>wh,COVARIANCE_S:()=>Th,FORECAST:()=>Eh,GROWTH:()=>Dh,INTERCEPT:()=>Oh,LARGE:()=>kh,LINEST:()=>Ah,LOGEST:()=>jh,MATTHEWS:()=>Mh,MAX:()=>Nh,MAXA:()=>Ph,MAXIFS:()=>Fh,MEDIAN:()=>Ih,MIN:()=>Lh,MINA:()=>Rh,MINIFS:()=>zh,PEARSON:()=>Vh,PERCENTILE:()=>Uh,PERCENTILE_EXC:()=>Wh,PERCENTILE_INC:()=>Gh,POLYFIT_COEFFS:()=>Kh,POLYFIT_FORECAST:()=>qh,QUARTILE:()=>Jh,QUARTILE_EXC:()=>Yh,QUARTILE_INC:()=>Xh,RANK:()=>Zh,RSQ:()=>Qh,SLOPE:()=>$h,SMALL:()=>eg,SPEARMAN:()=>tg,STDEV:()=>ng,STDEVA:()=>ag,STDEVP:()=>og,STDEVPA:()=>sg,STDEV_P:()=>rg,STDEV_S:()=>ig,STEYX:()=>cg,TREND:()=>lg,VAR:()=>ug,VARA:()=>pg,VARP:()=>mg,VARPA:()=>hg,VAR_P:()=>dg,VAR_S:()=>fg});let ih=[{value:!0,label:E(`b is calculated normally`)},{value:!1,label:E(`b is forced to 1`)}],ah=[{value:!1,label:E(`do not return additional regression statistics`)},{value:!0,label:E(`return additional regression statistics`)}],oh=[{value:1,label:E(`order 1 (Linear)`)},{value:2,label:E(`order 2 (Quadratic)`)},{value:3,label:E(`order 3 (Cubic)`)},{value:4,label:E(`order 4 (Quartic)`)},{value:5,label:E(`order 5 (Quintic)`)},{value:6,label:E(`order 6 (Sextic)`)}],sh=[{value:!0,label:E(`Compute intercept`)},{value:!1,label:E(`Force intercept to 0`)}],ch=[{value:0,label:E(`Minimum value`)},{value:1,label:E(`First quartile (25th percentile)`)},{value:2,label:E(`Median value (50th percentile)`)},{value:3,label:E(`Third quartile (75th percentile)`)},{value:4,label:E(`Maximum value`)}];function lh(e,t){let n=[],r=[],i=0,a=0;ga([e],e=>{n.push(e),i+=1}),ga([t],e=>{r.push(e),a+=1}),Mu(i===a,E(`[[FUNCTION_NAME]] has mismatched argument count %s vs %s.`,i,a));let o=[],s=[];for(let e=0;e<i;e++){let t=n[e]?.value,i=r[e]?.value;typeof t==`number`&&typeof i==`number`&&(s.push(t),o.push(i))}return{flatDataX:o,flatDataY:s}}function uh(e,t,n){let{flatDataX:r,flatDataY:i}=lh(e,t),a=i.length;Nu(a),n&&Nu(a-1);let o=0,s=0;for(let e=0;e<a;e++)o+=i[e],s+=r[e];let c=o/a,l=s/a,u=0;for(let e=0;e<a;e++)u+=(i[e]-c)*(r[e]-l);return u/(a-+!!n)}function dh(e,t,n,r){let i=0,a=n?xa:ba,o=a(e,(e,t)=>(i+=1,e+t),0,r);Nu(i),t&&Nu(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function fh(e,t,n,r){let i=M(t,r);Mu(n?0<=i&&i<=1:0<i&&i<1,E(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`));let a=[],o,s=0;return ga(e,e=>{let t=e?.value;typeof t==`number`&&(o=Na(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),Mu(s!==0,Ba),n||Mu(1/(s+1)<=i&&i<=s/(s+1),E(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),Gi(a,i,n)}let ph={description:E(`Average magnitude of deviations from mean.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){let t=0,n=ba(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new $i(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return ba(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},mh={description:E(`Numerical average value in a dataset, ignoring text.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the average value.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the average value.`))],compute:function(...e){return{value:Ku(e,this.locale),format:ta(e[0])}},isExported:!0},hh=E(`[[FUNCTION_NAME]] has mismatched range sizes.`),gh=E(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),_h={description:E(`Weighted average.`),args:[H(`values (number, range<number>)`,E(`Values to average.`)),H(`weights (number, range<number>)`,E(`Weights for each corresponding value.`)),H(`additional_values (number, range<number>, repeating)`,E(`Additional values to average.`)),H(`additional_weights (number, range<number>, repeating)`,E(`Additional weights.`))],compute:function(...e){let t=0,n=0;for(let r=0;r<e.length-1;r+=2){let i=e[r],a=e[r+1];if(!Fu(i,a))return new A(hh);if(Ir(i))for(let e=0;e<i.length;e++)for(let r=0;r<i[0].length;r++){let o=i[e][r].value,s=Ir(a)?a?.[e][r].value:M(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new A(gh);t+=o*s,n+=s;continue}if(c!==l)return new A(E(`[[FUNCTION_NAME]] expects number values.`))}else{let e=M(i,this.locale),r=Ir(a)?a?.[0][0].value:M(a,this.locale);if(typeof r==`number`){if(r<0)return new A(gh);t+=e*r,n+=r}}}return n===0?new $i(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:ta(e[0])}}},vh={description:E(`Numerical average value in a dataset.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the average value.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the average value.`))],compute:function(...e){let t=0,n=xa(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new $i(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:ta(e[0])}},isExported:!0},yh={description:E(`Average of values depending on criteria.`),args:[H(`criteria_range (number, range<number>)`,E(`The range to check against criterion.`)),H(`criterion (string)`,E(`The pattern or test to apply to criteria_range.`)),H(`average_range (number, range<number>, default=criteria_range)`,E(`The range to average. If not included, criteria_range is used for the average instead.`))],compute:function(e,t,n){let r=I(n===void 0?e:n),i=0,a=0;return Ma([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new $i(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},bh={description:E(`Average of values depending on multiple criteria.`),args:[H(`average_range (range)`,E(`The range to average.`)),H(`criteria_range1 (range)`,E(`The range to check against criterion1.`)),H(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1.`)),H(`criteria_range2 (any, range, repeating)`,E(`Additional criteria_range and criterion to check.`)),H(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=I(e),r=0,i=0;return Ma(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new $i(E(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},xh={description:E(`The number of numeric values in dataset.`),args:[H(`value1 (number, any, range<number>)`,E(`The first value or range to consider when counting.`)),H(`value2 (number, any, range<number>, repeating)`,E(`Additional values or ranges to consider when counting.`))],compute:function(...e){return qu(e,this.locale)},isExported:!0},Sh={description:E(`The number of values in a dataset.`),args:[H(`value1 (any, range)`,E(`The first value or range to consider when counting.`)),H(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider when counting.`))],compute:function(...e){return Ju(e)},isExported:!0},Ch={description:E(`The covariance of a dataset.`),args:[H(`data_y (any, range)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (any, range)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return uh(e,t,!1)},isExported:!0},wh={description:E(`The covariance of a dataset.`),args:[H(`data_y (any, range)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (any, range)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return uh(e,t,!1)},isExported:!0},Th={description:E(`The sample covariance of a dataset.`),args:[H(`data_y (any, range)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (any, range)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return uh(e,t,!0)},isExported:!0},Eh={description:E(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[H(`x (number, range<number>)`,E(`The value(s) on the x-axis to forecast.`)),H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t,n){let{flatDataX:r,flatDataY:i}=lh(t,n);return r.length===0||i.length===0?new Xi(Ba):id([i],[r],Ca(I(e),e=>M(e,this.locale)),!0)},isExported:!0},Dh={description:E(`Fits points to exponential growth trend.`),args:[H(`known_data_y (range<number>)`,E(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.`)),H(`known_data_x (range<number>, default={1;2;3;...})`,E(`The values of the independent variable(s) corresponding with known_data_y.`)),H(`new_data_x (any, range, default=known_data_x)`,E(`The data points to return the y values for on the ideal curve fit.`)),H(`b (boolean, default=TRUE)`,E(`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.`),ih)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new A(Va(`known_data_y`)):nd(id(rd(sa(e,`known_data_y`)),sa(t,`known_data_x`),sa(n,`new_data_y`),P(r)))}},Oh={description:E(`Compute the intercept of the linear regression.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lh(e,t);if(n.length===0||r.length===0)return new Xi(Ba);let[[],[i]]=Qu([n],[r]);return i},isExported:!0},kh={description:E(`Nth largest element from a data set.`),args:[H(`data (any, range)`,E(`Array or range containing the dataset to consider.`)),H(`n (number)`,E(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(M(t?.value,this.locale)),r=[],i,a=0;ga([e],e=>{typeof e?.value==`number`&&(i=Na(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.shift(),a--))});let o=r.shift();return o===void 0?new A(Ba):a<n?new A(E(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},Ah={description:E(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>, default={1;2;3;...})`,E(`The range representing the array or matrix of independent data.`)),H(`calculate_b (boolean, default=TRUE)`,E(`A flag specifying whether to compute the slope or not`),ih),H(`verbose (boolean, default=FALSE)`,E(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),ah)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new A(Va(`data_y`)):Qu(sa(t,`data_x`),sa(e,`data_y`),P(n),P(r))},isExported:!0},jh={description:E(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>, optional, default={1;2;3;...})`,E(`The range representing the array or matrix of independent data.`)),H(`calculate_b (boolean, default=TRUE)`,E(`A flag specifying whether to compute the slope or not`),ih),H(`verbose (boolean, default=FALSE)`,E(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),ah)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new A(Va(`data_y`));let i=Qu(sa(t,`data_x`),rd(sa(e,`data_y`)),P(n),P(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},Mh={description:E(`Compute the Matthews correlation coefficient of a dataset.`),args:[H(`data_x (range)`,E(`The range representing the array or matrix of observed data.`)),H(`data_y (range)`,E(`The range representing the array or matrix of predicted data.`))],compute:function(e,t){let n=e.flat(),r=t.flat();if(Gu(n,r),n.length===0||r.length===0)return new Xi(Ba);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=P(n[e]);t===P(r[e])?t?o++:a++:t?c++:s++}return(o*a-s*c)/Math.sqrt((o+s)*(o+c)*(a+s)*(a+c))},isExported:!1},Nh={description:E(`Maximum value in a numeric dataset.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the maximum value.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the maximum value.`))],compute:function(...e){return Yu(e,this.locale)},isExported:!0},Ph={description:E(`Maximum numeric value in a dataset.`),args:[H(`value1 (any, range)`,E(`The first value or range to consider when calculating the maximum value.`)),H(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider when calculating the maximum value.`))],compute:function(...e){let t=xa(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:ta(e[0])}},isExported:!0},Fh={description:E(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[H(`range (range)`,E(`The range of cells from which the maximum will be determined.`)),H(`criteria_range1 (range)`,E(`The range of cells over which to evaluate criterion1.`)),H(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.`)),H(`criteria_range2 (any, range, repeating)`,E(`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.`)),H(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=-1/0;return Ma(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n<i?i:n)},this.locale),n===-1/0?0:n},isExported:!0},Ih={description:E(`Median value in a numeric dataset.`),args:[H(`value1 (any, range)`,E(`The first value or range to consider when calculating the median value.`)),H(`value2 (any, range, repeating)`,E(`Additional values or ranges to consider when calculating the median value.`))],compute:function(...e){let t=[];return _a(e,e=>{t.push(e)},this.locale),{value:fh(t,{value:.5},!0,this.locale),format:ta(t[0])}},isExported:!0},Lh={description:E(`Minimum value in a numeric dataset.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the minimum value.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the minimum value.`))],compute:function(...e){return Xu(e,this.locale)},isExported:!0},Rh={description:E(`Minimum numeric value in a dataset.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range to consider when calculating the minimum value.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to consider when calculating the minimum value.`))],compute:function(...e){let t=xa(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:ta(e[0])}},isExported:!0},zh={description:E(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[H(`range (range)`,E(`The range of cells from which the minimum will be determined.`)),H(`criteria_range1 (range)`,E(`The range of cells over which to evaluate criterion1.`)),H(`criterion1 (string)`,E(`The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.`)),H(`criteria_range2 (any, range, repeating)`,E(`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.`)),H(`criterion2 (string, repeating)`,E(`The pattern or test to apply to criteria_range2.`))],compute:function(e,...t){let n=1/0;return Ma(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n>i?i:n)},this.locale),n===1/0?0:n},isExported:!0};function Bh(e,t){let{flatDataX:n,flatDataY:r}=lh(e,t);if(n.length===0||r.length===0)return new Xi(Ba);let i=n.length,a=0,o=0,s=0,c=0,l=0;for(let e=0;e<i;e++){let t=n[e],i=r[e];a+=t,o+=i,s+=t*i,c+=t*t,l+=i*i}return(i*s-a*o)/Math.sqrt((i*c-a*a)*(i*l-o*o))}let Vh={description:E(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return Bh(e,t)},isExported:!0},Hh=Vh,Uh={description:E(`Value at a given percentile of a dataset.`),args:[H(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),H(`percentile (number)`,E(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return Gh.compute.bind(this)(e,t)},isExported:!0},Wh={description:E(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[H(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),H(`percentile (number)`,E(`The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.`))],compute:function(e,t){return{value:fh([e],t,!1,this.locale),format:ta(e)}},isExported:!0},Gh={description:E(`Value at a given percentile of a dataset.`),args:[H(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),H(`percentile (number)`,E(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:fh([e],t,!0,this.locale),format:ta(e)}},isExported:!0},Kh={description:E(`Compute the coefficients of polynomial regression of the dataset.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`)),H(`order (number)`,E(`The order of the polynomial to fit the data, between 1 and 6.`),oh),H(`intercept (boolean, default=TRUE)`,E(`A flag specifying whether to compute the intercept or not.`),sh)],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=lh(e,t);return i.length===0||a.length===0?new Xi(Ba):$u(a,i,M(n,this.locale),P(r))},isExported:!1},qh={description:E(`Predict value by computing a polynomial regression of the dataset.`),args:[H(`x (number, range<number>)`,E(`The value(s) on the x-axis to forecast.`)),H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`)),H(`order (number)`,E(`The order of the polynomial to fit the data, between 1 and 6.`),oh),H(`intercept (boolean, default=TRUE)`,E(`A flag specifying whether to compute the intercept or not.`),sh)],compute:function(e,t,n,r,i={value:!0}){let a=M(r,this.locale),{flatDataX:o,flatDataY:s}=lh(t,n);if(o.length===0||s.length===0)return new Xi(Ba);let c=$u(s,o,a,P(i)).flat();return Ca(I(e),e=>td(c,M(e,this.locale),a))},isExported:!1},Jh={description:E(`Value nearest to a specific quartile of a dataset.`),args:[H(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),H(`quartile_number (number)`,E(`Which quartile value to return.`),ch)],compute:function(e,t){return Xh.compute.bind(this)(e,t)},isExported:!0},Yh={description:E(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[H(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),H(`quartile_number (number)`,E(`Which quartile value, exclusive of 0 and 4, to return.`),[{value:1,label:E(`First quartile (25th percentile)`)},{value:2,label:E(`Median value (50th percentile)`)},{value:3,label:E(`Third quartile (75th percentile)`)}])],compute:function(e,t){let n={value:.25*Math.trunc(M(t,this.locale))};return{value:fh([e],n,!1,this.locale),format:ta(e)}},isExported:!0},Xh={description:E(`Value nearest to a specific quartile of a dataset.`),args:[H(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),H(`quartile_number (number)`,E(`Which quartile value to return.`),ch)],compute:function(e,t){let n={value:.25*Math.trunc(M(t,this.locale))};return{value:fh([e],n,!0,this.locale),format:ta(e)}},isExported:!0},Zh={description:E(`Returns the rank of a specified value in a dataset.`),args:[H(`value (number)`,E(`The value whose rank will be determined.`)),H(`data (range)`,E(`The range containing the dataset to consider.`)),H(`is_ascending (boolean, default=FALSE)`,E(`Whether to consider the values in data in descending or ascending order.`),[{value:!1,label:E(`Descending`)},{value:!0,label:E(`Ascending`)}])],compute:function(e,t,n={value:!1}){let r=P(n),i=M(e,this.locale),a=1,o=!1;for(let e of t)for(let t of e){if(typeof t.value!=`number`)continue;let e=M(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Xi(E(`Value not found in the given data.`))},isExported:!0},Qh={description:E(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=Bh(e,t);if(n instanceof Error)throw n;return n**2},isExported:!0},$h={description:E(`Compute the slope of the linear regression.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lh(e,t);if(n.length===0||r.length===0)return new Xi(Ba);let[[i]]=Qu([n],[r]);return i},isExported:!0},eg={description:E(`Nth smallest element in a data set.`),args:[H(`data (any, range)`,E(`The array or range containing the dataset to consider.`)),H(`n (number)`,E(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(M(t?.value,this.locale)),r=[],i,a=0;ga([e],e=>{typeof e?.value==`number`&&(i=Na(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.pop(),a--))});let o=r.pop();return o===void 0?new A(Ba):a<n?new A(E(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},tg={description:E(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lh(t,e);if(n.length===0||r.length===0)return new Xi(Ba);let i=n.length,a=n.map((e,t)=>[e,r[t]]);a.sort((e,t)=>e[0]-t[0]);for(let e=0;e<i;++e)a[e][0]=e;a.sort((e,t)=>e[1]-t[1]);let o=0;for(let e=0;e<i;++e)o+=(a[e][0]-e)**2;return 1-6*o/(i**3-i)},isExported:!1},ng={description:E(`Standard deviation.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Math.sqrt(ug.compute.bind(this)(...e))},isExported:!0},rg={description:E(`Standard deviation of entire population.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Math.sqrt(dg.compute.bind(this)(...e))},isExported:!0},ig={description:E(`Standard deviation.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Math.sqrt(fg.compute.bind(this)(...e))},isExported:!0},ag={description:E(`Standard deviation of sample (text as 0).`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return Math.sqrt(pg.compute.bind(this)(...e))},isExported:!0},og={description:E(`Standard deviation of entire population.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Math.sqrt(mg.compute.bind(this)(...e))},isExported:!0},sg={description:E(`Standard deviation of entire population (text as 0).`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return Math.sqrt(hg.compute.bind(this)(...e))},isExported:!0},cg={description:E(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[H(`data_y (range<number>)`,E(`The range representing the array or matrix of dependent data.`)),H(`data_x (range<number>)`,E(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=lh(e,t);return n.length===0||r.length===0?new Xi(Ba):Qu([n],[r],!0,!0)[1][2]},isExported:!0},lg={description:E(`Fits points to linear trend derived via least-squares.`),args:[H(`known_data_y (number, range<number>)`,E(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.`)),H(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,E(`The values of the independent variable(s) corresponding with known_data_y.`)),H(`new_data_x (number, range<number>, optional, default=known_data_x)`,E(`The data points to return the y values for on the ideal curve fit.`)),H(`b (boolean, optional, default=TRUE)`,E(`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.`),ih)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new A(Va(`known_data_y`)):id(sa(e,`known_data_y`),sa(t,`known_data_x`),sa(n,`new_data_y`),P(r))}},ug={description:E(`Variance.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return dh(e,!0,!1,this.locale)},isExported:!0},dg={description:E(`Variance of entire population.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return dh(e,!1,!1,this.locale)},isExported:!0},fg={description:E(`Variance.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return dh(e,!0,!1,this.locale)},isExported:!0},pg={description:E(`Variance of sample (text as 0).`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the sample.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the sample.`))],compute:function(...e){return dh(e,!0,!0,this.locale)},isExported:!0},mg={description:E(`Variance of entire population.`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return dh(e,!1,!1,this.locale)},isExported:!0},hg={description:E(`Variance of entire population (text as 0).`),args:[H(`value1 (number, range<number>)`,E(`The first value or range of the population.`)),H(`value2 (number, range<number>, repeating)`,E(`Additional values or ranges to include in the population.`))],compute:function(...e){return dh(e,!1,!0,this.locale)},isExported:!0};var gg=l({DAVERAGE:()=>yg,DCOUNT:()=>bg,DCOUNTA:()=>xg,DGET:()=>Sg,DMAX:()=>Cg,DMIN:()=>wg,DPRODUCT:()=>Tg,DSTDEV:()=>Eg,DSTDEVP:()=>Dg,DSUM:()=>Og,DVAR:()=>kg,DVARP:()=>Ag});function _g(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(N(e[t][0]).toUpperCase(),t);let o=t?.value;if(typeof o!=`number`&&typeof o!=`string`)throw new A(E(`The field must be a number or a string`));let s;if(typeof o==`number`){if(s=Math.trunc(o)-1,s<0||a-1<s)throw new A(E(`The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.`,{fieldValue:o.toString(),dimRowDB:a.toString()}))}else{let e=N(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new A(E(`The field (%s) must be one of %s.`,N(t),[...i.keys()].toString()))}let c=n[0].length;if(c<2)throw new A(E(`The criteria range contains %s row, it must be at least 2 rows.`,c.toString()));let l=new Set,u=e[0].length;for(let t=1;t<c;t++){let a=[],o=!0;for(let r=0;r<n.length;r++){let s=N(n[r][0]).toUpperCase(),c=i.get(s),l=n[r][t];if(l.value!==null)if(c!==void 0)a.push([e[c].slice(1,u)]),a.push(l);else{o=!1;break}}if(o)if(a.length>0)Ma(a,(e,t)=>{l.add(t)},r,!0);else{l=new Set(Array(u-1).keys());break}}let d=e[s];return[...l].map(e=>d[e+1])}let vg=[H(`database (range)`,E(`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.`)),H(`field (number, string)`,E(`Indicates which column in database contains the values to be extracted and operated on.`)),H(`criteria (range)`,E(`An array or range containing zero or more criteria to filter the database values by before operating.`))],yg={description:E(`Average of a set of values from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return mh.compute.bind(this)([r])},isExported:!0},bg={description:E(`Counts values from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return xh.compute.bind(this)([r])},isExported:!0},xg={description:E(`Counts values and text from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return Sh.compute.bind(this)([r])},isExported:!0},Sg={description:E(`Single value from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return r.length===1?r[0]:new A(E(`More than one match found in DGET evaluation.`))},isExported:!0},Cg={description:E(`Maximum of values from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return Nh.compute.bind(this)([r])},isExported:!0},wg={description:E(`Minimum of values from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return Lh.compute.bind(this)([r])},isExported:!0},Tg={description:E(`Product of values from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return Mm.compute.bind(this)([r])},isExported:!0},Eg={description:E(`Standard deviation of population sample from table.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return ng.compute.bind(this)([r])},isExported:!0},Dg={description:E(`Standard deviation of entire population from table.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return og.compute.bind(this)([r])},isExported:!0},Og={description:E(`Sum of values from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return Ym.compute.bind(this)([r])},isExported:!0},kg={description:E(`Variance of population sample from table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return ug.compute.bind(this)([r])},isExported:!0},Ag={description:E(`Variance of a population from a table-like range.`),args:vg,compute:function(e,t,n){let r=_g(e,t,n,this.locale);return mg.compute.bind(this)([r])},isExported:!0},jg=E(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),Mg=E(`There must be both positive and negative values in cashflow_amounts.`),Ng=e=>E(`The cost (%s) must be positive or null.`,e),Pg=e=>E(`The cost (%s) must be strictly positive.`,e),Fg=e=>E(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),Ig=e=>E(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),Lg=e=>E(`The depreciation factor (%s) must be strictly positive.`,e),Rg=e=>E(`The discount (%s) must be different from -1.`,e),zg=e=>E(`The discount (%s) must be strictly positive.`,e),Bg=e=>E(`The discount (%s) must be smaller than 1.`,e),Vg=e=>E(`The effective_rate (%s) must be strictly positive.`,e),Hg=e=>E(`The end_period (%s) must be positive or null.`,e),Ug=(e,t)=>E(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),Wg=e=>E(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),Gg=(e,t)=>E(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),Kg=e=>E(`The first_period (%s) must be strictly positive.`,e),qg=e=>E(`The future_value (%s) must be strictly positive.`,e),Jg=e=>E(`The investment (%s) must be strictly positive.`,e),Yg=e=>E(`The issue (%s) must be positive or null.`,e),Xg=(e,t)=>E(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),Zg=e=>E(`The last_period (%s) must be strictly positive.`,e),Qg=e=>E(`The life (%s) must be strictly positive.`,e),$g=(e,t)=>E(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),e_=e=>E(`The month (%s) must be between 1 and 12 inclusive.`,e),t_=e=>E(`The nominal_rate (%s) must be strictly positive.`,e),n_=e=>E(`The number_of_periods (%s) must be different from zero.`,e),r_=e=>E(`The number_of_periods (%s) must be strictly positive.`,e),i_=e=>E(`The period must be between 1 and number_of_periods (%s)`,e),a_=(e,t)=>E(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),o_=e=>E(`The period (%s) must be positive or null.`,e),s_=e=>E(`The periods_by_year (%s) must be strictly positive.`,e),c_=(e,t)=>E(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),l_=e=>E(`The period (%s) must be strictly positive.`,e),u_=e=>E(`The present_value (%s) must be strictly positive.`,e),d_=e=>E(`The price (%s) must be strictly positive.`,e),f_=(e,t)=>E(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),p_=e=>E(`The purchase_date (%s) must be positive or null.`,e),m_=e=>E(`The rate_guess (%s) must be strictly greater than -1.`,e),h_=e=>E(`The rate (%s) must be positive or null.`,e),g_=e=>E(`The rate (%s) must be strictly positive.`,e),__=e=>E(`The redemption (%s) must be strictly positive.`,e),v_=e=>E(`The salvage (%s) must be positive or null.`,e),y_=(e,t)=>E(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),b_=(e,t)=>E(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),x_=(e,t)=>E(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),S_=(e,t)=>E(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),C_=e=>E(`The start_period (%s) must be positive or null.`,e),w_=(e,t)=>E(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),T_=e=>E(`The unit (%s) must be strictly positive.`,e),E_=e=>E(`The yield (%s) must be positive or null.`,e);function D_(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function O_(e){return![0,1,2,3,4].includes(e)}function k_(e){return![1,2,4].includes(e)}function A_(e,t,n){let r=F(e,n),i=F(t,n),a=F(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}let j_=[{value:0,label:E(`US (NASD) 30/360`)},{value:1,label:E(`Actual/Actual`)},{value:2,label:E(`Actual/360`)},{value:3,label:E(`Actual/365`)},{value:4,label:E(`European 30/360`)}];var M_=l({DATE:()=>P_,DATEDIF:()=>F_,DATEVALUE:()=>I_,DAY:()=>L_,DAYS:()=>R_,DAYS360:()=>z_,EDATE:()=>B_,EOMONTH:()=>V_,HOUR:()=>H_,ISOWEEKNUM:()=>U_,MINUTE:()=>W_,MONTH:()=>G_,MONTH_END:()=>cv,MONTH_START:()=>sv,NETWORKDAYS:()=>K_,NETWORKDAYS_INTL:()=>Y_,NOW:()=>X_,QUARTER:()=>lv,QUARTER_END:()=>dv,QUARTER_START:()=>uv,SECOND:()=>Z_,TIME:()=>Q_,TIMEVALUE:()=>$_,TODAY:()=>ev,WEEKDAY:()=>tv,WEEKNUM:()=>nv,WORKDAY:()=>rv,WORKDAY_INTL:()=>iv,YEAR:()=>av,YEARFRAC:()=>ov,YEAR_END:()=>pv,YEAR_START:()=>fv}),N_=function(e){return e.WHOLE_YEARS=`Y`,e.WHOLE_MONTHS=`M`,e.WHOLE_DAYS=`D`,e.DAYS_WITHOUT_WHOLE_MONTHS=`MD`,e.MONTH_WITHOUT_WHOLE_YEARS=`YM`,e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR=`YD`,e}(N_||{});let P_={description:E(`Converts year/month/day into a date.`),args:[H(`year (number)`,E(`The year component of the date.`)),H(`month (number)`,E(`The month component of the date.`)),H(`day (number)`,E(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=Math.trunc(M(n,this.locale));if(r<0||r>9999)return new A(E(`The year (%s) must be between 0 and 9999 inclusive.`,r.toString()));r<1900&&(r+=1900);let o=Ci(new O(r,i-1,a));return o<0?new A(E(`The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.`)):{value:o,format:this.locale.dateFormat}},isExported:!0},F_={description:E(`Calculates the number of days, months, or years between two dates.`),args:[H(`start_date (date)`,E(`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.`)),H(`end_date (date)`,E(`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.`)),H(`unit (string)`,E(`A text abbreviation for unit of time.`),[{value:`Y`,label:E(`The number of whole years between start_date and end_date`)},{value:`M`,label:E(`The number of whole months between start_date and end_date`)},{value:`D`,label:E(`The number of days between start_date and end_date`)},{value:`MD`,label:E(`The number of days between start_date and end_date after subtracting whole months`)},{value:`YM`,label:E(`The number of whole months between start_date and end_date after subtracting whole years`)},{value:`YD`,label:E(`The number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart`)}])],compute:function(e,t,n){let r=N(n).toUpperCase();if(!Object.values(N_).includes(r))return new A(aa(Object.values(N_),N(n)));let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Si(i),s=Si(a);if(a<i)return new A(E(`start_date (%s) should be on or before end_date (%s).`,o.toLocaleDateString(),s.toLocaleDateString()));switch(r){case`Y`:return Mi(o,s);case`M`:return Ai(o,s);case`D`:return ji(o,s);case`YM`:return Ai(o,s)-Mi(o,s)*12;case`MD`:let e=s.getDate()-o.getDate();return e<0&&(e=Ti(new O(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case`YD`:{if(Ni(i,a))return ji(o,s);let e=new O(o.getFullYear(),s.getMonth(),s.getDate()),t=ji(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=ji(o,e)),t}}},isExported:!0},I_={description:E(`Converts a date string to a date value.`),args:[H(`date_string (string)`,E(`The string representing the date.`))],compute:function(e){let t=N(e),n=fi(t,this.locale);return n===null?new A(E(`The date_string (%s) cannot be parsed to date/time.`,t.toString())):Math.trunc(n.value)},isExported:!0},L_={description:E(`Day of the month that a specific date falls on.`),args:[H(`date (string)`,E(`The date from which to extract the day.`))],compute:function(e){return F(e,this.locale).getDate()},isExported:!0},R_={description:E(`Number of days between two dates.`),args:[H(`end_date (date)`,E(`The end of the date range.`)),H(`start_date (date)`,E(`The start of the date range.`))],compute:function(e,t){let n=F(e,this.locale),r=F(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/Qr)},isExported:!0},z_={description:E(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[H(`start_date (date)`,E(`The start date to consider in the calculation.`)),H(`end_date (date)`,E(`The end date to consider in the calculation.`)),H(`method (boolean, default=false)`,E(`An indicator of what day count method to use.`),[{value:!1,label:E(`U.S. NASD method (default)`)},{value:!0,label:E(`European method`)}])],compute:function(e,t,n={value:!1}){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=ki(r,i,P(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},B_={description:E(`Date a number of months before/after another date.`),args:[H(`start_date (date)`,E(`The date from which to calculate the result.`)),H(`months (number)`,E(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:Ci(Di(F(e,this.locale),Math.trunc(M(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},V_={description:E(`Last day of a month before or after a date.`),args:[H(`start_date (date)`,E(`The date from which to calculate the result.`)),H(`months (number)`,E(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=F(e,this.locale),r=Math.trunc(M(t,this.locale));return{value:Ci(new O(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},H_={description:E(`Hour component of a specific time.`),args:[H(`time (date)`,E(`The time from which to calculate the hour component.`))],compute:function(e){return F(e,this.locale).getHours()},isExported:!0},U_={description:E(`ISO week number of the year.`),args:[H(`date (date)`,E(`The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`))],compute:function(e){let t=F(e,this.locale),n=t.getFullYear(),r=1;for(;new O(n,0,r).getDay()!==4;)r+=1;let i=new O(n,0,r-3),a=31;for(;new O(n,11,a).getDay()!==4;)--a;let o=new O(n,11,a+3),s;s=i.getTime()<=t.getTime()?t.getTime()<=o.getTime()?0:1:-1;let c;switch(s){case 0:c=i;break;case 1:c=new O(n,11,a+3+1);break;case-1:let e=1;for(;new O(n-1,0,e).getDay()!==4;)e+=1;c=new O(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/Qr;return Math.floor(l/7)+1},isExported:!0},W_={description:E(`Minute component of a specific time.`),args:[H(`time (date)`,E(`The time from which to calculate the minute component.`))],compute:function(e){return F(e,this.locale).getMinutes()},isExported:!0},G_={description:E(`Month of the year a specific date falls in`),args:[H(`date (date)`,E(`The date from which to extract the month.`))],compute:function(e){return F(e,this.locale).getMonth()+1},isExported:!0},K_={description:E(`Net working days between two provided days.`),args:[H(`start_date (date)`,E(`The start date of the period from which to calculate the number of net working days.`)),H(`end_date (date)`,E(`The end date of the period from which to calculate the number of net working days.`)),H(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the date serial numbers to consider holidays.`))],compute:function(e,t,n){return Y_.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function q_(e){let t=e?.value;if(typeof t==`string`){Mu(t.length===7&&[...t].every(e=>e===`0`||e===`1`),E(`When weekend is a string (%s) it must be composed of "0" or "1".`,t));let e=[];for(let n=0;n<7;n++)t[n]===`1`&&e.push((n+1)%7);return e}if(typeof t==`number`)return Mu(1<=t&&t<=7||11<=t&&t<=17,E(`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 A(E(`The weekend must be a number or a string.`))}let J_=[{value:1,label:E(`Saturday/Sunday are weekends`)},{value:2,label:E(`Sunday/Monday are weekends`)},{value:3,label:E(`Monday/Tuesday are weekends`)},{value:4,label:E(`Tuesday/Wednesday are weekends`)},{value:5,label:E(`Wednesday/Thursday are weekends`)},{value:6,label:E(`Thursday/Friday are weekends`)},{value:7,label:E(`Friday/Saturday are weekends`)},{value:11,label:E(`Sunday is the only weekend`)},{value:12,label:E(`Monday is the only weekend`)},{value:13,label:E(`Tuesday is the only weekend`)},{value:14,label:E(`Wednesday is the only weekend`)},{value:15,label:E(`Thursday is the only weekend`)},{value:16,label:E(`Friday is the only weekend`)},{value:17,label:E(`Saturday is the only weekend`)}],Y_={description:E(`Net working days between two dates (specifying weekends).`),args:[H(`start_date (date)`,E(`The start date of the period from which to calculate the number of net working days.`)),H(`end_date (date)`,E(`The end date of the period from which to calculate the number of net working days.`)),H(`weekend (any, default=1)`,E(`A number or string representing which days of the week are considered weekends.`),J_),H(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the dates to consider as holidays.`))],compute:function(e,t,n={value:1},r){let i=F(e,this.locale),a=F(t,this.locale),o=q_(n),s=new Set;r!==void 0&&ga([r],e=>{let t=F(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=O.fromTimestamp((c?i:a).getTime()),u=O.fromTimestamp((c?a:i).getTime()),d=l.getTime(),f=u.getTime(),p=0;for(;f<=d;)!o.includes(u.getDay())&&!s.has(f)&&(p+=1),u.setDate(u.getDate()+1),f=u.getTime();return c?-p:p},isExported:!0},X_={description:E(`Current date and time as a date value.`),args:[],compute:function(){let e=O.now(),t=e.getTime()-Zr.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Qr)+n,format:Du(this.locale)}},isExported:!0},Z_={description:E(`Minute component of a specific time.`),args:[H(`time (date)`,E(`The time from which to calculate the second component.`))],compute:function(e){return F(e,this.locale).getSeconds()},isExported:!0},Q_={description:E(`Converts hour/minute/second into a time.`),args:[H(`hour (number)`,E(`The hour component of the time.`)),H(`minute (number)`,E(`The minute component of the time.`)),H(`second (number)`,E(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=Math.trunc(M(n,this.locale));return i+=Math.floor(a/60),a=a%60+(a<0?60:0),r+=Math.floor(i/60),i=i%60+(i<0?60:0),r%=24,r<0?new A(E(`The function [[FUNCTION_NAME]] result cannot be negative`)):{value:r/24+i/1440+a/(1440*60),format:this.locale.timeFormat}},isExported:!0},$_={description:E(`Converts a time string into its serial number representation.`),args:[H(`time_string (string)`,E(`The string that holds the time representation.`))],compute:function(e){let t=N(e),n=fi(t,this.locale);if(n===null)return new A(E(`The time_string (%s) cannot be parsed to date/time.`,t));let r=n.value-Math.trunc(n.value);return r<0?1+r:r},isExported:!0},ev={description:E(`Current date as a date value.`),args:[],compute:function(){let e=O.now();return{value:Ci(new O(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},tv={description:E(`Day of the week of the date provided (as number).`),args:[H(`date (date)`,E(`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.`)),H(`type (number, default=1)`,E(`A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.`),[{value:1,label:E(`Numbers 1 (Sunday) trough 7 (Saturday)`)},{value:2,label:E(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:3,label:E(`Numbers 0 (Monday) trough 6 (Sunday)`)},{value:11,label:E(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:12,label:E(`Numbers 1 (Tuesday) trough 7 (Monday)`)},{value:13,label:E(`Numbers 1 (Wednesday) trough 7 (Tuesday)`)},{value:14,label:E(`Numbers 1 (Thursday) trough 7 (Wednesday)`)},{value:15,label:E(`Numbers 1 (Friday) trough 7 (Thursday)`)},{value:16,label:E(`Numbers 1 (Saturday) trough 7 (Friday)`)},{value:17,label:E(`Numbers 1 (Sunday) trough 7 (Saturday)`)}])],compute:function(e,t={value:1}){let n=F(e,this.locale),r=Math.round(M(t,this.locale)),i=n.getDay();if(!(1<=r&&r<=3)&&!(11<=r&&r<=17))return new A(E(`The type (%s) must be between 1 and 3 or between 11 and 17.`,r));switch(r){case 1:return i+1;case 2:return i===0?7:i;case 3:return i===0?6:i-1}let a=r-10,o=(i+1-a+7)%7;return o===0?7:o},isExported:!0},nv={description:E(`Week number of the year.`),args:[H(`date (date)`,E(`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.`)),H(`type (number, default=1)`,E(`A number representing the day that a week starts on. Sunday = 1.`),[{value:1,label:E(`Sunday`)},{value:2,label:E(`Monday`)},{value:11,label:E(`Monday`)},{value:12,label:E(`Tuesday`)},{value:13,label:E(`Wednesday`)},{value:14,label:E(`Thursday`)},{value:15,label:E(`Friday`)},{value:16,label:E(`Saturday`)},{value:17,label:E(`Sunday`)},{value:21,label:E(`ISO week number (Monday as first day of the week)`)}])],compute:function(e,t={value:1}){let n=F(e,this.locale),r=Math.round(M(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(r))return new A(E(`The type (%s) is out of range.`,r.toString()));if(r===21)return U_.compute.bind(this)(e);let i;i=r===1||r===2?r-1:r-10==7?0:r-10;let a=n.getFullYear(),o=1,s=new O(a,0,o);for(;s.getDay()!==i;)o+=1,s=new O(a,0,o);let c=(n.getTime()-s.getTime())/Qr;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},rv={description:E(`Date after a number of workdays.`),args:[H(`start_date (date)`,E(`The date from which to begin counting.`)),H(`num_days (number)`,E(`The number of working days to advance from start_date. If negative, counts backwards.`)),H(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:null}){return iv.compute.bind(this)(e,t,{value:1},n)},isExported:!0},iv={description:E(`Date after a number of workdays (specifying weekends).`),args:[H(`start_date (date)`,E(`The date from which to begin counting.`)),H(`num_days (number)`,E(`The number of working days to advance from start_date. If negative, counts backwards.`)),H(`weekend (any, default=1)`,E(`A number or string representing which days of the week are considered weekends.`),J_),H(`holidays (date, range<date>, optional)`,E(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:1},r){let i=F(e,this.locale),a=Math.trunc(M(t,this.locale));if(n.value===`1111111`)return new A(E(`The weekend must be different from '1111111'.`));let o=q_(n),s=new Set;r!==void 0&&ga([r],e=>{let t=F(e,this.locale);s.add(t.getTime())});let c=O.fromTimestamp(i.getTime()),l=c.getTime(),u=Math.sign(a),d=Math.abs(a);for(;d>0;)c.setDate(c.getDate()+u),l=c.getTime(),!o.includes(c.getDay())&&!s.has(l)&&--d;let f=l-Zr.getTime();return{value:Math.round(f/Qr),format:this.locale.dateFormat}},isExported:!0},av={description:E(`Year specified by a given date.`),args:[H(`date (date)`,E(`The date from which to extract the year.`))],compute:function(e){return F(e,this.locale).getFullYear()},isExported:!0},ov={description:E(`Exact number of years between two dates.`),args:[H(`start_date (date)`,E(`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.`)),H(`end_date (date)`,E(`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.`)),H(`day_count_convention (number, default=0)`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n={value:0}){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=Math.trunc(M(n,this.locale));return r<0?new A(E(`The start_date (%s) must be positive or null.`,r)):i<0?new A(E(`The end_date (%s) must be positive or null.`,i)):0>a||a>4?new A(E(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,a)):ki(r,i,a)}},sv={description:E(`First day of the month preceding a date.`),args:[H(`date (date)`,E(`The date from which to calculate the result.`))],compute:function(e){let t=F(e,this.locale);return{value:Ci(new O(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},cv={description:E(`Last day of the month following a date.`),args:[H(`date (date)`,E(`The date from which to calculate the result.`))],compute:function(e){return V_.compute.bind(this)(e,{value:0})}},lv={description:E(`Quarter of the year a specific date falls in`),args:[H(`date (date)`,E(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((F(e,this.locale).getMonth()+1)/3)}},uv={description:E(`First day of the quarter of the year a specific date falls in.`),args:[H(`date (date)`,E(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=lv.compute.bind(this)(e);return{value:Ci(new O(av.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},dv={description:E(`Last day of the quarter of the year a specific date falls in.`),args:[H(`date (date)`,E(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=lv.compute.bind(this)(e);return{value:Ci(new O(av.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},fv={description:E(`First day of the year a specific date falls in.`),args:[H(`date (date)`,E(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:Ci(new O(av.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},pv={description:E(`Last day of the year a specific date falls in.`),args:[H(`date (date)`,E(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:Ci(new O(av.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var mv=l({DELTA:()=>hv});let hv={description:E(`Compare two numeric values, returning 1 if they're equal.`),args:[H(`number1 (number)`,E(`The first number to compare.`)),H(`number2 (number, default=0)`,E(`The second number to compare.`))],compute:function(e,t={value:0}){return+(M(e,this.locale)===M(t,this.locale))},isExported:!0},gv=[`number`,`error`,`text`,`boolean`];function _v(e){let t=e===`asc`?1:-1;return(e,n)=>{if(e.type===`empty`)return n.type===`empty`?0:1;if(n.type===`empty`)return-1;let r=gv.indexOf(e.type)-gv.indexOf(n.type);return r===0&&(r=e.type===`text`||e.type===`error`?e.value.localeCompare(n.value):e.value-n.value),t*r}}function vv(e,t,n){let r=e.map((e,t)=>({index:t,type:e.type,value:e.value}));return(n?r.map(e=>e.type===`empty`?{...e,type:`number`,value:0}:e):r).sort(_v(t))}function yv(e,t,n,r,i){let a=r.right>r.left;if(e.model.getters.doesIntersectMerge(t,r)){a=!1;let n;for(let i=r.top;i<=r.bottom;i++){n=[];for(let a=r.left;a<=r.right;a++){let r=e.model.getters.getMerge({sheetId:t,col:a,row:i});r&&!n.includes(r.id.toString())&&n.push(r.id.toString())}if(n.length>=2){a=!0;break}}}if(a){bv(e,t,n,r,i);return}let o=e.model.getters.getContiguousZone(t,r);Rs(o,r)?bv(e,t,n,r,i):e.askConfirmation(E(`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?`),()=>bv(e,t,n,o,i),()=>bv(e,t,n,r,i))}function bv(e,t,n,r,i,a){let o=e.model.dispatch(`SORT_CELLS`,{sheetId:t,col:n.col,row:n.row,zone:r,sortDirection:i,sortOptions:a});if(o.isCancelledBecause(`InvalidSortZone`)){let{col:t,row:i}=n;e.model.selection.selectZone({cell:{col:t,row:i},zone:r}),e.raiseError(E(`Cannot sort. To sort, select only cells or only merges that have the same size.`))}if(o.isCancelledBecause(`SortZoneWithArrayFormulas`)){let{col:t,row:i}=n;e.model.selection.selectZone({cell:{col:t,row:i},zone:r}),e.raiseError(E(`Cannot sort a zone with array formulas.`))}}var xv=l({FILTER:()=>Cv,SORT:()=>wv,SORTN:()=>Tv,UNIQUE:()=>Ev});function Sv(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;Mu(n[e]!==void 0,E(`Value for parameter %s is missing in [[FUNCTION_NAME]].`,t))}let r=[],i=[],a=e.length;for(let o=0;o<n.length;o+=2){r.push(P(Hu(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(Ir(s)&&(s.length>1||s[0].length>1))Mu(s.length===1&&s[0].length===a,E(`Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.`,`sort_column${o+1}`,a,s.length,s[0].length)),i.push(s.flat().map(e=>e.value));else{let n=M(Hu(s)?.value,t);if(n<1||n>e[0].length)return e;i.push(e.map(e=>e[n-1].value))}}if(i.length===0)for(let t=0;t<e[0].length;t++)i.push(e.map(e=>e[t].value)),r.push(`asc`);let o={desc:_v(`desc`),asc:_v(`asc`)},s=S(0,e.length);return s.sort((e,t)=>{for(let[n,a]of i.entries()){let i=a[e],s=a[t],c={value:i,type:i===null?`empty`:typeof i==`string`?`text`:typeof i},l={value:s,type:s===null?`empty`:typeof s==`string`?`text`:typeof s},u=o[r[n]](c,l);if(u!==0)return u}return 0}),s.map(t=>e[t])}let Cv={description:E(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[H(`range (any, range<any>)`,E(`The data to be filtered.`)),H(`condition1 (boolean, range<boolean>)`,E(`A column or row containing true or false values corresponding to the first column or row of range.`)),H(`condition2 (boolean, range<boolean>, repeating)`,E(`Additional column or row containing true or false values.`))],compute:function(e,...t){let n=I(e),r=t.map(e=>Ca(I(e),e=>e.value));for(let e of r)if(!Pu(e))return new A(E(`The arguments condition must be a single column or row.`));if(!Fu(...t))return new A(E(`The arguments conditions must have the same dimensions.`));let i=r.map(e=>e.flat()),a=r[0].length===1?`row`:`col`;if(n=a===`row`?Ta(n):n,i.some(e=>e.length!==n.length))return new A(E(`FILTER has mismatched sizes on the range and conditions.`));let o=[];for(let e=0;e<n.length;e++){let t=n[e];i.every(t=>(typeof t[e]==`boolean`||typeof t[e]==`number`)&&t[e])&&o.push(t)}return o.length?a===`row`?Ta(o):o:new Xi(E(`No match found in FILTER evaluation`))},isExported:!1},wv={description:E(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[H(`range (range)`,E(`The data to be sorted.`)),H(`sort_column (any, range<number>, repeating)`,E(`The index of the column in range or a range outside of range containing the values by which to sort.`)),H(`is_ascending (boolean, repeating)`,E(`TRUE or FALSE indicating whether to sort sort_column in ascending order.`),[{value:!0,label:E(`Ascending`)},{value:!1,label:E(`Descending`)}])],compute:function(e,...t){return Ta(Sv(Ta(e),this.locale,...t))},isExported:!0},Tv={description:E(`Returns the first n items in a data set after performing a sort.`),args:[H(`range (range)`,E(`The data to be sorted.`)),H(`n (number)`,E(`The number of items to return.`)),H(`display_ties_mode (number, default=0)`,E(`A number representing the way to display ties.`)),H(`sort_column (number, range<number>, repeating)`,E(`The index of the column in range or a range outside of range containing the values by which to sort.`)),H(`is_ascending (boolean, repeating)`,E(`TRUE or FALSE indicating whether to sort sort_column in ascending order.`),[{value:!0,label:E(`Ascending`)},{value:!1,label:E(`Descending`)}])],compute:function(e,t,...n){let r=M(t?.value??1,this.locale),i=n.length%2==0?0:M(n[0]?.value,this.locale),a=n.length%2==0?n:n.slice(1);if(r<0)return new A(E(`Wrong value of 'n'. Expected a positive number. Got %s.`,r));if(i<0||i>3)return new A(E(`Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.`,i));let o=Sv(Ta(e),this.locale,...a),s=(e,t)=>JSON.stringify(o[e].map(e=>e.value))===JSON.stringify(o[t].map(e=>e.value));switch(i){case 0:return Ta(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return Ta(o.slice(0,e));return Ta(o);case 2:{let e=[o[0]];for(let t=1;t<o.length;t++)for(let n=0;n<t&&!s(t,n);n++)n===t-1&&e.push(o[t]);return Ta(e.slice(0,r))}case 3:{let e=[o[0]],t=1;for(let n=1;n<o.length&&(s(n,n-1)||t++,!(t>r));n++)e.push(o[n]);return Ta(e)}}},isExported:!1},Ev={description:E(`Unique rows in the provided source range.`),args:[H(`range (any, range<any>)`,E(`The data to filter by unique entries.`)),H(`by_column (boolean, default=FALSE)`,E(`Whether to filter the data by columns or by rows.`),[{value:!0,label:E(`Return unique columns`)},{value:!1,label:E(`Return unique rows`)}]),H(`exactly_once (boolean, default=FALSE)`,E(`Whether to return only entries with no duplicates.`),[{value:!0,label:E(`Return items that appear exactly once`)},{value:!1,label:E(`Return every distinct item`)}])],compute:function(e={value:``},t,n){if(!Ir(e))return[[e]];let r=P(t?.value)||!1,i=P(n?.value)||!1;r||(e=Ta(e));let a=new Map;for(let t of e){let e=JSON.stringify(t.map(e=>e.value)),n=a.get(e);n?n.count++:a.set(e,{data:t,count:1})}let o=[];for(let e of a.values())i&&e.count>1||o.push(e.data);return o.length?r?o:Ta(o):new A(E(`No unique values found`))},isExported:!0};var Dv=l({ACCRINTM:()=>Mv,AMORLINC:()=>Nv,COUPDAYBS:()=>Fv,COUPDAYS:()=>Pv,COUPDAYSNC:()=>Iv,COUPNCD:()=>Lv,COUPNUM:()=>Rv,COUPPCD:()=>zv,CUMIPMT:()=>Bv,CUMPRINC:()=>Vv,DB:()=>Hv,DDB:()=>Wv,DISC:()=>Gv,DOLLARDE:()=>Kv,DOLLARFR:()=>qv,DURATION:()=>Jv,EFFECT:()=>Yv,FV:()=>Zv,FVSCHEDULE:()=>Qv,INTRATE:()=>$v,IPMT:()=>ty,IRR:()=>ry,ISPMT:()=>iy,MDURATION:()=>ay,MIRR:()=>oy,NOMINAL:()=>sy,NPER:()=>cy,NPV:()=>uy,PDURATION:()=>dy,PMT:()=>py,PPMT:()=>hy,PRICE:()=>_y,PRICEDISC:()=>vy,PRICEMAT:()=>yy,PV:()=>gy,RATE:()=>xy,RECEIVED:()=>Sy,RRI:()=>Cy,SLN:()=>wy,SYD:()=>Ty,TBILLEQ:()=>Oy,TBILLPRICE:()=>Dy,TBILLYIELD:()=>ky,VDB:()=>Ay,XIRR:()=>jy,XNPV:()=>My,YIELD:()=>Ny,YIELDDISC:()=>Py,YIELDMAT:()=>Fy});let Ov=[{value:1,label:E(`Annual`)},{value:2,label:E(`Semi-annual`)},{value:4,label:E(`Quarterly`)}],kv=[{value:0,label:E(`End of period (default)`)},{value:1,label:E(`Beginning of period`)}],Av=[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`),Ov),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)];function jv(e,t,n,r,i=1e-10,a){let o=n,s,c,l,u=!1,d=0,f;do{if(l=e(o),isNaN(l)){Mu(d<r&&a!==void 0,E(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++,o=a(f),f=o;continue}s=o-l/t(o),c=Math.abs(s-o),o=s,u=c<i||Math.abs(l)<i,Mu(d<r,E(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let Mv={description:E(`Accrued interest of security paying at maturity.`),args:[H(`issue (date)`,E(`The date the security was initially issued.`)),H(`maturity (date)`,E(`The maturity date of the security.`)),H(`rate (number)`,E(`The annualized rate of interest.`)),H(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(r,this.locale),c=M(n,this.locale),l=Math.trunc(M(i,this.locale));if(a<0)return new A(Yg(a));if(a>=o)return new A($g(a,o));if(O_(l))return new A(Ig(l));if(s<=0)return new A(__(s));if(c<=0)return new A(g_(c));let u=ki(a,o,l);return s*c*u},isExported:!0},Nv={description:E(`Depreciation for an accounting period.`),args:[H(`cost (number)`,E(`The initial cost of the asset.`)),H(`purchase_date (date)`,E(`The date the asset was purchased.`)),H(`first_period_end (date)`,E(`The date the first period ended.`)),H(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),H(`period (number)`,E(`The single period within life for which to calculate depreciation.`)),H(`rate (number)`,E(`The deprecation rate.`)),H(`day_count_convention (number, optional)`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=M(e,this.locale),c=Math.trunc(M(t,this.locale)),l=Math.trunc(M(n,this.locale)),u=M(r,this.locale),d=M(i,this.locale),f=M(a,this.locale),p=Math.trunc(M(o,this.locale));if(s<=0)return new A(Pg(s));if(c<0)return new A(p_(c));if(u<0)return new A(v_(u));if(u>s)return new A(y_(u,s));if(d<0)return new A(o_(d));if(f<=0)return new A(g_(f));if(O_(p))return new A(Ig(p));if(c>l)return new A(f_(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=ki(c,l,p),_=c===l?h:h*g,v=s-_-h*m;return v>=u?m===0?_:h:u-v<h?h-(u-v):0},isExported:!0},Pv={description:E(`Days in coupon period containing settlement date.`),args:Av,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A($g(i,a));if(k_(o))return new A(Fg(o));if(O_(s))return new A(Ig(s));if(s===1){let i=zv.compute.bind(this)(e,t,n,r).value,a=Lv.compute.bind(this)(e,t,n,r).value;return M(a,this.locale)-M(i,this.locale)}return(s===3?365:360)/o},isExported:!0},Fv={description:E(`Days from settlement until next coupon.`),args:Av,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A($g(i,a));if(k_(o))return new A(Fg(o));if(O_(s))return new A(Ig(s));let c=zv.compute.bind(this)(e,t,n,r).value,l=M(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=ki(l,i,s);return Math.round(e*360)}let u=F(i,this.locale),d=F(l,this.locale),f=d.getFullYear(),p=u.getFullYear(),m=d.getMonth()+1,h=u.getMonth()+1,g=d.getDate(),_=u.getDate();return m===2&&h===2&&Ei(d)&&Ei(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&Ei(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},Iv={description:E(`Days from settlement until next coupon.`),args:Av,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A($g(i,a));if(k_(o))return new A(Fg(o));if(O_(s))return new A(Ig(s));let c=Lv.compute.bind(this)(e,t,n,r).value,l=M(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=ki(i,l,s);return Math.round(e*360)}let u=Fv.compute.bind(this)(e,t,n,r);return M(Pv.compute.bind(this)(e,t,n,r),this.locale)-M(u,this.locale)},isExported:!0},Lv={description:E(`Next coupon date after the settlement date.`),args:Av,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A($g(i,a));if(k_(o))return new A(Fg(o));if(O_(s))return new A(Ig(s));let c=12/o,l=Rv.compute.bind(this)(e,t,n,r);return{value:Ci(Di(F(a,this.locale),-(M(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},Rv={description:E(`Number of coupons between settlement and maturity.`),args:Av,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A($g(i,a));if(k_(o))return new A(Fg(o));if(O_(s))return new A(Ig(s));let c=1,l=a,u=12/o;for(;l>i;)l=Ci(Di(F(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},zv={description:E(`Last coupon date prior to or on the settlement date.`),args:Av,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(M(e,this.locale)),a=Math.trunc(M(t,this.locale)),o=Math.trunc(M(n,this.locale)),s=Math.trunc(M(r,this.locale));if(i>=a)return new A($g(i,a));if(k_(o))return new A(Fg(o));if(O_(s))return new A(Ig(s));let c=12/o,l=Rv.compute.bind(this)(e,t,n,r);return{value:Ci(Di(F(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},Bv={description:E(`Cumulative interest paid over a set of periods.`),args:[H(`rate (number)`,E(`The interest rate.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`present_value (number)`,E(`The current value of the annuity.`)),H(`first_period (number)`,E(`The number of the payment period to begin the cumulative calculation.`)),H(`last_period (number)`,E(`The number of the payment period to end the cumulative calculation.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r,i,a={value:0}){let o=M(r,this.locale),s=M(i,this.locale),c=M(e,this.locale),l=M(n,this.locale),u=M(t,this.locale),d=+!!P(a);if(u<=0)return new A(r_(u));if(o<=0)return new A(Kg(o));if(s<=0)return new A(Zg(s));if(o>s)return new A(Gg(o,s));if(s>u)return new A(Xg(s,u));if(c<=0)return new A(g_(c));if(l<=0)return new A(u_(l));let f=0;for(let e=o;e<=s;e++)f+=ey(c,e,u,l,0,d);return f},isExported:!0},Vv={description:E(`Cumulative principal paid over a set of periods.`),args:[H(`rate (number)`,E(`The interest rate.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`present_value (number)`,E(`The current value of the annuity.`)),H(`first_period (number)`,E(`The number of the payment period to begin the cumulative calculation.`)),H(`last_period (number)`,E(`The number of the payment period to end the cumulative calculation.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r,i,a={value:0}){let o=M(r,this.locale),s=M(i,this.locale),c=M(e,this.locale),l=M(n,this.locale),u=M(t,this.locale),d=+!!P(a);if(u<=0)return new A(r_(u));if(o<=0)return new A(Kg(o));if(s<=0)return new A(Zg(s));if(o>s)return new A(Gg(o,s));if(s>u)return new A(Xg(s,u));if(c<=0)return new A(g_(c));if(l<=0)return new A(u_(l));let f=0;for(let e=o;e<=s;e++)f+=my(c,e,u,l,0,d);return f},isExported:!0},Hv={description:E(`Depreciation via declining balance method.`),args:[H(`cost (number)`,E(`The initial cost of the asset.`)),H(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),H(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),H(`period (number)`,E(`The single period within life for which to calculate depreciation.`)),H(`month (number, optional)`,E(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=Math.trunc(M(r,this.locale)),l=i.length?Math.trunc(M(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new A(Ng(a));if(o<0)return new A(v_(o));if(c<=0)return new A(l_(c));if(s<=0)return new A(Qg(s));if(1>l||l>12)return new A(e_(l));if(c>u)return new A(a_(c,u));let d=l/12,f=1-(o/a)**(1/s);f=Math.round(f*1e3)/1e3;let p=a,m=a*(1-f*d);for(let e=1;e<c;e++)p=m,m=p*(1-f),e===s&&(m=p*(1-f*(1-d)));return{value:p-m,format:`#,##0.00`}},isExported:!0},Uv=`#,##0.00`,Wv={description:E(`Depreciation via double-declining balance method.`),args:[H(`cost (number)`,E(`The initial cost of the asset.`)),H(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),H(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),H(`period (number)`,E(`The single period within life for which to calculate depreciation.`)),H(`factor (number, default=2)`,E(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=M(i,this.locale);if(a<0)return new A(Ng(a));if(o<0)return new A(v_(o));if(c<=0)return new A(l_(c));if(s<=0)return new A(Qg(s));if(c>s)return new A(c_(c,s));if(l<=0)return new A(Lg(l));if(a===0||o>=a)return{value:0,format:Uv};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:Uv};if(c<=1)return{value:a*u,format:Uv};let d=a*(1-u)**(c-1),f=a*(1-u)**c,p=f<o?d-o:d-f;return{value:Math.max(p,0),format:Uv}},isExported:!0},Gv={description:E(`Discount rate of a security based on price.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`price (number)`,E(`The price at which the security is bought per 100 face value.`)),H(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A($g(a,o));if(O_(l))return new A(Ig(l));if(s<=0)return new A(d_(s));if(c<=0)return new A(__(c));let u=ki(a,o,l);return(c-s)/c/u},isExported:!0},Kv={description:E(`Convert a decimal fraction to decimal value.`),args:[H(`fractional_price (number)`,E(`The price quotation given using fractional decimal conventions.`)),H(`unit (number)`,E(`The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));if(r<=0)return new A(T_(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},qv={description:E(`Convert a decimal value to decimal fraction.`),args:[H(`decimal_price (number)`,E(`The price quotation given as a decimal value.`)),H(`unit (number)`,E(`The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));if(r<=0)return new A(T_(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},Jv={description:E(`Number of periods for an investment to reach a value.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`rate (number)`,E(`The annualized rate of interest.`)),H(`yield (number)`,E(`The expected annual yield of the security.`)),H(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`),Ov),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(M(e,this.locale)),s=Math.trunc(M(t,this.locale)),c=M(n,this.locale),l=M(r,this.locale),u=Math.trunc(M(i,this.locale)),d=Math.trunc(M(a,this.locale));if(o>=s)return new A($g(o,s));if(k_(u))return new A(Fg(u));if(O_(d))return new A(Ig(d));if(c<0)return new A(h_(c));if(l<0)return new A(E_(l));let f=ki(o,s,d),p=f-Math.trunc(f)||1/u,m=Math.ceil(f*u),h=c/u,g=l/u,_=0,v=0;for(let e=1;e<=m;e++){let t=(h+ +(e===m))/(1+g)**e;v+=(p+(e-1)/u)*t,_+=t}return _===0?0:v/_},isExported:!0},Yv={description:E(`Annual effective interest rate.`),args:[H(`nominal_rate (number)`,E(`The nominal interest rate per year.`)),H(`periods_per_year (number)`,E(`The number of compounding periods per year.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));return n<=0?new A(t_(n)):r<=0?new A(s_(r)):(1+n/r)**+r-1},isExported:!0};function Xv(e,t,n,r,i){return e===0?-(r+n*t):-r*(1+e)**t-n*(1+e*i)*((1+e)**t-1)/e}let Zv={description:E(`Future value of an annuity investment.`),args:[H(`rate (number)`,E(`The interest rate.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`payment_amount (number)`,E(`The amount per period to be paid.`)),H(`present_value (number, default=0)`,E(`The current value of the annuity.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:Xv(M(e,this.locale),M(t,this.locale),M(n,this.locale),M(r,this.locale),+!!P(i)),format:`#,##0.00`}},isExported:!0},Qv={description:E(`Future value of principal from series of rates.`),args:[H(`principal (number)`,E(`The amount of initial capital or value to compound against.`)),H(`rate_schedule (number, range<number>)`,E(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=M(e,this.locale);return ya([t],(e,t)=>e*(1+M(t,this.locale)),n)},isExported:!0},$v={description:E(`Calculates effective interest rate.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`investment (number)`,E(`The amount invested in the security.`)),H(`redemption (number)`,E(`The amount to be received at maturity.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(r,this.locale),c=M(n,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A($g(a,o));if(c<=0)return new A(Jg(c));if(s<=0)return new A(__(s));if(O_(l))return new A(Ig(l));let u=ki(a,o,l);return(s-c)/c/u},isExported:!0};function ey(e,t,n,r,i,a){return fy(e,n,r,i,a)-my(e,t,n,r,i,a)}let ty={description:E(`Payment on the principal of an investment.`),args:[H(`rate (number)`,E(`The annualized rate of interest.`)),H(`period (number)`,E(`The amortization period, in terms of number of periods.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`present_value (number)`,E(`The current value of the annuity.`)),H(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:ey(M(e,this.locale),M(t,this.locale),M(n,this.locale),M(r,this.locale),M(i,this.locale),+!!P(a)),format:`#,##0.00`}},isExported:!0},ny=.1,ry={description:E(`Internal rate of return given periodic cashflows.`),args:[H(`cashflow_amounts (number, range<number>)`,E(`An array or range containing the income or payments associated with the investment.`)),H(`rate_guess (number, default=${ny})`,E(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:ny}){let n=M(t,this.locale);if(n<=-1)return new A(m_(n));let r=!1,i=!1,a=[];if(_a([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new A(Mg);let o=a.shift();function s(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*e**(r-i)),t*e**r)}function c(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*(r-i)*e**(r-i-1)),t*r*e**(r-1))}function l(e){return s(e,o,a)}function u(e){return c(e,o,a)}return{value:jv(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},iy={description:E(`Returns the interest paid at a particular period of an investment.`),args:[H(`rate (number)`,E(`The interest rate.`)),H(`period (number)`,E(`The period for which you want to view the interest payment.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`present_value (number)`,E(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=M(e,this.locale),a=M(t,this.locale),o=M(n,this.locale),s=M(r,this.locale);return o===0?new A(n_(o)):-1*(s-a/o*s)*i},isExported:!0},ay={description:E(`Modified Macaulay duration.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`rate (number)`,E(`The annualized rate of interest.`)),H(`yield (number)`,E(`The expected annual yield of the security.`)),H(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`),Ov),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=Jv.compute.bind(this)(e,t,n,r,i,a),s=M(r,this.locale),c=Math.trunc(M(i,this.locale));return M(o,this.locale)/(1+s/c)},isExported:!0},oy={description:E(`Modified internal rate of return.`),args:[H(`cashflow_amounts (range<number>)`,E(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),H(`financing_rate (number)`,E(`The interest rate paid on funds invested.`)),H(`reinvestment_return_rate (number)`,E(`The return (as a percentage) earned on reinvestment of income received from the investment.`))],compute:function(e,t,n){let r=M(t,this.locale),i=M(n,this.locale),a=Ta(e).flat().filter(e=>e.value!==null).map(e=>M(e,this.locale)),o=a.length,s=0,c=0;for(let e of S(0,o)){let t=a[e];t>=0?s+=t*(i+1)**(o-e-1):c+=t/(r+1)**e}if(c===0||s===0)return new A(Mg);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},sy={description:E(`Annual nominal interest rate.`),args:[H(`effective_rate (number)`,E(`The effective interest rate per year.`)),H(`periods_per_year (number)`,E(`The number of compounding periods per year.`))],compute:function(e,t){let n=M(e,this.locale),r=Math.trunc(M(t,this.locale));return n<=0?new A(Vg(n)):r<=0?new A(s_(r)):((n+1)**(1/r)-1)*r},isExported:!0},cy={description:E(`Number of payment periods for an investment.`),args:[H(`rate (number)`,E(`The interest rate.`)),H(`payment_amount (number)`,E(`The amount of each payment made.`)),H(`present_value (number)`,E(`The current value of the annuity.`)),H(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=+!!P(i);if(a===0)return-(c+s)/o;let u=o*(1+a*l)/a;return Math.log((u-c)/(s+u))/Math.log(1+a)},isExported:!0};function ly(e,t,n,r){let i=0;return ba(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let uy={description:E(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[H(`discount (number)`,E(`The discount rate of the investment over one period.`)),H(`cashflow1 (number, range<number>)`,E(`The first future cash flow.`)),H(`cashflow2 (number, range<number>, repeating)`,E(`Additional future cash flows.`))],compute:function(e,...t){let n=M(e,this.locale);return n===-1?new A(Rg(n)):{value:ly(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},dy={description:E(`Computes the number of periods needed for an investment to reach a value.`),args:[H(`rate (number)`,E(`The rate at which the investment grows each period.`)),H(`present_value (number)`,E(`The investment's current value.`)),H(`future_value (number)`,E(`The investment's desired future value.`))],compute:function(e,t,n){let r=M(e,this.locale),i=M(t,this.locale),a=M(n,this.locale);return r<=0?new A(g_(r)):i<=0?new A(u_(i)):a<=0?new A(qg(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function fy(e,t,n,r,i){if(t<=0)throw new A(r_(t));if(e===0)return-(r+n)/t;let a=-(n*(1+e)**t+r);return a=a*e/((1+e*i)*((1+e)**t-1)),a}let py={description:E(`Periodic payment for an annuity investment.`),args:[H(`rate (number)`,E(`The annualized rate of interest.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`present_value (number)`,E(`The current value of the annuity.`)),H(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r={value:0},i={value:0}){let a=M(t,this.locale),o=M(e,this.locale),s=+!!P(i),c=M(r,this.locale);return{value:fy(o,a,M(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function my(e,t,n,r,i,a){if(n<=0)throw new A(r_(n));if(t<=0||t>n)throw new A(i_(n));let o=fy(e,n,r,i,a);return a===1&&t===1?o:o+-Xv(e,a===0?t-1:t-2,o,r+o*a,0)*e}let hy={description:E(`Payment on the principal of an investment.`),args:[H(`rate (number)`,E(`The annualized rate of interest.`)),H(`period (number)`,E(`The amortization period, in terms of number of periods.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`present_value (number)`,E(`The current value of the annuity.`)),H(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=M(n,this.locale),s=M(e,this.locale),c=M(t,this.locale),l=+!!P(a),u=M(i,this.locale);return{value:my(s,c,o,M(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},gy={description:E(`Present value of an annuity investment.`),args:[H(`rate (number)`,E(`The interest rate.`)),H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`payment_amount (number)`,E(`The amount per period to be paid.`)),H(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=M(e,this.locale),o=M(t,this.locale),s=M(n,this.locale),c=M(r,this.locale),l=+!!P(i);return{value:a?-(s*(1+a*l)*((1+a)**o-1)/a+c)/(1+a)**o:-(c+s*o),format:`#,##0.00`}},isExported:!0},_y={description:E(`Price of a security paying periodic interest.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`rate (number)`,E(`The annualized rate of interest.`)),H(`yield (number)`,E(`The expected annual yield of the security.`)),H(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),H(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`),Ov),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(M(e,this.locale)),c=Math.trunc(M(t,this.locale)),l=M(n,this.locale),u=M(r,this.locale),d=M(i,this.locale),f=Math.trunc(M(a,this.locale)),p=Math.trunc(M(o,this.locale));if(s>=c)return new A($g(s,c));if(k_(f))return new A(Fg(f));if(O_(p))return new A(Ig(p));if(l<0)return new A(h_(l));if(u<0)return new A(E_(u));if(d<=0)return new A(__(d));let m=ki(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=1+u/f,v=100*l/f;if(h===1)return(v+d)/(g*u/f+1)-v*(1-g);let y=0;for(let e=1;e<=h;e++)y+=v/_**(e-1+g);return d/_**(h-1+g)+y-v*(1-g)},isExported:!0},vy={description:E(`Price of a discount security.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`discount (number)`,E(`The discount rate of the security at time of purchase.`)),H(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A($g(a,o));if(O_(l))return new A(Ig(l));if(s<=0)return new A(zg(s));if(c<=0)return new A(__(c));let u=ki(a,o,l);return c-s*c*u},isExported:!0},yy={description:E(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`issue (date)`,E(`The date the security was initially issued.`)),H(`rate (number)`,E(`The annualized rate of interest.`)),H(`yield (number)`,E(`The expected annual yield of the security.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(M(e,this.locale)),s=Math.trunc(M(t,this.locale)),c=Math.trunc(M(n,this.locale)),l=M(r,this.locale),u=M(i,this.locale),d=Math.trunc(M(a,this.locale));if(o<=c)return new A(S_(o,c));if(o>=s)return new A($g(o,s));if(O_(d))return new A(Ig(d));if(l<0)return new A(h_(l));if(u<0)return new A(E_(u));let f=ki(o,s,d),p=ki(o,c,d),m=100+ki(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},by=.1,xy={description:E(`Interest rate of an annuity investment.`),args:[H(`number_of_periods (number)`,E(`The number of payments to be made.`)),H(`payment_per_period (number)`,E(`The amount per period to be paid.`)),H(`present_value (number)`,E(`The current value of the annuity.`)),H(`future_value (number, default=0)`,E(`The future value remaining after the final payment has been made.`)),H(`end_or_beginning (number, default=0)`,E(`The timing of the payment payments are due for each period.`),kv),H(`rate_guess (number, default=${by})`,E(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:by}){let o=M(e,this.locale),s=M(t,this.locale),c=+!!P(i),l=M(a,this.locale)||by,u=M(r,this.locale),d=M(n,this.locale);return o<=0?new A(r_(o)):D_([s,d,u])?l<=-1?new A(m_(l)):(u-=s*c,d+=s*c,{value:jv(e=>{let t=(1+e)**+o,n=(t-1)/e;return u+d*t+s*n},e=>{let t=(1+e)**(o-1),n=((1+e)**+o-1)/e,r=o*t/e-n/e;return d*o*t+s*r},l,40,1e-5),format:`0%`}):new A(E(`There must be both positive and negative values in [payment_amount, present_value, future_value].`))},isExported:!0},Sy={description:E(`Amount received at maturity for a security.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`investment (number)`,E(`The amount invested (irrespective of face value of each security).`)),H(`discount (number)`,E(`The discount rate of the security invested in.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));return a>=o?new A($g(a,o)):O_(l)?new A(Ig(l)):s<=0?new A(Jg(s)):c<=0?new A(zg(c)):s/(1-c*ki(a,o,l))},isExported:!0},Cy={description:E(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[H(`number_of_periods (number)`,E(`The number of periods.`)),H(`present_value (number)`,E(`The present value of the investment.`)),H(`future_value (number)`,E(`The future value of the investment.`))],compute:function(e,t,n){let r=M(e,this.locale),i=M(t,this.locale),a=M(n,this.locale);return r<=0?new A(r_(r)):(a/i)**(1/r)-1},isExported:!0},wy={description:E(`Depreciation of an asset using the straight-line method.`),args:[H(`cost (number)`,E(`The initial cost of the asset.`)),H(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),H(`life (number)`,E(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=M(e,this.locale),i=M(t,this.locale),a=M(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},Ty={description:E(`Depreciation via sum of years digit method.`),args:[H(`cost (number)`,E(`The initial cost of the asset.`)),H(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),H(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),H(`period (number)`,E(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=M(e,this.locale),a=M(t,this.locale),o=M(n,this.locale),s=M(r,this.locale);if(s<=0)return new A(l_(s));if(o<=0)return new A(Qg(o));if(s>o)return new A(c_(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function Ey(e,t,n){return 100*(1-n*ki(e,t,2))}let Dy={description:E(`Price of a US Treasury bill.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`discount (number)`,E(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=M(n,this.locale);return r>=i?new A($g(r,i)):A_(r,i,this.locale)?a<=0?new A(zg(a)):a>=1?new A(Bg(a)):Ey(r,i,a):new A(x_(r,i))},isExported:!0},Oy={description:E(`Equivalent rate of return for a US Treasury bill.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`discount (number)`,E(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=M(n,this.locale);if(r>=i)return new A($g(r,i));if(!A_(r,i,this.locale))return new A(x_(r,i));if(a<=0)return new A(zg(a));if(a>=1)return new A(Bg(a));let o=R_.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=Ey(r,i,a)/100,c=o/(o===366?366:365);return(-2*c+2*Math.sqrt(c**2-(2*c-1)*(1-1/s)))/(2*c-1)},isExported:!0},ky={description:E(`The yield of a US Treasury bill based on price.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`price (number)`,E(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(M(e,this.locale)),i=Math.trunc(M(t,this.locale)),a=M(n,this.locale);if(r>=i)return new A($g(r,i));if(!A_(r,i,this.locale))return new A(x_(r,i));if(a<=0)return new A(d_(a));let o=ki(r,i,2);return(100-a)/a*(1/o)},isExported:!0},Ay={description:E(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[H(`cost (number)`,E(`The initial cost of the asset.`)),H(`salvage (number)`,E(`The value of the asset at the end of depreciation.`)),H(`life (number)`,E(`The number of periods over which the asset is depreciated.`)),H(`start (number)`,E(`Starting period to calculate depreciation.`)),H(`end (number)`,E(`Ending period to calculate depreciation.`)),H(`factor (number, default=2)`,E(`The number of months in the first year of depreciation.`)),H(`no_switch (number, default=false)`,E(`Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.`),[{value:!1,label:E(`Switch to straight-line depreciation`)},{value:!0,label:E(`Do not switch to straight-line depreciation`)}])],compute:function(e,t,n,r,i,a={value:2},o={value:!1}){a||=0;let s=M(e,this.locale),c=M(t,this.locale),l=M(n,this.locale),u=Math.trunc(M(r,this.locale)),d=Math.trunc(M(i,this.locale)),f=M(a,this.locale),p=P(o);if(s<0)return new A(Ng(s));if(c<0)return new A(v_(c));if(l<=0)return new A(Qg(l));if(u<0)return new A(C_(u));if(d<0)return new A(Hg(d));if(u>d)return new A(w_(u,d));if(d>l)return new A(Ug(d,l));if(f<=0)return new A(Lg(f));if(s===0)return 0;if(c>=s)return u<1?s-c:0;let m=f/l;if(m>=1)return u<1?s-c:0;let h=s,g=0,_=0,v=!1;for(let e=0;e<d;e++){if(!v||p){let t=h*m,n=l-e,r=(h-c)/n;!p&&r>t?(v=!0,g=r):g=t}let t=Math.max(h-g,c);e>=u&&(_+=h-t),h=t}return _},isExported:!0},jy={description:E(`Internal rate of return given non-periodic cash flows.`),args:[H(`cashflow_amounts (range<number>)`,E(`An range containing the income or payments associated with the investment.`)),H(`cashflow_dates (range<number>)`,E(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),H(`rate_guess (number, default=${by})`,E(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:by}){let r=M(n,this.locale);if(!Fu(e,t))return new A(jg);let i=e.flat().map(e=>M(e,this.locale)),a=t.flat().map(e=>M(e,this.locale));if(!D_(i))return new A(Mg);if(a.some(e=>e<a[0]))return new A(Wg(a[0]));if(r<=-1)return new A(m_(r));let o=new Map;for(let e of S(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e));return jv(e=>{let t=c[0];for(let n of S(1,c.length)){let r=(s[0]-s[n])/365;t+=c[n]*(1+e)**r}return t},e=>{let t=0;for(let n of S(1,c.length)){let r=(s[0]-s[n])/365;t+=r*c[n]*(1+e)**(r-1)}return t},r,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},My={description:E(`Net present value given to non-periodic cash flows..`),args:[H(`discount (number)`,E(`The discount rate of the investment over one period.`)),H(`cashflow_amounts (number, range<number>)`,E(`An range containing the income or payments associated with the investment.`)),H(`cashflow_dates (number, range<number>)`,E(`An range with dates corresponding to the cash flows in cashflow_amounts.`))],compute:function(e,t,n){let r=M(e,this.locale);if(!Fu(t,n))return new A(jg);let i=I(t).flat().map(e=>ca(e,this.locale)),a=I(n).flat().map(e=>ca(e,this.locale));if(a.some(e=>e<a[0]))return new A(Wg(a[0]));if(r<=0)return new A(g_(r));if(i.length===1)return i[0];let o=new Map;for(let e of S(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e)),l=c[0];for(let e of S(1,c.length)){let t=(s[0]-s[e])/365;l+=c[e]*(1+r)**t}return l},isExported:!0},Ny={description:E(`Annual yield of a security paying periodic interest.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`rate (number)`,E(`The annualized rate of interest.`)),H(`price (number)`,E(`The price at which the security is bought per 100 face value.`)),H(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),H(`frequency (number)`,E(`The number of interest or coupon payments per year (1, 2, or 4).`),Ov),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(M(e,this.locale)),c=Math.trunc(M(t,this.locale)),l=M(n,this.locale),u=M(r,this.locale),d=M(i,this.locale),f=Math.trunc(M(a,this.locale)),p=Math.trunc(M(o,this.locale));if(s>=c)return new A($g(s,c));if(k_(f))return new A(Fg(f));if(O_(p))return new A(Ig(p));if(l<0)return new A(h_(l));if(u<=0)return new A(d_(u));if(d<=0)return new A(__(d));let m=ki(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=100*l/f;if(h===1){let e=u+_*(1-g);return(d+_-e)*f*(1/g)/e}function v(e,t,n,r,i,a){let o=a-(e+i*(1-t))*r**(n-1+t);for(let e=1;e<=n;e++)o+=i*r**(e-1);return o}function y(e,t,n,r,i){let a=-(e+i*(1-t))*(n-1+t)*r**(n-2+t);for(let e=1;e<=n;e++)a+=i*(e-1)*r**(e-2);return a}function ee(e){return v(u,g,h,e,_,d)}function te(e){return y(u,g,h,e,_)}return(jv(ee,te,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},Py={description:E(`Annual yield of a discount security.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`price (number)`,E(`The price at which the security is bought per 100 face value.`)),H(`redemption (number)`,E(`The redemption amount per 100 face value, or par.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(M(e,this.locale)),o=Math.trunc(M(t,this.locale)),s=M(n,this.locale),c=M(r,this.locale),l=Math.trunc(M(i,this.locale));if(a>=o)return new A($g(a,o));if(O_(l))return new A(Ig(l));if(s<=0)return new A(d_(s));if(c<=0)return new A(__(c));let u=ki(a,o,l);return(c/s-1)/u},isExported:!0},Fy={description:E(`Annual yield of a security paying interest at maturity.`),args:[H(`settlement (date)`,E(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),H(`maturity (date)`,E(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),H(`issue (date)`,E(`The date the security was initially issued.`)),H(`rate (number)`,E(`The annualized rate of interest.`)),H(`price (number)`,E(`The price at which the security is bought.`)),H(`day_count_convention (number, default=0 )`,E(`An indicator of what day count method to use.`),j_)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(M(e,this.locale)),s=Math.trunc(M(t,this.locale)),c=Math.trunc(M(n,this.locale)),l=M(r,this.locale),u=M(i,this.locale),d=Math.trunc(M(a,this.locale));if(o>=s)return new A($g(o,s));if(O_(d))return new A(Ig(d));if(o<c)return new A(b_(o,c));if(l<0)return new A(h_(l));if(u<=0)return new A(d_(u));let f=ki(c,s,d),p=ki(c,o,d),m=ki(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0},Iy=(e,t=()=>!0)=>[{goTo:e,guard:t}],Ly=(e,t=()=>!0)=>({goTo:e,guard:t}),Ry={0:{REFERENCE:Iy(2),NUMBER:Iy(4),SYMBOL:[Ly(3,e=>Ec(e.value)),Ly(4,e=>Dc(e.value))]},3:{SPACE:Iy(3),OPERATOR:Iy(5,e=>e.value===`:`)},4:{SPACE:Iy(4),OPERATOR:Iy(6,e=>e.value===`:`)},2:{SPACE:Iy(2),OPERATOR:Iy(1,e=>e.value===`:`)},1:{SPACE:Iy(1),NUMBER:Iy(7),REFERENCE:Iy(7,e=>Ac(e.value)),SYMBOL:Iy(7,e=>Oc(e.value)||kc(e.value))},5:{SPACE:Iy(5),SYMBOL:Iy(7,e=>Oc(e.value)),REFERENCE:Iy(7,e=>Ac(e.value))},6:{SPACE:Iy(6),NUMBER:Iy(7),REFERENCE:Iy(7,e=>Ac(e.value)),SYMBOL:Iy(7,e=>kc(e.value))},7:{}};function zy(e){let t=0,n=Ry[0],r=``;for(;n!==void 0;){let i=e[t++];if(!i)return null;let a=n[i.type]?.find(e=>e.guard(i)),o=a?a.goTo:void 0;switch(o){case void 0:return null;case 7:return r+=i.value,e.splice(0,t),{type:`REFERENCE`,value:r};default:n=Ry[o],r+=i.value;break}}return null}function By(e,t=D){let n=Jl(e,t),r=[];for(;n.length;)r.push(zy(n)||n.shift());return r}let Vy=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,Hy=[`-`,`+`],Uy=[`%`];var Wy=class{tokens;currentIndex=0;current;length;constructor(e){this.tokens=e,this.current=e[0],this.length=e.length}shift(){let e=this.tokens[this.currentIndex];return this.current=this.tokens[++this.currentIndex],e}get next(){return this.tokens[this.currentIndex+1]}};let Gy={"%":40,"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function Ky(e){let t=e.shift();if(!t)throw new qi;switch(t.type){case`DEBUGGER`:let n=Xy(e,1e3);return n.debug=!0,n;case`NUMBER`:return{type:`NUMBER`,value:Wi(t.value,D),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`STRING`:return{type:`STRING`,value:ct(t.value),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`INVALID_REFERENCE`:return{type:`REFERENCE`,value:k.InvalidReference,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`REFERENCE`:if(e.current?.value===`:`&&e.next?.type===`REFERENCE`){e.shift();let n=e.shift();return{type:`REFERENCE`,value:`${t.value}:${n?.value}`,tokenStartIndex:t.tokenIndex,tokenEndIndex:n.tokenIndex}}return{type:`REFERENCE`,value:t.value,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`SYMBOL`:let r=t.value;if(e.current?.type===`LEFT_PAREN`&&Vy.test(t.value)&&r===pt(r,`'`)){let{args:n,rightParen:i}=qy(e);return{type:`FUNCALL`,value:r,args:n,tokenStartIndex:t.tokenIndex,tokenEndIndex:i.tokenIndex}}let i=r.toUpperCase();return i===`TRUE`||i===`FALSE`?{type:`BOOLEAN`,value:i===`TRUE`,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:{type:`SYMBOL`,value:pt(t.value,`'`),tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex};case`LEFT_PAREN`:let a=Xy(e),o=Yy(e,`RIGHT_PAREN`,E(`Missing closing parenthesis`));return{...a,tokenStartIndex:t.tokenIndex,tokenEndIndex:o.tokenIndex};case`OPERATOR`:let s=t.value;if(Hy.includes(s)){let n=Xy(e,Gy[s]);return{type:`UNARY_OPERATION`,value:s,operand:n,tokenStartIndex:t.tokenIndex,tokenEndIndex:n.tokenEndIndex}}throw new qi(E(`Unexpected token: %s`,t.value));default:throw new qi(E(`Unexpected token: %s`,t.value))}}function qy(e){if(Yy(e,`LEFT_PAREN`,E(`Missing opening parenthesis`)),e.current?.type===`RIGHT_PAREN`)return{args:[],rightParen:Yy(e,`RIGHT_PAREN`)};let t=[];for(t.push(Jy(e));e.current?.type!==`RIGHT_PAREN`;)Yy(e,`ARG_SEPARATOR`,E(`Wrong function call`)),t.push(Jy(e));return{args:t,rightParen:Yy(e,`RIGHT_PAREN`)}}function Jy(e){let t=e.current;return t?.type===`ARG_SEPARATOR`||t?.type===`RIGHT_PAREN`?{type:`EMPTY`,value:``,tokenStartIndex:t.tokenIndex,tokenEndIndex:t.tokenIndex}:Xy(e)}function Yy(e,t,n){let r=e.shift();if(!r||r.type!==t)throw new qi(n);return r}function Xy(e,t=0){if(e.length===0)throw new qi;let n=Ky(e);for(;e.current?.type===`OPERATOR`&&Gy[e.current.value]>t;){let t=e.shift(),r=t.value;if(Uy.includes(r))n={type:`UNARY_OPERATION`,value:r,operand:n,postfix:!0,tokenStartIndex:n.tokenStartIndex,tokenEndIndex:t.tokenIndex};else{let t=Xy(e,Gy[r]);n={type:`BIN_OPERATION`,value:r,left:n,right:t,tokenStartIndex:n.tokenStartIndex,tokenEndIndex:t.tokenEndIndex}}}return n}function Zy(e){return Qy(By(e))}function Qy(e){let t=new Wy(e.map((e,t)=>({type:e.type,value:e.value,tokenIndex:t})).filter(e=>e.type!==`SPACE`));t.current?.value===`=`&&t.shift();let n=Xy(t);if(t.current)throw new qi;return n}function $y(e,t,n){return nb(e,e=>e.type===t?n(e):e)}function eb(e){return Array.from(tb(e))}function*tb(e){switch(yield e,e.type){case`FUNCALL`:for(let t of e.args)yield*tb(t);break;case`UNARY_OPERATION`:yield*tb(e.operand);break;case`BIN_OPERATION`:yield*tb(e.left),yield*tb(e.right);break}}function nb(e,t){switch(e=t(e),e.type){case`FUNCALL`:return{...e,args:e.args.map(e=>nb(e,t))};case`UNARY_OPERATION`:return{...e,operand:nb(e.operand,t)};case`BIN_OPERATION`:return{...e,right:nb(e.right,t),left:nb(e.left,t)};default:return e}}function rb(e){let t=0;return e.map(e=>{let n=e.value.toString().length,r=Object.assign({},e,{start:t,end:t+n,length:n});return t=r.end,r})}function ib(e){let t=[],n=0;return e.map((r,i)=>{if(r.type===`LEFT_PAREN`){t.push(n+1),n=0;for(let n=i-1;n>=0;n--){if(e[n].type===`SPACE`){e[n].parenthesesCode=t.join(`:`);continue}e[n].type===`SYMBOL`&&(e[n].parenthesesCode=t.join(`:`));break}}return r.parenthesesCode=t.join(`:`),r.type===`RIGHT_PAREN`&&t.length&&(n=t.pop()),r})}function ab(e){let t=[],n=``;function r(e){if(t.length===0)return;let n=t.at(-1);if(n&&n.argsTokens){let{argsTokens:t,argPosition:r}=n;t[r]||(t[r]=[]),t[r].push({value:e.value,type:e.type})}}return e.map((e,i)=>{switch([`SPACE`,`LEFT_PAREN`].includes(e.type)||(n=``),e.type){case`SYMBOL`:r(e),n=e.value;break;case`LEFT_PAREN`:t.push({parent:n,argPosition:0,argsTokens:[],args:[]}),r(e),n=``;break;case`RIGHT_PAREN`:t.pop()?.argsTokens?.flat().forEach(r),r(e);break;case`ARG_SEPARATOR`:t.length&&t[t.length-1].argPosition++,r(e);break;default:r(e);break}if(t.length){let n=t[t.length-1];n.parent&&(e.functionContext=Object.assign({},n))}return e})}function ob(e){for(let t of e)if(t.functionContext){let{argsTokens:e,args:n}=t.functionContext;if(delete t.functionContext.argsTokens,n.length||!e)continue;e[0]?.[0]?.type===`LEFT_PAREN`&&(e[0]=e[0].slice(1));for(let t of e){let e=t;e.at(0)?.type===`ARG_SEPARATOR`&&(e=e.slice(1));try{n.push(Qy(e))}catch{n.push(void 0)}}}return e}function sb(e,t){return ob(ab(ib(rb(By(e,t)))))}function cb(e){if(e.type!==`REFERENCE`)return e;let{xc:t,sheetName:n}=jc(e.value),[r,i]=t.split(`:`),a=lb(r),o=i?`:${lb(i)}`:``;return{...e,value:Mc(n,a+o)}}function lb(e){switch(fb(e)){case`none`:e=ub(e,`colrow`);break;case`colrow`:e=ub(e,`row`);break;case`row`:e=ub(e,`col`);break;case`col`:e=ub(e,`none`);break}return e}function ub(e,t){let n;({sheetName:n,xc:e}=jc(e)),n=n?mt(n)+`!`:``,e=e.replace(/\$/g,``);let r=e.indexOf(`:`);return r>=0?`${n}${db(e.slice(0,r),t)}:${db(e.slice(r+1),t)}`:n+db(e,t)}function db(e,t){let n=e.search(/[0-9]/),r=n!==0,i=n>=0;switch(t){case`col`:return r?`$`+e:e;case`row`:return i?e.slice(0,n)+`$`+e.slice(n):e;case`colrow`:return!i||!r?`$`+e:`$`+e.slice(0,n)+`$`+e.slice(n);case`none`:return e}}function fb(e){return hb(e)?`colrow`:pb(e)?`col`:mb(e)?`row`:`none`}function pb(e){return e.startsWith(`$`)}function mb(e){return e.includes(`$`,1)}function hb(e){return e.startsWith(`$`)&&e.length>1&&e.slice(1).includes(`$`)}function gb(e,t,n){let r=(t.startsWith(`=`)?sb(t,n):[]).filter(t=>t.start<=e.start&&t.end>=e.start||t.start>=e.start&&t.start<e.end),i=r.filter(e=>e.type===`REFERENCE`);if(i.length===0)return;let a=r.map(cb).map(e=>e.value).join(``),o=r[0].start,s=r[r.length-1].end,c=t.slice(0,o)+a+t.slice(s),l=c.length-t.length,u={start:i[0].start,end:i[i.length-1].end+l};return i.length===1&&e.start===e.end&&(u.start=u.end),{content:c,selection:u}}var _b=l({CELL:()=>yb,ISBLANK:()=>Db,ISERR:()=>bb,ISERROR:()=>xb,ISFORMULA:()=>kb,ISLOGICAL:()=>Sb,ISNA:()=>Cb,ISNONTEXT:()=>wb,ISNUMBER:()=>Tb,ISTEXT:()=>Eb,NA:()=>Ob});let vb=[{value:`address`,label:E(`Returns an absolute reference as plain text of the top left cell in reference.`)},{value:`col`,label:E(`Returns the column number of the cell in reference.`)},{value:`contents`,label:E(`Returns the value contained in the top left cell in reference.`)},{value:`format`,label:E(`Returns the format of the top left cell in reference.`)},{value:`row`,label:E(`Returns the row number of the top left cell in reference.`)},{value:`type`,label:E(`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.`)}],yb={description:E(`Gets information about a cell.`),args:[H(`info_type (string)`,E(`The type of information requested.`),vb),H(`reference (meta, range<meta>)`,E(`The reference to the cell.`))],compute:function(e,t){let n=N(e).toLowerCase();if(!vb.map(e=>e.value).includes(n))return new A(E(`The info_type should be one of %s.`,vb.join(`, `)));let r=this.__originSheetId,i=t[0][0].value,{sheetName:a,xc:o}=jc(i);a=a===this.getters.getSheetName(r)?void 0:a;let s=Mc(a,ub(o,`colrow`)),c=this.getters.getRangeFromSheetXC(r,s);switch(n){case`address`:return this.getters.getRangeString(c,r);case`col`:return c.zone.left+1;case`contents`:{let e={sheetId:c.sheetId,col:c.zone.left,row:c.zone.top};return this.getters.getEvaluatedCell(e).value}case`format`:{let 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`:{let e={sheetId:c.sheetId,col:c.zone.left,row:c.zone.top},t=this.getters.getEvaluatedCell(e).type;return t===`empty`?`b`:t===`text`?`l`:`v`}}return``},isExported:!0},bb={description:E(`Whether a value is an error other than #N/A.`),args:[H(`value (any)`,E(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return j(t)&&t!==k.NotAvailable},isExported:!0},xb={description:E(`Whether a value is an error.`),args:[H(`value (any)`,E(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return j(t)},isExported:!0},Sb={description:E("Whether a value is `true` or `false`."),args:[H(`value (any)`,E(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},Cb={description:E(`Whether a value is the error #N/A.`),args:[H(`value (any)`,E(`The value to be verified as an error type.`))],compute:function(e){return e?.value===k.NotAvailable},isExported:!0},wb={description:E(`Whether a value is non-textual.`),args:[H(`value (any)`,E(`The value to be checked.`))],compute:function(e){return!Eb.compute.bind(this)(e)},isExported:!0},Tb={description:E(`Whether a value is a number.`),args:[H(`value (any)`,E(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},Eb={description:E(`Whether a value is text.`),args:[H(`value (any)`,E(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&j(e?.value)===!1},isExported:!0},Db={description:E(`Whether the referenced cell is empty`),args:[H(`value (any)`,E(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},Ob={description:E(`Returns the error value #N/A.`),args:[],compute:function(){return{value:k.NotAvailable}},isExported:!0},kb={description:E(`Checks whether there is a reference to a cell that contains a formula, and returns TRUE or FALSE.`),args:[H(`cell_reference (meta)`,E(`A reference to a cell.`))],compute:function(e){let{sheetName:t,xc:n}=jc(e.value),{col:r,row:i}=ir(n),a=(t&&this.getters.getSheetIdByName(t))??this.__originSheetId;return this.getters.getCell({sheetId:a,col:r,row:i})?.isFormula??!1},isExported:!0};var Ab=l({AND:()=>jb,FALSE:()=>Mb,IF:()=>Nb,IFERROR:()=>Pb,IFNA:()=>Fb,IFS:()=>Ib,NOT:()=>Lb,OR:()=>Rb,SWITCH:()=>zb,TRUE:()=>Bb,XOR:()=>Vb});let jb={description:E("Logical `and` operator."),args:[H(`logical_expression1 (boolean, range<boolean>)`,E(`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.`)),H(`logical_expression2 (boolean, range<boolean>, repeating)`,E(`More expressions that represent logical values.`))],compute:function(...e){let{result:t,foundBoolean:n}=Ou(e);return n?t:new A(Ba)},isExported:!0},Mb={description:E("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},Nb={description:E(`Returns value depending on logical expression.`),args:[H(`logical_expression (boolean, range<boolean>)`,E(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.`)),H(`value_if_true (any, range)`,E(`The value the function returns if logical_expression is TRUE.`)),H(`value_if_false (any, range, default=FALSE)`,E(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return Wu(e)?Ea(Nb.compute,[e,t,n]):(P(Hu(e))?t:n)??{value:0}},isExported:!0},Pb={description:E(`Value if it is not an error, otherwise 2nd argument.`),args:[H(`value (any, range)`,E(`The value to return if value itself is not an error.`)),H(`value_if_error (any, range, default="empty")`,E(`The value the function returns if value is an error.`))],compute:function(e,t){return Wu(e)?Ea(Pb.compute,[e,t]):(j(Hu(e)?.value)?t:e)??{value:0}},isExported:!0},Fb={description:E(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[H(`value (any, range)`,E(`The value to return if value itself is not #N/A an error.`)),H(`value_if_error (any, range, default="empty")`,E(`The value the function returns if value is an #N/A error.`))],compute:function(e,t){return Wu(e)?Ea(Fb.compute,[e,t]):(Hu(e)?.value===k.NotAvailable?t:e)??{value:0}},isExported:!0},Ib={description:E(`Returns a value depending on multiple logical expressions.`),args:[H(`condition1 (boolean, range<boolean>)`,E(`The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.`)),H(`value1 (any, range)`,E(`The returned value if condition1 is TRUE.`)),H(`condition2 (boolean, any, range, repeating)`,E(`Additional conditions to be evaluated if the previous ones are FALSE.`)),H(`value2 (any, range, repeating)`,E(`Additional values to be returned if their corresponding conditions are TRUE.`))],compute:function(...e){if(e.length%2!=0)return new A(E(`Wrong number of arguments. Expected an even number of arguments.`));for(;e.length>0;){if(Wu(e[0]))return Ea(Ib.compute,e);let t=P(Hu(e.shift())),n=e.shift();if(t)return n??{value:0}}return new A(E(`No match.`))},isExported:!0},Lb={description:E(`Returns opposite of provided logical value.`),args:[H(`logical_expression (boolean)`,E(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!P(e)},isExported:!0},Rb={description:E("Logical `or` operator."),args:[H(`logical_expression1 (boolean, range<boolean>)`,E(`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.`)),H(`logical_expression2 (boolean, range<boolean>, repeating)`,E(`More expressions that evaluate to logical values.`))],compute:function(...e){let{result:t,foundBoolean:n}=ku(e);return n?t:new A(Ba)},isExported:!0},zb={description:E(`Returns a value by comparing cases to an expression.`),args:[H(`expression (number, boolean, string)`,E(`The value to be checked.`)),H(`case1 (number, boolean, string)`,E(`The first case to be checked against expression.`)),H(`value1 (any)`,E(`The corresponding value to be returned if case1 matches expression.`)),H(`case2 (any, repeating)`,E(`Additional cases to try if the previous ones don't match expression.`)),H(`value2 (any, repeating)`,E(`Additional values to be returned if their corresponding cases match expression.`)),H(`default (any, default="empty")`,E(`An optional default value to be returned if none of the cases match expression.`))],compute:function(e,...t){let n=t.length%2==0?na(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&j(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},Bb={description:E("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},Vb={description:E("Logical `xor` operator."),args:[H(`logical_expression1 (boolean, range<boolean>)`,E(`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.`)),H(`logical_expression2 (boolean, range<boolean>, repeating)`,E(`More expressions that evaluate to logical values.`))],compute:function(...e){let t=!1,n=!1;return Oa(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new A(Ba)},isExported:!0},Hb={Errors:{InvalidRange:E(`The range is invalid`),FirstArgMissing:E(`The argument is missing. Please provide a value`),SecondArgMissing:E(`The second argument is missing. Please provide a value`),MinNaN:E(`The minpoint must be a number`),MidNaN:E(`The midpoint must be a number`),MaxNaN:E(`The maxpoint must be a number`),ValueUpperInflectionNaN:E(`The first value must be a number`),ValueLowerInflectionNaN:E(`The second value must be a number`),MinBiggerThanMax:E(`Minimum must be smaller then Maximum`),MinBiggerThanMid:E(`Minimum must be smaller then Midpoint`),MidBiggerThanMax:E(`Midpoint must be smaller then Maximum`),LowerBiggerThanUpper:E(`Lower inflection point must be smaller than upper inflection point`),MinInvalidFormula:E(`Invalid Minpoint formula`),MaxInvalidFormula:E(`Invalid Maxpoint formula`),MidInvalidFormula:E(`Invalid Midpoint formula`),ValueUpperInvalidFormula:E(`Invalid upper inflection point formula`),ValueLowerInvalidFormula:E(`Invalid lower inflection point formula`),EmptyRange:E(`A range needs to be defined`),ValueCellIsInvalidFormula:E(`At least one of the provided values is an invalid formula`),Unexpected:E(`The rule is invalid for an unknown reason`)},ColorScale:E(`Color scale`),IconSet:E(`Icon set`),DataBar:E(`Data bar`)},Ub={Series:E(`Series`),BackgroundColor:E(`Background color`),StackedBarChart:E(`Stacked bar chart`),StackedLineChart:E(`Stacked line chart`),StackedAreaChart:E(`Stacked area chart`),StackedColumnChart:E(`Stacked column chart`),CumulativeData:E(`Cumulative data`),TreatLabelsAsText:E(`Treat labels as text`),AggregatedChart:E(`Aggregate`),Errors:{Unexpected:E(`The chart definition is invalid for an unknown reason`),InvalidDataSet:E(`The dataset is invalid`),InvalidLabelRange:E(`Labels are invalid`),InvalidScorecardKeyValue:E(`The key value is invalid`),InvalidScorecardBaseline:E(`The baseline value is invalid`),InvalidGaugeDataRange:E(`The data range is invalid`),EmptyGaugeRangeMin:E(`A minimum range limit value is needed`),GaugeRangeMinNaN:E(`The minimum range limit value must be a number`),EmptyGaugeRangeMax:E(`A maximum range limit value is needed`),GaugeRangeMaxNaN:E(`The maximum range limit value must be a number`),GaugeLowerInflectionPointNaN:E(`The lower inflection point value must be a number`),GaugeUpperInflectionPointNaN:E(`The upper inflection point value must be a number`)},GeoChart:{ColorScales:{blues:E(`Blues`),cividis:E(`Cividis`),greens:E(`Greens`),greys:E(`Greys`),oranges:E(`Oranges`),purples:E(`Purples`),rainbow:E(`Rainbow`),reds:E(`Reds`),viridis:E(`Viridis`)}}},Wb={Custom:E(`Custom`)},Gb=E(`Merged cells are preventing this operation. Unmerge those cells and try again.`),Kb=E(`The header row of a table can't be moved.`),qb={Errors:{Unexpected:E(`Cannot split the selection for an unknown reason`),NoSplitSeparatorInSelection:E(`There is no match for the selected separator in the selection`),MoreThanOneColumnSelected:E(`Only a selection from a single column can be split`),SplitWillOverwriteContent:E(`Splitting will overwrite existing content`)}},Jb={Errors:{Unexpected:E(`Cannot remove duplicates for an unknown reason`),MoreThanOneRangeSelected:E(`Please select only one range of cells`),EmptyTarget:E(`Please select a range of cells containing values.`),NoColumnsProvided:E(`Please select at latest one column to analyze.`),WillRemoveExistingMerge:E(`This operation is not possible due to a merge. Please remove the merges first than try again.`)}},U={DateIs:{today:E(`today`),yesterday:E(`yesterday`),tomorrow:E(`tomorrow`),lastWeek:E(`in the past week`),lastMonth:E(`in the past month`),lastYear:E(`in the past year`)},DateIsBefore:{today:E(`today`),yesterday:E(`yesterday`),tomorrow:E(`tomorrow`),lastWeek:E(`one week ago`),lastMonth:E(`one month ago`),lastYear:E(`one year ago`)},CriterionError:{notEmptyValue:E(`The value must not be empty`),numberValue:E(`The value must be a number`),dateValue:E(`The value must be a date`),validRange:E(`The value must be a valid range`),validFormula:E(`The formula must be valid`)},Errors:{InvalidRange:E(`The range is invalid.`),InvalidDataValidationCriterionValue:E(`One or more of the provided criteria values are invalid. Please review and correct them.`),InvalidNumberOfCriterionValues:E(`One or more of the provided criteria values are missing.`),Unexpected:E(`The rule is invalid for an unknown reason.`)}},Yb={Errors:{Unexpected:E(`The table zone is invalid for an unknown reason`),TableOverlap:E(`You cannot create overlapping tables.`),NonContinuousTargets:E(`A table can only be created on a continuous selection.`),InvalidRange:E(`The range is invalid`),TargetOutOfSheet:E(`The range is out of the sheet`)},Checkboxes:{hasFilters:E(`Filter button`),headerRow:E(`Header row(s)`),bandedRows:E(`Banded rows`),firstColumn:E(`First column`),lastColumn:E(`Last column`),bandedColumns:E(`Banded columns`),automaticAutofill:E(`Automatically autofill formulas`),totalRow:E(`Total row`),isDynamic:E(`Auto-adjust to formula result`)},Tooltips:{filterWithoutHeader:E(`Cannot have filters without a header row`),isDynamic:E(`For tables based on array formulas only`)}},Xb={labels:{no_calculations:E(`No calculations`),"%_of_grand_total":E(`% of grand total`),"%_of_col_total":E(`% of column total`),"%_of_row_total":E(`% of row total`),"%_of":E(`% of`),"%_of_parent_row_total":E(`% of parent row total`),"%_of_parent_col_total":E(`% of parent column total`),"%_of_parent_total":E(`% of parent total`),difference_from:E(`Difference from`),"%_difference_from":E(`% difference from`),running_total:E(`Running total`),"%_running_total":E(`% Running total`),rank_asc:E(`Rank smallest to largest`),rank_desc:E(`Rank largest to smallest`),index:E(`Index`)},descriptions:{"%_of_grand_total":()=>E(`Displayed as % of grand total`),"%_of_col_total":()=>E(`Displayed as % of column total`),"%_of_row_total":()=>E(`Displayed as % of row total`),"%_of":e=>E(`Displayed as % of "%s"`,e),"%_of_parent_row_total":e=>E(`Displayed as % of parent row total of "%s"`,e),"%_of_parent_col_total":()=>E(`Displayed as % of parent column total`),"%_of_parent_total":e=>E(`Displayed as % of parent "%s" total`,e),difference_from:e=>E(`Displayed as difference from "%s"`,e),"%_difference_from":e=>E(`Displayed as % difference from "%s"`,e),running_total:e=>E(`Displayed as running total based on "%s"`,e),"%_running_total":e=>E(`Displayed as % running total based on "%s"`,e),rank_asc:e=>E(`Displayed as rank from smallest to largest based on "%s"`,e),rank_desc:e=>E(`Displayed as rank largest to smallest based on "%s"`,e),index:()=>E(`Displayed as index`)},documentation:{no_calculations:E(`Displays the value that is entered in the field.`),"%_of_grand_total":E(`Displays values as a percentage of the grand total of all the values or data points in the report.`),"%_of_col_total":E(`Displays all the values in each column or series as a percentage of the total for the column or series.`),"%_of_row_total":E(`Displays the value in each row or category as a percentage of the total for the row or category.`),"%_of":E(`Displays values as a percentage of the value of the Base item in the Base field.`),"%_of_parent_row_total":E(`Calculates values as follows:
17
17
  (value for the item) / (value for the parent item on rows)`),"%_of_parent_col_total":E(`Calculates values as follows:
18
18
  (value for the item) / (value for the parent item on columns)`),"%_of_parent_total":E(`Calculates values as follows:
19
19
  (value for the item) / (value for the parent item of the selected Base field)`),difference_from:E(`Displays values as the difference from the value of the Base item in the Base field.`),"%_difference_from":E(`Displays values as the percentage difference from the value of the Base item in the Base field.`),running_total:E(`Displays the value for successive items in the Base field as a running total.`),"%_running_total":E(`Calculates the value as a percentage for successive items in the Base field that are displayed as a running total.`),rank_asc:E(`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:E(`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:E(`Calculates values as follows:
@@ -1687,7 +1687,7 @@ stores.inject(MyMetaStore, storeInstance);
1687
1687
  border-left: 2px solid ${ye};
1688
1688
  }
1689
1689
  }
1690
- `;var JH=class extends t.Component{static template=`o-spreadsheet-PivotMeasureDisplayPanel`;static props={onCloseSidePanel:Function,pivotId:String,measure:Object};static components={Section:X,Checkbox:bA,RadioSelection:WV};measureDisplayTypeLabels=Xb.labels;measureDisplayDescription=Xb.documentation;store;setup(){this.store=mf(qH,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 YH(e,t){let n=e.getActiveSheetId();return dc(XH(e,t).map(R)).map(t=>({range:e.getRangeFromZone(n,t),noFill:!0,color:v}))}function XH(e,t){let n=[],r=e.getActiveSheetId();for(let i of e.getSheetViewVisibleCols())for(let a of e.getSheetViewVisibleRows()){let o={sheetId:r,col:i,row:a};t===e.getPivotIdFromPosition(o)&&n.push(o)}return n}B`
1690
+ `;var JH=class extends t.Component{static template=`o-spreadsheet-PivotMeasureDisplayPanel`;static props={onCloseSidePanel:Function,pivotId:String,measure:Object};static components={Section:X,Checkbox:bA,RadioSelection:WV};measureDisplayTypeLabels=Xb.labels;measureDisplayDescription=Xb.documentation;store;setup(){this.store=mf(qH,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 YH(e,t){let n=e.getActiveSheetId();return dc(XH(e,t).map(R)).map(t=>({range:e.getRangeFromZone(n,t),noFill:!0,color:v}))}function XH(e,t){let n=[],r=e.getActiveSheetId();for(let i of e.getSheetViewVisibleCols())for(let a of e.getSheetViewVisibleRows()){let o={sheetId:r,col:i,row:a};e.getPivotIdsFromPosition(o).includes(t)&&n.push(o)}return n}B`
1691
1691
  .pivot-defer-update {
1692
1692
  min-height: 40px;
1693
1693
  }
@@ -1752,17 +1752,17 @@ stores.inject(MyMetaStore, storeInstance);
1752
1752
  .add-calculated-measure {
1753
1753
  cursor: pointer;
1754
1754
  }
1755
- `;var sU=class extends t.Component{static template=`o-spreadsheet-PivotLayoutConfigurator`;static components={AddDimensionButton:eU,PivotDimension:tU,PivotDimensionOrder:rU,PivotDimensionGranularity:nU,PivotMeasureEditor:aU,PivotSortSection:oU,PivotCustomGroupsCollapsible:QH};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=(0,t.useRef)(`pivot-dimensions`);dragAndDrop=sA();AGGREGATORS=Cd;composerFocus;isDateOrDatetimeField=kd;setup(){this.composerFocus=z(Sf)}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getDimensionElementsRects(),{columns:r,rows:i}=this.props.definition,a=[...r.map(e=>e.nameWithGranularity),`__rows_title__`,...i.map(e=>e.nameWithGranularity)],o=r.concat(i),s=a.map((e,t)=>({id:e,size:n[t+1].height,position:n[t+1].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:s,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=a.findIndex(t=>t===e);if(n===t)return;let r=[...a];r.splice(n,1),r.splice(t,0,e);let i=r.slice(0,r.indexOf(`__rows_title__`)),s=r.slice(r.indexOf(`__rows_title__`)+1);this.props.onDimensionsUpdated({columns:i.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(C),rows:s.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(C)})}})}getGranularitiesFor(e){return kd(e)?e.type===`date`?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(t.button!==0||t.target.tagName===`SELECT`||t.target.tagName===`INPUT`||this.composerFocus.focusMode!==`inactive`)return;let n=this.getDimensionElementsRects(),{measures:r,columns:i,rows:a}=this.props.definition,o=r.map(e=>e.id),s=3+i.length+a.length,c=o.map((e,t)=>({id:e,size:n[t+s].height,position:n[t+s].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=o.findIndex(t=>t===e);if(n===t)return;let i=[...o];i.splice(n,1),i.splice(t,0,e),this.props.onDimensionsUpdated({measures:i.map(e=>r.find(t=>t.id===e)).filter(C)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{let t=getComputedStyle(e),n=e.getBoundingClientRect();return{x:n.x,y:n.y,width:n.width+parseInt(t.marginLeft||`0`)+parseInt(t.marginRight||`0`),height:n.height+parseInt(t.marginTop||`0`)+parseInt(t.marginBottom||`0`)}})}removeDimension(e){let{columns:t,rows:n}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:n.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){let{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){let{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:`asc`}])})}addRowDimension(e){let{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:`asc`}])})}addMeasureDimension(e){let{measures:t}=this.props.definition,n=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,n),fieldName:e,aggregator:n}])})}updateMeasure(e,t){let{measures:n}=this.props.definition,r={measures:n.map(n=>n.id===e.id?t:n)};this.props.definition.sortedColumn?.measure===e.id&&(r.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(r)}getMeasureId(e,t){let n=e.replaceAll(`'`,``)+(t?`:${t}`:``),r=n,i=2;for(;this.props.definition.measures.some(e=>e.id===r);)r=`${n}:${i}`,i++;return r}getDefaultMeasureAggregator(e){let t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:`count`}addCalculatedMeasure(){let{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,`sum`),fieldName:t,aggregator:`sum`,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:`=0`}}])})}getCustomField(e){return this.env.model.getters.getPivotCoreDefinition(this.props.pivotId).customFields?.[e.nameWithGranularity]}updateOrder(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n)})}updateGranularity(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n)})}getMeasureDescription(e){let t=e.display;if(!t||t.type===`no_calculations`)return``;let n=this.env.model.getters.getPivot(this.props.pivotId),r=[...n.definition.columns,...n.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=r?zd(r):``;return Xb.descriptions[t.type](i)}getHugeDimensionErrorMessage(e){let t=this.env.model.getters.getPivot(this.props.pivotId).getPossibleFieldValues(e);return t.length>100?E(`This dimension contains a lot of values (%s), and might slow down the pivot table.`,t.length):void 0}},cU=class extends t.Component{static template=`o-spreadsheet-PivotTitleSection`;static components={CogWheelMenu:PV,Section:X,TextInput:kV};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:E(`Flip axes`),icon:`o-spreadsheet-Icon.EXCHANGE`,execute:this.props.flipAxis},{name:E(`Duplicate`),icon:`o-spreadsheet-Icon.COPY`,execute:()=>this.duplicatePivot()},{name:E(`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(){let e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),n=this.env.model.dispatch(`DUPLICATE_PIVOT_IN_NEW_SHEET`,{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t}),r;r=n.isSuccessful?E(`Pivot duplicated.`):n.isCancelledBecause(`PivotInError`)?E(`Cannot duplicate a pivot in error.`):E(`Pivot duplication failed.`);let i=n.isSuccessful?`success`:`danger`;this.env.notifyUser({text:r,sticky:!1,type:i}),n.isSuccessful&&this.env.openSidePanel(`PivotSidePanel`,{pivotId:e})}delete(){this.env.askConfirmation(E(`Are you sure you want to delete this pivot?`),()=>{this.env.model.dispatch(`REMOVE_PIVOT`,{pivotId:this.props.pivotId})})}onNameChanged(e){let t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.props.pivotId,pivot:{...t,name:e}})}};let lU=[`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`];function uU(e,t){let n=`"${t?`${e.name}:${t}`:e.name}"`,r=e.string===e.name?n:e.string+n;return{text:n,description:e.string+(e.help?` (${e.help})`:``),htmlContent:[{value:n,color:ot.STRING}],fuzzySearchKey:r}}function dU(e){let t=`"${e.id}"`,n=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:ot.STRING}],fuzzySearchKey:n}}function fU(e,t){let n=e.end,r=e.end;e.type!==`ARG_SEPARATOR`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}function pU(e,t){let n=e.end,r=e.end;e.type!==`LEFT_PAREN`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}function mU(e){let t=e.functionContext?.args[0];if(!(!t||![`STRING`,`NUMBER`].includes(t.type)))return t.value}function hU(e){return fC(e,lU)[0]}function gU(e){return fC(e,lU).length}var _U=class extends bf{pivotId;mutators=[`reset`,`deferUpdates`,`applyUpdate`,`discardPendingUpdate`,`update`];updatesAreDeferred;draft=null;notification=this.get(qk);alreadyNotified=!1;alreadyNotifiedForPivotSize=!1;constructor(e,t){super(e),this.pivotId=t,this.updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){switch(e.type){case`UPDATE_PIVOT`:e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){let e=vR.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){let e=[{name:`__count`,string:E(`Count`),type:`integer`,aggregator:`sum`}],t=this.fields;for(let n in t){let r=t[n];r&&vR.get(this.pivot.type).isMeasureCandidate(r)&&e.push(r)}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){let e=[],t=this.fields;for(let n in t){let r=t[n];r&&vR.get(this.pivot.type).isGroupable(r)&&e.push(r)}let{columns:n,rows:r,measures:i}=this.definition,a=i.concat(r).concat(n).map(e=>e.fieldName),o=this.unusedGranularities;return e.filter(e=>kd(e)?!a.includes(e.name)||o[e.name].size>0:!a.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return vR.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return vR.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this.updatesAreDeferred=!0,this.draft=null}deferUpdates(e){e===!1&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this.updatesAreDeferred=e}applyUpdate(){if(this.draft){if(this.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot()){let e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:`info`,text:E(`Pivot updates only work with dynamic pivot tables. Use the formula '%s' or re-insert the static pivot from the Data menu.`,e),sticky:!0})}let e=this.getters.getPivot(this.pivotId),t=e.isValid()?e.getExpandedTableStructure().numberOfCells:0;!this.alreadyNotifiedForPivotSize&&t>5e5&&(this.alreadyNotifiedForPivotSize=!0,this.notification.notifyUser({type:`warning`,text:Zb(t,this.getters.getLocale()),sticky:!0}))}}discardPendingUpdate(){this.draft=null}update(e){let t=this.getters.getPivotCoreDefinition(this.pivotId),n={...t,...this.draft,...e},r={...n,columns:n.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:n.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:n.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display})),sortedColumn:this.shouldKeepSortedColumn(n)?n.sortedColumn:void 0};if(r.collapsedDomains){let{COL:e,ROW:t}=r.collapsedDomains;r.collapsedDomains={COL:e.filter(e=>this.areDomainFieldsValid(e,r.columns)),ROW:t.filter(e=>this.areDomainFieldsValid(e,r.rows))}}if(!this.draft&&w(t,r))return;let i=this.addDefaultDateTimeGranularity(this.fields,r);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0,t=this.getters.getPivotFormulaId(this.pivotId);for(let n of this.getters.getVisibleCellPositions()){let r=this.getters.getCell(n);if(r?.isFormula){let n=hU(r.compiledFormula.tokens),i=n?.args[0]?.value;if(n&&t===i.toString()){if(n.functionName===`PIVOT`)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){let{columns:n,rows:r}=t,i=b(n),a=b(r),o=this.getUnusedGranularities(e,t);for(let t of i.concat(a)){let n=e[t.fieldName]?.type;if((n===`date`||n===`datetime`)&&!t.granularity){let e=o[t.fieldName]?.values().next().value;o[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:a}}getUnusedGranularities(e,t){let{columns:n,rows:r,measures:i}=t,a=n.concat(r).concat(i).filter(t=>{let n=e[t.fieldName]?.type;return n===`date`||n===`datetime`}),o={};for(let t of a)o[t.fieldName]=new Set(e[t.fieldName]?.type===`date`?this.dateGranularities:this.datetimeGranularities);for(let e of a)o[e.fieldName].delete(e.granularity);return o}shouldKeepSortedColumn(e){let{sortedColumn:t}=e;if(!t)return!0;let n=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find(e=>e.id===t.measure)&&w(n.columns,e.columns)}areDomainFieldsValid(e,t){let n=t.map(({fieldName:e,granularity:t})=>e+(t?`:${t}`:``));for(let t=0;t<e.length;t++)if(e[t].field!==n[t])return!1;return!0}},vU=class extends t.Component{static template=`o-spreadsheet-PivotSpreadsheetSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:sU,Section:X,SelectionInput:mA,Checkbox:bA,PivotDeferUpdate:ZH,PivotTitleSection:cU};store;state;pivotSidePanelRef=(0,t.useRef)(`pivotSidePanel`);setup(){this.store=mf(_U,this.props.pivotId),this.state=(0,t.useState)({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return this.store.isDirty&&this.state.rangeHasChanged?!1:this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,`forceSheetReference`)]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;let t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){let{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}};let yU=new g;yU.add(`SPREADSHEET`,{editor:vU});var bU=class extends t.Component{static template=`o-spreadsheet-PivotSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:sU,Section:X};setup(){MH(this)}get sidePanelEditor(){let e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw Error(`pivotId does not correspond to a pivot.`);return yU.get(e.type).editor}get highlights(){return YH(this.env.model.getters,this.props.pivotId)}};B`
1755
+ `;var sU=class extends t.Component{static template=`o-spreadsheet-PivotLayoutConfigurator`;static components={AddDimensionButton:eU,PivotDimension:tU,PivotDimensionOrder:rU,PivotDimensionGranularity:nU,PivotMeasureEditor:aU,PivotSortSection:oU,PivotCustomGroupsCollapsible:QH};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=(0,t.useRef)(`pivot-dimensions`);dragAndDrop=sA();AGGREGATORS=Cd;composerFocus;isDateOrDatetimeField=kd;setup(){this.composerFocus=z(Sf)}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getDimensionElementsRects(),{columns:r,rows:i}=this.props.definition,a=[...r.map(e=>e.nameWithGranularity),`__rows_title__`,...i.map(e=>e.nameWithGranularity)],o=r.concat(i),s=a.map((e,t)=>({id:e,size:n[t+1].height,position:n[t+1].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:s,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=a.findIndex(t=>t===e);if(n===t)return;let r=[...a];r.splice(n,1),r.splice(t,0,e);let i=r.slice(0,r.indexOf(`__rows_title__`)),s=r.slice(r.indexOf(`__rows_title__`)+1);this.props.onDimensionsUpdated({columns:i.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(C),rows:s.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(C)})}})}getGranularitiesFor(e){return kd(e)?e.type===`date`?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(t.button!==0||t.target.tagName===`SELECT`||t.target.tagName===`INPUT`||this.composerFocus.focusMode!==`inactive`)return;let n=this.getDimensionElementsRects(),{measures:r,columns:i,rows:a}=this.props.definition,o=r.map(e=>e.id),s=3+i.length+a.length,c=o.map((e,t)=>({id:e,size:n[t+s].height,position:n[t+s].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=o.findIndex(t=>t===e);if(n===t)return;let i=[...o];i.splice(n,1),i.splice(t,0,e),this.props.onDimensionsUpdated({measures:i.map(e=>r.find(t=>t.id===e)).filter(C)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{let t=getComputedStyle(e),n=e.getBoundingClientRect();return{x:n.x,y:n.y,width:n.width+parseInt(t.marginLeft||`0`)+parseInt(t.marginRight||`0`),height:n.height+parseInt(t.marginTop||`0`)+parseInt(t.marginBottom||`0`)}})}removeDimension(e){let{columns:t,rows:n}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:n.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){let{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){let{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:`asc`}])})}addRowDimension(e){let{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:`asc`}])})}addMeasureDimension(e){let{measures:t}=this.props.definition,n=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,n),fieldName:e,aggregator:n}])})}updateMeasure(e,t){let{measures:n}=this.props.definition,r={measures:n.map(n=>n.id===e.id?t:n)};this.props.definition.sortedColumn?.measure===e.id&&(r.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(r)}getMeasureId(e,t){let n=e.replaceAll(`'`,``)+(t?`:${t}`:``),r=n,i=2;for(;this.props.definition.measures.some(e=>e.id===r);)r=`${n}:${i}`,i++;return r}getDefaultMeasureAggregator(e){let t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:`count`}addCalculatedMeasure(){let{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,`sum`),fieldName:t,aggregator:`sum`,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:`=0`}}])})}getCustomField(e){return this.env.model.getters.getPivotCoreDefinition(this.props.pivotId).customFields?.[e.nameWithGranularity]}updateOrder(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n)})}updateGranularity(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n)})}getMeasureDescription(e){let t=e.display;if(!t||t.type===`no_calculations`)return``;let n=this.env.model.getters.getPivot(this.props.pivotId),r=[...n.definition.columns,...n.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=r?zd(r):``;return Xb.descriptions[t.type](i)}getHugeDimensionErrorMessage(e){let t=this.env.model.getters.getPivot(this.props.pivotId).getPossibleFieldValues(e);return t.length>100?E(`This dimension contains a lot of values (%s), and might slow down the pivot table.`,t.length):void 0}},cU=class extends t.Component{static template=`o-spreadsheet-PivotTitleSection`;static components={CogWheelMenu:PV,Section:X,TextInput:kV};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:E(`Flip axes`),icon:`o-spreadsheet-Icon.EXCHANGE`,execute:this.props.flipAxis},{name:E(`Duplicate`),icon:`o-spreadsheet-Icon.COPY`,execute:()=>this.duplicatePivot()},{name:E(`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(){let e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),n=this.env.model.dispatch(`DUPLICATE_PIVOT_IN_NEW_SHEET`,{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t}),r;r=n.isSuccessful?E(`Pivot duplicated.`):n.isCancelledBecause(`PivotInError`)?E(`Cannot duplicate a pivot in error.`):E(`Pivot duplication failed.`);let i=n.isSuccessful?`success`:`danger`;this.env.notifyUser({text:r,sticky:!1,type:i}),n.isSuccessful&&this.env.openSidePanel(`PivotSidePanel`,{pivotId:e})}delete(){this.env.askConfirmation(E(`Are you sure you want to delete this pivot?`),()=>{this.env.model.dispatch(`REMOVE_PIVOT`,{pivotId:this.props.pivotId})})}onNameChanged(e){let t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.props.pivotId,pivot:{...t,name:e}})}};let lU=[`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`];function uU(e,t){let n=`"${t?`${e.name}:${t}`:e.name}"`,r=e.string===e.name?n:e.string+n;return{text:n,description:e.string+(e.help?` (${e.help})`:``),htmlContent:[{value:n,color:ot.STRING}],fuzzySearchKey:r}}function dU(e){let t=`"${e.id}"`,n=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:ot.STRING}],fuzzySearchKey:n}}function fU(e,t){let n=e.end,r=e.end;e.type!==`ARG_SEPARATOR`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}function pU(e,t){let n=e.end,r=e.end;e.type!==`LEFT_PAREN`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}function mU(e){let t=e.functionContext?.args[0];if(!(!t||![`STRING`,`NUMBER`].includes(t.type)))return t.value}function hU(e){return fC(e,lU)[0]}function gU(e){return fC(e,lU)}function _U(e){return fC(e,lU).length}var vU=class extends bf{pivotId;mutators=[`reset`,`deferUpdates`,`applyUpdate`,`discardPendingUpdate`,`update`];updatesAreDeferred;draft=null;notification=this.get(qk);alreadyNotified=!1;alreadyNotifiedForPivotSize=!1;constructor(e,t){super(e),this.pivotId=t,this.updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){switch(e.type){case`UPDATE_PIVOT`:e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){let e=vR.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){let e=[{name:`__count`,string:E(`Count`),type:`integer`,aggregator:`sum`}],t=this.fields;for(let n in t){let r=t[n];r&&vR.get(this.pivot.type).isMeasureCandidate(r)&&e.push(r)}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){let e=[],t=this.fields;for(let n in t){let r=t[n];r&&vR.get(this.pivot.type).isGroupable(r)&&e.push(r)}let{columns:n,rows:r,measures:i}=this.definition,a=i.concat(r).concat(n).map(e=>e.fieldName),o=this.unusedGranularities;return e.filter(e=>kd(e)?!a.includes(e.name)||o[e.name].size>0:!a.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return vR.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return vR.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this.updatesAreDeferred=!0,this.draft=null}deferUpdates(e){e===!1&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this.updatesAreDeferred=e}applyUpdate(){if(this.draft){if(this.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot()){let e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:`info`,text:E(`Pivot updates only work with dynamic pivot tables. Use the formula '%s' or re-insert the static pivot from the Data menu.`,e),sticky:!0})}let e=this.getters.getPivot(this.pivotId),t=e.isValid()?e.getExpandedTableStructure().numberOfCells:0;!this.alreadyNotifiedForPivotSize&&t>5e5&&(this.alreadyNotifiedForPivotSize=!0,this.notification.notifyUser({type:`warning`,text:Zb(t,this.getters.getLocale()),sticky:!0}))}}discardPendingUpdate(){this.draft=null}update(e){let t=this.getters.getPivotCoreDefinition(this.pivotId),n={...t,...this.draft,...e},r={...n,columns:n.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:n.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:n.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display})),sortedColumn:this.shouldKeepSortedColumn(n)?n.sortedColumn:void 0};if(r.collapsedDomains){let{COL:e,ROW:t}=r.collapsedDomains;r.collapsedDomains={COL:e.filter(e=>this.areDomainFieldsValid(e,r.columns)),ROW:t.filter(e=>this.areDomainFieldsValid(e,r.rows))}}if(!this.draft&&w(t,r))return;let i=this.addDefaultDateTimeGranularity(this.fields,r);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0,t=this.getters.getPivotFormulaId(this.pivotId);for(let n of this.getters.getVisibleCellPositions()){let r=this.getters.getCell(n);if(r?.isFormula){let n=hU(r.compiledFormula.tokens),i=n?.args[0]?.value;if(n&&t===i.toString()){if(n.functionName===`PIVOT`)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){let{columns:n,rows:r}=t,i=b(n),a=b(r),o=this.getUnusedGranularities(e,t);for(let t of i.concat(a)){let n=e[t.fieldName]?.type;if((n===`date`||n===`datetime`)&&!t.granularity){let e=o[t.fieldName]?.values().next().value;o[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:a}}getUnusedGranularities(e,t){let{columns:n,rows:r,measures:i}=t,a=n.concat(r).concat(i).filter(t=>{let n=e[t.fieldName]?.type;return n===`date`||n===`datetime`}),o={};for(let t of a)o[t.fieldName]=new Set(e[t.fieldName]?.type===`date`?this.dateGranularities:this.datetimeGranularities);for(let e of a)o[e.fieldName].delete(e.granularity);return o}shouldKeepSortedColumn(e){let{sortedColumn:t}=e;if(!t)return!0;let n=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find(e=>e.id===t.measure)&&w(n.columns,e.columns)}areDomainFieldsValid(e,t){let n=t.map(({fieldName:e,granularity:t})=>e+(t?`:${t}`:``));for(let t=0;t<e.length;t++)if(e[t].field!==n[t])return!1;return!0}},yU=class extends t.Component{static template=`o-spreadsheet-PivotSpreadsheetSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:sU,Section:X,SelectionInput:mA,Checkbox:bA,PivotDeferUpdate:ZH,PivotTitleSection:cU};store;state;pivotSidePanelRef=(0,t.useRef)(`pivotSidePanel`);setup(){this.store=mf(vU,this.props.pivotId),this.state=(0,t.useState)({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return this.store.isDirty&&this.state.rangeHasChanged?!1:this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,`forceSheetReference`)]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;let t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){let{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}};let bU=new g;bU.add(`SPREADSHEET`,{editor:yU});var xU=class extends t.Component{static template=`o-spreadsheet-PivotSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:sU,Section:X};setup(){MH(this)}get sidePanelEditor(){let e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw Error(`pivotId does not correspond to a pivot.`);return bU.get(e.type).editor}get highlights(){return YH(this.env.model.getters,this.props.pivotId)}};B`
1756
1756
  .o-checkbox-selection {
1757
1757
  max-height: 300px;
1758
1758
  }
1759
- `;var xU=class extends t.Component{static template=`o-spreadsheet-RemoveDuplicatesPanel`;static components={ValidationMessages:ZB,Section:X,Checkbox:bA};static props={onCloseSidePanel:Function};state=(0,t.useState)({hasHeader:!1,columns:{}});setup(){this.updateColumns(),(0,t.onWillUpdateProps)(()=>this.updateColumns())}toggleHasHeader(){this.state.hasHeader=!this.state.hasHeader}toggleAllColumns(){let e=!this.isEveryColumnSelected;for(let t in this.state.columns)this.state.columns[t]=e}toggleColumn(e){this.state.columns[e]=!this.state.columns[e]}onRemoveDuplicates(){this.env.model.dispatch(`REMOVE_DUPLICATES`,{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()})}getColLabel(e){let t=parseInt(e),n=E(`Column %s`,Yn(t));if(this.state.hasHeader){let e=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone().top,i=this.env.model.getters.getEvaluatedCell({sheetId:e,col:t,row:r});i.type!==`empty`&&(n+=` - ${i.value}`)}return n}get isEveryColumnSelected(){return Object.values(this.state.columns).every(e=>e)}get errorMessages(){let e=this.env.model.canDispatch(`REMOVE_DUPLICATES`,{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()}).reasons,t=new Set;for(let n of e)t.add(Jb.Errors[n]||Jb.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){let e=Us(this.env.model.getters.getSelectedZone());return E(`%(row_count)s rows and %(column_count)s columns selected`,{row_count:e.numberOfRows,column_count:e.numberOfCols})}get canConfirm(){return this.errorMessages.length===0}updateColumns(){let e=this.env.model.getters.getSelectedZone(),t=this.state.columns,n={};for(let r=e.left;r<=e.right;r++)n[r]=r in t?t[r]:!0;this.state.columns=n}getColsToAnalyze(){return Object.keys(this.state.columns).filter(e=>this.state.columns[e]).map(e=>parseInt(e))}};B`
1759
+ `;var SU=class extends t.Component{static template=`o-spreadsheet-RemoveDuplicatesPanel`;static components={ValidationMessages:ZB,Section:X,Checkbox:bA};static props={onCloseSidePanel:Function};state=(0,t.useState)({hasHeader:!1,columns:{}});setup(){this.updateColumns(),(0,t.onWillUpdateProps)(()=>this.updateColumns())}toggleHasHeader(){this.state.hasHeader=!this.state.hasHeader}toggleAllColumns(){let e=!this.isEveryColumnSelected;for(let t in this.state.columns)this.state.columns[t]=e}toggleColumn(e){this.state.columns[e]=!this.state.columns[e]}onRemoveDuplicates(){this.env.model.dispatch(`REMOVE_DUPLICATES`,{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()})}getColLabel(e){let t=parseInt(e),n=E(`Column %s`,Yn(t));if(this.state.hasHeader){let e=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone().top,i=this.env.model.getters.getEvaluatedCell({sheetId:e,col:t,row:r});i.type!==`empty`&&(n+=` - ${i.value}`)}return n}get isEveryColumnSelected(){return Object.values(this.state.columns).every(e=>e)}get errorMessages(){let e=this.env.model.canDispatch(`REMOVE_DUPLICATES`,{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()}).reasons,t=new Set;for(let n of e)t.add(Jb.Errors[n]||Jb.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){let e=Us(this.env.model.getters.getSelectedZone());return E(`%(row_count)s rows and %(column_count)s columns selected`,{row_count:e.numberOfRows,column_count:e.numberOfCols})}get canConfirm(){return this.errorMessages.length===0}updateColumns(){let e=this.env.model.getters.getSelectedZone(),t=this.state.columns,n={};for(let r=e.left;r<=e.right;r++)n[r]=r in t?t[r]:!0;this.state.columns=n}getColsToAnalyze(){return Object.keys(this.state.columns).filter(e=>this.state.columns[e]).map(e=>parseInt(e))}};B`
1760
1760
  .o-locale-preview {
1761
1761
  border: 1px solid ${ye};
1762
1762
  background-color: ${xe};
1763
1763
  }
1764
- `;var SU=class extends t.Component{static template=`o-spreadsheet-SettingsPanel`;static components={Section:X,ValidationMessages:ZB,BadgeSelection:VV};static props={onCloseSidePanel:Function};loadedLocales=[];setup(){(0,t.onWillStart)(()=>this.loadLocales())}onLocaleChange(e){let t=this.loadedLocales.find(t=>t.code===e);t&&this.env.model.dispatch(`UPDATE_LOCALE`,{locale:t})}async loadLocales(){this.loadedLocales=(await this.env.loadLocales()).filter(e=>{let t=uu(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t}).sort((e,t)=>e.name.localeCompare(t.name))}get numberFormatPreview(){return L(1234567.89,{format:`#,##0.00`,locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){let e=this.env.model.getters.getLocale();return L(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){let e=this.env.model.getters.getLocale();return L(1.6,{format:Du(e),locale:e})}get firstDayOfWeek(){return _o[this.env.model.getters.getLocale().weekStart%7]}get currentLocale(){return this.env.model.getters.getLocale()}get supportedLocales(){let e=this.currentLocale,t=this.loadedLocales.find(t=>t.code===e.code);if(!t)return[...this.loadedLocales,e].sort((e,t)=>e.name.localeCompare(t.name));if(!w(e,t)){let n=this.loadedLocales.indexOf(t),r=[...this.loadedLocales];return r[n]=e,r.sort((e,t)=>e.name.localeCompare(t.name)),r}return this.loadedLocales}};let CU={SplitIsDestructive:E(`This will overwrite data in the subsequent columns. Split anyway?`)};function wU(e,t,n){let r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n});return r.isCancelledBecause(`SplitWillOverwriteContent`)&&e.askConfirmation(CU.SplitIsDestructive,()=>{r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n,force:!0})}),r}let TU=[{name:E(`Detect automatically`),value:`auto`},{name:E(`Custom separator`),value:`custom`},{name:E(`Space`),value:` `},{name:E(`Comma`),value:`,`},{name:E(`Semicolon`),value:`;`},{name:E(`Line Break`),value:`
1765
- `}];var EU=class extends t.Component{static template=`o-spreadsheet-SplitIntoColumnsPanel`;static components={ValidationMessages:ZB,Section:X,Checkbox:bA};static props={onCloseSidePanel:Function};state=(0,t.useState)({separatorValue:`auto`,addNewColumns:!1,customSeparator:``});setup(){let e=z(Sf);(0,t.useEffect)(e=>{e!==`inactive`&&this.props.onCloseSidePanel()},()=>[e.focusMode]),(0,t.onMounted)(()=>{e.activeComposer.stopEdition()})}onSeparatorChange(e){this.state.separatorValue=e}updateCustomSeparator(e){e.target&&(this.state.customSeparator=e.target.value)}updateAddNewColumnsCheckbox(e){this.state.addNewColumns=e}confirm(){wU(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){let e=this.env.model.canDispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(let n of e)switch(n){case`SplitWillOverwriteContent`:case`EmptySplitSeparator`:break;default:t.add(qb.Errors[n]||qb.Errors.Unexpected)}return Array.from(t)}get warningMessages(){let e=[];return this.env.model.canDispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes(`SplitWillOverwriteContent`)&&e.push(qb.Errors.SplitWillOverwriteContent),e}get separatorValue(){return this.state.separatorValue===`custom`?this.state.customSeparator:this.state.separatorValue===`auto`?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return TU}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}};function DU(e,t){return e.model.getters.isTableStyleEditable(t)?f([{id:`editTableStyle`,name:E(`Edit table style`),execute:e=>e.openSidePanel(`TableStyleEditorPanel`,{styleId:t}),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.EDIT`},{id:`deleteTableStyle`,name:E(`Delete table style`),execute:e=>e.model.dispatch(`REMOVE_TABLE_STYLE`,{tableStyleId:t}),icon:`o-spreadsheet-Icon.TRASH`}]):[]}function OU(e,t,n,r){e.resetTransform(),kU(e,t,n,r),AU(e,t,n,r),jU(e,t,n,r)}function kU(e,t,n,r){e.save();for(let i=0;i<5;i++)for(let a=0;a<5;a++)e.fillStyle=t.styles[i][a].fillColor||`#fff`,e.fillRect(i*n,a*r,n,r);e.restore()}function AU(e,t,n,r){e.save(),e.translate(0,.5),e.lineWidth=1;for(let i=0;i<5;i++)for(let a=0;a<5;a++){let o=t.borders[i][a];o.top&&(e.strokeStyle=o.top.color,e.beginPath(),e.moveTo(i*n,a*r),e.lineTo(i*n+n,a*r),e.stroke()),o.bottom&&(e.strokeStyle=o.bottom.color,e.beginPath(),e.moveTo(i*n,a*r+r),e.lineTo(i*n+n,a*r+r),e.stroke())}e.resetTransform(),e.translate(.5,0);for(let i=0;i<5;i++)for(let a=0;a<5;a++){let o=t.borders[i][a];o.left&&(e.strokeStyle=o.left.color,e.beginPath(),e.moveTo(i*n,a*r),e.lineTo(i*n,a*r+r),e.stroke()),o.right&&(e.strokeStyle=o.right.color,e.beginPath(),e.moveTo(i*n+n,a*r),e.lineTo(i*n+n,a*r+r+1),e.stroke())}e.restore()}function jU(e,t,n,r){e.save(),e.translate(0,.5),e.lineWidth=1;let i=Math.floor(n/4),a=Math.floor(r/2);for(let o=0;o<5;o++)for(let s=0;s<5;s++)e.strokeStyle=t.styles[o][s].textColor||`#000`,e.beginPath(),e.moveTo(o*n+i+1,s*r+a),e.lineTo(o*n+n-i,s*r+a),e.stroke();e.restore()}B`
1764
+ `;var CU=class extends t.Component{static template=`o-spreadsheet-SettingsPanel`;static components={Section:X,ValidationMessages:ZB,BadgeSelection:VV};static props={onCloseSidePanel:Function};loadedLocales=[];setup(){(0,t.onWillStart)(()=>this.loadLocales())}onLocaleChange(e){let t=this.loadedLocales.find(t=>t.code===e);t&&this.env.model.dispatch(`UPDATE_LOCALE`,{locale:t})}async loadLocales(){this.loadedLocales=(await this.env.loadLocales()).filter(e=>{let t=uu(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t}).sort((e,t)=>e.name.localeCompare(t.name))}get numberFormatPreview(){return L(1234567.89,{format:`#,##0.00`,locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){let e=this.env.model.getters.getLocale();return L(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){let e=this.env.model.getters.getLocale();return L(1.6,{format:Du(e),locale:e})}get firstDayOfWeek(){return _o[this.env.model.getters.getLocale().weekStart%7]}get currentLocale(){return this.env.model.getters.getLocale()}get supportedLocales(){let e=this.currentLocale,t=this.loadedLocales.find(t=>t.code===e.code);if(!t)return[...this.loadedLocales,e].sort((e,t)=>e.name.localeCompare(t.name));if(!w(e,t)){let n=this.loadedLocales.indexOf(t),r=[...this.loadedLocales];return r[n]=e,r.sort((e,t)=>e.name.localeCompare(t.name)),r}return this.loadedLocales}};let wU={SplitIsDestructive:E(`This will overwrite data in the subsequent columns. Split anyway?`)};function TU(e,t,n){let r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n});return r.isCancelledBecause(`SplitWillOverwriteContent`)&&e.askConfirmation(wU.SplitIsDestructive,()=>{r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n,force:!0})}),r}let EU=[{name:E(`Detect automatically`),value:`auto`},{name:E(`Custom separator`),value:`custom`},{name:E(`Space`),value:` `},{name:E(`Comma`),value:`,`},{name:E(`Semicolon`),value:`;`},{name:E(`Line Break`),value:`
1765
+ `}];var DU=class extends t.Component{static template=`o-spreadsheet-SplitIntoColumnsPanel`;static components={ValidationMessages:ZB,Section:X,Checkbox:bA};static props={onCloseSidePanel:Function};state=(0,t.useState)({separatorValue:`auto`,addNewColumns:!1,customSeparator:``});setup(){let e=z(Sf);(0,t.useEffect)(e=>{e!==`inactive`&&this.props.onCloseSidePanel()},()=>[e.focusMode]),(0,t.onMounted)(()=>{e.activeComposer.stopEdition()})}onSeparatorChange(e){this.state.separatorValue=e}updateCustomSeparator(e){e.target&&(this.state.customSeparator=e.target.value)}updateAddNewColumnsCheckbox(e){this.state.addNewColumns=e}confirm(){TU(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){let e=this.env.model.canDispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(let n of e)switch(n){case`SplitWillOverwriteContent`:case`EmptySplitSeparator`:break;default:t.add(qb.Errors[n]||qb.Errors.Unexpected)}return Array.from(t)}get warningMessages(){let e=[];return this.env.model.canDispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes(`SplitWillOverwriteContent`)&&e.push(qb.Errors.SplitWillOverwriteContent),e}get separatorValue(){return this.state.separatorValue===`custom`?this.state.customSeparator:this.state.separatorValue===`auto`?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return EU}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}};function OU(e,t){return e.model.getters.isTableStyleEditable(t)?f([{id:`editTableStyle`,name:E(`Edit table style`),execute:e=>e.openSidePanel(`TableStyleEditorPanel`,{styleId:t}),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.EDIT`},{id:`deleteTableStyle`,name:E(`Delete table style`),execute:e=>e.model.dispatch(`REMOVE_TABLE_STYLE`,{tableStyleId:t}),icon:`o-spreadsheet-Icon.TRASH`}]):[]}function kU(e,t,n,r){e.resetTransform(),AU(e,t,n,r),jU(e,t,n,r),MU(e,t,n,r)}function AU(e,t,n,r){e.save();for(let i=0;i<5;i++)for(let a=0;a<5;a++)e.fillStyle=t.styles[i][a].fillColor||`#fff`,e.fillRect(i*n,a*r,n,r);e.restore()}function jU(e,t,n,r){e.save(),e.translate(0,.5),e.lineWidth=1;for(let i=0;i<5;i++)for(let a=0;a<5;a++){let o=t.borders[i][a];o.top&&(e.strokeStyle=o.top.color,e.beginPath(),e.moveTo(i*n,a*r),e.lineTo(i*n+n,a*r),e.stroke()),o.bottom&&(e.strokeStyle=o.bottom.color,e.beginPath(),e.moveTo(i*n,a*r+r),e.lineTo(i*n+n,a*r+r),e.stroke())}e.resetTransform(),e.translate(.5,0);for(let i=0;i<5;i++)for(let a=0;a<5;a++){let o=t.borders[i][a];o.left&&(e.strokeStyle=o.left.color,e.beginPath(),e.moveTo(i*n,a*r),e.lineTo(i*n,a*r+r),e.stroke()),o.right&&(e.strokeStyle=o.right.color,e.beginPath(),e.moveTo(i*n+n,a*r),e.lineTo(i*n+n,a*r+r+1),e.stroke())}e.restore()}function MU(e,t,n,r){e.save(),e.translate(0,.5),e.lineWidth=1;let i=Math.floor(n/4),a=Math.floor(r/2);for(let o=0;o<5;o++)for(let s=0;s<5;s++)e.strokeStyle=t.styles[o][s].textColor||`#000`,e.beginPath(),e.moveTo(o*n+i+1,s*r+a),e.lineTo(o*n+n-i,s*r+a),e.stroke();e.restore()}B`
1766
1766
  .o-table-style-list-item {
1767
1767
  border: 1px solid transparent;
1768
1768
  border-radius: 4px;
@@ -1789,7 +1789,7 @@ stores.inject(MyMetaStore, storeInstance);
1789
1789
  }
1790
1790
  }
1791
1791
  }
1792
- `;var MU=class extends t.Component{static template=`o-spreadsheet-TableStylePreview`;static components={MenuPopover:ck};static props={tableConfig:Object,tableStyle:Object,class:String,styleId:{type:String,optional:!0},selected:{type:Boolean,optional:!0},onClick:{type:Function,optional:!0}};canvasRef=(0,t.useRef)(`canvas`);menu=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});setup(){(0,t.onWillUpdateProps)(e=>{(!w(this.props.tableConfig,e.tableConfig)||!w(this.props.tableStyle,e.tableStyle))&&this.drawTable(e)}),(0,t.onMounted)(()=>this.drawTable(this.props))}drawTable(e){let t=this.canvasRef.el.getContext(`2d`),{width:n,height:r}=this.canvasRef.el.getBoundingClientRect();this.canvasRef.el.width=n,this.canvasRef.el.height=r,OU(t,vI(e.tableConfig,e.tableStyle,5,5),(n-1)/5,(r-1)/5)}onContextMenu(e){this.props.styleId&&(this.menu.menuItems=DU(this.env,this.props.styleId),this.menu.isOpen=!0,this.menu.anchorRect={x:e.clientX,y:e.clientY,width:0,height:0})}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get styleName(){return this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId).displayName:``}get isStyleEditable(){return this.props.styleId?this.env.model.getters.isTableStyleEditable(this.props.styleId):!1}editTableStyle(){this.env.openSidePanel(`TableStyleEditorPanel`,{styleId:this.props.styleId})}};B`
1792
+ `;var NU=class extends t.Component{static template=`o-spreadsheet-TableStylePreview`;static components={MenuPopover:ck};static props={tableConfig:Object,tableStyle:Object,class:String,styleId:{type:String,optional:!0},selected:{type:Boolean,optional:!0},onClick:{type:Function,optional:!0}};canvasRef=(0,t.useRef)(`canvas`);menu=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});setup(){(0,t.onWillUpdateProps)(e=>{(!w(this.props.tableConfig,e.tableConfig)||!w(this.props.tableStyle,e.tableStyle))&&this.drawTable(e)}),(0,t.onMounted)(()=>this.drawTable(this.props))}drawTable(e){let t=this.canvasRef.el.getContext(`2d`),{width:n,height:r}=this.canvasRef.el.getBoundingClientRect();this.canvasRef.el.width=n,this.canvasRef.el.height=r,kU(t,vI(e.tableConfig,e.tableStyle,5,5),(n-1)/5,(r-1)/5)}onContextMenu(e){this.props.styleId&&(this.menu.menuItems=OU(this.env,this.props.styleId),this.menu.isOpen=!0,this.menu.anchorRect={x:e.clientX,y:e.clientY,width:0,height:0})}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get styleName(){return this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId).displayName:``}get isStyleEditable(){return this.props.styleId?this.env.model.getters.isTableStyleEditable(this.props.styleId):!1}editTableStyle(){this.env.openSidePanel(`TableStyleEditorPanel`,{styleId:this.props.styleId})}};B`
1793
1793
  .o-table-style-popover {
1794
1794
  /* 7 tables preview + padding by line */
1795
1795
  width: calc((66px + 4px * 2) * 7 + 1.5rem * 2);
@@ -1834,7 +1834,7 @@ stores.inject(MyMetaStore, storeInstance);
1834
1834
  }
1835
1835
  }
1836
1836
  }
1837
- `;var NU=class extends t.Component{static template=`o-spreadsheet-TableStylesPopover`;static components={Popover:ik,TableStylePreview:MU};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0}};categories=ZA;tableStyleListRef=(0,t.useRef)(`tableStyleList`);state=(0,t.useState)({selectedCategory:this.initialSelectedCategory});setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!Kw(this.tableStyleListRef.el,e)&&(this.props.closePopover(),e.hasClosedTableStylesPopover=!0)}get displayedStyles(){let 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})}};B`
1837
+ `;var PU=class extends t.Component{static template=`o-spreadsheet-TableStylesPopover`;static components={Popover:ik,TableStylePreview:NU};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0}};categories=ZA;tableStyleListRef=(0,t.useRef)(`tableStyleList`);state=(0,t.useState)({selectedCategory:this.initialSelectedCategory});setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!Kw(this.tableStyleListRef.el,e)&&(this.props.closePopover(),e.hasClosedTableStylesPopover=!0)}get displayedStyles(){let 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})}};B`
1838
1838
  .o-table-style-picker {
1839
1839
  border: 1px solid ${ye};
1840
1840
  border-radius: 3px;
@@ -1858,7 +1858,7 @@ stores.inject(MyMetaStore, storeInstance);
1858
1858
  }
1859
1859
  }
1860
1860
  }
1861
- `;var PU=class extends t.Component{static template=`o-spreadsheet-TableStylePicker`;static components={TableStylesPopover:NU,TableStylePreview:MU};static props={table:Object};state=(0,t.useState)({popoverProps:void 0});getDisplayedTableStyles(){let e=this.env.model.getters.getTableStyles(),t=e[this.props.table.config.styleId].category,n=Object.keys(e).filter(n=>e[n].category===t),r=n.indexOf(this.props.table.config.styleId);if(r===-1)return r;let i=Math.floor(r/4)*4;return n.slice(i)}onStylePicked(e){let t=this.env.model.getters.getActiveSheetId();this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,config:{styleId:e}}),this.closePopover()}onArrowButtonClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps){this.closePopover();return}let{bottom:t,right:n}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`top-right`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}};B`
1861
+ `;var FU=class extends t.Component{static template=`o-spreadsheet-TableStylePicker`;static components={TableStylesPopover:PU,TableStylePreview:NU};static props={table:Object};state=(0,t.useState)({popoverProps:void 0});getDisplayedTableStyles(){let e=this.env.model.getters.getTableStyles(),t=e[this.props.table.config.styleId].category,n=Object.keys(e).filter(n=>e[n].category===t),r=n.indexOf(this.props.table.config.styleId);if(r===-1)return r;let i=Math.floor(r/4)*4;return n.slice(i)}onStylePicked(e){let t=this.env.model.getters.getActiveSheetId();this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,config:{styleId:e}}),this.closePopover()}onArrowButtonClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps){this.closePopover();return}let{bottom:t,right:n}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`top-right`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}};B`
1862
1862
  .o-table-panel {
1863
1863
  input.o-table-n-of-headers {
1864
1864
  width: 14px;
@@ -1870,7 +1870,7 @@ stores.inject(MyMetaStore, storeInstance);
1870
1870
  height: 14px;
1871
1871
  }
1872
1872
  }
1873
- `;var FU=class extends t.Component{static template=`o-spreadsheet-TablePanel`;static components={TableStylePicker:PU,SelectionInput:mA,ValidationMessages:ZB,Checkbox:bA,Section:X};static props={onCloseSidePanel:Function,table:Object};state;setup(){let e=this.env.model.getters.getActiveSheetId();this.state=(0,t.useState)({tableZoneErrors:[],tableXc:this.env.model.getters.getRangeString(this.props.table.range,e),filtersEnabledIfPossible:this.props.table.config.hasFilters})}updateHasFilters(e){this.state.filtersEnabledIfPossible=e,this.updateTableConfig(`hasFilters`,e)}updateTableConfig(e,t){let n=this.env.model.getters.getActiveSheetId();return this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:n,zone:this.props.table.range.zone,config:{[e]:t}})}updateHasHeaders(e){let t=+!!e;this.updateNumberOfHeaders(t)}updateTableIsDynamic(e){let t=e?`dynamic`:`forceStatic`;if(t===this.props.table.type)return;let n=this.env.model.getters.getTable(hI(this.props.table));if(!n)return;let r=this.env.model.getters.getActiveSheetId(),i=this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:r,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(n.range),tableType:t}),a=this.env.model.getters.getCoreTable(hI(this.props.table));if(i.isSuccessful&&a){let e=a.range;this.state.tableXc=this.env.model.getters.getRangeString(e,r),this.state.tableZoneErrors=[]}}onChangeNumberOfHeaders(e){let t=e.target,n=parseInt(t.value);this.updateNumberOfHeaders(n).isSuccessful||(t.value=this.props.table.config.numberOfHeaders.toString())}updateNumberOfHeaders(e){let t=e>0&&(this.tableConfig.hasFilters||this.state.filtersEnabledIfPossible);return this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:this.env.model.getters.getActiveSheetId(),zone:this.props.table.range.zone,config:{numberOfHeaders:e,hasFilters:t}})}onRangeChanged(e){let t=this.env.model.getters.getActiveSheetId();this.state.tableXc=e[0];let n=this.env.model.getters.getRangeFromSheetXC(t,this.state.tableXc);this.state.tableZoneErrors=this.env.model.canDispatch(`UPDATE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromXc(t,this.state.tableXc),tableType:this.getNewTableType(n.zone)}).reasons}onRangeConfirmed(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getRangeFromSheetXC(e,this.state.tableXc);if(nc(t.zone)===1){let n=this.env.model.getters.getContiguousZone(e,t.zone);t=this.env.model.getters.getRangeFromZone(e,n)}let n=t.zone,r=this.props.table.range.zone,i=n.top===r.top&&n.left===r.left?`RESIZE_TABLE`:`UPDATE_TABLE`,a=this.env.model.dispatch(i,{sheetId:e,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(t),tableType:this.getNewTableType(t.zone)}),o={sheetId:e,col:t.zone.left,row:t.zone.top},s=this.env.model.getters.getCoreTable(o);if(a.isSuccessful&&s){let t=hI(s);this.env.model.selection.selectZone({zone:R(t),cell:t});let n=s.range;this.state.tableXc=this.env.model.getters.getRangeString(n,e)}}deleteTable(){let e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch(`REMOVE_TABLE`,{sheetId:e,target:[this.props.table.range.zone]})}getNewTableType(e){if(this.props.table.type===`forceStatic`)return`forceStatic`;let t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.canCreateDynamicTableOnZones(t,[e])?`dynamic`:`static`}get tableConfig(){return this.props.table.config}get errorMessages(){return(this.state.tableZoneErrors||[]).map(e=>Yb.Errors[e]||Yb.Errors.Unexpected)}getCheckboxLabel(e){return Yb.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:Yb.Tooltips.filterWithoutHeader}get canBeDynamic(){let e=this.env.model.getters.getActiveSheetId();return this.props.table.type===`dynamic`||this.env.model.getters.canCreateDynamicTableOnZones(e,[this.props.table.range.zone])}get dynamicTableTooltip(){return Yb.Tooltips.isDynamic}};B`
1873
+ `;var IU=class extends t.Component{static template=`o-spreadsheet-TablePanel`;static components={TableStylePicker:FU,SelectionInput:mA,ValidationMessages:ZB,Checkbox:bA,Section:X};static props={onCloseSidePanel:Function,table:Object};state;setup(){let e=this.env.model.getters.getActiveSheetId();this.state=(0,t.useState)({tableZoneErrors:[],tableXc:this.env.model.getters.getRangeString(this.props.table.range,e),filtersEnabledIfPossible:this.props.table.config.hasFilters})}updateHasFilters(e){this.state.filtersEnabledIfPossible=e,this.updateTableConfig(`hasFilters`,e)}updateTableConfig(e,t){let n=this.env.model.getters.getActiveSheetId();return this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:n,zone:this.props.table.range.zone,config:{[e]:t}})}updateHasHeaders(e){let t=+!!e;this.updateNumberOfHeaders(t)}updateTableIsDynamic(e){let t=e?`dynamic`:`forceStatic`;if(t===this.props.table.type)return;let n=this.env.model.getters.getTable(hI(this.props.table));if(!n)return;let r=this.env.model.getters.getActiveSheetId(),i=this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:r,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(n.range),tableType:t}),a=this.env.model.getters.getCoreTable(hI(this.props.table));if(i.isSuccessful&&a){let e=a.range;this.state.tableXc=this.env.model.getters.getRangeString(e,r),this.state.tableZoneErrors=[]}}onChangeNumberOfHeaders(e){let t=e.target,n=parseInt(t.value);this.updateNumberOfHeaders(n).isSuccessful||(t.value=this.props.table.config.numberOfHeaders.toString())}updateNumberOfHeaders(e){let t=e>0&&(this.tableConfig.hasFilters||this.state.filtersEnabledIfPossible);return this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:this.env.model.getters.getActiveSheetId(),zone:this.props.table.range.zone,config:{numberOfHeaders:e,hasFilters:t}})}onRangeChanged(e){let t=this.env.model.getters.getActiveSheetId();this.state.tableXc=e[0];let n=this.env.model.getters.getRangeFromSheetXC(t,this.state.tableXc);this.state.tableZoneErrors=this.env.model.canDispatch(`UPDATE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromXc(t,this.state.tableXc),tableType:this.getNewTableType(n.zone)}).reasons}onRangeConfirmed(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getRangeFromSheetXC(e,this.state.tableXc);if(nc(t.zone)===1){let n=this.env.model.getters.getContiguousZone(e,t.zone);t=this.env.model.getters.getRangeFromZone(e,n)}let n=t.zone,r=this.props.table.range.zone,i=n.top===r.top&&n.left===r.left?`RESIZE_TABLE`:`UPDATE_TABLE`,a=this.env.model.dispatch(i,{sheetId:e,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(t),tableType:this.getNewTableType(t.zone)}),o={sheetId:e,col:t.zone.left,row:t.zone.top},s=this.env.model.getters.getCoreTable(o);if(a.isSuccessful&&s){let t=hI(s);this.env.model.selection.selectZone({zone:R(t),cell:t});let n=s.range;this.state.tableXc=this.env.model.getters.getRangeString(n,e)}}deleteTable(){let e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch(`REMOVE_TABLE`,{sheetId:e,target:[this.props.table.range.zone]})}getNewTableType(e){if(this.props.table.type===`forceStatic`)return`forceStatic`;let t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.canCreateDynamicTableOnZones(t,[e])?`dynamic`:`static`}get tableConfig(){return this.props.table.config}get errorMessages(){return(this.state.tableZoneErrors||[]).map(e=>Yb.Errors[e]||Yb.Errors.Unexpected)}getCheckboxLabel(e){return Yb.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:Yb.Tooltips.filterWithoutHeader}get canBeDynamic(){let e=this.env.model.getters.getActiveSheetId();return this.props.table.type===`dynamic`||this.env.model.getters.canCreateDynamicTableOnZones(e,[this.props.table.range.zone])}get dynamicTableTooltip(){return Yb.Tooltips.isDynamic}};B`
1874
1874
  .o-table-style-editor-panel {
1875
1875
  .o-table-style-list-item {
1876
1876
  margin: 2px 7px;
@@ -1882,15 +1882,15 @@ stores.inject(MyMetaStore, storeInstance);
1882
1882
  }
1883
1883
  }
1884
1884
  }
1885
- `;let IU=`#3C78D8`;var LU=class extends t.Component{static template=`o-spreadsheet-TableStyleEditorPanel`;static components={Section:X,RoundColorPicker:aA,TableStylePreview:MU};static props={onCloseSidePanel:Function,onStylePicked:{type:Function,optional:!0},styleId:{type:String,optional:!0}};state=(0,t.useState)(this.getInitialState());setup(){(0,t.useExternalListener)(window,`click`,()=>this.state.pickerOpened=!1)}getInitialState(){let e=this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId):null;return{pickerOpened:!1,primaryColor:e?.primaryColor||IU,selectedTemplateName:e?.templateName||`lightColoredText`,styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=mn(e)?e:IU,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){let e=this.props.styleId||this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch(`CREATE_TABLE_STYLE`,{tableStyleId:e,tableStyleName:this.state.styleName,templateName:this.state.selectedTemplateName,primaryColor:this.state.primaryColor}),this.props.onStylePicked?.(e),this.props.onCloseSidePanel()}onCancel(){this.props.onCloseSidePanel()}onDelete(){this.props.styleId&&(this.env.model.dispatch(`REMOVE_TABLE_STYLE`,{tableStyleId:this.props.styleId}),this.props.onCloseSidePanel())}get colorPreviewStyle(){return V({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(pj).filter(e=>e!==`none`)}get previewTableConfig(){return{bandedColumns:!1,bandedRows:!0,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,totalRow:!0,hasFilters:!0,styleId:``}}get selectedStyle(){return this.computeTableStyle(this.state.selectedTemplateName)}computeTableStyle(e){return mj(this.state.styleName,e,this.state.primaryColor)}};let RU=new g;RU.add(`ConditionalFormatting`,{title:E(`Conditional formatting`),Body:IH}),RU.add(`ChartPanel`,{title:E(`Chart`),Body:kH,computeState:(e,t)=>{let n=e.getSelectedFigureId(),r=n?e.getChartIdFromFigureId(n):t.chartId;return!r||!e.isChartDefined(r)?{isOpen:!1}:{isOpen:!0,props:{chartId:r}}}}),RU.add(`FindAndReplace`,{title:E(`Find and Replace`),Body:WH}),RU.add(`CustomCurrency`,{title:E(`Custom currency format`),Body:RH}),RU.add(`SplitToColumns`,{title:E(`Split text into columns`),Body:EU}),RU.add(`Settings`,{title:E(`Spreadsheet settings`),Body:SU}),RU.add(`RemoveDuplicates`,{title:E(`Remove duplicates`),Body:xU}),RU.add(`DataValidation`,{title:E(`Data validation`),Body:VH}),RU.add(`DataValidationEditor`,{title:E(`Data validation`),Body:zH}),RU.add(`MoreFormats`,{title:E(`More date formats`),Body:KH}),RU.add(`TableSidePanel`,{title:E(`Edit table`),Body:FU,computeState:e=>{let t=e.getFirstTableInSelection();return t?{isOpen:!0,props:{table:e.getCoreTable(hI(t))},key:t.id}:{isOpen:!1}}}),RU.add(`TableStyleEditorPanel`,{title:E(`Create custom table style`),Body:LU,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??`new`})}),RU.add(`PivotSidePanel`,{title:(e,t)=>E(`Pivot #%s`,e.model.getters.getPivotFormulaId(t.pivotId)),Body:bU,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),RU.add(`PivotMeasureDisplayPanel`,{title:(e,t)=>E(`Measure "%s" options`,e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id).displayName),Body:JH,computeState:(e,t)=>{try{return e.getPivot(t.pivotId).getMeasure(t.measure.id),{isOpen:!0,props:t,key:`pivot_measure_display_${t.pivotId}_${t.measure.id}`}}catch{return{isOpen:!1}}}}),RU.add(`CarouselPanel`,{title:E(`Carousel`),Body:FV,computeState:(e,t)=>{let n=t.figureId||e.getSelectedFigureId();return!n||!e.doesCarouselExist(n)?{isOpen:!1}:{isOpen:!0,props:{figureId:n}}}});var zU=class{mutators=[`setSmallThreshhold`];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}},BU=class extends bf{mutators=[`open`,`replace`,`toggle`,`close`,`changePanelSize`,`resetPanelSize`,`togglePinPanel`,`closeMainPanel`,`changeSpreadsheetWidth`,`toggleCollapsePanel`];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(zU);get isMainPanelOpen(){return this.mainPanel&&this.mainPanel.componentTag?this.computeState(this.mainPanel).isOpen:!1}get isSecondaryPanelOpen(){return this.secondaryPanel&&this.secondaryPanel.componentTag?this.computeState(this.secondaryPanel).isOpen:!1}get mainPanelProps(){return this.mainPanel?this.getPanelProps(this.mainPanel):void 0}get mainPanelKey(){return this.mainPanel?this.getPanelKey(this.mainPanel):void 0}get secondaryPanelProps(){return this.secondaryPanel?this.getPanelProps(this.secondaryPanel):void 0}get secondaryPanelKey(){return this.secondaryPanel?this.getPanelKey(this.secondaryPanel):void 0}get totalPanelSize(){return(this.mainPanel?.size||0)+(this.secondaryPanel?.size??0)}getPanelProps(e){let t=this.computeState(e);return t.isOpen?(e.currentPanelProps=t.props??e.currentPanelProps,t.props??{}):{}}getPanelKey(e){let t=this.computeState(e);if(t.isOpen)return t.key}open(e,t={}){if(this.screenWidthStore.isSmall)return;let n={currentPanelProps:t,componentTag:e,size:350},r=this.computeState(n);if(!r.isOpen)return;if(!this.mainPanel||!this.mainPanel.isPinned||this.mainPanelKey===r.key){this._openPanel(`mainPanel`,n,r);return}let i=this.mainPanel.isCollapsed?350:this.mainPanel.size;if(!this.secondaryPanel&&i+350>this.availableWidth){this.get(qk).notifyUser({sticky:!1,type:`warning`,text:E(`The window is too small to display multiple side panels.`)});return}this._openPanel(`secondaryPanel`,n,r)}replace(e,t,n={}){let r={currentPanelProps:n,componentTag:e,size:350},i=this.computeState(r);if(!i.isOpen)return;let a=()=>{this.mainPanel?.isCollapsed&&this.toggleCollapsePanel(`mainPanel`)},o=this.mainPanelKey===i.key,s=this.secondaryPanelKey===i.key;if(o&&this.secondaryPanel){this.close(),a();return}if(s){this.closeMainPanel(),this.togglePinPanel(),a();return}let c=this.mainPanelKey===t?`mainPanel`:`secondaryPanel`;this._openPanel(c,r,i)}_openPanel(e,t,n){let r=this[e];r&&t.componentTag!==r.componentTag&&r.currentPanelProps?.onCloseSidePanel?.(),this[e]={currentPanelProps:n.props??{},componentTag:t.componentTag,size:r?.size||350,isCollapsed:r?.isCollapsed||!1,isPinned:r&&`isPinned`in r?r.isPinned:!1},this[e].isCollapsed&&this.toggleCollapsePanel(e)}toggle(e,t){let n=this.mainPanel?.isPinned?this.secondaryPanel:this.mainPanel;n&&e===n.componentTag?this.close():this.open(e,t)}close(){if(this.mainPanel?.isPinned){this.secondaryPanel&&=(this.secondaryPanel.currentPanelProps.onCloseSidePanel?.(),void 0);return}this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=void 0}closeMainPanel(){this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel||void 0,this.secondaryPanel=void 0}changePanelSize(e,t){let n=this[e];if(!n||`isCollapsed`in n&&n.isCollapsed)return;t=Math.max(t,350);let r=e===`mainPanel`?this.secondaryPanel?.size||0:this.mainPanel?.size||0;t>this.availableWidth-r&&(e===`mainPanel`&&this.secondaryPanel&&(this.secondaryPanel.size=Math.max(this.availableWidth-t,350),r=this.secondaryPanel.size),t=Math.max(this.availableWidth-r,350)),n.size=t}resetPanelSize(e){this[e]&&(this[e].size=350)}togglePinPanel(){this.mainPanel&&(this.mainPanel.isPinned=!this.mainPanel.isPinned,!this.mainPanel.isPinned&&this.secondaryPanel&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel,this.secondaryPanel=void 0))}toggleCollapsePanel(e){let t=this[e];t&&(t.isCollapsed?(t.isCollapsed=!1,this.changePanelSize(e,350)):(t.isCollapsed=!0,t.size=45))}computeState({componentTag:e,currentPanelProps:t}){let n=RU.get(e).computeState,r=n?n(this.getters,t):{isOpen:!0,props:t};return r.isOpen?{...r,key:r.key||e}:r}changeSpreadsheetWidth(e){this.availableWidth=e-150,this.secondaryPanel&&e-this.totalPanelSize<150&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0),this.mainPanel&&e-this.totalPanelSize<150&&(this.mainPanel.size=Math.max(e-150,350))}};let VU=`#777`;B`
1885
+ `;let LU=`#3C78D8`;var RU=class extends t.Component{static template=`o-spreadsheet-TableStyleEditorPanel`;static components={Section:X,RoundColorPicker:aA,TableStylePreview:NU};static props={onCloseSidePanel:Function,onStylePicked:{type:Function,optional:!0},styleId:{type:String,optional:!0}};state=(0,t.useState)(this.getInitialState());setup(){(0,t.useExternalListener)(window,`click`,()=>this.state.pickerOpened=!1)}getInitialState(){let e=this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId):null;return{pickerOpened:!1,primaryColor:e?.primaryColor||LU,selectedTemplateName:e?.templateName||`lightColoredText`,styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=mn(e)?e:LU,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){let e=this.props.styleId||this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch(`CREATE_TABLE_STYLE`,{tableStyleId:e,tableStyleName:this.state.styleName,templateName:this.state.selectedTemplateName,primaryColor:this.state.primaryColor}),this.props.onStylePicked?.(e),this.props.onCloseSidePanel()}onCancel(){this.props.onCloseSidePanel()}onDelete(){this.props.styleId&&(this.env.model.dispatch(`REMOVE_TABLE_STYLE`,{tableStyleId:this.props.styleId}),this.props.onCloseSidePanel())}get colorPreviewStyle(){return V({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(pj).filter(e=>e!==`none`)}get previewTableConfig(){return{bandedColumns:!1,bandedRows:!0,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,totalRow:!0,hasFilters:!0,styleId:``}}get selectedStyle(){return this.computeTableStyle(this.state.selectedTemplateName)}computeTableStyle(e){return mj(this.state.styleName,e,this.state.primaryColor)}};let zU=new g;zU.add(`ConditionalFormatting`,{title:E(`Conditional formatting`),Body:IH}),zU.add(`ChartPanel`,{title:E(`Chart`),Body:kH,computeState:(e,t)=>{let n=e.getSelectedFigureId(),r=n?e.getChartIdFromFigureId(n):t.chartId;return!r||!e.isChartDefined(r)?{isOpen:!1}:{isOpen:!0,props:{chartId:r}}}}),zU.add(`FindAndReplace`,{title:E(`Find and Replace`),Body:WH}),zU.add(`CustomCurrency`,{title:E(`Custom currency format`),Body:RH}),zU.add(`SplitToColumns`,{title:E(`Split text into columns`),Body:DU}),zU.add(`Settings`,{title:E(`Spreadsheet settings`),Body:CU}),zU.add(`RemoveDuplicates`,{title:E(`Remove duplicates`),Body:SU}),zU.add(`DataValidation`,{title:E(`Data validation`),Body:VH}),zU.add(`DataValidationEditor`,{title:E(`Data validation`),Body:zH}),zU.add(`MoreFormats`,{title:E(`More date formats`),Body:KH}),zU.add(`TableSidePanel`,{title:E(`Edit table`),Body:IU,computeState:e=>{let t=e.getFirstTableInSelection();return t?{isOpen:!0,props:{table:e.getCoreTable(hI(t))},key:t.id}:{isOpen:!1}}}),zU.add(`TableStyleEditorPanel`,{title:E(`Create custom table style`),Body:RU,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??`new`})}),zU.add(`PivotSidePanel`,{title:(e,t)=>E(`Pivot #%s`,e.model.getters.getPivotFormulaId(t.pivotId)),Body:xU,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),zU.add(`PivotMeasureDisplayPanel`,{title:(e,t)=>E(`Measure "%s" options`,e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id).displayName),Body:JH,computeState:(e,t)=>{try{return e.getPivot(t.pivotId).getMeasure(t.measure.id),{isOpen:!0,props:t,key:`pivot_measure_display_${t.pivotId}_${t.measure.id}`}}catch{return{isOpen:!1}}}}),zU.add(`CarouselPanel`,{title:E(`Carousel`),Body:FV,computeState:(e,t)=>{let n=t.figureId||e.getSelectedFigureId();return!n||!e.doesCarouselExist(n)?{isOpen:!1}:{isOpen:!0,props:{figureId:n}}}});var BU=class{mutators=[`setSmallThreshhold`];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}},VU=class extends bf{mutators=[`open`,`replace`,`toggle`,`close`,`changePanelSize`,`resetPanelSize`,`togglePinPanel`,`closeMainPanel`,`changeSpreadsheetWidth`,`toggleCollapsePanel`];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(BU);get isMainPanelOpen(){return this.mainPanel&&this.mainPanel.componentTag?this.computeState(this.mainPanel).isOpen:!1}get isSecondaryPanelOpen(){return this.secondaryPanel&&this.secondaryPanel.componentTag?this.computeState(this.secondaryPanel).isOpen:!1}get mainPanelProps(){return this.mainPanel?this.getPanelProps(this.mainPanel):void 0}get mainPanelKey(){return this.mainPanel?this.getPanelKey(this.mainPanel):void 0}get secondaryPanelProps(){return this.secondaryPanel?this.getPanelProps(this.secondaryPanel):void 0}get secondaryPanelKey(){return this.secondaryPanel?this.getPanelKey(this.secondaryPanel):void 0}get totalPanelSize(){return(this.mainPanel?.size||0)+(this.secondaryPanel?.size??0)}getPanelProps(e){let t=this.computeState(e);return t.isOpen?(e.currentPanelProps=t.props??e.currentPanelProps,t.props??{}):{}}getPanelKey(e){let t=this.computeState(e);if(t.isOpen)return t.key}open(e,t={}){if(this.screenWidthStore.isSmall)return;let n={currentPanelProps:t,componentTag:e,size:350},r=this.computeState(n);if(!r.isOpen)return;if(!this.mainPanel||!this.mainPanel.isPinned||this.mainPanelKey===r.key){this._openPanel(`mainPanel`,n,r);return}let i=this.mainPanel.isCollapsed?350:this.mainPanel.size;if(!this.secondaryPanel&&i+350>this.availableWidth){this.get(qk).notifyUser({sticky:!1,type:`warning`,text:E(`The window is too small to display multiple side panels.`)});return}this._openPanel(`secondaryPanel`,n,r)}replace(e,t,n={}){let r={currentPanelProps:n,componentTag:e,size:350},i=this.computeState(r);if(!i.isOpen)return;let a=()=>{this.mainPanel?.isCollapsed&&this.toggleCollapsePanel(`mainPanel`)},o=this.mainPanelKey===i.key,s=this.secondaryPanelKey===i.key;if(o&&this.secondaryPanel){this.close(),a();return}if(s){this.closeMainPanel(),this.togglePinPanel(),a();return}let c=this.mainPanelKey===t?`mainPanel`:`secondaryPanel`;this._openPanel(c,r,i)}_openPanel(e,t,n){let r=this[e];r&&t.componentTag!==r.componentTag&&r.currentPanelProps?.onCloseSidePanel?.(),this[e]={currentPanelProps:n.props??{},componentTag:t.componentTag,size:r?.size||350,isCollapsed:r?.isCollapsed||!1,isPinned:r&&`isPinned`in r?r.isPinned:!1},this[e].isCollapsed&&this.toggleCollapsePanel(e)}toggle(e,t){let n=this.mainPanel?.isPinned?this.secondaryPanel:this.mainPanel;n&&e===n.componentTag?this.close():this.open(e,t)}close(){if(this.mainPanel?.isPinned){this.secondaryPanel&&=(this.secondaryPanel.currentPanelProps.onCloseSidePanel?.(),void 0);return}this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=void 0}closeMainPanel(){this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel||void 0,this.secondaryPanel=void 0}changePanelSize(e,t){let n=this[e];if(!n||`isCollapsed`in n&&n.isCollapsed)return;t=Math.max(t,350);let r=e===`mainPanel`?this.secondaryPanel?.size||0:this.mainPanel?.size||0;t>this.availableWidth-r&&(e===`mainPanel`&&this.secondaryPanel&&(this.secondaryPanel.size=Math.max(this.availableWidth-t,350),r=this.secondaryPanel.size),t=Math.max(this.availableWidth-r,350)),n.size=t}resetPanelSize(e){this[e]&&(this[e].size=350)}togglePinPanel(){this.mainPanel&&(this.mainPanel.isPinned=!this.mainPanel.isPinned,!this.mainPanel.isPinned&&this.secondaryPanel&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel,this.secondaryPanel=void 0))}toggleCollapsePanel(e){let t=this[e];t&&(t.isCollapsed?(t.isCollapsed=!1,this.changePanelSize(e,350)):(t.isCollapsed=!0,t.size=45))}computeState({componentTag:e,currentPanelProps:t}){let n=zU.get(e).computeState,r=n?n(this.getters,t):{isOpen:!0,props:t};return r.isOpen?{...r,key:r.key||e}:r}changeSpreadsheetWidth(e){this.availableWidth=e-150,this.secondaryPanel&&e-this.totalPanelSize<150&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0),this.mainPanel&&e-this.totalPanelSize<150&&(this.mainPanel.size=Math.max(e-150,350))}};let HU=`#777`;B`
1886
1886
  .o-table-resizer {
1887
1887
  width: ${6}px;
1888
1888
  height: ${6}px;
1889
- border-bottom: ${3}px solid ${VU};
1890
- border-right: ${3}px solid ${VU};
1889
+ border-bottom: ${3}px solid ${HU};
1890
+ border-right: ${3}px solid ${HU};
1891
1891
  cursor: nwse-resize;
1892
1892
  }
1893
- `;var HU=class extends t.Component{static template=`o-spreadsheet-TableResizer`;static props={table:Object};state=(0,t.useState)({highlightZone:void 0});dragNDropGrid=pB(this.env);setup(){MH(this)}get containerStyle(){let e=this.props.table.range.zone,t={...e,left:e.right,top:e.bottom},n=this.env.model.getters.getVisibleRect(t);return n.height===0||n.width===0?V({display:`none`}):V({top:`${n.y+n.height-6}px`,left:`${n.x+n.width-6}px`})}onMouseDown(e){let t=this.props.table.range.zone,n={col:t.left,row:t.top};document.body.style.cursor=`nwse-resize`,this.dragNDropGrid.start(e,(e,t,r)=>{this.state.highlightZone={left:n.col,top:n.row,right:Math.max(e,n.col),bottom:Math.max(t,n.row)}},()=>{document.body.style.cursor=``;let e=this.state.highlightZone;if(!e)return;let t=this.props.table.range.sheetId;this.env.model.dispatch(`RESIZE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0})}get highlights(){return this.state.highlightZone?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:VU,noFill:!0}]:[]}};let UU={ROW:uB,COL:rB,CELL:zR,GROUP_HEADERS:cB,UNGROUP_HEADERS:lB};var WU=class extends t.Component{static template=`o-spreadsheet-Grid`;static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:BB,GridOverlay:oV,GridPopover:sV,HeadersOverlay:pV,MenuPopover:ck,Autofill:hB,ClientTag:_B,Highlight:SV,Popover:ik,VerticalScrollBar:EV,HorizontalScrollBar:TV,TableResizer:HU,Selection:DV};HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=pB(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=z(Kk),this.menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=z(hk),this.composerFocusStore=z(Sf),this.DOMFocusableElementStore=z(Dk),this.sidePanel=z(BU),this.paintFormatStore=z(nV),this.clientFocusStore=z(fB),z(dB),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),(0,t.useExternalListener)(document.body,`cut`,this.copy.bind(this,!0)),(0,t.useExternalListener)(document.body,`copy`,this.copy.bind(this,!1)),(0,t.useExternalListener)(document.body,`paste`,this.paste),(0,t.onMounted)(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),hV(`canvas`,this.env.model,()=>this.env.model.getters.getSheetViewDimensionWithHeaders()),this.onMouseWheel=vV((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=z(TA),(0,t.useEffect)((e,t)=>{!e&&!t&&this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),_V(this.gridRef,this.moveCanvas.bind(this),()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){return V({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===`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===`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":()=>xF(this.env),"Alt+=":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:n}=this.env.model.getters.getSelection(),r=this.env.model.getters.getAutomaticSums(e,t,n.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&r.length<=1){let t=r[0]?.zone?this.env.model.getters.zoneToXC(e,r[0].zone):``,n=`=SUM(${t})`;this.onComposerCellFocused(n,{start:5,end:5+t.length})}else this.env.model.dispatch(`SUM_SELECTION`)},"Alt+Enter":()=>{let e=this.env.model.getters.getActiveCell();e.link&&Yr(e.link,this.env)},"Ctrl+Home":()=>{let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,n)},"Ctrl+End":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,`COL`,this.env.model.getters.getNumberCols(e)-1,0),n=this.env.model.getters.findVisibleHeader(e,`ROW`,this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,n)},"Shift+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+D":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":()=>YP(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{let e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),n=this.env.model.getters.getSelectedZones().length===1,r=e.size>0&&n,i=t.size>0&&n;r&&!i?dF(this.env):i&&!r&&lF(this.env)},"Ctrl+Alt+-":()=>{let e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&t.length===0?this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`COL`,elements:e}):t.length>0&&e.length===0&&this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch(`ACTIVATE_NEXT_SHEET`)},"Shift+PageUp":()=>{this.env.model.dispatch(`ACTIVATE_PREVIOUS_SHEET`)},PageDown:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_DOWN`),PageUp:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_UP`),"Ctrl+K":()=>wF(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()&&this.composerFocusStore.activeComposer.editionMode===`inactive`&&this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw Error(`Grid el is not defined.`);return this.gridRef.el}getAutofillPosition(){let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-8/2,top:t.y+t.height-8/2}}get isAutofillVisible(){let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(t.width===0||t.height===0)}onGridResized(){let{height:e,width:t}=this.props.getGridSize();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:t-48,height:e-26,gridOffsetX:48,gridOffsetY:26})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}processSpaceKey(e){this.env.model.getters.hasBooleanValidationInZones(this.env.model.getters.getSelectedZones())&&(e.preventDefault(),e.stopPropagation(),this.env.model.dispatch(`TOGGLE_CHECKBOX`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()}))}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}get focusedClients(){return this.clientFocusStore.focusedClients}getGridRect(){return{...Jw(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,n,r){if(r.preventDefault(),this.composerFocusStore.activeComposer.editionMode===`editing`&&this.composerFocusStore.activeComposer.stopEdition(),n.expandZone?this.env.model.selection.setAnchorCorner(e,t):n.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t),this.env.isMobile())return;let i=e,a=t;this.dragNDropGrid.start(r,(e,t,n)=>{n.preventDefault(),(e!==i&&e!==-1||t!==a&&t!==-1)&&(i=e===-1?i:e,a=t===-1?a:t,this.env.model.selection.setAnchorCorner(i,a))},()=>{this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){let n=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:n,col:e,row:t})),this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t}).type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),kk(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=nT(e),n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}if(t===` `){this.processSpaceKey(e);return}if(e.key.startsWith(`Arrow`)){this.processArrows(e);return}}onInputContextMenu(e){e.preventDefault();let t=this.env.model.getters.getSelectedZone(),{left:n,top:r}=t,i=`CELL`;this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(n)?i=`COL`:this.env.model.getters.getActiveRows().has(r)&&(i=`ROW`);let{x:a,y:o,width:s}=this.env.model.getters.getVisibleRect(t),c=this.getGridRect();this.toggleContextMenu(i,c.x+a+s,c.y+o)}onCellRightClicked(e,t,{x:n,y:r}){let i=this.env.model.getters.getSelectedZones(),a=i[i.length-1],o=`CELL`;Vs(e,t,a)?this.env.model.getters.getActiveCols().has(e)?o=`COL`:this.env.model.getters.getActiveRows().has(t)&&(o=`ROW`):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(o,n,r)}toggleContextMenu(e,t,n){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.anchorRect={x:t,y:n,width:0,height:0},this.menuState.menuItems=UU[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?wI(this.env):this.env.model.dispatch(`COPY`);let n=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(n),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();let t=e.clipboardData;if(!t)return;let n=[...t.files]?.find(e=>Ml.includes(e.type)),r={content:{"text/plain":t?.getData(`text/plain`),"text/html":t?.getData(`text/html`)}};n&&(r.content[n.type]=n);let i=this.env.model.getters.getSelectedZones(),a=this.env.model.getters.isCutOperation(),o=this.env.model.getters.getClipboardId(),s=Il(r.content);o===s.data?.clipboardId?UP(this.env,i):await WP(this.env,i,s),a&&await this.env.clipboard.write({"text/plain":``})}clearFormatting(){this.env.model.dispatch(`CLEAR_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(this.env.model.getters.getSelectedZones().length!==1)return;let t=this.env.model.getters.getActiveRows().size>0,n=this.env.model.getters.getActiveCols().size>0;n&&t?this.processHeaderGroupingEventOnWholeSheet(e):n?this.processHeaderGroupingEventOnHeaders(e,`COL`):t?this.processHeaderGroupingEventOnHeaders(e,`ROW`):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone(),i=t===`COL`?r.left:r.top,a=t===`COL`?r.right:r.bottom;switch(e){case`right`:this.env.model.dispatch(`GROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`left`:this.env.model.dispatch(`UNGROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break}}processHeaderGroupingEventOnWholeSheet(e){let t=this.env.model.getters.getActiveSheetId();e===`up`?(this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`})):e===`down`&&(this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`}))}processHeaderGroupingEventOnGrid(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSelectedZone();switch(e){case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`right`:{let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRect(n),i=this.getGridRect();this.toggleContextMenu(`GROUP_HEADERS`,e+r+i.x,t+i.y);break}case`left`:{if(!fI(this.env,`COL`)&&!fI(this.env,`ROW`))return;let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRect(n),i=this.getGridRect();this.toggleContextMenu(`UNGROUP_HEADERS`,e+r+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:`cellFocus`})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:`contentFocus`})}get staticTables(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(_I)}get displaySelectionHandler(){return this.env.isMobile()&&this.composerFocusStore.activeComposer.editionMode===`inactive`}};let GU=new g;GU.add(`SPREADSHEET`,!1);var KU=class extends t.Component{static template=`o-spreadsheet-ClickableCellSortIcon`;static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=z(rV)}get style(){let e=this.env.model.getters.getCellComputedStyle(this.props.position);return V({color:e.textColor||`#374151C2`,"background-color":this.getBackgroundColor(e)})}get verticalJustifyClass(){switch(this.env.model.getters.getCellComputedStyle(this.props.position).verticalAlign){case`top`:return`justify-content-start`;case`middle`:return`justify-content-center`;default:return`justify-content-end`}}getBackgroundColor(e){let t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?En(e.fillColor||`#FFFFFF`,t):e.fillColor||`#FFFFFF`}},qU=class extends t.Component{static template=`o-spreadsheet-FullScreenFigure`;static props={};static components={ChartFigure:dk};fullScreenFigureStore;ref=(0,t.useRef)(`fullScreenFigure`);spreadsheetRect=nk();figureRegistry=pk;setup(){this.fullScreenFigureStore=z(qO);let e=z(If),n;(0,t.onWillUpdateProps)(()=>{n!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+`-fullscreen`),n=this.figureUI?.id}),(0,t.useEffect)(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){e.key===`Escape`&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return pk.get(this.figureUI.tag).Component}};B`
1893
+ `;var UU=class extends t.Component{static template=`o-spreadsheet-TableResizer`;static props={table:Object};state=(0,t.useState)({highlightZone:void 0});dragNDropGrid=pB(this.env);setup(){MH(this)}get containerStyle(){let e=this.props.table.range.zone,t={...e,left:e.right,top:e.bottom},n=this.env.model.getters.getVisibleRect(t);return n.height===0||n.width===0?V({display:`none`}):V({top:`${n.y+n.height-6}px`,left:`${n.x+n.width-6}px`})}onMouseDown(e){let t=this.props.table.range.zone,n={col:t.left,row:t.top};document.body.style.cursor=`nwse-resize`,this.dragNDropGrid.start(e,(e,t,r)=>{this.state.highlightZone={left:n.col,top:n.row,right:Math.max(e,n.col),bottom:Math.max(t,n.row)}},()=>{document.body.style.cursor=``;let e=this.state.highlightZone;if(!e)return;let t=this.props.table.range.sheetId;this.env.model.dispatch(`RESIZE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0})}get highlights(){return this.state.highlightZone?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:HU,noFill:!0}]:[]}};let WU={ROW:uB,COL:rB,CELL:zR,GROUP_HEADERS:cB,UNGROUP_HEADERS:lB};var GU=class extends t.Component{static template=`o-spreadsheet-Grid`;static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:BB,GridOverlay:oV,GridPopover:sV,HeadersOverlay:pV,MenuPopover:ck,Autofill:hB,ClientTag:_B,Highlight:SV,Popover:ik,VerticalScrollBar:EV,HorizontalScrollBar:TV,TableResizer:UU,Selection:DV};HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=pB(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=z(Kk),this.menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=z(hk),this.composerFocusStore=z(Sf),this.DOMFocusableElementStore=z(Dk),this.sidePanel=z(VU),this.paintFormatStore=z(nV),this.clientFocusStore=z(fB),z(dB),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),(0,t.useExternalListener)(document.body,`cut`,this.copy.bind(this,!0)),(0,t.useExternalListener)(document.body,`copy`,this.copy.bind(this,!1)),(0,t.useExternalListener)(document.body,`paste`,this.paste),(0,t.onMounted)(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),hV(`canvas`,this.env.model,()=>this.env.model.getters.getSheetViewDimensionWithHeaders()),this.onMouseWheel=vV((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=z(TA),(0,t.useEffect)((e,t)=>{!e&&!t&&this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),_V(this.gridRef,this.moveCanvas.bind(this),()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){return V({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===`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===`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":()=>xF(this.env),"Alt+=":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:n}=this.env.model.getters.getSelection(),r=this.env.model.getters.getAutomaticSums(e,t,n.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&r.length<=1){let t=r[0]?.zone?this.env.model.getters.zoneToXC(e,r[0].zone):``,n=`=SUM(${t})`;this.onComposerCellFocused(n,{start:5,end:5+t.length})}else this.env.model.dispatch(`SUM_SELECTION`)},"Alt+Enter":()=>{let e=this.env.model.getters.getActiveCell();e.link&&Yr(e.link,this.env)},"Ctrl+Home":()=>{let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,n)},"Ctrl+End":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,`COL`,this.env.model.getters.getNumberCols(e)-1,0),n=this.env.model.getters.findVisibleHeader(e,`ROW`,this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,n)},"Shift+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+D":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":()=>YP(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{let e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),n=this.env.model.getters.getSelectedZones().length===1,r=e.size>0&&n,i=t.size>0&&n;r&&!i?dF(this.env):i&&!r&&lF(this.env)},"Ctrl+Alt+-":()=>{let e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&t.length===0?this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`COL`,elements:e}):t.length>0&&e.length===0&&this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch(`ACTIVATE_NEXT_SHEET`)},"Shift+PageUp":()=>{this.env.model.dispatch(`ACTIVATE_PREVIOUS_SHEET`)},PageDown:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_DOWN`),PageUp:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_UP`),"Ctrl+K":()=>wF(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()&&this.composerFocusStore.activeComposer.editionMode===`inactive`&&this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw Error(`Grid el is not defined.`);return this.gridRef.el}getAutofillPosition(){let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-8/2,top:t.y+t.height-8/2}}get isAutofillVisible(){let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(t.width===0||t.height===0)}onGridResized(){let{height:e,width:t}=this.props.getGridSize();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:t-48,height:e-26,gridOffsetX:48,gridOffsetY:26})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}processSpaceKey(e){this.env.model.getters.hasBooleanValidationInZones(this.env.model.getters.getSelectedZones())&&(e.preventDefault(),e.stopPropagation(),this.env.model.dispatch(`TOGGLE_CHECKBOX`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()}))}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}get focusedClients(){return this.clientFocusStore.focusedClients}getGridRect(){return{...Jw(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,n,r){if(r.preventDefault(),this.composerFocusStore.activeComposer.editionMode===`editing`&&this.composerFocusStore.activeComposer.stopEdition(),n.expandZone?this.env.model.selection.setAnchorCorner(e,t):n.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t),this.env.isMobile())return;let i=e,a=t;this.dragNDropGrid.start(r,(e,t,n)=>{n.preventDefault(),(e!==i&&e!==-1||t!==a&&t!==-1)&&(i=e===-1?i:e,a=t===-1?a:t,this.env.model.selection.setAnchorCorner(i,a))},()=>{this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){let n=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:n,col:e,row:t})),this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t}).type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),kk(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=nT(e),n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}if(t===` `){this.processSpaceKey(e);return}if(e.key.startsWith(`Arrow`)){this.processArrows(e);return}}onInputContextMenu(e){e.preventDefault();let t=this.env.model.getters.getSelectedZone(),{left:n,top:r}=t,i=`CELL`;this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(n)?i=`COL`:this.env.model.getters.getActiveRows().has(r)&&(i=`ROW`);let{x:a,y:o,width:s}=this.env.model.getters.getVisibleRect(t),c=this.getGridRect();this.toggleContextMenu(i,c.x+a+s,c.y+o)}onCellRightClicked(e,t,{x:n,y:r}){let i=this.env.model.getters.getSelectedZones(),a=i[i.length-1],o=`CELL`;Vs(e,t,a)?this.env.model.getters.getActiveCols().has(e)?o=`COL`:this.env.model.getters.getActiveRows().has(t)&&(o=`ROW`):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(o,n,r)}toggleContextMenu(e,t,n){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.anchorRect={x:t,y:n,width:0,height:0},this.menuState.menuItems=WU[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?wI(this.env):this.env.model.dispatch(`COPY`);let n=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(n),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();let t=e.clipboardData;if(!t)return;let n=[...t.files]?.find(e=>Ml.includes(e.type)),r={content:{"text/plain":t?.getData(`text/plain`),"text/html":t?.getData(`text/html`)}};n&&(r.content[n.type]=n);let i=this.env.model.getters.getSelectedZones(),a=this.env.model.getters.isCutOperation(),o=this.env.model.getters.getClipboardId(),s=Il(r.content);o===s.data?.clipboardId?UP(this.env,i):await WP(this.env,i,s),a&&await this.env.clipboard.write({"text/plain":``})}clearFormatting(){this.env.model.dispatch(`CLEAR_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(this.env.model.getters.getSelectedZones().length!==1)return;let t=this.env.model.getters.getActiveRows().size>0,n=this.env.model.getters.getActiveCols().size>0;n&&t?this.processHeaderGroupingEventOnWholeSheet(e):n?this.processHeaderGroupingEventOnHeaders(e,`COL`):t?this.processHeaderGroupingEventOnHeaders(e,`ROW`):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone(),i=t===`COL`?r.left:r.top,a=t===`COL`?r.right:r.bottom;switch(e){case`right`:this.env.model.dispatch(`GROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`left`:this.env.model.dispatch(`UNGROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break}}processHeaderGroupingEventOnWholeSheet(e){let t=this.env.model.getters.getActiveSheetId();e===`up`?(this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`})):e===`down`&&(this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`}))}processHeaderGroupingEventOnGrid(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSelectedZone();switch(e){case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`right`:{let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRect(n),i=this.getGridRect();this.toggleContextMenu(`GROUP_HEADERS`,e+r+i.x,t+i.y);break}case`left`:{if(!fI(this.env,`COL`)&&!fI(this.env,`ROW`))return;let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRect(n),i=this.getGridRect();this.toggleContextMenu(`UNGROUP_HEADERS`,e+r+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:`cellFocus`})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:`contentFocus`})}get staticTables(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(_I)}get displaySelectionHandler(){return this.env.isMobile()&&this.composerFocusStore.activeComposer.editionMode===`inactive`}};let KU=new g;KU.add(`SPREADSHEET`,!1);var qU=class extends t.Component{static template=`o-spreadsheet-ClickableCellSortIcon`;static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=z(rV)}get style(){let e=this.env.model.getters.getCellComputedStyle(this.props.position);return V({color:e.textColor||`#374151C2`,"background-color":this.getBackgroundColor(e)})}get verticalJustifyClass(){switch(this.env.model.getters.getCellComputedStyle(this.props.position).verticalAlign){case`top`:return`justify-content-start`;case`middle`:return`justify-content-center`;default:return`justify-content-end`}}getBackgroundColor(e){let t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?En(e.fillColor||`#FFFFFF`,t):e.fillColor||`#FFFFFF`}},JU=class extends t.Component{static template=`o-spreadsheet-FullScreenFigure`;static props={};static components={ChartFigure:dk};fullScreenFigureStore;ref=(0,t.useRef)(`fullScreenFigure`);spreadsheetRect=nk();figureRegistry=pk;setup(){this.fullScreenFigureStore=z(qO);let e=z(If),n;(0,t.onWillUpdateProps)(()=>{n!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+`-fullscreen`),n=this.figureUI?.id}),(0,t.useEffect)(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){e.key===`Escape`&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return pk.get(this.figureUI.tag).Component}};B`
1894
1894
  .o_pivot_html_renderer {
1895
1895
  width: 100%;
1896
1896
  border-collapse: collapse;
@@ -1926,17 +1926,17 @@ stores.inject(MyMetaStore, storeInstance);
1926
1926
  background: #e7f2f6;
1927
1927
  }
1928
1928
  }
1929
- `;var JU=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:bA};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getExpandedTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(N(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Ad(e,i).join(`,`)})`,value:L(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Ad(e,i).join(`,`)})`,value:L(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${Ad(e,i).join(`,`)})`,value:L(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=N(r.values[r.values.length-1]);for(let n of t.rows){let t=[];for(let e=0;e<n.fields.length;e++)t.push({value:n.fields[e]},{value:n.values[e]});for(let e=0;e<r.fields.length-1;e++)t.push({value:r.fields[e]},{value:r.values[e]});let o=this.pivot.parseArgsToPivotDomain(t),{value:s,format:c}=this.pivot.getPivotCellValueAndFormat(a,o),l=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${Ad(e,o,a).join(`,`)})`,value:L(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},YU=class extends Lp{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i}){super(t),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=r,this.canDispatch=i}import(e){}export(e){}adaptRanges(e,t,n){}garbageCollectExternalResources(){}},XU=class extends YU{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>b(e)));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Ue.style,color:e.border.color||Ue.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of gt(r))if(e.dimension===`COL`){let n=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{let n=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r=this.borders[e]?.[t]?.[n];return r?.top||r?.bottom||r?.left||r?.right?b(r):null}getBordersColors(e){let t=[],n=this.borders[e];if(n){for(let e of n.filter(C))for(let n of e)if(n)for(let e of[`top`,`bottom`,`left`,`right`]){let r=n[e]?.color;r&&t.push(r)}}return t}ensureColumnBorderContinuity(e,t,n){let r=S(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=S(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&w(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(C);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?S(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n){this.borders[e]&&this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfColumn(e,t,n)})}shiftBordersVertically(e,t,n){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfRow(e,t,n)}))}moveBordersOfRow(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach(a=>{let o=i[a]?.[t+n],s=i[a]?.[t];this.history.update(`borders`,e,a,t+n,r?s:s||o),this.history.update(`borders`,e,a,t,void 0)})}moveBordersOfColumn(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getRowsRange(e).forEach(a=>{let o=i[t+n]?.[a],s=i[t]?.[a];this.history.update(`borders`,e,t+n,a,r?s:s||o),r&&this.history.update(`borders`,e,t,a,void 0)})}setBorder(e,t,n,r,i=!0){let a=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;(i||!this.borders[e]?.[t]?.[n]?.left)&&(this.history.update(`borders`,e,t,n,`left`,r?.left),r?.left&&t>0&&!w(this.borders[e]?.[t-1]?.[n]?.right,r?.left)&&this.history.update(`borders`,e,t-1,n,`right`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.top)&&(this.history.update(`borders`,e,t,n,`top`,r?.top),r?.top&&n>0&&!w(this.borders[e]?.[t]?.[n-1]?.bottom,r?.top)&&this.history.update(`borders`,e,t,n-1,`bottom`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.right)&&(this.history.update(`borders`,e,t,n,`right`,r?.right),r?.right&&t<a&&!w(this.borders[e]?.[t+1]?.[n]?.left,r?.right)&&this.history.update(`borders`,e,t+1,n,`left`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.bottom)&&(this.history.update(`borders`,e,t,n,`bottom`,r?.bottom),r?.bottom&&n<o&&!w(this.borders[e]?.[t]?.[n+1]?.top,r?.bottom)&&this.history.update(`borders`,e,t,n+1,`top`,void 0))}clearBorders(e,t,n=!1){let r=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(let a of ms(t))for(let t=a.top;t<=a.bottom;t++){n&&(a.left>0&&this.history.update(`borders`,e,a.left-1,t,`right`,void 0),a.right<r&&this.history.update(`borders`,e,a.right+1,t,`left`,void 0));for(let r=a.left;r<=a.right;r++)this.history.update(`borders`,e,r,t,void 0),n&&(a.top>0&&this.history.update(`borders`,e,r,a.top-1,`bottom`,void 0),a.bottom<i&&this.history.update(`borders`,e,r,a.bottom+1,`top`,void 0))}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t,!0);for(let i of ms(t)){if(n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r,right:r,bottom:r,left:r});if(n===`h`||n===`hv`){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:r});for(let n=i.top+1;n<i.bottom;n++)this.addBorder(e,t,n,{top:r,bottom:r});this.addBorder(e,t,i.bottom,{top:r})}}if(n===`v`||n===`hv`){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:r});for(let n=i.left+1;n<i.right;n++)this.addBorder(e,n,t,{left:r,right:r});this.addBorder(e,i.right,t,{left:r})}}if(n===`left`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:r});if(n===`top`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||w(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let[n,r]of gc(t.id,t.borders)){let{sheetId:t,col:i,row:a}=n,o=e.borders[r];this.setBorder(t,i,a,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Ts(e))}export(e){let t={};for(let n of e.sheets){let e={};for(let r=0;r<n.colNumber;r++)for(let i=0;i<n.rowNumber;i++){let a=this.getCellBorder({sheetId:n.id,col:r,row:i});if(a){let o=mc(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=hc(e)}e.borders=t}exportForExcel(e){this.export(e)}},ZU=class extends YU{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges({applyChange:e},t,n){for(let r of Object.keys(this.cells))for(let i of Object.values(this.cells[r]||{}))if(i.isFormula){for(let a of i.compiledFormula.dependencies)if(a.sheetId===t||a.invalidSheetName===n.old){let t=e(a);t.changeType!==`NONE`&&this.history.update(`cells`,r,i.id,`compiledFormula`,`dependencies`,i.compiledFormula.dependencies.indexOf(a),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&&e.format!==void 0&&this.setFormatter(e.sheetId,e.target,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of ms(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n=this.getters.getCell({sheetId:e,col:t,row:r});(n?.isFormula||n?.content)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}}setFormatter(e,t,n){for(let r of ms(t))for(let t=r.top;t<=r.bottom;t++)for(let i=r.left;i<=r.right;i++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:i,row:t,format:n})}clearFormatting(e,t){for(let n of ms(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=S(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=S(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){for(let t of e.sheets){let n=t.id,r=new LF;for(let e in t.cells)if(t.cells[e]){let{col:n,row:i}=ir(e),a={sheetId:t.id,col:n,row:i};r.set(a,{content:t.cells[e]})}for(let[e,n]of[[`style`,t.styles],[`format`,t.formats]])for(let[i,a]of gc(t.id,n)){let t=r.get(i);t?t[e]=a:r.set(i,{[e]:a})}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}}export(e){let t={},n={};for(let r of e.sheets){let e=[],i=[],a={},o=Object.keys(this.cells[r.id]||{}).map(e=>this.getters.getCellPosition(e)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let r of o){let o=this.getters.getCell(r),s=T(r.col,r.row),c=this.extractCustomStyle(o);if(Object.keys(c).length){let n=mc(c,t);e[n]??=[],e[n].push(r)}if(o.format){let e=mc(o.format,n);i[e]??=[],i[e].push(r)}o.content&&(a[s]=o.content)}r.styles=hc(e),r.formats=hc(i),r.cells=a}e.styles=t,e.formats=n}importCell(e,t,n,r){let i=this.getNextUid();return this.createCell(i,t||``,r,n,e)}exportForExcel(e){this.export(e);let t=[];for(let n in e.formats||[])Qo(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}extractCustomStyle(e){let t={...e.style},n=Hi(e.content,D)?Re:Le;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return this.cells[e]||{}}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){if(!n.length)return Mt(t.map(e=>e.value));let i=0;return Mt(t.map(t=>{if(t.type===`REFERENCE`){let t=n[i++];return this.getters.getRangeString(t,e,{useBoundedReference:r})}return t.value}))}getTranslatedCellFormula(e,t,n,r){let i=this.getters.createAdaptedRanges(iC(r).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t,n){let r=iC(n).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),i=this.getters.removeRangesSheetPrefix(t,r);return this.getFormulaString(t,n,i)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=T(t.left,t.top,n[0]),i=T(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyle(e,t,n){for(let r of ms(t))for(let t=r.left;t<=r.right;t++)for(let i=r.top;i<=r.bottom;i++){let r=this.getters.getCell({sheetId:e,col:t,row:i});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:i,style:n?{...r?.style,...n}:void 0})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextUid(){let e=this.nextId.toString();return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o=a?Wt(r?.content||void 0):i?.content||``,s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextUid(),u=this.createCell(l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}createCell(e,t,n,r,i){return t.startsWith(`=`)?this.createFormulaCell(e,t,n,r,i):this.createLiteralCell(e,t,n,r)}createLiteralCell(e,t,n,r){let i=this.getters.getLocale(),a=ts(t,i);return n||=typeof a==`number`?Io(t,i)||Lo(t):void 0,!$o(n)&&!j(t)&&(t=N(a)),{id:e,content:t,style:r,format:n,isFormula:!1,parsedValue:a}}createFormulaCell(e,t,n,r,i){let a=rC(t);return a.dependencies.length?this.createFormulaCellWithDependencies(e,a,n,r,i):{id:e,content:t,style:r,format:n,isFormula:!0,compiledFormula:{...a,dependencies:[]}}}createFormulaCellWithDependencies(e,t,n,r,i){let a=[];for(let e of t.dependencies)a.push(this.getters.getRangeFromSheetXC(i,e));return new QU(e,t,n,r,a,i,this.getters.getRangeString)}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?Vs(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.content&&!t.style&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.content===e.content)&&(!r||w(t?.style,e.style))&&(!i||t?.format===e.format)?`NoChanges`:`Success`}},QU=class{id;format;style;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,n,r,i,a,o){this.id=e,this.format=n,this.style=r,this.sheetId=a,this.getRangeString=o;let s=0,c=t.tokens.map(e=>e.type===`REFERENCE`?new $U(i,s++,this.sheetId,this.getRangeString):e);this.compiledFormula={...t,dependencies:i,tokens:c}}get content(){return Mt(this.compiledFormula.tokens.map(e=>e.value))}get contentWithFixedReferences(){let e=0;return Mt(this.compiledFormula.tokens.map(t=>{if(t.type===`REFERENCE`){let t=e++;return this.getRangeString(this.compiledFormula.dependencies[t],this.sheetId,{useBoundedReference:!0})}return t.value}))}},$U=class{ranges;rangeIndex;sheetId;getRangeString;type=`REFERENCE`;constructor(e,t,n,r){this.ranges=e,this.rangeIndex=t,this.sheetId=n,this.getRangeString=r}get value(){let e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}},eW=class extends YU{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getFigureIdFromChartId`,`getContextCreationChart`];charts={};createChart=_O(this.getters);validateChartDefinition=e=>yO(this,e.definition);adaptRanges(e){for(let[t,n]of Object.entries(this.charts)){if(!n)continue;let r=n.chart.updateRanges(e);this.history.update(`charts`,t,r?{figureId:n.figureId,chart:r}:void 0)}}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkFigureArguments,this.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`:let{col:t,row:n,offset:r,size:i,sheetId:a,figureId:o}=e;!this.getters.getFigure(a,o)&&r!==void 0&&t!==void 0&&n!==void 0&&this.addFigure(o,a,t,n,r,i),this.addChart(e.figureId,e.chartId,e.definition);break;case`UPDATE_CHART`:this.addChart(e.figureId,e.chartId,e.definition);break;case`DUPLICATE_SHEET`:for(let t of this.getChartIds(e.sheetId)){let{chart:n,figureId:r}=this.charts[t]||{};if(!n||!r)continue;let i=this.getters.getFigure(e.sheetId,r);if(!i)continue;let a=r.split(`??`).pop(),o=`${e.sheetIdTo}??${a}`,s=t.split(`??`).pop(),c=`${e.sheetIdTo}??${s}`,l=n.duplicateInDuplicatedSheet(e.sheetIdTo);l&&this.dispatch(`CREATE_CHART`,{figureId:o,chartId:c,col:i.col,row:i.row,offset:i.offset,size:{width:i.width,height:i.height},definition:l.getDefinition(),sheetId:e.sheetIdTo})}break;case`DELETE_FIGURE`:for(let t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch(`DELETE_CHART`,{chartId:t,sheetId:e.sheetId});break;case`DELETE_CHART`:this.isChartDefined(e.chartId)&&this.history.update(`charts`,e.chartId,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){let t=this.charts[e]?.chart.type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.chart.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.chart.getDefinition();if(!t)throw Error(`There is no chart with the given id: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures){for(let e of t.figures)if(e.tag===`chart`){let n=e.data.chartId,r=this.createChart(e.id,e.data,t.id);this.charts[n]={chart:r,figureId:e.id}}else if(e.tag===`carousel`)for(let n in e.data.chartDefinitions||{}){let r=e.data.chartDefinitions[n],i=this.createChart(e.id,r,t.id);this.charts[n]={chart:i,figureId:e.id}}}}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t,r=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&e.tag===`chart`&&r){let t=this.charts[r]?.chart.getDefinition();t&&(e.data={...t,chartId:r},n.push(e))}else if(e&&e.tag===`carousel`){let r=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),i={};for(let e of r)i[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:i},n.push(e)}else n.push(e)}t.figures=n}}addFigure(e,t,n,r,i,a={width:536,height:335}){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`chart`})}addChart(e,t,n){let r=this.getters.getFigureSheetId(e);if(r){let i=this.createChart(e,n,r);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&&w(this.getChartDefinition(e.chartId),e.definition)?`NoChanges`:`Success`}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||e.offset!==void 0&&e.col!==void 0&&e.row!==void 0?`Success`:`MissingFigureArguments`}};function tW(e){return e===``?NaN:Number(e)}var nW=class extends YU{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};adaptCFFormulas({applyChange:e,adaptFormulaString:t}){for(let n in this.cfRules)for(let r of this.cfRules[n])if(r.rule.type===`DataBarRule`&&r.rule.rangeValues){let t=e(r.rule.rangeValues);switch(t.changeType){case`REMOVE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,t.range);break}}else if(r.rule.type===`CellIsRule`)for(let e=0;e<r.rule.values.length;e++)this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`values`,e,t(n,r.rule.values[e]));else if(r.rule.type===`IconSetRule`)for(let e of[`lowerInflectionPoint`,`upperInflectionPoint`])r.rule[e].type===`formula`&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,r.rule[e].value));else if(r.rule.type===`ColorScaleRule`)for(let e of[`minimum`,`maximum`,`midpoint`]){let i=r.rule[e];i?.type===`formula`&&i?.value&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,i.value))}}adaptCFRanges(e,{applyChange:t}){for(let n of this.cfRules[e])for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}adaptRanges(e,t){let n=t?[t]:Object.keys(this.cfRules);for(let t of n)this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)Vs(t,n,e.zone)&&r.push(i);return new Set(r.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,n,r){if(n.length===0&&r.length===0)return;let i=this.getters.getConditionalFormats(e),a=i.findIndex(e=>e.id===t.id),o=[];a>-1&&(o=i[a].ranges.map(ws));let s=ms(o,r);return ms([...n,...s],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:n}={useBoundedReference:!1}){let r=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:n}));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:n})},ranges:r}:{...t,rule:{...t.rule},ranges:r}}mapToConditionalFormatInternal(e,t){let n=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:n}:{...t,rule:{...t.rule},ranges:n}}addConditionalFormatting(e,t){let n=this.cfRules[t].slice(),r=n.findIndex(t=>t.id===e.id),i=this.mapToConditionalFormatInternal(t,e);r>-1?n.splice(r,1,i):n.push(i),this.history.update(`cfRules`,t,n)}checkValidPriorityChange(e,t,n){if(!this.cfRules[n])return`InvalidSheetId`;let r=this.cfRules[n].findIndex(t=>t.id===e);if(r===-1)return`InvalidConditionalFormatId`;let i=r-t;return i<0||i>=this.cfRules[n].length?`InvalidConditionalFormatId`:`Success`}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}checkCFRule(e){let t=e.cf.rule;switch(t.type){case`CellIsRule`:return Mr.has(t.operator)?this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkCFHasChanged(e){let t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),n=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return n&&w(t,n)?`NoChanges`:`Success`}checkOperatorArgsNumber(e){let t=Y.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(t===void 0||t>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);let n=[],r=e=>e===void 0||e===``;return t>=1&&r(e.values[0])&&n.push(`FirstArgMissing`),t>=2&&r(e.values[1])&&n.push(`SecondArgMissing`),n.length?n:`Success`}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(rC(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){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?`LowerBiggerThanUpper`:`Success`}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&tW(t)>=tW(n)?`MinBiggerThanMax`:`Success`}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&tW(t)>=tW(n)?`MidBiggerThanMax`:`Success`}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&tW(t)>=tW(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&rC(t||``).isBadExpression)return`ValueCellIsInvalidFormula`;return`Success`}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},rW=class extends YU{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e,t){this.adaptDVRanges(t,e),this.adaptDVFormulas(e)}adaptDVFormulas({adaptFormulaString:e}){for(let t in this.rules){let n=this.rules[t];for(let r=n.length-1;r>=0;r--){let n=this.rules[t][r];for(let i=0;i<n.criterion.values.length;i++){let a=e(t,n.criterion.values[i]);this.history.update(`rules`,t,r,`criterion`,`values`,i,a)}}}}adaptDVRanges(e,{applyChange:t}){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return!this.getters.tryGetSheet(e.sheetId)||e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid));case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return`UnknownDataValidationRule`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=b(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>zc(e.sheetId,e.sheetIdTo,t))}));this.history.update(`rules`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.rules};delete t[e.sheetId],this.history.update(`rules`,t);break}case`REMOVE_DATA_VALIDATION_RULE`:this.removeDataValidationRule(e.sheetId,e.id);break;case`ADD_DATA_VALIDATION_RULE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case`DELETE_CONTENT`:{let t=ms(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(e&&(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!this.getters.getCell({sheetId:n,col:r,row:t})?.content)){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,T(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(Vs(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&(t.criterion.displayStyle===`arrow`||t.criterion.displayStyle===`chip`):!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=b(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of Vc(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...b(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return Y.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=Y.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=Y.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||rC(e).isBadExpression:!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}checkValidRange(e){return e.ranges.map(e=>this.getters.getRangeFromRangeData(e)).map(t=>this.getters.getRangeString(t,e.sheetId)).some(e=>!this.getters.isRangeValid(e))?`InvalidRange`:`Success`}},iW=class extends YU{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];adaptRanges({applyChange:e},t){for(let n of this.getFigures(t)){let r=e(this.getters.getRangeFromZone(t,{left:n.col,right:n.col,top:n.row,bottom:n.row}));if(r.changeType===`MOVE`)this.history.update(`figures`,t,n.id,`col`,r.range.zone.right),this.history.update(`figures`,t,n.id,`row`,r.range.zone.bottom);else if(r.changeType===`REMOVE`){let r=e(this.getters.getRangeFromZone(t,{left:0,right:n.col-1,top:0,bottom:n.row-1})),{offset:i,col:a,row:o}=n;r.changeType!==`NONE`&&(a=r.range.zone.right+1,o=r.range.zone.bottom+1),{offset:i,col:a,row:o}=this.getPositionInSheet(t,{...n,col:a,row:o}),this.history.update(`figures`,t,n.id,`offset`,i),this.history.update(`figures`,t,n.id,`col`,a),this.history.update(`figures`,t,n.id,`row`,o)}}}allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case`UPDATE_FIGURE`:return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case`DELETE_FIGURE`:return this.checkFigureExists(e);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{figureId:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:let t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case`UPDATE_FIGURE`:this.updateFigure(e);break;case`DELETE_FIGURE`:this.removeFigure(e.figureId,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case`DUPLICATE_SHEET`:for(let t of this.getFigures(e.sheetId)){let n=t.id,r=this.figures[e.sheetId]?.[n];if(!r)continue;let i=n.split(`??`).pop(),a=`${e.sheetIdTo}??${i}`;this.dispatch(`CREATE_FIGURE`,{figureId:a,...r,size:{width:r.width,height:r.height},sheetId:e.sheetIdTo})}break}}onColRemove(e){let t=this.getters.getNumberCols(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+this.getters.getColSize(e,r);for(let t of this.getFigures(e))if(t.offset.x+t.width>n[t.col]){let r=t.offset.x,i=t.col;for(r=Math.min(r,n[i]-t.width);r<0&&i>0;)i--,r=n[i]-t.width;r!==t.offset.x&&this.history.update(`figures`,e,t.id,`offset`,{x:Math.max(r,0),y:t.offset.y}),i!==t.col&&this.history.update(`figures`,e,t.id,`col`,i)}}onRowRemove(e){let t=this.getters.getNumberRows(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+(this.getters.getUserRowSize(e,r)??23);for(let t of this.getFigures(e))if(t.offset.y+t.height>n[t.row]){let r=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??23;t<r;t=this.getters.getUserRowSize(e,i)??23)i+=1,r-=t;for(r=Math.min(r,n[i]-t.height);r<0&&i>0;)i--,r=n[i]-t.height;r!==t.offset.y&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(0,r)}),i!==t.row&&this.history.update(`figures`,e,t.id,`row`,i)}else t.offset.y+t.height>n[0]&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(n[0]-t.height,0)})}getPositionInSheet(e,t){let{numberOfRows:n,numberOfCols:r}=this.getters.getSheetSize(e),i=0,a=0,o,s,{col:c,row:l}=t,u={...t.offset};for(o=n;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??23;for(l>o?(l=o,u.y=Math.max(i-t.height,0)):l===o&&(u.y=x(u.y,0,Math.max(i-t.height,0))),s=r;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return c>s?(c=s,u.x=Math.max(a-t.width,0)):s===c&&(u.x=x(u.x,0,Math.max(a-t.width,0))),{col:c,row:l,offset:u}}updateFigure(e){if(!(`figureId`in e)||!(`sheetId`in e))return;let{figureId:t,sheetId:n,...r}=e,i={...this.getFigure(n,t),...r};for(let[e,t]of Object.entries(r))switch(e){case`tag`:this.history.update(`figures`,n,i.id,e,t);break;case`offset`:this.history.update(`figures`,n,i.id,e,t);break;case`col`:case`row`:case`width`:case`height`:t!==void 0&&this.history.update(`figures`,n,i.id,e,t);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e){return this.figures[e.sheetId]?.[e.figureId]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?`DuplicatedFigureId`:`Success`}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?`WrongSheetPosition`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){return this.export(e)}},aW=class extends YU{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,b(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=qt(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ft(e.position,e.base),r=t[e.base],i=Jt(t,Array(e.quantity).fill(r),n);this.history.update(`sizes`,e.sheetId,e.dimension,i);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of S(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of S(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},oW=class extends YU{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?`TooManyHiddenElements`:en(e.elements)<0||$t(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,b(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=Ft(e.position,e.base),n=Jt([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return Rt(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=S(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...S(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},sW=class extends YU{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?`InvalidFigureId`:`Success`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.getters.getFigure(e.sheetId,e.figureId)||this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:b(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}garbageCollectExternalResources(){let e=new Set(this.getAllImages().map(e=>e.path));for(let t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,n,r,i,a){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`image`})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:b(e)})}t.images=[...t.images,...n]}}getAllImages(){let e=[];for(let t in this.images)e.push(...Object.values(this.images[t]||{}).filter(C));return e}},cW=class extends YU{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`getSelectionRangeString`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(C))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e,t){this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(C)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(C)}getSelectionRangeString(e,t){let n=this.getters.expandZone(e.sheetId,e.zone),r=Nc({...e,zone:{...n,bottom:Ic(e)?void 0:n.bottom,right:Lc(e)?void 0:n.right}},this.getters.getSheetSize),i=this.getters.getRangeString(r,t);if(this.isSingleCellOrMerge(e.sheetId,e.zone)){let{sheetName:e,xc:t}=jc(i);return Mc(e,t.split(`:`)[0])}return i}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(zs(t,n))return!0;return!1}doesColumnsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(r.id,t,i,n,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(r.id,i,t,i,n))return!0;return!1}expandZone(e,t){let{left:n,right:r,top:i,bottom:a}=t,o={left:n,right:r,top:i,bottom:a};for(let t in this.merges[e]){let n=this.getMergeById(e,parseInt(t));n&&zs(n,o)&&(o=Fs(n,o))}return Rs(o,t)?o:this.expandZone(e,o)}isInSameMerge(e,t,n,r,i){let a=this.getMerge({sheetId:e,col:t,row:n}),o=this.getMerge({sheetId:e,col:r,row:i});return!a||!o?!1:Rs(a,o)}isInMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e];return r?t in r&&!!r[t]?.[n]:!1}getMainCellPosition(e){let t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){let n=this.getters.getHiddenColsGroups(e),r=this.getters.getHiddenRowsGroups(e);for(let e of n)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of r)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){let n=this.getMerge({sheetId:e,col:t.left,row:t.top});if(n)return Rs(t,n);let{numberOfCols:r,numberOfRows:i}=Us(t);return r===1&&i===1}isMainCellPosition(e){return w(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=x(r,0,this.getters.getNumberCols(e)-1),a=x(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&n.content!==``)return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:uW(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?`MergeIsDestructive`:`Success`}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&zs(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);return ic(t,n,r)?`FrozenPaneOverlap`:`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!Rs(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=x(r,0,this.getters.getNumberCols(e)-1),a=x(a,0,this.getters.getNumberRows(e)-1),T(n,i)===T(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,As({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!Rs(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,{applyChange:t}){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=Us(a.range.zone);t===1&&i===1?this.removeMerge(e,n):this.history.update(`merges`,e,parseInt(r,10),a.range);break}}this.history.update(`mergeCellMap`,e,{});for(let t of this.getMerges(e))for(let{col:n,row:r}of Ks(t))this.history.update(`mergeCellMap`,e,n,r,t.id)}import(e){let t=e.sheets||[];for(let e of t)this.history.update(`merges`,e.id,{}),this.history.update(`mergeCellMap`,e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let n of t)this.addMerge(e,Ts(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...lW(e))}}exportForExcel(e){this.export(e)}};function lW(e){return Object.entries(e).map(([e,t])=>t?uW(parseInt(e,10),t):void 0).filter(C).map(e=>T(e.left,e.top)+`:`+T(e.right,e.bottom))}function uW(e,t){return{...t.zone,id:e}}var dW=class{getters;providers=[];isAdaptingRanges=!1;constructor(e){this.getters=e}static getters=[`copyFormulaStringForSheet`,`extendRange`,`getRangeString`,`getRangeFromSheetXC`,`createAdaptedRanges`,`getRangeData`,`getRangeDataFromXc`,`getRangeDataFromZone`,`getRangeFromRangeData`,`getRangeFromZone`,`getRangesUnion`,`recomputeRanges`,`isRangeValid`,`removeRangesSheetPrefix`];allowDispatch(e){return e.type===`MOVE_RANGES`?e.target.length===1?`Success`:`InvalidZones`:`Success`}beforeHandle(e){}handle(e){if(this.isAdaptingRanges)throw Error(`Plugins cannot dispatch commands during adaptRanges phase`);let t=Gc(e);t&&this.executeOnAllRanges(t)}finalize(){}verifyRangeRemoved(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!Os(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}executeOnAllRanges(e){this.isAdaptingRanges=!0;let t={applyChange:this.verifyRangeRemoved(e.applyChange),adaptRangeString:(t,n)=>hC(t,n,e),adaptFormulaString:(t,n)=>mC(t,n,e)};for(let n of this.providers)n(t,e.sheetId,e.sheetName);this.isAdaptingRanges=!1}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,n,r){return e.map(e=>{if(!Os(e.zone))return e;let i=e.prefixSheet?e.sheetId:r,a=Lc(e),o=Ic(e),s={...e.unboundedZone,left:a&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:a?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:o&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:n),bottom:o?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:n)};return Wc(Nc({...e,sheetId:i,zone:s},this.getters.getSheetSize))})}removeRangesSheetPrefix(e,t){return t.map(t=>t.prefixSheet&&t.sheetId===e?{...t,prefixSheet:!1}:t)}extendRange(e,t,n){let r=t===`COL`?e.zone.right+n:e.zone.right,i=t===`ROW`?e.zone.bottom+n:e.zone.bottom,a={left:e.zone.left,top:e.zone.top,right:Lc(e)?void 0:r,bottom:Ic(e)?void 0:i};return Nc({...e,zone:a},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!Tc.test(t)||!this.getters.tryGetSheet(e))return Fc(t);let{sheetName:n}=jc(t);return Pc({xc:t,sheetId:this.getters.getSheetIdByName(n)||e,invalidSheetName:n&&!this.getters.getSheetIdByName(n)?n:void 0},this.getters.getSheetSize)}getRangeString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){return e?e.invalidXc?e.invalidXc:this.getters.tryGetSheet(e.sheetId)?Rc(e,t,this.getters.getSheetName,n):k.InvalidReference:k.InvalidReference}getRangeDataFromXc(e,t){let n=this.getters.getRangeFromSheetXC(e,t);return this.getRangeDataFromZone(n.sheetId,n.unboundedZone)}getRangeDataFromZone(e,t){return t=this.getters.getUnboundedZone(e,t),{_sheetId:e,_zone:t}}getRangeData(e){return this.getRangeDataFromZone(e.sheetId,e.unboundedZone)}getRangeFromZone(e,t){return Nc({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){return ms(e.map(e=>e.unboundedZone),t.map(e=>e.unboundedZone)).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){return this.getters.tryGetSheet(e._sheetId)?Nc({prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]},this.getters.getSheetSize):Fc(k.InvalidReference)}isRangeValid(e){if(!e)return!1;let{xc:t,sheetName:n}=jc(e);return t.match(Tc)!==null&&(!n||this.getters.getSheetIdByName(n)!==void 0)}getRangesUnion(e){let t=Is(...e.map(e=>e.unboundedZone));return this.getRangeFromZone(e[0].sheetId,t)}copyFormulaStringForSheet(e,t,n,r){if(!n.startsWith(`=`))return n;let i=rC(n),a=i.dependencies.map(n=>{let i=this.getters.getRangeFromSheetXC(e,n);return r===`keepSameReference`?i:zc(e,t,i)});return this.getters.getFormulaString(t,i.tokens,a)}},fW=class extends YU{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`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==`Success`)return t;switch(e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?`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{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),`Success`}catch{return`WrongSheetMove`}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||mn(e.color)?`Success`:`InvalidColor`;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?`Success`:`NotEnoughSheets`;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?`InvalidQuantity`:`Success`:`InvalidHeaderIndex`;case`REMOVE_COLUMNS_ROWS`:{let t=en(e.elements),n=$t(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?`InvalidHeaderIndex`:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return`Success`}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,sl(t.name),t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.newName);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`)}}import(e){for(let t of e.sheets)this.sheetIdsMapName[sl(t.name)]=t.id;for(let t of e.sheets){let e=t.name||`Sheet`+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:nl(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(C).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e)return this.sheetIdsMapName[sl(e)]}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(C)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return al(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?Rt(n,S(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&e.col!==void 0&&`row`in e&&e.row!==void 0&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(Os))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>Hs(e,n))?`Success`:`TargetOutOfSheet`}return`Success`}updateCellPosition(e){let{sheetId:t,cellId:n,col:r,row:i}=e;n?this.setNewPosition(n,t,r,i):this.clearPosition(t,r,i)}setNewPosition(e,t,n,r){let i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update(`cellPosition`,e,{row:r,col:n,sheetId:t}),this.history.update(`sheets`,t,`rows`,r,`cells`,n,e)}clearPosition(e,t,n){let r=this.sheets[e]?.rows[n].cells[t];r&&(this.history.update(`cellPosition`,r,void 0),this.history.update(`sheets`,e,`rows`,n,`cells`,t,void 0))}setGridLinesVisibility(e,t){this.history.update(`sheets`,e,`areGridLinesVisible`,t)}createSheet(e,t,n,r,i){let a={id:e,name:t,numberOfCols:n,rows:nl(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(`There is not enough visible sheets`)}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId),n=e.type===`RENAME_SHEET`?e.newName:e.name;if(t!==void 0&&n===t)return`UnchangedSheetName`;let{orderedSheetIds:r,sheets:i}=this,a=n&&n.trim().toLowerCase();return r.find(t=>cl(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:Xe.test(a)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[sl(n)],r[sl(t)]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=b(this.getSheet(e));r.id=t,r.name=n;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[sl(r.name)]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return ol(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[sl(t)],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of gt(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(ir),n=e.rowNumber,r=e.colNumber;for(let{col:e,row:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return`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`}},pW=class extends YU{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};nextTableId=1;adaptRanges({applyChange:e},t){for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return oc(t)?this.checkValidations(e,e=>this.getTablesOverlappingZones(e.sheetId,t).length?`TableOverlap`:`Success`,e=>this.checkTableConfigUpdateIsValid(e.config)):`NonContinuousTargets`;case`UPDATE_TABLE`:return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,e=>this.checkTableConfigUpdateIsValid(e.config)):`TableNotFound`;case`ADD_MERGE`:for(let t of this.getCoreTables(e.sheetId)){let n=t.range.zone;for(let t of e.target)if(zs(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{});break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.consumeNextId(),a=e.config||QA,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!Ls(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t);break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>Hs(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(C):[]}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>Vs(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>zs(e.range.zone,t)))}extendTableDown(e,t){let n=this.getters.extendRange(t.range,`ROW`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}extendTableRight(e,t){let n=this.getters.extendRange(t.range,`COL`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:n,row:r},i){if(!e)return`none`;let a=i.range.zone,o=`none`;if(a.bottom+1===r&&n>=a.left&&n<=a.right?o=`down`:a.right+1===n&&r>=a.top&&r<=a.bottom&&(o=`right`),o===`none`)return`none`;let s=o===`down`?{...a,bottom:a.bottom+1,top:a.bottom+1}:{...a,right:a.right+1,left:a.right+1};for(let e=s.top;e<=s.bottom;e++)for(let n=s.left;n<=s.right;n++){let r={sheetId:t,col:n,row:e};if(this.getters.getCell(r)?.content||this.getters.isInMerge(r)||this.getTablesOverlappingZones(t,[R(r)]).length)return`none`}return o}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return`Success`;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==`Success`)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?`TableOverlap`:`Success`:`TableNotFound`}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?`InvalidTableConfig`:`Success`}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of S(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.consumeNextId();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=$s(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of S(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.consumeNextId();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,$s(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return gI(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return gI(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:b(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:b(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=gI(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<Us(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.consumeNextId(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}consumeNextId(){let e=`${this.nextTableId}`;return this.history.update(`nextTableId`,this.nextTableId+1),e}import(e){for(let t of e.sheets)for(let e of t.tables||[]){let n=this.consumeNextId(),r=e.config||QA,i=this.getters.getRangeFromSheetXC(t.id,e.range),a=e.type||`static`,o=a===`dynamic`?this.createDynamicTable(n,i,r):this.createStaticTable(n,a,i,r);this.history.update(`tables`,t.id,o.id,o)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:As(e.range.zone),type:e.type};w(e.config,QA)||(n.config=e.config),t.tables.push(n)}}exportForExcel(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n=As(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},mW=class extends YU{static getters=[`getCarousel`,`doesCarouselExist`];carousels={};allowDispatch(e){switch(e.type){case`CREATE_CAROUSEL`:return this.getters.getFigure(e.sheetId,e.figureId)?`DuplicatedFigureId`:`Success`;case`UPDATE_CAROUSEL`:return this.carousels[e.sheetId]?.[e.figureId]?`Success`:`InvalidFigureId`}return`Success`}handle(e){switch(e.type){case`CREATE_CAROUSEL`:this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch(`CREATE_FIGURE`,{...e,tag:`carousel`}),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`UPDATE_CAROUSEL`:this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`carousel`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getCarousel(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:{items:i.items.map(t=>{if(t.type===`carouselDataView`)return{...t};let n=t.chartId.split(`??`).pop(),r=`${e.sheetIdTo}??${n}`;return{...t,chartId:r}})}})}}break}case`DELETE_FIGURE`:this.history.update(`carousels`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`carousels`,e.sheetId,void 0);break}}doesCarouselExist(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){let n=new Set(e.definition.items.filter(e=>e.type===`chart`).map(e=>e.chartId));for(let r of t)r.type===`chart`&&!n.has(r.chartId)&&this.dispatch(`DELETE_CHART`,{chartId:r.chartId,sheetId:e.sheetId})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`carousel`);for(let n of e)this.history.update(`carousels`,t.id,n.id,{items:n.data.items,title:n.data.title})}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`carousel`);for(let n of e)this.carousels[t.id]?.[n.id]&&(n.data={...n.data,...this.carousels[t.id]?.[n.id]})}}},hW=class extends YU{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(S(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=b(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=Ft(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&S(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Gt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=rl(n,r,[o.start,o.end]);(s!==o.start||c!==o.end)&&this.history.update(`groups`,e,t,a,{...o,start:s,end:c})}}moveGroupsOnHeaderDeletion(e,t,n){let r=this.getHeaderGroups(e,t),i=[];for(let e of r){let t=il(n,S(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=Uj(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=Uj(t,e,n.end+1);r.collapsed=!0}}}}}},gW=class extends YU{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?w(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`}return`Success`}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new nR(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=b(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,b(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break}}adaptRanges({applyChange:e,adaptFormulaString:t}){for(let t in this.pivots){let n=b(this.pivots[t]?.definition);if(!n)continue;let r=vR.get(n.type)?.adaptRanges?.(this.getters,n,e);r&&!w(n,r)&&this.history.update(`pivots`,t,`definition`,r)}for(let n in this.compiledMeasureFormulas)for(let r in this.compiledMeasureFormulas[n]){let i=this.pivots[n]?.definition.measures.find(e=>e.id===r);if(!i||!i.computedBy)continue;let a=i.computedBy.sheetId,{formula:o,dependencies:s}=this.compiledMeasureFormulas[n][r];this.history.update(`compiledMeasureFormulas`,n,r,`formula`,`dependencies`,o.dependencies.map(t=>e(t).range)),this.history.update(`compiledMeasureFormulas`,n,i.id,`dependencies`,s.map(t=>e(t).range));let c=i.computedBy.formula,l=t(a,c);l!==c&&this.replaceMeasureFormula(n,i,l)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:b(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=this.compileMeasureFormula(n.computedBy.sheetId,n.computedBy.formula);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.tokens){if(o.type!==`SYMBOL`)continue;let a=i.measures.find(e=>mt(e.id)===o.value&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.dependencies.filter(e=>!e.invalidXc)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:Md(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){let n=rC(t),r=n.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return{...n,dependencies:r}}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId})}checkSortedColumnInMeasures(e){let t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?`InvalidDefinition`:`Success`}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}checkCustomFieldsAreValid(e){for(let t in e.customFields){let n=e.customFields[t],r=new Set,i=new Set,a=!1;for(let e of n.groups){if(!e.name||i.has(e.name)||e.values.some(e=>r.has(e))||e.isOtherGroup&&a)return`InvalidPivotCustomField`;e.values.forEach(e=>r.add(e)),i.add(e.name),a||=!!e.isOtherGroup}}return`Success`}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||Td(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},_W=class extends YU{static getters=[`getLocale`];locale=D;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return uu(e.locale)?`Success`:`InvalidLocale`}return`Success`}handle(e){switch(e.type){case`UPDATE_LOCALE`:let t=this.locale,n=e.locale;this.history.update(`locale`,n),this.changeCellsDateFormatWithLocale(t,n);break}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(let n of this.getters.getSheetIds())for(let[r,i]of Object.entries(this.getters.getCells(n))){let n;if(i.format===e.dateFormat&&(n=t.dateFormat),i.format===e.timeFormat&&(n=t.timeFormat),i.format===Du(e)&&(n=Du(t)),n){let{col:e,row:t,sheetId:i}=this.getters.getCellPosition(r);this.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:i,format:n})}}}import(e){this.locale=e.settings?.locale??D}export(e){e.settings={locale:this.locale}}},vW=class extends YU{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return`Success`}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!Os(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},yW=class extends YU{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(!pj[e.templateName])return`InvalidTableStyle`;try{pn(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=mj(e.tableStyleName,e.templateName,e.primaryColor);this.history.update(`styles`,e.tableStyleId,t);break;case`REMOVE_TABLE_STYLE`:let n={...this.styles};delete n[e.tableStyleId],this.history.update(`styles`,n);for(let t of this.getters.getSheetIds())for(let n of this.getters.getCoreTables(t))n.config.styleId===e.tableStyleId&&this.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{styleId:QA.styleId}});break}}getTableStyle(e){if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return an(E(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!fj[e]}import(e){for(let e in fj)this.styles[e]=fj[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=mj(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)fj[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},bW=class extends Lp{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}};let xW=new g;xW.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let SW=zS.mapping;function CW(e,t,n){return new wW(e,t,n).getParameters()}var wW=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(SW),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){let n=this.getRangeError(e);if(n)return n;let r={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};return t?(this.computeCell(r),{value:Mc(this.getters.getSheetName(e.sheetId),As(e.zone))}):this.computeCell(r)}range(e,t){let n=this.getRangeError(e);if(n)return[[n]];let r=e.sheetId,i=e.zone,a=Ls(i,this.getters.getSheetZone(r));if(!a)return[[]];let{top:o,left:s,bottom:c,right:l}=i,u=`${r}-${o}-${s}-${c}-${l}-${t}`;if(u in this.rangeCache)return this.rangeCache[u];let d=a.bottom-a.top+1,f=a.right-a.left+1,p=Array(f),m=this.getters.getSheetName(e.sheetId);for(let e=a.left;e<=a.right;e++){let n=e-a.left;p[n]=Array(d);for(let i=a.top;i<=a.bottom;i++){let o=i-a.top,s=this.computeCell({sheetId:r,col:e,row:i});p[n][o]=t?{value:Mc(m,T(e,i))}:s}}return this.rangeCache[u]=p,p}getRangeError(e){if(!Os(e.zone))return new Yi;if(e.invalidSheetName)return new Yi(E(`Invalid sheet name: %s`,e.invalidSheetName))}},TW=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),EW=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new DW,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new DW),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&w(e.data,t.data)}},DW=class extends TW.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},OW=class e{profilesStartingPosition=[0];profiles=new Map([[0,[]]]);constructor(e=[]){for(let t of e)this.add(t)}isEmpty(){return this.profiles.size===1&&this.profiles.get(0)?.length===0}add(e){hs(this.profilesStartingPosition,this.profiles,[e])}delete(e){hs(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return gs(this.profilesStartingPosition,this.profiles,e)}difference(e){let t=this.copy();for(let n of e)t.delete(n);return t}copy(){let t=new e;t.profilesStartingPosition=[...this.profilesStartingPosition],t.profiles=new Map;for(let[e,n]of this.profiles)t.profiles.set(e,[...n]);return t}[Symbol.iterator](){return bs(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}},kW=class e{setsBySheetId={};constructor(e=[]){for(let t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new OW),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(let t of e)this.add(t)}addPosition(e){this.add(Uc(e))}addManyPositions(e){for(let t of e)this.addPosition(t)}has(e){return this.setsBySheetId[e.sheetId]?this.setsBySheetId[e.sheetId].has(e.zone):!1}hasPosition(e){return this.has(Uc(e))}delete(e){this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].delete(e.zone)}deleteMany(e){for(let t of e)this.delete(t)}deleteManyPositions(e){for(let t of e)this.delete(Uc(t))}difference(t){let n=new e;for(let e in this.setsBySheetId)n.setsBySheetId[e]=this.setsBySheetId[e];for(let e in t.setsBySheetId)n.setsBySheetId[e]&&(n.setsBySheetId[e]=n.setsBySheetId[e].difference(t.setsBySheetId[e]));return n}copy(){let t=new e;for(let e in this.setsBySheetId)t.setsBySheetId[e]=this.setsBySheetId[e].copy();return t}clear(){this.setsBySheetId={}}isEmpty(){for(let e in this.setsBySheetId)if(!this.setsBySheetId[e].isEmpty())return!1;return!0}[Symbol.iterator](){let e=[];for(let t in this.setsBySheetId)for(let n of this.setsBySheetId[t])e.push({sheetId:t,zone:n});return e[Symbol.iterator]()}},AW=class{rTree;constructor(e=[]){let t=jW(e);this.rTree=new EW(t)}insert(e){let t=this.rTree.search(e.boundingBox),n=e.boundingBox,r=t.find(({boundingBox:e})=>e.sheetId===n.sheetId&&e.zone.left===n.zone.left&&e.zone.top===n.zone.top&&e.zone.right===n.zone.right&&e.zone.bottom===n.zone.bottom);r?r.data.add(e.data):this.rTree.insert({...e,data:new kW([e.data])})}search({zone:e,sheetId:t}){let n=new kW;for(let{data:r}of this.rTree.search({zone:e,sheetId:t}))n.addMany(r);return n}remove(e){let t=this.rTree.search(e.boundingBox),n=e.boundingBox,r=t.find(({boundingBox:e})=>e.sheetId===n.sheetId&&e.zone.left===n.zone.left&&e.zone.top===n.zone.top&&e.zone.right===n.zone.right&&e.zone.bottom===n.zone.bottom);r?r.data.delete(e.data):this.rTree.remove({...e,data:new kW([e.data])})}};function jW(e){let t=0,n=0;for(let r=0;r<e.length;r++){let i=e[r].boundingBox.zone;i.right>t&&(t=i.right),i.bottom>n&&(n=i.bottom)}t+=1,n+=1;let r=(((n+1)*t+1)*n+1)*t<=2**53-1;r||console.warn(`Max col/row size exceeded, using slow zone key`);let i={};for(let a of e){let e=a.boundingBox.sheetId;i[e]||(i[e]={});let o=a.boundingBox.zone,s=0;s=r?o.left+o.top*t+o.right*t*n+o.bottom*t*n*t:`${o.left},${o.top},${o.right},${o.bottom}`,i[e][s]?i[e][s].data.add(a.data):i[e][s]={boundingBox:a.boundingBox,data:new kW([a.data])}}let a=[];for(let e in i){let t=i[e];for(let e in t)a.push(t[e])}return a}var MW=class{dependencies=new LF;rTree;constructor(e=[]){this.rTree=new AW(e)}removeAllDependencies(e){let t=this.dependencies.get(e);if(t){for(let e of t)this.rTree.remove(e);this.dependencies.delete(e)}}addDependencies(e,t){let n=t.map(({sheetId:t,zone:n})=>({data:{sheetId:e.sheetId,zone:R(e)},boundingBox:{zone:n,sheetId:t}}));for(let e of n)this.rTree.insert(e);let r=this.dependencies.get(e);r?r.push(...n):this.dependencies.set(e,n)}getCellsDependingOn(e,t=new kW){t=t.copy();let n=Array.from(e).reverse();for(;n.length>0;){let e=n.pop();t.add(e);let r=this.rTree.search(e);n.push(...r.difference(t))}for(let n of e)t.delete(n);return t}},NW=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=PW(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function PW(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var FW=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=NW.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},IW=class{resultsToArrayFormulas=new EW;arrayFormulasToResults=new LF;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||LW}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let LW=[],RW=Object.freeze(ns({...new Ji,origin:void 0})),zW=Object.freeze(ns({value:null}));var BW=class{context;getters;compilationParams;evaluatedCells=new LF;formulaDependencies=Nt(new MW);blockedArrayFormulas=new FW({});spreadingRelations=new IW;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=CW(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||zW}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===`error`&&!(t.ignoreSpillError&&r?.value===k.SpilledBlocked)?R(e):Fs(R(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type!==`empty`)return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,R(e)).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t);for(let e of t)this.compilationParams.ensureRange(e,!1)}updateCompilationParametersForIsolatedFormula(e){this.compilationParams=CW(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.updateDependencies=void 0,this.compilationParams.evalContext.addDependencies=void 0,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParameters(){this.compilationParams=CW(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new FW(e)}evaluateCells(e){let t=performance.now(),n=new kW;n.addManyPositions(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(n)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=new kW;for(let n of e){let e=this.getters.getCell(n)?.content,r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.addPosition(r),e||t.addPosition(n)}for(let e of[...t])t.addMany(this.getArrayFormulasBlockedBy(e.sheetId,e.zone));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new IW,this.formulaDependencies=Nt(()=>{let e=[];for(let t of this.getters.getSheetIds()){let n=this.getters.getCells(t);for(let r in n){let i=n[r];if(i.isFormula){let n=i.compiledFormula.dependencies;for(let i of n)i.invalidSheetName||i.invalidXc||e.push({data:{sheetId:t,zone:R(this.getters.getCellPosition(r))},boundingBox:{sheetId:i.sheetId,zone:i.zone}})}}}return new MW(e)})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new LF;let t=[];for(let e of this.getters.getSheetIds()){let n=this.getters.getSheetZone(e);t.push({sheetId:e,zone:n})}this.evaluate(t),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=rC(t),i=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,{...r,dependencies:i})}evaluateCompiledFormula(e,t,n){try{let r=UW(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return Ir(r)?Ca(r,HW):HW(r)}catch(e){return VS(e,``)}}getArrayFormulasBlockedBy(e,t){let n=new kW,r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addManyPositions(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteManyPositions(i),n.addMany(this.getCellsDependingOn(n)),n}nextRangesToUpdate=new kW;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new kW(e);let t=0;for(;!this.nextRangesToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();let e=[...this.nextRangesToUpdate];this.nextRangesToUpdate.clear(),this.clearEvaluatedRanges(e);for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++){let n={sheetId:t.sheetId,col:a,row:e};if(this.nextRangesToUpdate.hasPosition(n))continue;let r=this.computeCell(n);r!==zW&&this.evaluatedCells.set(n,r)}}xW.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}clearEvaluatedRanges(e){for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++)this.evaluatedCells.delete({sheetId:t.sheetId,col:a,row:e})}}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return zW;let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?RW:(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):es(n,i,e))}catch(t){return t.value=t?.value||k.GenericError,t.message=t?.message||WS,t.origin=e,t.errorOriginPosition=t?.errorOriginPosition,ns(t)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=UW(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!Ir(n)){let r=ns(HW(n),this.getters.getLocale(),t,e);return r.type===`error`&&(r.errorOriginPosition=n.errorOriginPosition??e),r}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return ns({value:0},this.getters.getLocale(),t);if(i===1&&r===1)return ns(HW(n[0][0]),this.getters.getLocale(),t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),VW(r,i,this.checkCollision(e)),VW(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),ns(HW(n[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){let n=this.getCellsDependingOn(Gs(t).map(t=>({sheetId:e,zone:t})));n.delete({sheetId:e,zone:t}),this.nextRangesToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw o?new Qi(E(`Result couldn't be automatically expanded. Please insert more rows.`)):s?new Qi(E(`Result couldn't be automatically expanded. Please insert more columns.`)):new Qi(E(`Result couldn't be automatically expanded. Please insert more columns and rows.`))}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:n},r){if(this.getters.getMergesInZone(e,{top:n,bottom:n+r[0].length-1,left:t,right:t+r.length-1}).length!==0)throw new Qi(E(`Merged cells found in the spill zone. Please unmerge cells before using array formulas.`))}checkCollision(e){let{sheetId:t,col:n,row:r}=e;return(i,a)=>{let o={sheetId:t,col:i+n,row:a+r};if(this.getters.getCell(o)?.content||this.getters.getEvaluatedCell(o).type!==`empty`)throw this.blockedArrayFormulas.add(e),new Qi(E(`Array result was not expanded because it would overwrite data.`),o);this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=ns(HW(r[i][a]),this.getters.getLocale(),s,o);c.type===`error`&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r};this.getters.getCell(t)?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextRangesToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return RW;this.symbolsBeingComputed.add(t);try{return e?.(t)||new qi(E(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}};function VW(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function HW(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function UW(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}var WW=class extends bW{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getRangeFormattedValues`,`getRangeValues`,`getRangeFormats`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new BW(e.custom,this.getters)}beforeHandle(e){(yr.has(e.type)||xr.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:if(e.cellIds)for(let t=0;t<e.cellIds.length;t++)this.positionsToUpdate.push(this.getters.getCellPosition(e.cellIds[t]));else this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return Ir(r)?Ca(r,e=>e.value):r.value}evaluateFormulaResult(e,t,n){return this.evaluator.evaluateFormulaResult(e,t,n)}evaluateCompiledFormula(e,t,n){return this.evaluator.evaluateCompiledFormula(e,t,n)}getRangeFormattedValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).formattedValue)}getRangeValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).value)}getRangeFormats(e){let t=this.getters.tryGetSheet(e.sheetId);return t===void 0?[]: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 Ks(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return Ks(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return Ks(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=T(t.col,t.row),i=n.value,a=!1,o,s=!0,c=e.sheets.find(e=>e.id===t.sheetId),l=this.getCorrespondingFormulaCell(t);if(l){let u=this.getters.getCell(t);if(s=dC(l.compiledFormula.tokens),a=s&&u?.content===l.content,!s&&i!==``){o=(i??``).toString();let t=n.format;if(t){let n=mc(t,e.formats);c.formats[r]=n}}}let u=c.cells[r],d;d=s&&a&&l instanceof QU?l.contentWithFixedReferences:s?u:o,c.cells[r]=d,c.cellValues[r]=i===k.BadExpression?void 0:i;let f=this.getSpreadZone(t);f&&(c.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,f),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let GW=/"(#[0-9a-fA-F]{6})"/g;function KW(e){let t=[{leadColor:_n(255,0,0),colors:[]},{leadColor:_n(255,128,0),colors:[]},{leadColor:_n(128,128,0),colors:[]},{leadColor:_n(128,255,0),colors:[]},{leadColor:_n(0,255,0),colors:[]},{leadColor:_n(0,255,128),colors:[]},{leadColor:_n(0,255,255),colors:[]},{leadColor:_n(0,127,255),colors:[]},{leadColor:_n(0,0,255),colors:[]},{leadColor:_n(127,0,255),colors:[]},{leadColor:_n(128,0,128),colors:[]},{leadColor:_n(255,0,128),colors:[]}];for(let n of e.map(xn)){let e=500,r=0;t.forEach((t,i)=>{let a=qW(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>Cn(e).s-Cn(t).s)).flat().map(bn)}function qW(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var JW=class extends bW{customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds())for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));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);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return KW(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push(dn(t.minimum.color)),n.push(t.midpoint?dn(t.midpoint.color):void 0),n.push(dn(t.maximum.color)))}return n.filter(C)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getDefinition()).matchAll(GW)].map(e=>e[1])}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(C):[]}tryToAddColors(e){for(let t of e){if(!mn(t))continue;let e=pn(t);t&&!Ie.includes(e)&&this.history.update(`customColors`,e,!0)}}},YW=class extends bW{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};createRuntimeChart=vO(this.getters);handle(e){if(yr.has(e.type)||Sr.has(e.type)||br.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:AC(e)};if(!t)return{background:oe,fontColor:AC(oe)};let n=t.zone.left,r=t.zone.top,i=t.sheetId,a=this.getters.getCellComputedStyle({sheetId:i,col:n,row:r}),o=a.fillColor||`#FFFFFF`;return{background:o,fontColor:a.textColor||AC(o)}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===r.id);if(!e)continue;let i=this.getters.getChart(e),a=i?.getDefinitionForExcel(this.getters);if(a)n.push({...r,data:a});else{if(!i)continue;let n=this.getters.getChartType(e),a=jT(this.getters.getChartRuntime(e),r,n);a&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:a,size:{width:r.width,height:r.height}}})}}t.charts=n}}},XW=class extends bW{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(yr.has(e.type)||Sr.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=Nt(()=>this.getComputedStyles(e)),this.computedIcons[e]=Nt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=Nt(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(e=>e.startsWith(`=`)?rC(e):void 0);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let s={sheetId:e,col:o,row:i},c=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s.tokens):t});this.getRuleResultForTarget(s,{...n.rule,values:c})&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,t).zone,a=this.getters.getEvaluatedCellsInZone(e,i).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?$t(a):en(a);case`number`:return Number(n.value);case`percentage`:let t=en(a);return t+($t(a)-t)*Number(n.value)/100;case`percentile`:return Gi(a,Number(n.value)/100,!0);case`formula`:let i=n.value&&this.getters.evaluateFormula(e,n.value);return typeof i==`number`?i:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==`number`)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=$t(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===`number`).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!Vs(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:dn(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:n.minimum.color}];n.midpoint&&a&&c.push({value:a,color:n.midpoint.color}),c.push({value:o,color:n.maximum.color});let l=Kn(c);for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let a=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(a.type===`number`){let e=x(a.value,i,o);r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=l(e)}}}getRuleResultForTarget(e,t){let n=this.getters.getEvaluatedCell(e);if(n.type===`error`)return!1;let{sheetId:r}=e,i=Y.get(t.operator),a=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(r,t,e)??``:ts(t,D));if(a.some(Wu))return!1;let o={type:t.operator,values:a.map(Hu)};return i.isValueValid(n.value??``,o,this.getters,r)}};let ZW={isValid:!0};var QW=class extends bW{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};handle(e){if(yr.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:`#E7E9ED`}}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=Y.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?E(`The value must not be a formula`):this.isValidFormula(t)?void 0:U.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?E(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}getDataValidationRangeValues(e,t){let n=this.getters.getRangeFromSheetXC(e,String(t.values[0])),r=[],i=new Set;for(let e of Ks(n.zone)){let t=this.getters.getEvaluatedCell({...e,sheetId:n.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),r.push({label:t.formattedValue,value:t.value?.toString()||``}))}return r}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return ZW;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:ZW}hasChip(e){let t=this.getters.getValidationRuleForCell(e);return(t?.criterion.type===`isValueInList`||t?.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`chip`}getDataValidationStyle(e){let t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;let n=this.getters.getEvaluatedCell(e),r=this.getValueColor(t,n.value);if(r)return{fillColor:r,textColor:Mn(r)}}getValueColor(e,t){if(!(e.criterion.type!==`isValueInList`&&e.criterion.type!==`isValueInRange`)){for(let n in e.criterion.colors)if(n.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[n]}}isValidFormula(e){return!rC(e).isBadExpression}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||ZW}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of Vc(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=Nt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?ZW:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=Y.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,t,o,i);if(s.some(Wu))return;let c={...i,values:s.map(Hu)};if(!a.isValueValid(e,c,this.getters,r))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>Vs(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n,r){return r.values.map(r=>{if(!r.startsWith(`=`))return ts(r,D);let i=rC(r),a=this.getters.getTranslatedCellFormula(e,n.col,n.row,i.tokens);return this.getters.evaluateFormula(e,a,t)})}};let $W=new g;$W.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value;return{svg:n?Nj:jj,hoverSvg:n?Nj:Mj,priority:2,horizontalAlign:`center`,size:17,margin:2,position:t,type:`data_validation_checkbox`,onClick:(e,t)=>{let r=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||r?.isFormula)return;let i=n?`FALSE`:`TRUE`;t.model.dispatch(`UPDATE_CELL`,{...e,content:i})}}}}),$W.add(`data_validation_chip_icon`,(e,t)=>{let n=e.getDataValidationChipStyle(t);if(n){let r=e.getCellComputedStyle(t);return{svg:kj(n),hoverSvg:Aj(n),priority:10,horizontalAlign:`right`,size:xl(r),margin:4,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_chip_icon`}}}),$W.add(`data_validation_list_icon`,(e,t)=>{if(!e.isReadonly()&&e.cellHasListDataValidationIcon(t)){let n=e.getCellComputedStyle(t);return{svg:Tj(n),hoverSvg:Dj(n),priority:2,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_list_icon`}}}),$W.add(`filter_icon`,(e,t)=>{if(e.isFilterHeader(t)){let n=e.isFilterActive(t),r=vn(e.getCellComputedStyle(t).fillColor||`#fff`)<.45;return{type:`filter_icon`,svg:Fj(n,r,!1),hoverSvg:Fj(n,r,!0),priority:3,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let n=t.getStore(TA),r=n.persistentCellPopover;if(r.isOpen&&r.col===e.col&&r.row===e.row&&r.type===`FilterMenu`){n.close();return}n.open(e,`FilterMenu`)}}}}),$W.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:Ij[n].svg,priority:1,horizontalAlign:`left`,size:xl(r),margin:4,position:t}}}),$W.add(`pivot_collapse`,(e,t)=>{if(!e.isSpillPivotFormula(t))return;let n=e.getPivotCellFromPosition(t),r=e.getPivotIdFromPosition(t);if(n.type===`HEADER`&&r&&n.domain.length){let i=e.getPivotCoreDefinition(r),a=e.isDashboard(),o=n.dimension===`COL`?i.columns:i.rows,s=!a&&n.domain.length!==o.length,c=(i.collapsedDomains?.[n.dimension]??[]).some(e=>w(e,n.domain)),l=n.dimension===`ROW`?(n.domain.length-1)*15:0;return{type:`pivot_collapse`,priority:4,horizontalAlign:`left`,size:s||!a&&n.dimension===`ROW`&&i.rows.length>1?12:0,margin:s?4+l:l,svg:s?Pj(c,!1):void 0,hoverSvg:s?Pj(c,!0):void 0,position:t,onClick:eG}}});function eG(e,t){let n=t.model.getters.getPivotCellFromPosition(e),r=t.model.getters.getPivotIdFromPosition(e);if(!r||n.type!==`HEADER`)return;let i=t.model.getters.getPivotCoreDefinition(r),a=i.collapsedDomains?.[n.dimension]?[...i.collapsedDomains[n.dimension]]:[],o=a.findIndex(e=>w(e,n.domain));o===-1?a.push(n.domain):a.splice(o,1);let s=i.collapsedDomains?{...i.collapsedDomains}:{COL:[],ROW:[]};s[n.dimension]=a,t.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...i,collapsedDomains:s}})}$W.add(`pivot_dashboard_sorting`,(e,t)=>{if(!e.isDashboard()||e.getPivotCellFromPosition(t).type!==`MEASURE_HEADER`)return;let n=e.getPivotCellSortDirection(t);if(n!==`asc`&&n!==`desc`)return;let r=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${n}`,priority:5,horizontalAlign:`right`,size:17,margin:2,svg:n===`asc`?Ej(r):Tj(r),position:t,onClick:void 0}});var tG=class extends bW{static getters=[`doesCellHaveGridIcon`,`getCellIcons`,`getCellIconRect`];cellIconsCache={};handle(e){e.type!==`SET_VIEWPORT_OFFSET`&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){let n=e.position,r=this.getters.getCell(n);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,r?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,n){let r=e.x,i=e.x+e.width;switch(t){case`right`:return i-n.margin-n.size;case`left`:return r+n.margin;default:let e=Math.floor((i-r-n.size)/2);return i-n.size-e}}computeCellIcons(e){let t={left:void 0,right:void 0,center:void 0},n=$W.getAll();for(let r of n){let n=r(this.getters,e);n&&(!t[n.horizontalAlign]||n.priority>t[n.horizontalAlign].priority)&&(t[n.horizontalAlign]=n)}if(t.center&&(t.left||t.right)){let e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(C)}doesCellHaveGridIcon(e){return!!this.getCellIcons(e).length}},nG=class extends bW{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(yr.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tables={};return}switch(e.type){case`CREATE_TABLE`:case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`DELETE_CONTENT`:this.tables={};break}}finalize(){for(let e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){let t=[],n=this.getters.getCoreTables(e);for(let e of n)e.type!==`dynamic`&&t.push(e);let r=[...t];for(let i of n){if(i.type!==`dynamic`)continue;let n=this.coreTableToTable(e,i),a=n.range.zone;for(let e of r){let t=e.range.zone;zs(a,t)&&(a=t.left>a.left?{...a,right:Math.min(a.right,t.left-1)}:{...a,bottom:Math.min(a.bottom,t.top-1)})}t.push({...n,range:this.getters.getRangeFromZone(e,a)})}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){let t=this.getTable(e);if(!(!t||!t.config.hasFilters))return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:n}){return this.getTables(e).find(e=>Vs(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>zs(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){let t=[];for(let n of this.getTables(e)){if(!n.config.hasFilters)continue;let r=n.range.zone,i=r.top;for(let n=r.left;n<=r.right;n++)t.push({sheetId:e,col:n,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:n}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===n)}canCreateDynamicTableOnZones(e,t){if(!oc(t))return!1;let n=Fs(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);if(!i){let e=this.getters.getEvaluatedCell(r);return e.value===k.SpilledBlocked&&!e.errorOriginPosition}else if(w(i,r)&&nc(n)===1)return!0;return w(n,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=gI(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!Ks(t.range.zone).some(t=>this.getters.getArrayFormulaSpreadingOn({sheetId:e,...t}))}exportForExcel(e){for(let t of e.sheets){let n=[];for(let r of t.tables){let i=Ts(r.range),a={sheetId:t.id,col:i.left,row:i.top},o=this.getters.getCoreTable(a),s=this.getTable(a);if(!o||!s||this.isTableExcelExportable(t.id,o)){n.push(r);continue}t.styles=t.styles||{},t.borders=t.borders||{};for(let n of Ks(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=T(n.col,n.row);if(!kt(i)){let n=mc(i,e.styles);t.styles[o]=n}if(a){let n=mc(a,e.borders);t.borders[o]=n}}}t.tables=n}}},rG=class extends bW{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=document.createElement(`canvas`).getContext(`2d`);beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=Ft(e.position,e.base),n=Array(e.quantity).fill(void 0),r=Jt(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=b(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=qt(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of S(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of Ks(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getMaxAnchorOffset(e,t,n){let{numberOfRows:r,numberOfCols:i}=this.getters.getSheetSize(e),a=0;for(;a<t&&r>0;r--)a+=this.getRowSize(e,r-1);let o=0;for(;o<n&&i>0;i--)o+=this.getters.getColSize(e,i-1);return{col:i,row:r,offset:{x:o-n,y:a-t}}}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return ul(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCells(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let iG=`0.00%`;function aG(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=wd[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return VS(t,e.aggregator.toUpperCase())}}let i=this.getters.getMeasureCompiledFormula(this.pivotId,e),a=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,e=>{let{columns:n,rows:r}=this.definition;if(n.find(t=>t.nameWithGranularity===e)){let{colDomain:n}=LL(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Xi:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=LL(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Xi:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return Ir(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=LL(this,t),i=super.getExpandedTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=Nd(this.definition.getDimension(r.field),t[n]?.value);if(r.field===t[n]?.field&&r.value===e)return this.getSubTreeMatchingDomain(r.children,t,n+1)}return[]}treeToLeafDomains(e,t=[]){let n=[];for(let r of e){let e=this.definition.getDimension(r.field),i=[...t,{field:r.field,value:r.value,type:e.type}];r.children.length===0?n.push(i):n.push(...this.treeToLeafDomains(r.children,i))}return n}getMeasureDisplayValue(e,t){let n=this.getMeasure(e),r=this._getPivotCellValueAndFormat(e,t);if(!n.display||n.display.type===`no_calculations`||r.message)return r;let i=n.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:k.NotAvailable,message:E(`Field "%s" not found in pivot for measure display calculation`,i)};try{let e=n.display;switch(e.type){case`%_of_grand_total`:return this.asPercentOfGrandTotal(r,n);case`%_of_col_total`:return this.asPercentOfColumnTotal(r,n,t);case`%_of_row_total`:return this.asPercentOfRowTotal(r,n,t);case`%_of_parent_row_total`:return this.asPercentOfParentRowTotal(r,n,t);case`%_of_parent_col_total`:return this.asPercentOfParentColumnTotal(r,n,t);case`index`:return this.asIndex(r,n,t);case`%_of_parent_total`:return this.asPercentOfParentTotal(r,n,t,e);case`running_total`:return this.asRunningTotal(r,n,t,e,`running_total`);case`%_running_total`:return this.asRunningTotal(r,n,t,e,`%_running_total`);case`rank_asc`:return this.asRank(r,n,t,e,`asc`);case`rank_desc`:return this.asRank(r,n,t,e,`desc`);case`%_of`:return this.asPercentOf(r,n,t,e);case`difference_from`:return this.asDifferenceFrom(r,n,t,e);case`%_difference_from`:return this.asDifferenceFromInPercent(r,n,t,e)}return r}catch(e){return VS(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:k.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:iG}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:k.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:iG}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:k.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:iG}}asPercentOfParentRowTotal(e,t,n){let r=FL(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:iG}}asPercentOfParentColumnTotal(e,t,n){let r=IL(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:iG}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!GL(i,n))return{value:``};let a=UL(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:iG}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value:k.DivisionByZero}:{value:r*o/(a*i),format:void 0}}asRunningTotal(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;let o=i===`running_total`?this.runningTotal:this.runningTotalInPercent,s=o[t.id]?.[a];s||(s=this.computeRunningTotal(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=LL(this,n),u=JL(l),d=JL(c);return{value:s[u]?.[d]??``,format:i===`running_total`?e.format:iG}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!GL(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:k.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:iG}:s===void 0?{value:k.NullError}:{value:s/o,format:iG}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!GL(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a)||0;return o===`sameValue`?{value:``}:{value:this.measureValueToNumber(e)-o,format:e.format}}asDifferenceFromInPercent(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!GL(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:k.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:k.NullError}:{value:(s-o)/o,format:iG}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!GL(a,n))return{value:``};let o=i===`asc`?this.rankAsc:this.rankDesc,s=o[t.id]?.[a];s||(s=this.computeRank(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=LL(this,n),u=JL(l),d=JL(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=KL(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=Ta(o));for(let s of o){let o=JL(RL(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:RL(this,i,t.domain)})).filter(e=>GL(t,e.rowDomain)),l=Object.groupBy(c,e=>XL(e.rowDomain,t));for(let e in l)l[e]=nn(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=JL(RL(this,i,e.domain)),a=l[XL(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:rn(r)}computeRunningTotal(e,t,n){let r={},i=KL(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=Ta(o));for(let s of o){let o=JL(RL(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:RL(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>GL(t,e.rowDomain));for(let e of l){let n=JL(e.rowDomain),i=ZL(e.rowDomain,t),a=(c[i]||0)+e.value;c[i]=a,r[o][n]=a}if(n===`%_running_total`)for(let e of l){let n=e.rowDomain,i=JL(n),a=ZL(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:rn(r)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=LL(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=LL(this,t).colDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,n,r){let i=r===`(previous)`||r===`(next)`?qL(this,t,n,r):WL(t,n,r);if(w(i,t))return`sameValue`;if(!i||!BL(this,i))throw new Xi;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){let e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){let e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;let t=this.definition.sortedColumn.measure;Vd(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let oG=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function sG(e){return oG.includes(e.type)}var cG=class extends bW{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotCellSortDirection`,`getPivotIdFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`];pivots={};unusedPivots;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(yr.has(e.type))for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0});switch(e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.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;let t=e.commands.filter(sG);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:gR();break}}getPivotIdFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){let n=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(n){let e=n.args[0]?.toString();return e&&this.getters.getPivotId(e)}}}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens)?.functionName===`PIVOT`:!1}getFirstPivotFunction(e,t){let n=hU(t);if(!n)return;let{functionName:r,args:i}=n;return{functionName:r,args:i.map(t=>{if(t.type===`EMPTY`)return;if(t.type===`STRING`||t.type===`BOOLEAN`||t.type===`NUMBER`)return t.value;let n=PB(t);return this.getters.evaluateFormula(e,n)})}}getPivotCellFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||gU(t.compiledFormula.tokens)===0)return rR;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!r)return rR;let{functionName:i,args:a}=r,o=a[0];if(!o)return rR;let s=this.getters.getPivotId(o.toString());if(!s)return rR;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!t.content.replaceAll(` `,``).toUpperCase().startsWith(`=PIVOT`))return rR;try{if(i===`PIVOT`){let t=Hu(a[2]),r=t===void 0?!0:P(t),i=Hu(a[3]),o=Hu(a[5]),s=o===void 0?!0:P(o),l={displayColumnHeaders:i===void 0?!0:P(i),displayTotals:r,displayMeasuresRow:s},u=c.getCollapsedTableStructure().getPivotCells(l),d=e.col-n.col,f=e.row-n.row;return u[d][f]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>Ir(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`){let e=c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})));return{type:`HEADER`,domain:e,dimension:LL(c,e).colDomain.length?`COL`:`ROW`}}let[o,...s]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(s.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return rR}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return an(E(`Calculated measure 1`),t,{compute:(e,t)=>E(`Calculated measure %s`,t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){return this._getUnusedPivots().includes(e)}getPivotCellSortDirection(e){let t=this.getters.getPivotIdFromPosition(e),n=this.getters.getPivotCellFromPosition(e);if(n.type===`EMPTY`||n.type===`HEADER`||!t)return;let r=this.getters.getPivot(t),i=LL(r,n.domain).colDomain,a=r.definition.sortedColumn;return a?.measure===n.measure&&w(a.domain,i)?a.order:`none`}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=b(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=aG(vR.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivots(){if(this.unusedPivots!==void 0)return this.unusedPivots;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n in this.getters.getCells(t)){let t=this.getters.getCellPosition(n),r=this.getPivotIdFromPosition(t);if(r&&(e.delete(r),!e.size))return this.unusedPivots=[],[]}return this.unusedPivots=[...e],this.unusedPivots}};let lG=new g;lG.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=Math.abs(e.current).toString();n=`0`.repeat(Math.max(e.numberPostfixLength-n.length,0))+n;let r=`${e.prefix}${n}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:{props:{content:r}}}}}).add(`INCREMENT_MODIFIER`,{apply:(e,t,n)=>{e.current+=e.increment;let r=e.current.toString(),i=n.getLocale(),a=L(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=F(e.current,n.getLocale());r.setFullYear(r.getFullYear()+e.increment.years||0),r.setMonth(r.getMonth()+e.increment.months||0),r.setDate(r.getDate()+e.increment.days||0);let i=wi(r);e.current=i;let a=n.getLocale(),o=L(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:o}}:void 0}}}).add(`COPY_MODIFIER`,{apply:(e,t,n)=>{let r=t.cell?.content||``,i={locale:n.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:t.cell?es(t.cell,i).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula.tokens);return{cellData:{border:t.border,style:o.style,format:o.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let uG=new g,dG=/(\d+)$/,fG=/^(.*\D+)/,pG=/^(.*\D+)(\d+)$/,mG=/^0*/;function hG(e,t,n){let r=[],i=!1;for(let a of t){a===e&&(i=!0);let t=a===void 0||a.isFormula?void 0:es(a,{locale:D,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function gG(e){let t=[],n=e[0];for(let r=1;r<e.length;r++){let i=e[r];t.push(i-n),n=i}return t.reduce((e,t)=>e+t,0)/t.length}function _G(e){let t=1;return e.length>=2&&(t=gG(e)*e.length),t}function vG(e){return e.length<2?e[0]||{years:0,months:0,days:0}:e.every(t=>t.years===e[0].years&&t.months===e[0].months&&t.days===e[0].days)?e[0]:void 0}function yG(e){if(e.length<2)return 1;let t=e.map(e=>F(e,D)),n=vG(bG(t));if(n===void 0)return;let r=Object.values(n).filter(e=>e!==0).length===1,i=Object.values(n).every(e=>e===0);if(!r||i){let n=t.map((e,n)=>{if(n===0)return 0;let r=t[n-1];return Math.floor(e.getTime())-Math.floor(r.getTime())}).slice(1);if(n.every(e=>e===n[0]))return e.length*(e[1]-e[0])}return{years:n.years*e.length,months:n.months*e.length,days:n.days*e.length}}uG.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&jo(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&es(e,{locale:D}).type===`text`&&pG.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(dG)[0]),i=e.content.match(fG)[0],a=hG(e,t,e=>e.type===`text`&&pG.test(e.value)).filter(e=>i===(e.value??``).toString().match(fG)[0]).map(e=>(e.value??``).toString().match(dG)[0]),o=a.reduce((e,t)=>{let n=t.match(mG)[0].length;return n>e[1]?[t,n]:e},[a[0],0]),s=o[1]?o[0].length:0,c=_G(a.map(e=>parseInt(e)));return[`up`,`left`].includes(n)&&a.length===1&&(c=-c),{type:`ALPHANUMERIC_INCREMENT_MODIFIER`,prefix:i,current:r,increment:c,numberPostfixLength:s}},sequence:15}).add(`copy_text`,{condition:e=>!e.isFormula&&es(e,{locale:D}).type===`text`,generateRule:()=>({type:`COPY_MODIFIER`}),sequence:20}).add(`update_formula`,{condition:e=>e.isFormula,generateRule:(e,t)=>({type:`FORMULA_MODIFIER`,increment:t.length,current:0}),sequence:30}).add(`increment_dates`,{condition:(e,t)=>!e.isFormula&&es(e,{locale:D}).type===`number`&&!!e.format&&jo(e.format),generateRule:(e,t)=>{let n=yG(hG(e,t,e=>e.type===`number`&&!!e.format&&jo(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=es(e,{locale:D});return typeof n==`object`?{type:`DATE_INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}:{type:`INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}},sequence:25}).add(`increment_number`,{condition:e=>!e.isFormula&&es(e,{locale:D}).type===`number`,generateRule:(e,t,n)=>{let r=hG(e,t,e=>e.type===`number`&&!jo(e.format||``)).map(e=>Number(e.value)),i=_G(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=es(e,{locale:D});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function bG(e){return e.length<2?[{years:0,months:0,days:0}]:e.map((t,n)=>{if(n===0)return{years:0,months:0,days:0};let r=O.fromTimestamp(e[n-1].getTime()),i=Mi(r,t),a=Ai(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:ji(r,t)}}).slice(1)}var xG=class{cells;getters;index=0;direction;constructor(e,t,n){this.cells=e,this.getters=t,this.direction=n}next(){let e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:n,tooltip:r}=lG.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:n,tooltip:r,origin:{col:e.data.col,row:e.data.row}}}},SG=class extends Rp{static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:x(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:x(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(T(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(T(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(T(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(T(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(R({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s=this.getters.getRulesByCell(e,r,i),c=T(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(R({col:a,row:o})))}autofillCell(e,t){this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t.col,row:t.row,content:t.content||``,style:t.style||null,format:t.format||``}),this.dispatch(`AUTOFILL_CELL`,t)}autofillBorders(e,t){for(let n in t){let r=n===`undefined`?void 0:JSON.parse(n);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,border:r,target:ms(t[n])})}}autofillConditionalFormats(e,t){for(let n in t){let r=t[n],i=this.getters.getConditionalFormats(e).find(e=>e.id===n);if(!i)continue;let a=this.getters.getAdaptedCfRanges(e,i,r.map(Ts),[]);a&&this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:a,sheetId:e})}}autofillDataValidations(e,t){for(let n in t){let r=t[n],i=this.getters.getDataValidationRule(e,n);if(!i)continue;let a=ms(i.ranges.map(e=>e.zone).concat(r),[]);this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:i,ranges:a.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){let n=this.getters.getSelectedZone();if(Vs(e,t,n)){this.autofillZone=void 0;return}switch(this.direction=this.getDirection(e,t),this.direction){case`up`:this.saveZone(t,n.top-1,n.left,n.right),this.steps=n.top-t;break;case`down`:this.saveZone(n.bottom+1,t,n.left,n.right),this.steps=t-n.bottom;break;case`left`:this.saveZone(n.top,n.bottom,e,n.left-1),this.steps=n.left-e;break;case`right`:this.saveZone(n.top,n.bottom,n.right+1,e),this.steps=e-n.right;break}this.autofill(!1)}autofillAuto(){let e=this.getters.getActivePosition(),t=this.getters.getTable(e),n=t?t.range.zone.bottom:this.getAutofillAutoLastRow(),r=this.getters.getSelectedZone();for(let t=r.bottom+1;t<=n;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==`empty`){n=t-1;break}n>r.bottom&&(this.select(e.col,n),this.autofill(!0))}getAutofillAutoLastRow(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId(),n=e.left,r=e.bottom;if(n>0){let e={sheetId:t,col:n-1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n-1,row:r}}if(r===e.bottom&&(n=e.right,n<=this.getters.getNumberCols(t))){let e={sheetId:t,col:n+1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n+1,row:r}}return r-1}computeNewCell(e,t,n){let{cellData:r,tooltip:i,origin:a}=e.next(),{content:o,style:s,border:c,format:l}=r;return this.tooltip=i,{originCol:a.col,originRow:a.row,col:t,row:n,content:o,style:s,border:c,format:l}}getRule(e,t){let n=uG.getAll().sort((e,t)=>e.sequence-t.sequence).find(n=>n.condition(e,t));return n&&this.direction&&n.generateRule(e,t,this.direction)}createGenerator(e){let t=[],n=[],r=this.getters.getActiveSheetId();for(let t of e){let{col:e,row:i}=ir(t),a=this.getters.getCell({sheetId:r,col:e,row:i});n.push({col:e,row:i,cell:a,sheetId:r})}let i=n.map(e=>e.cell);for(let e of n){let n={type:`COPY_MODIFIER`};e&&e.cell&&(n=this.getRule(e.cell,i)||n);let r=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:r},rule:n})}return new xG(t,this.getters,this.direction)}saveZone(e,t,n,r){this.autofillZone={top:e,bottom:t,left:n,right:r}}getDirection(e,t){let n=this.getters.getSelectedZone(),r={up:{number:n.top-t,value:`up`},down:{number:t-n.bottom,value:`down`},left:{number:n.left-e,value:`left`},right:{number:e-n.right,value:`right`}};if(Object.values(r).map(e=>+(e.number>0)).reduce((e,t)=>e+t)===1)return Object.values(r).find(e=>+(e.number>0)).value;let i=r.up.number>0?`up`:`down`,a=r.left.number>0?`left`:`right`;return Math.abs(r[i].number)>=Math.abs(r[a].number)?r[i].value:r[a].value}autofillMerge(e,t){let{originCol:n,originRow:r,col:i,row:a}=t,o={sheetId:e,col:i,row:a},s={sheetId:e,col:n,row:r};if(this.getters.isInMerge(o)&&!this.getters.isInMerge(s)){let t=this.getters.getMerge(o);t&&this.dispatch(`REMOVE_MERGE`,{sheetId:e,target:[t]})}let c=this.getters.getMerge(s);c?.left===n&&c?.top===r&&this.dispatch(`ADD_MERGE`,{sheetId:e,target:[{top:a,bottom:a+c.bottom-c.top,left:i,right:i+c.right-c.left}]})}drawLayer(e){if(!this.autofillZone)return;let{ctx:t,thinLineWidth:n}=e,{x:r,y:i,width:a,height:o}=this.getters.getVisibleRect(this.autofillZone);a>0&&o>0&&(t.strokeStyle=`black`,t.lineWidth=n,t.setLineDash([3]),t.strokeRect(r,i,a,o),t.setLineDash([]))}},CG=class extends Rp{static getters=[`getAutomaticSums`];handle(e){switch(e.type){case`SUM_SELECTION`:let e=this.getters.getActiveSheetId(),{zones:t,anchor:n}=this.getters.getSelection();for(let r of t){let t=this.getAutomaticSums(e,r,n.cell);this.dispatchCellUpdates(e,t)}break}}getAutomaticSums(e,t,n){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,n):this.sumData(e,t)}sumData(e,t){let n=this.dimensionsToSum(e,t),r=this.sumDimensions(e,t,n).filter(({zone:t})=>!this.getters.isEmpty(e,t));return n.has(`ROW`)&&n.has(`COL`)&&r.push(this.sumTotal(t)),r}sumAdjacentData(e,t,n){let{col:r,row:i}=Vs(n.col,n.row,t)?n:{col:t.left,row:t.top},a=this.findAdjacentData(e,r,i);return a?this.getters.isSingleCellOrMerge(e,t)||Ws(Fs(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,Fs(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=S(n,-1,-1),a=$t(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=gt(i.filter(e=>this.isNumber(r[e])))[0]||[];return $t(o)<a?1/0:en(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&jo(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){let n=new Set;return Ws(t)?(n.add(Us(t).numberOfCols===1?`COL`:`ROW`),n):(this.lastColIsEmpty(e,t)&&n.add(`ROW`),this.lastRowIsEmpty(e,t)&&n.add(`COL`),n.size===0&&n.add(`COL`),n)}sumDimensions(e,t,n){return[...n.has(`COL`)?this.sumColumns(t,e):[],...n.has(`ROW`)?this.sumRows(t,e):[]]}sumTotal(e){let{bottom:t,right:n}=e;return{position:{col:n,row:t},zone:{...e,top:t,right:n-1}}}sumColumns(e,t){let n=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,n.bottom-1)},Ks(n).map(t=>({position:t,zone:{...e,right:t.col,left:t.col}}))}sumRows(e,t){let n=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,n.right-1)},Ks(n).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(let n of t){let{col:t,row:r}=n.position;this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:`=SUM(${this.getters.zoneToXC(e,n.zone)})`})}}nextEmptyRow(e,t){let n=t.bottom+1,{left:r,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:n,top:n,left:r,right:i});)n++;return{...t,top:n,bottom:n}}nextEmptyCol(e,t){let n=t.right+1,{top:r,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:n,right:n,top:r,bottom:i});)n++;return{...t,left:n,right:n}}transpose(e){return new Set([...e.values()].map(e=>e===`COL`?`ROW`:`COL`))}};let wG=new class extends g{addTransformation(e,t,n){this.content[e]||(this.content[e]=new Map);for(let r of t)this.content[e].set(r,n);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}},TG=new class extends g{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};wG.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],RG),wG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],RG),wG.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],kG),wG.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`,`UPDATE_CAROUSEL`],AG),wG.addTransformation(`DELETE_CHART`,[`UPDATE_CHART`],jG),wG.addTransformation(`DELETE_CHART`,[`UPDATE_CAROUSEL`],MG),wG.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],NG),wG.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],PG),wG.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],FG),wG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],FG),wG.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],IG),wG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],IG),wG.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],LG),wG.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],zG),wG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],zG),wG.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],OG),wG.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],DG),wG.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],EG),wG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],EG);function EG(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=of(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function DG(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function OG(e,t){if(e.pivotId!==t.pivotId)return e}function kG(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function AG(e,t){if(e.figureId!==t.figureId)return e}function jG(e,t){if(e.chartId!==t.chartId)return e}function MG(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!(e.type===`chart`&&e.chartId===t.chartId))}}}function NG(e,t){return e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`}),e.name===t.name?{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1}:e}function PG(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!zs(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function FG(e,t){if(e.sheetId!==t.sheetId||(e.type===`FREEZE_COLUMNS`?`COL`:`ROW`)!==t.dimension)return e;let n=e.quantity;if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);for(let t of e)n>t&&n--}if(t.type===`ADD_COLUMNS_ROWS`){let e=t.position===`before`?t.base-1:t.base;n=n>e?n+t.quantity:n}return n>0?{...e,quantity:n}:void 0}function IG(e,t){if(e.sheetId!==t.sheetId)return e;let n=of(e.zone,t);if(!n)return;let r=e.newTableRange?sf(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function LG(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:QA.styleId}}:e}function RG(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=il(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=rl(Ft(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function zG(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=S(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=il(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=rl(Ft(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function BG(e,t){let n=e.content&&mC(e.sheetId,e.content,t);return{...e,content:n}}TG.add(`UPDATE_CELL`,BG);function VG(e,t){let n=e.cf.rule;if(e={...e,cf:{...e.cf}},n.type===`CellIsRule`)e.cf.rule={...n,values:n.values.map(n=>mC(e.sheetId,n,t))};else if(n.type===`ColorScaleRule`){let{minimum:r,maximum:i,midpoint:a}=n;e.cf.rule={...n,minimum:{...r,value:r.value&&mC(e.sheetId,r.value,t)},maximum:{...i,value:i.value&&mC(e.sheetId,i.value,t)},midpoint:a?{...a,value:mC(e.sheetId,a.value,t)}:void 0}}else if(n.type===`IconSetRule`){let{upperInflectionPoint:r,lowerInflectionPoint:i}=n;e.cf.rule={...n,upperInflectionPoint:{...r,value:mC(e.sheetId,r.value,t)},lowerInflectionPoint:{...i,value:mC(e.sheetId,i.value,t)}}}else n.type===`DataBarRule`&&(e.cf.rule={...n,rangeValues:n.rangeValues?hC(e.sheetId,n.rangeValues,t).range:void 0});return e}TG.add(`ADD_CONDITIONAL_FORMAT`,VG);function HG(e,t){return e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}},e.rule.criterion.values=e.rule.criterion.values.map(n=>mC(e.sheetId,n,t)),e}TG.add(`ADD_DATA_VALIDATION_RULE`,HG);function UG(e,t){return e=b(e),e.pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=mC(e.computedBy.sheetId,e.computedBy.formula,t))}),e}TG.add(`ADD_PIVOT`,UG),TG.add(`UPDATE_PIVOT`,UG),TG.add(`CREATE_CHART`,WG),TG.add(`UPDATE_CHART`,WG);function WG(e,t){return{...e,definition:bO(e.sheetId,e.definition,t)}}let GG=[{match:pr,fn:XG},{match:hr,fn:ZG},{match:vr,fn:QG},{match:_r,fn:tK},{match:mr,fn:eK},{match:gr,fn:$G}];function KG(e,t){let n=wG.getTransformation(e.type,t.type),r=n?n(e,t):YG(e,t);return r&&qG(r,t)}function qG(e,t){let n=TG.get(e.type);if(!n)return e;let r=Gc(t);return r?n(e,r):e}function JG(e,t){let n=[...e],r=new Set(wG.getKeys());for(let e of t)(r.has(e.type)||Kc.contains(e.type))&&(n=n.reduce((t,n)=>{let r=KG(n,e);return r&&t.push(r),t},[]));return n}function YG(e,t){for(let{match:n,fn:r}of GG)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function XG(e,t){if(!(`sheetId`in t))return e;let n=t.type===`DELETE_SHEET`&&t.sheetId;return e.sheetId===n?`IGNORE_COMMAND`:e.type===`CREATE_SHEET`||t.type===`CREATE_SHEET`||e.sheetId!==t.sheetId?e:`SKIP_TRANSFORMATION`}function ZG(e,t){let n=XG(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=of(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function QG(e,t){let n=XG(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=of(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function $G(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>sf(e,t)).filter(C);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function eK(e,t){let n=XG(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;if(t.type!==`ADD_COLUMNS_ROWS`&&t.type!==`REMOVE_COLUMNS_ROWS`)return`SKIP_TRANSFORMATION`;if(t.dimension!==e.dimension)return e;let r=[];return t.type===`REMOVE_COLUMNS_ROWS`?r=il(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=rl(Ft(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function tK(e,t){let n=XG(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?nK(e,t):t.type===`ADD_MERGE`?rK(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function nK(e,t){let n=t.dimension===`COL`?`col`:`row`,r=e[n];if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);if(e.includes(r))return`IGNORE_COMMAND`;for(let t of e)r>=t&&r--}return t.type===`ADD_COLUMNS_ROWS`&&(r>t.base||r===t.base&&t.position===`before`)&&(r+=t.quantity),{...e,[n]:r}}function rK(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&Vs(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var iK=class{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,n,r,i,a){this.rootCommand=r,this.timestamp=a,this.id=e,this.clientId=t,this._commands=[...n],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}},aK=class extends Error{},oK=class extends cf{revisions;transportService;serverRevisionId;clients={};clientId=`local`;debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new jl;lastLocalOperation;constructor(e,t,n=We){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.debouncedMove=At(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new iK(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}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),void 0)}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.sendToTransport({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.sendToTransport({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){let t=this.clients[e];if(!t)throw new aK(`The client left the session`);return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(C))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId]){this.awaitingClientPosition=e;return}let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getCurrentClient();this.clients[this.clientId]={...r,position:e},this.sendToTransport({type:n,version:1,client:{...r,position:e}}).then(()=>{this.pendingMessages.length>0&&!this.waitingAck&&this.sendPendingMessage()})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){if(this.isWrongServerRevisionId(e)){this.trigger(`unexpected-revision-id`);return}switch(e.type){case`CLIENT_MOVED`:this.onClientMoved(e);break;case`CLIENT_JOINED`:this.onClientJoined(e);break;case`CLIENT_LEFT`:this.onClientLeft(e);break;case`REVISION_REDONE`:this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-redone`,{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case`REVISION_UNDONE`:this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-undone`,{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case`REMOTE_REVISION`:let{clientId:t,commands:n,timestamp:r}=e,i=new iK(e.nextRevisionId,t,n,void 0,void 0,r);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);let t=this.pendingMessages.filter(e=>e.type===`REMOTE_REVISION`).map(e=>e.commands).flat();this.trigger(`remote-revision-received`,{commands:JG(n,t)})}break;case`SNAPSHOT_CREATED`:{let t=new iK(e.nextRevisionId,`server`,[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger(`snapshot`),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger(`collaborative-event-received`)}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;let t=this.clients[this.clientId];if(t){let{position:e}=t;e&&this.sendToTransport({type:`CLIENT_MOVED`,version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),!this.waitingAck&&this.sendPendingMessage()}async sendToTransport(e){return this.transportService.sendMessage(e)}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if(e.type===`REMOTE_REVISION`){let t=this.revisions.get(e.nextRevisionId);t.commands.length===0&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.
1930
- ${JSON.stringify(e)}`);this.waitingAck=!0,this.sendToTransport({...e,serverRevisionId:this.serverRevisionId}).catch(e=>{if(!(e instanceof aK))throw e.cause||e;this.waitingAck=!1})}}acknowledge(e){switch((e.type===`REVISION_UNDONE`||e.type===`REVISION_REDONE`)&&(this.waitingUndoRedoAck=!1),e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`SNAPSHOT_CREATED`:this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case`REVISION_UNDONE`:{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId);let t=this.pendingMessages.findIndex(e=>e.type===`REMOTE_REVISION`);t!==-1&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if(e.type===`CLIENT_MOVED`&&e.client.id===this.clientId)return!0;switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter(({type:e})=>e!==`REVISION_REDONE`&&e!==`REVISION_UNDONE`)}},sK=class extends Rp{static getters=[`getClientsToDisplay`,`getClient`,`getCurrentClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];colors=new Gn(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 aK)return[];throw e}let e=this.getters.getActiveSheetId(),t=[];for(let n of this.getters.getConnectedClients())n.id!==this.getters.getCurrentClient().id&&n.position&&n.position.sheetId===e&&this.isPositionValid(n.position)&&t.push({...n,position:n.position});return t}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getters.getActiveSheetId();for(let e of this.getClientsToDisplay()){let{row:i,col:a}=e.position,o=this.getters.expandZone(r,{top:i,bottom:i,left:a,right:a}),{x:s,y:c,width:l,height:u}=this.getters.getVisibleRect(o);if(l<=0||u<=0)continue;let d=e.color;t.fillStyle=`${d}10`,t.lineWidth=4*n,t.strokeStyle=d,t.globalCompositeOperation=`multiply`,t.fillRect(s,c,l,u),t.globalCompositeOperation=`source-over`,t.strokeRect(s,c,l,u),t.font=`bold ${Ve+1}px ${He}`}}},cK=class extends Rp{allowDispatch(e){switch(e.type){case`REMOVE_DUPLICATES`:return this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique))}return`Success`}handle(e){switch(e.type){case`REMOVE_DUPLICATES`:this.removeDuplicates(e.columns,e.hasHeader);break;case`TRIM_WHITESPACE`:this.trimWhitespace();break}}removeDuplicates(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getSelectedZone();t&&(r.top+=1);let i=this.getUniqueRowsIndexes(n,r.top,r.bottom,e),a=i.length;if(a===Us(r).numberOfRows){this.notifyRowsRemovedAndRemaining(0,a);return}let o=i.map(e=>({left:r.left,top:e,right:r.right,bottom:e})),s=new Yd(this.getters,this.dispatch),c=s.copy(Nl(n,o),!1);if(!c)return;this.dispatch(`CLEAR_CELLS`,{target:[r],sheetId:n});let l={left:r.left,top:r.top,right:r.left,bottom:r.top};s.paste({zones:[l],sheetId:n},c,{isCutOperation:!1});let u={left:r.left,top:r.top-+!!t,right:r.right,bottom:r.top+a-1};this.selection.selectZone({cell:{col:u.left,row:u.top},zone:u});let d=r.bottom-r.top+1-a;this.notifyRowsRemovedAndRemaining(d,a)}getUniqueRowsIndexes(e,t,n,r){let i=new Map;for(let a of S(t,n+1)){let t=r.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:a}).value);Object.values(i).some(e=>w(e,t))||(i[a]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:`info`,text:E(`%s duplicate rows found and removed.
1931
- %s unique rows remain.`,e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return this.getters.getSelectedZones().length===1?`Success`:`MoreThanOneRangeSelected`}checkNoMergeInZone(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?`WillRemoveExistingMerge`:`Success`}checkRangeContainsValues(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedZone();return e.hasHeader&&(n.top+=1),this.getters.getEvaluatedCellsInZone(t,n).every(e=>e.type===`empty`)?`EmptyTarget`:`Success`}checkNoColumnProvided(e){return e.columns.length===0?`NoColumnsProvided`:`Success`}checkColumnsIncludedInZone(e){let t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?`ColumnsNotIncludedInZone`:`Success`}checkColumnsAreUnique(e){return e.columns.length===new Set(e.columns).size?`Success`:`DuplicatesColumnsSelected`}trimWhitespace(){let e=ms(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(Ks).flat()){let e=this.getters.getCell({col:r,row:i,sheetId:t});if(!e)continue;let a=Xt(e.content);a!==e.content&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:a}))}let r=n?E(`Trimmed whitespace from %s cells.`,n):E(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}},lK=class extends Rp{handle(e){switch(e.type){case`SET_DECIMAL`:this.setDecimal(e.sheetId,e.target,e.step);break;case`SET_FORMATTING_WITH_PIVOT`:this.setContextualFormat(e.sheetId,e.target,e.format);break}}setContextualFormat(e,t,n){let r=[],i={};for(let n of ms(t))for(let t=n.left;t<=n.right;t++)for(let a=n.top;a<=n.bottom;a++){let n={sheetId:e,col:t,row:a},o=this.getters.getPivotCellFromPosition(n);if(this.isSpilledPivotValueFormula(n,o)){r.push(n);let e=this.getters.getPivotIdFromPosition(n)||``;i[e]??=new Set,i[e].add(o.measure)}}let a=ms(r.map(R));for(let e in i){let t=i[e],r=this.getters.getPivotCoreDefinition(e);this.dispatch(`UPDATE_PIVOT`,{pivotId:e,pivot:{...r,measures:r.measures.map(e=>t.has(e.id)?{...e,format:n}:e)}})}this.dispatch(`SET_FORMATTING`,{sheetId:e,target:a,format:``}),this.dispatch(`SET_FORMATTING`,{sheetId:e,target:ms(t,a),format:n})}isSpilledPivotValueFormula(e,t){let n=this.getters.getCell(e);return t.type===`VALUE`&&!n?.isFormula}setDecimal(e,t,n){let r={};for(let i of ms(t))for(let t of Ks(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=Jo(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=ms(r[t].map(e=>R(e)));this.setContextualFormat(e,n,t)}}getCellNumberFormat(e){for(let t of[e]){let e=this.getters.getEvaluatedCell(t);if(e.type===`number`&&!(e.format&&jo(e.format)))return e.format||Fo(e.value)}}},uK=class extends Rp{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){console.error(`No geoJsonService provided to the model`);return}let t=this.geoJsonCache[e];if(!(t instanceof Promise)){if(t!==void 0)return t??void 0;this.geoJsonCache[e]=new Promise(async t=>{let n=await this.geoJsonService?.getTopoJson(e);this.geoJsonCache[e]=this.convertToGeoJson(n),this.dispatch(`EVALUATE_CHARTS`),t()})}}geoFeatureNameToId(e,t){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}return this.geoJsonService.geoFeatureNameToId(e,t)}convertToGeoJson(e){if(!e)return null;if(e.type===`Topology`){let t=window.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return t.type===`FeatureCollection`?t.features:[t]}else if(e.type===`FeatureCollection`)return e.features;throw Error(`Invalid TopoJSON`)}},dK=class extends Rp{static getters=[`getNextVisibleCellPosition`,`findVisibleHeader`,`findLastVisibleColRowIndex`,`findFirstVisibleColRowIndex`,`isRowHidden`,`isColHidden`,`isHeaderHidden`];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,n){return t===`COL`?this.isColHidden(e,n):this.isRowHidden(e,n)}getNextVisibleCellPosition({sheetId:e,col:t,row:n}){return{sheetId:e,col:this.findVisibleHeader(e,`COL`,t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,n,r){if(n<=r){for(let i=n;i<=r;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}if(n>r){for(let i=n;i>=r;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}}findLastVisibleColRowIndex(e,t,{last:n,first:r}){return S(n,r,-1).find(n=>!this.isHeaderHidden(e,t,n))||r}findFirstVisibleColRowIndex(e,t){let n=this.getters.getNumberHeaders(e,t);for(let r=0;r<n;r++)if(t===`COL`&&!this.isColHidden(e,r)||t===`ROW`&&!this.isRowHidden(e,r))return r}exportForExcel(e){for(let t of e.sheets)for(let[e,n]of Object.entries(t.rows))n.isHidden=this.isRowHidden(t.id,Number(e))}},fK=class extends Rp{static getters=[];allowDispatch(e){switch(e.type){case`DUPLICATE_PIVOT_IN_NEW_SHEET`:if(!this.getters.isExistingPivot(e.pivotId))return`PivotIdNotFound`;if(!this.getters.getPivot(e.pivotId).isValid())return`PivotInError`;break}return`Success`}handle(e){switch(e.type){case`INSERT_NEW_PIVOT`:this.insertNewPivot(e.pivotId,e.newSheetId);break;case`DUPLICATE_PIVOT_IN_NEW_SHEET`:this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case`INSERT_PIVOT_WITH_TABLE`:this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case`SPLIT_PIVOT_FORMULA`:this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){nc(this.getters.getSelectedZone())===1&&this.selection.selectTableAroundSelection();let n=this.getters.getActiveSheetId();this.dispatch(`ADD_PIVOT`,{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:n},columns:[],rows:[],measures:[],name:E(`New pivot`),type:`SPREADSHEET`}});let r=this.getters.getSheetIds().findIndex(e=>e===n)+1,i=this.getters.getPivotFormulaId(e);this.dispatch(`CREATE_SHEET`,{sheetId:t,name:E(`Pivot #%(formulaId)s`,{formulaId:i}),position:r}),this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:t});let a=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,a.getCollapsedTableStructure().export(),`dynamic`)}duplicatePivotInNewSheet(e,t,n){this.dispatch(`DUPLICATE_PIVOT`,{pivotId:e,newPivotId:t,duplicatedPivotName:E(`%s (copy)`,this.getters.getPivotCoreDefinition(e).name)});let r=this.getters.getActiveSheetId(),i=this.getters.getSheetIds().indexOf(r)+1,a=this.getters.getPivotFormulaId(t),o=this.getters.getPivotName(t);if(this.dispatch(`CREATE_SHEET`,{sheetId:n,name:this.getPivotDuplicateSheetName(E(`%(newPivotName)s (Pivot #%(formulaId)s)`,{newPivotName:o,formulaId:a})),position:i}).isSuccessful){this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:r,sheetIdTo:n});let i=this.getters.getPivot(e);this.insertPivotWithTable(n,0,0,t,i.getCollapsedTableStructure().export(),`dynamic`)}}getPivotDuplicateSheetName(e){let t=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e));return an(ht(e),t)}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new nR(o,s,c,l||{}),d=u.columns.length-1;this.resizeSheet(e,t,n,u);let f=this.getters.getPivotFormulaId(r),p;a===`dynamic`?(this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:n,content:`=PIVOT(${f})`}),p={left:t,right:t,top:n,bottom:n}):(this.dispatch(`INSERT_PIVOT`,{sheetId:e,col:t,row:n,pivotId:r,table:u.export()}),p={left:t,right:t+u.getNumberOfDataColumns(),top:n,bottom:n+d+u.rows.length}),this.dispatch(`CREATE_TABLE`,{tableType:a,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,p)],config:{...tt,numberOfHeaders:d}})}resizeSheet(e,t,n,r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}splitPivotFormula(e,t,n,r){let i=this.getters.getSpreadZone({sheetId:e,col:t,row:n});if(!i)return;let a=this.getters.getPivotFormulaId(r),o=new Map;for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++){let r={sheetId:e,col:t,row:n};o.set(r,this.getters.getPivotCellFromPosition(r))}for(let[e,t]of o)this.dispatch(`UPDATE_CELL`,{...e,content:Md(a,t)});if(this.getters.getCoreTable({sheetId:e,col:t,row:n})?.type===`dynamic`){let r=R({col:t,row:n}),a=this.getters.getRangeDataFromZone(e,i);this.dispatch(`UPDATE_TABLE`,{sheetId:e,zone:r,newTableRange:a,tableType:`static`})}}},pK=class extends Rp{allowDispatch(e){switch(e.type){case`SORT_CELLS`:return Vs(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):`InvalidSortAnchor`}return`Success`}handle(e){switch(e.type){case`SORT_CELLS`:this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{});break}}checkMerge({sheetId:e,zone:t}){return this.getters.doesIntersectMerge(e,t)&&Ks(t).some(({col:t,row:n})=>!this.getters.isInMerge({sheetId:e,col:t,row:n}))?`InvalidSortZone`:`Success`}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return`Success`;let n=this.getters.getMerges(e).filter(e=>zs(e,t)),r=Us(n[0]),[i,a]=[r.numberOfCols,r.numberOfRows];return n.every(e=>{let[t,n]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&n===a})?`Success`:`InvalidSortZone`}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return Ks(t).some(({col:t,row:n})=>{let r=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:n});return r&&!w(r,{sheetId:e,col:t,row:n})})?`SortZoneWithArrayFormulas`:`Success`}hasHeader(e,t){if(t[0].length===1)return!1;let n=t.map(t=>t.map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).type));return n[0][0]===`empty`&&(n=n.slice(1)),n.some(e=>e[0]===`empty`)?!1:!!n.some(e=>e[1]!==`empty`&&e[0]!==e[1])}sortZone(e,t,n,r,i){let[a,o]=this.mainCellsSteps(e,n),s=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,c=Object.assign({},n),l=this.mainCells(e,n);!i.sortHeaders&&this.hasHeader(e,l)&&(c.top+=o),l=this.mainCells(e,c);let u=l[s-c.left],d=vv(u.map(e=>this.getters.getEvaluatedCell(e)),r,!!i.emptyCellAsZero).map(e=>e.index),[f,p]=[l.length,l[0].length],m=[];for(let e=0;e<f;e++)for(let t=0;t<p;t++){let{col:n,row:r,sheetId:i}=l[e][d[t]],s=this.getters.getCell({sheetId:i,col:n,row:r}),u=c.left+e*a,f=c.top+t*o,p={sheetId:i,col:u,row:f,content:``};if(s){let e=s.content;if(s.isFormula){let t=this.getters.getCellPosition(s.id);e=this.getters.getTranslatedCellFormula(i,0,f-t.row,s.compiledFormula.tokens)}p.style=s.style,p.content=e,p.format=s.format}m.push(p)}m.forEach(e=>this.dispatch(`UPDATE_CELL`,e))}mainCellsSteps(e,t){let n=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[n?n.right-n.left+1:1,n?n.bottom-n.top+1:1]}mainCells(e,t){let[n,r]=this.mainCellsSteps(e,t),i=[],a=S(t.left,t.right+1,n),o=S(t.top,t.bottom+1,r);for(let t of a){let n=[];i.push(n);for(let r of o)n.push({sheetId:e,col:t,row:r})}return i}},mK=class extends Rp{static getters=[`shouldShowFormulas`];showFormulas=!1;handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.showFormulas=e.show;break}}shouldShowFormulas(){return this.showFormulas}},hK=class extends Rp{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(let t of e.cols){let n=this.getColMaxWidth(e.sheetId,t);n!==0&&this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:[t],dimension:`COL`,size:n,sheetId:e.sheetId})}break;case`AUTORESIZE_ROWS`:this.autoResizeRows(e.sheetId,e.rows);break;case`DELETE_UNFILTERED_CONTENT`:let t=[];for(let n of e.target){let r=gt(S(n.top,n.bottom+1).filter(t=>!this.getters.isRowFiltered(e.sheetId,t)));for(let e of r)t.push({...n,top:e[0],bottom:e[e.length-1]})}this.dispatch(`DELETE_CONTENT`,{sheetId:e.sheetId,target:t});break}}getCellWidth(e){let t=this.getters.getCellComputedStyle(e),n=0,r=this.getters.getEvaluatedCell(e).formattedValue;if(r){let e=Cl(this.ctx,r,t,void 0);n+=Math.max(...e.map(e=>ml(this.ctx,e,t)))}for(let t of this.getters.getCellIcons(e))n+=t.margin+t.size;if(this.getters.getDataValidationChipStyle(e)&&(n+=10),n===0)return 0;if(n+=8,t.wrapping===`wrap`){let t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,n)}return n}getTextWidth(e,t){return ml(this.ctx,e,t)}getCellText(e,t){let n=this.getters.getCell(e),r=this.getters.getLocale();if(t?.showFormula&&n?.isFormula)return gu(n.content,r);if(t?.showFormula&&!n?.content)return``;{let i=this.getters.getEvaluatedCell(e),a=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>ml(this.ctx,e,n?.style||{})}:void 0;return L(i.value,{format:i.format,locale:r,formatWidth:a})}}getCellMultiLineText(e,t){let n=this.getters.getCellStyle(e),r=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.formatWidth});return Cl(this.ctx,r,n,t.wrapText?t.maxWidth:void 0)}computeTextYCoordinate(e,t,n=ze,r=1){let i=e.y+1,a=ll(t,r);if(e.height>a+8){if(n===`middle`)return Math.ceil(i+(e.height-a)/2);if(n===`bottom`)return i+e.height-a-4}return i+4}getContiguousZone(e,t){let n=t=>{for(let n of S(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:n,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:n,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(let n of S(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:n}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:n}))return{...t,right:t.right+1}}return t},r=!1,i=t;do{r=!1;let e=n(i);Rs(i,e)||(r=!0,i=e)}while(r);return i}isCellEmpty(e){let t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===`empty`}getColMaxWidth(e,t){let n=Ks(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,$t(n))}checkSheetExists(e){return`sheetId`in e&&this.getters.tryGetSheet(e.sheetId)===void 0?`InvalidSheetId`:`Success`}checkZonesAreInSheet(e){let t=`sheetId`in e?e.sheetId:this.getters.tryGetActiveSheetId();if(`ranges`in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId)))return`InvalidSheetId`;let n=this.getters.getCommandZones(e);return!t&&n.length>0?`NoActiveSheet`:t&&n.length>0?this.getters.checkZonesExistInSheet(t,n):`Success`}autoResizeRows(e,t){let n=[];for(let r of t){let t=0;for(let n of this.getters.getRowCells(e,r)){let r=this.getters.getCellById(n);if(!r)continue;let i=this.getters.getCellPosition(r.id),a=this.getters.getColSize(e,i.col);if(r.isFormula||this.getters.getArrayFormulaSpreadingOn(i)){let e=this.getters.getEvaluatedCell(i).formattedValue,n=dl(this.ctx,e,r?.style,a);n>t&&n>23&&(t=n)}else{let e=r.content,n=dl(this.ctx,e,r?.style,a);n>=t&&n>23&&(t=0)}}n.push(t||null)}let r=new Map(n.map(e=>[e,[]]));for(let e=0;e<n.length;e++)r.get(n[e])?.push(t[e]);for(let[t,n]of r)this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:n,dimension:`ROW`,size:t,sheetId:e})}},gK=class extends Rp{static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(yr.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(vK(e)){`sheetId`in e?delete this.tableStyles[e.sheetId]:this.tableStyles={};return}}finalize(){for(let e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(let t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}computeTableStyle(e,t){return Nt(()=>{let{config:n,numberOfCols:r,numberOfRows:i}=this.getTableRuntimeConfig(e,t),a=vI(n,this.getters.getTableStyle(t.config.styleId),r,i),o=this.getTableMapping(e,t),s={borders:{},styles:{}};for(let e=0;e<r;e++){let t=o.colMapping[e];s.borders[t]={},s.styles[t]={};for(let n=0;n<i;n++){let r=o.rowMapping[n];s.borders[t][r]=a.borders[e][n],s.styles[t][r]=a.styles[e][n]}}return s})}getTableRuntimeConfig(e,t){let n=t.range.zone,r={...t.config},i=n.right-n.left+1,a=n.bottom-n.top+1;for(let i=n.top;i<=n.bottom;i++)this.getters.isRowHidden(e,i)&&(a--,i-n.top<t.config.numberOfHeaders&&(r.numberOfHeaders--,r.numberOfHeaders<0&&(r.numberOfHeaders=0)),i===n.bottom&&(r.totalRow=!1));for(let t=n.left;t<=n.right;t++)this.getters.isColHidden(e,t)&&(i--,t===n.left&&(r.firstColumn=!1),t===n.right&&(r.lastColumn=!1));return{config:r,numberOfCols:i,numberOfRows:a}}getTableMapping(e,t){let n={},r={},i=0,a=0,o=t.range.zone;for(let t=o.left;t<=o.right;t++)if(!this.getters.isColHidden(e,t)){n[i]=t,i++;for(let t=o.top;t<=o.bottom;t++)this.getters.isRowHidden(e,t)||(r[a]=t,a++)}return{colMapping:n,rowMapping:r}}};let _K=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 vK(e){return _K.has(e.type)}var yK=class extends Rp{static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles=new LF;borders=new LF;handle(e){if(yr.has(e.type)||e.type===`UPDATE_CELL`||e.type===`SET_FORMATTING`||e.type===`CLEAR_FORMATTING`||e.type===`ADD_DATA_VALIDATION_RULE`||e.type===`REMOVE_DATA_VALIDATION_RULE`||e.type===`EVALUATE_CELLS`){this.styles=new LF,this.borders=new LF;return}if(vK(e)){`sheetId`in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new LF,this.borders=new LF);return}if(Sr.has(e.type)){this.styles=new LF;return}if(Cr.has(e.type)){this.borders=new LF;return}}getCellComputedBorder(e){let t=this.borders.get(e);return t===void 0&&(t=this.computeCellBorder(e),this.borders.set(e,t)),t}getCellComputedStyle(e){let t=this.styles.get(e);return t===void 0&&(t=this.computeCellStyle(e),this.styles.set(e,t)),t}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...zt(this.getters.getCellTableBorder(e)||{}),...zt(t)};return kt(n)?null:n}computeCellStyle(e){let t=this.getters.getCell(e),n=this.getters.getCellConditionalFormatStyle(e),r=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e),a={...zt(r),...zt(i),...zt(t?.style),...zt(n)};return this.getters.getEvaluatedCell(e).link&&!a.textColor&&(a.textColor=le),a}},bK=class extends Rp{static getters=[`hasBooleanValidationInZones`];handle(e){switch(e.type){case`TOGGLE_CHECKBOX`:this.toggleCheckbox(e.sheetId,e.target);break}}hasBooleanValidationInZones(e){let t=this.getters.getActiveSheetId();for(let n of e)for(let e=n.left;e<=n.right;e++)for(let r=n.top;r<=n.bottom;r++)if(this.getters.isCellValidCheckbox({col:e,row:r,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n={col:t,row:r,sheetId:e};if(this.getters.isCellValidCheckbox(n)){let e=this.getters.getEvaluatedCell(n).value?`FALSE`:`TRUE`;this.dispatch(`UPDATE_CELL`,{...n,content:e})}}}},xK=class extends Rp{handle(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:if(e.rule.criterion.type===`isBoolean`){let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));for(let e of Vc(t)){let t=this.getters.getCell(e),n=this.getters.getEvaluatedCell(e);if(!t?.content)this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`});else if(t?.content&&n.type===`empty`){let n;if(t.content.startsWith(`=`)){let r=this.getters.evaluateFormula(e.sheetId,t.content);n=(Ir(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!vt(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==`boolean`&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}},SK=class extends Rp{static getters=[`dynamicTranslate`];dynamicTranslate(e){return e}};let CK=[wK,TK,DK,OK];function wK(e,t){return`sheetId`in t?{...b(t),sheetId:e.getActiveSheetId()}:t}function TK(e,t){return!(`target`in t)||!Array.isArray(t.target)?t:{...b(t),target:e.getSelectedZones()}}function EK(e,t){return`zone`in t?{...b(t),zone:e.getSelectedZone()}:t}function DK(e,t){if(!(`row`in t)||!(`col`in t))return t;let{col:n,row:r}=e.getActivePosition();return{...b(t),col:n,row:r}}function OK(e,t){return`ranges`in t?{...b(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}let kK=new jl;function AK(e,t){let n=kK.smallUuid();return{...wK(e,t),figureId:n,chartId:n}}function jK(e,t){return{...wK(e,t),figureId:kK.smallUuid()}}function MK(e,t){let n=DK(e,wK(e,t));return n.figureId=kK.smallUuid(),n}function NK(e,t){let n=b(t);n.sheetId=kK.smallUuid();let r=t.name||e.getSheet(e.getActiveSheetId()).name,i=r.match(/(.+?)\d*$/)?.[1]||r;return n.name=e.getNextSheetName(i),n}function PK(e,t){let n=e.getActivePosition();return{...wK(e,t),base:t.dimension===`COL`?n.col:n.row}}function FK(e,t){let n=e.getSelectedZone();return{...wK(e,t),elements:t.dimension===`COL`?S(n.left,n.right+1):S(n.top,n.bottom+1)}}function IK(e,t){let n=e.getSelectedZone();return{...b(t),zone:n}}function LK(e,t){let n=b(t),{top:r,bottom:i,left:a,right:o}=e.getSelectedZone();return`cols`in n?n.cols=S(a,o+1):`rows`in n&&(n.rows=S(r,i+1)),n}function RK(e,t){let n=e.getSelectedZone();return{...wK(e,t),col:n.left,row:n.top,zone:n}}function zK(e,t){return{type:`REPEAT_PASTE`,pasteOption:b(t.pasteOption),target:e.getSelectedZones()}}function BK(e,t){let n=e.getSelectedZone();return{...wK(e,t),start:t.dimension===`COL`?n.left:n.top,end:t.dimension===`COL`?n.right:n.bottom}}let VK=new g;VK.add(`UPDATE_CELL`,UK),VK.add(`CLEAR_CELL`,UK),VK.add(`CLEAR_CELLS`,UK),VK.add(`DELETE_CONTENT`,UK),VK.add(`ADD_MERGE`,UK),VK.add(`REMOVE_MERGE`,UK),VK.add(`SET_FORMATTING`,UK),VK.add(`CLEAR_FORMATTING`,UK),VK.add(`SET_BORDER`,UK),VK.add(`CREATE_TABLE`,UK),VK.add(`REMOVE_TABLE`,UK),VK.add(`HIDE_SHEET`,UK),VK.add(`ADD_COLUMNS_ROWS`,PK),VK.add(`REMOVE_COLUMNS_ROWS`,FK),VK.add(`HIDE_COLUMNS_ROWS`,FK),VK.add(`RESIZE_COLUMNS_ROWS`,FK),VK.add(`CREATE_SHEET`,NK),VK.add(`CREATE_FIGURE`,MK),VK.add(`CREATE_CHART`,AK),VK.add(`CREATE_IMAGE`,jK),VK.add(`GROUP_HEADERS`,BK),VK.add(`UNGROUP_HEADERS`,BK),VK.add(`UNFOLD_HEADER_GROUPS_IN_ZONE`,EK),VK.add(`FOLD_HEADER_GROUPS_IN_ZONE`,EK);let HK=new g;HK.add(`PASTE`,zK),HK.add(`INSERT_CELL`,IK),HK.add(`DELETE_CELL`,IK),HK.add(`AUTORESIZE_COLUMNS`,LK),HK.add(`AUTORESIZE_ROWS`,LK),HK.add(`SORT_CELLS`,RK),HK.add(`SUM_SELECTION`,UK),HK.add(`SET_DECIMAL`,UK),HK.add(`DELETE_UNFILTERED_CONTENT`,UK);function UK(e,t){let n=b(t);for(let t of CK)n=t(e,n);return n}function WK(e,t){if(t&&VK.contains(t.type))return VK.get(t.type)(e,t)}function GK(e,t,n){if(HK.contains(t.type))return HK.get(t.type)(e,t,n)}function KK(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:Dr(e.rootCommand)?VK.contains(e.rootCommand.type):HK.contains(e.rootCommand.type)}function qK(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return Dr(e.rootCommand)?WK(t,e.rootCommand):GK(t,e.rootCommand,e.commands)}var JK=class extends Rp{static getters=[`canUndo`,`canRedo`];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on(`new-local-state-update`,this,this.onNewLocalStateUpdate),this.session.on(`snapshot`,this,()=>{this.undoStack=[],this.redoStack=[]})}allowDispatch(e){switch(e.type){case`REQUEST_UNDO`:if(!this.canUndo())return`EmptyUndoStack`;break;case`REQUEST_REDO`:if(!this.canRedo())return`EmptyRedoStack`;break}return`Success`}handle(e){switch(e.type){case`REQUEST_UNDO`:case`REQUEST_REDO`:this.requestHistoryChange(e.type===`REQUEST_UNDO`?`UNDO`:`REDO`)}}finalize(){}requestHistoryChange(e){let t=e===`UNDO`?this.undoStack.pop():this.redoStack.pop();if(!t){let e=this.getPossibleRevisionToRepeat();if(!e)return;let t=qK(e,this.getters);if(!t)return;if(!Array.isArray(t)){this.dispatch(t.type,t);return}for(let e of t)this.dispatch(e.type,e);return}e===`UNDO`?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0?!0:KK(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},YK=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,N(e.value)])}isValuePresent(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(n)}isHeaderPresent(e){let t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(n)}trackHeader(e){let t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}},XK=class extends Rp{static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new YK,this.trackPresencePivotId=e.pivotId;break;case`PIVOT_STOP_PRESENCE_TRACKING`:this.trackPresencePivotId=void 0;break}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw Error(`Tracker not initialized`);return this.tracker}}},ZK=class extends Rp{static getters=[`getAutomaticSeparator`];allowDispatch(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:return this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e)}return`Success`}handle(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:this.splitIntoColumns(e);break}}getAutomaticSeparator(){let e=this.getters.getSelectedCells();for(let t of e)if(t.value&&t.type===`text`){let e=this.getAutoSeparatorForString(t.value);if(e)return e}return` `}getAutoSeparatorForString(e){for(let t of[`
1932
- `,`;`,`,`,` `,`.`])if(e.includes(t))return t}splitIntoColumns({separator:e,addNewColumns:t}){let n=this.getters.getSelectedZone(),r=this.getters.getActiveSheetId(),i=this.getSplittedCols(n,e);t&&this.addColsToAvoidCollisions(n,i),this.removeMergesInSplitZone(n,i),this.addColumnsToNotOverflowSheet(n,i);for(let e=0;e<i.length;e++){let t=n.top+e,a=i[e],o=n.left,s=this.getters.getCell({sheetId:r,col:o,row:t});if(!(a.length===1&&a[0]===s?.content))for(let[e,n]of a.entries())this.dispatch(`UPDATE_CELL`,{sheetId:r,col:o+e,row:t,content:du(n,this.getters.getLocale()),format:``,style:s?.style||null})}}getSplittedCols(e,t){if(!t)throw Error(`Separator cannot be empty`);let n=this.getters.getActiveSheetId(),r=[];for(let i of S(e.top,e.bottom+1)){let a=this.getters.getEvaluatedCell({sheetId:n,col:e.left,row:i}).formattedValue;r.push(this.splitAndRemoveTrailingEmpty(a,t))}return r}splitAndRemoveTrailingEmpty(e,t){let n=e.split(t);for(;n.length>1&&n[n.length-1]===``;)n.pop();return n}willSplittedColsOverwriteContent(e,t){let n=this.getters.getActiveSheetId();for(let r of S(e.top,e.bottom+1)){let i=t[r-e.top];for(let t=1;t<i.length;t++){let i=this.getters.getCell({sheetId:n,col:e.left+t,row:r});if(i&&i.content)return!0}}return!1}removeMergesInSplitZone(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length)),i={...e,right:e.left+r-1},a=this.getters.getMergesInZone(n,i);this.dispatch(`REMOVE_MERGE`,{sheetId:n,target:a})}addColsToAvoidCollisions(e,t){let n=this.getters.getActiveSheetId(),r=0;for(let i of S(e.top,e.bottom+1)){let a={sheetId:n,col:e.left,row:i},o=t[i-e.top],s=this.getColsToAddToAvoidCollision(a,o);r=Math.max(r,s)}r&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:e.left,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:r,position:`after`})}getColsToAddToAvoidCollision(e,t){let n=t.length;for(let t=1;t<n;t++){let r=e.col+t,i=this.getters.getCell({...e,col:r});if(i&&i.content)return n-t}return 0}addColumnsToNotOverflowSheet(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length-1)),i=this.getters.getNumberCols(n)-1;e.left+r>i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:i,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:e.left+r-i,position:`after`})}checkSingleColSelected(){return this.getters.isSingleColSelected()?`Success`:`MoreThanOneColumnSelected`}checkNonEmptySelector(e){return e.separator===``?`EmptySplitSeparator`:`Success`}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return`Success`;let t=this.getters.getSelectedZones()[0],n=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,n)?`SplitWillOverwriteContent`:`Success`}checkSeparatorInSelection({separator:e}){let t=this.getters.getSelectedCells();for(let n of t)if(n.formattedValue.includes(e))return`Success`;return`NoSplitSeparatorInSelection`}},QK=class extends Rp{handle(e){switch(e.type){case`AUTOFILL_TABLE_COLUMN`:let t=this.getters.getCoreTable(e),n=this.getters.getCell(e);if(!t?.config.automaticAutofill||t.type===`dynamic`||!n?.isFormula)return;let{col:r,row:i}=e,a=mI(t.range.zone,t.config);if(a&&Vs(r,i,a)){let t=e.autofillRowStart??a.top,n=e.autofillRowEnd??a.bottom,r={...a,top:t,bottom:n};this.autofillTableZone(e,r)}break}}autofillTableZone(e,t){if(t.top===t.bottom)return;let{col:n,row:r,sheetId:i}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==r&&this.getters.getEvaluatedCell({col:n,row:e,sheetId:i}).type!==`empty`)return;let a={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.bottom}),this.dispatch(`AUTOFILL`),this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.top}),this.dispatch(`AUTOFILL`),this.selection.selectZone(a)}},$K=class extends Rp{allowDispatch(e){switch(e.type){case`RESIZE_TABLE`:let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return`TableNotFound`;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;return r.top!==n.top||r.left!==n.left?`InvalidTableResize`:this.canDispatch(`UPDATE_TABLE`,{...e}).reasons}return`Success`}handle(e){switch(e.type){case`RESIZE_TABLE`:{let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch(`UPDATE_TABLE`,{...e}),!t)return;let n=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(n.right,n.bottom),!t.config.automaticAutofill)return;let r=t.range.zone;if(n.bottom>=r.bottom){for(let t=n.left;t<=n.right;t++){let i={col:t,row:r.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.content.startsWith(`=`)&&this.dispatch(`AUTOFILL_TABLE_COLUMN`,{...i,autofillRowStart:r.bottom,autofillRowEnd:n.bottom})}break}}}}},eq=class extends Rp{static layers=[`Clipboard`];static getters=[`getClipboardTextAndImageContent`,`getClipboardId`,`getClipboardTextContent`,`isCutOperation`];status=`invisible`;originSheetId;copiedData;_isCutOperation=!1;clipboardId=new jl().uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new jl}allowDispatch(e){switch(e.type){case`CUT`:let t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case`PASTE_FROM_OS_CLIPBOARD`:{let t=this.convertTextToClipboardData(e.clipboardContent.text??``),n=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:n,isCutOperation:!1})}case`PASTE`:{if(!this.copiedData)return`EmptyClipboard`;let t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].top===0&&e[0].bottom===0)return`InvalidCopyPasteSelection`;break}case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].left===0&&e[0].right===0)return`InvalidCopyPasteSelection`;break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}}return`Success`}handle(e){switch(e.type){case`COPY`:case`CUT`:let t=this.getters.getSelectedZones();this.status=`visible`,this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation=e.type===`CUT`,this.copiedData=this.copy(t);break;case`PASTE_FROM_OS_CLIPBOARD`:{this._isCutOperation=!1;let t=e.clipboardContent;if(t.data?.version!==bP()&&(t={...t},delete t.data),t.imageData){let n=this.getters.getActiveSheetId(),r=this.uuidGenerator.uuidv4(),i=t.imageData,a=CO(this.getters,i.size);this.dispatch(`CREATE_IMAGE`,{definition:i,size:a,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:n,figureId:r})}t.data?this.copiedData=t.data:this.copiedData=this.convertTextToClipboardData(t.text??``);let n=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:n,selectTarget:!0,isCutOperation:!1}),this.status=`invisible`,this.copiedData=void 0;break}case`PASTE`:{let t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status=`invisible`,this._isCutOperation&&=(this.copiedData=void 0,!1);break}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZone(),t=e.top!==e.bottom,n={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZone(),t=e.left!==e.right,n={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`CLEAN_CLIPBOARD_HIGHLIGHT`:this.status=`invisible`;break;case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Os(t[0])){this.dispatch(`CLEAR_CELLS`,{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}let r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`ADD_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard(e.position===`before`?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case`REMOVE_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;for(let t of e.elements)if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}this.status=`invisible`;break;case`REPEAT_PASTE`:this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case`DELETE_SHEET`:if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status=`invisible`);break;default:Dr(e)&&(this.status=`invisible`)}}convertTextToClipboardData(e){let t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),n={};for(let{handlerName:r,handler:i}of t){let t=i.convertTextToClipboardData(e);n[r]=t;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])t&&e in t&&(n[e]=t[e])}return n}selectClipboardHandlers(e){let t=`figureId`in e?af.figureHandlers:af.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){let t=this.getClipboardData(e);for(let{handler:e}of this.selectClipboardHandlers(t)){let n=e.isCutAllowed(t);if(n!==`Success`)return n}return`Success`}isPasteAllowed(e,t,n){for(let{handler:r}of this.selectClipboardHandlers(t)){let i=r.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...n});if(i!==`Success`)return i}return`Success`}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;let{zones:n}=this.copiedData;for(let r of n)if(t===`COL`&&e<=r.right||t===`ROW`&&e<=r.bottom)return!0;return!1}copy(e,t=`copyPaste`){let n={},r=this.getClipboardData(e);for(let{handlerName:e,handler:i}of this.selectClipboardHandlers(r)){let a=i.copy(r,this._isCutOperation,t);n[e]=a;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])a&&e in a&&(n[e]=a[e])}return n}paste(e,t,n){if(!t)return;let r=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:a,zone:o,selectedZones:s}=zl(r,e,t,i,n);o!==void 0&&this.addMissingDimensions(r,o.right-o.left+1,o.bottom-o.top+1,o.left,o.top),Rl(i,t,a,n),n?.selectTarget&&Bl(this.selection,e,s)}addMissingDimensions(e,t,n,r,i){let a=n+i-this.getters.getNumberRows(e);a>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a,position:`after`});let o=t+r-this.getters.getNumberCols(e);o>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:o,position:`after`})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){let e=await this.getImageContent(),t=e?.type,n={"text/plain":this.getPlainTextContent(),"text/html":await this.getHTMLContent()};return t&&e&&(n[t]=e),n}getSheetData(){let e={version:bP(),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(` `)).join(`
1929
+ `;var YU=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:bA};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getExpandedTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(N(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Ad(e,i).join(`,`)})`,value:L(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Ad(e,i).join(`,`)})`,value:L(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${Ad(e,i).join(`,`)})`,value:L(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=N(r.values[r.values.length-1]);for(let n of t.rows){let t=[];for(let e=0;e<n.fields.length;e++)t.push({value:n.fields[e]},{value:n.values[e]});for(let e=0;e<r.fields.length-1;e++)t.push({value:r.fields[e]},{value:r.values[e]});let o=this.pivot.parseArgsToPivotDomain(t),{value:s,format:c}=this.pivot.getPivotCellValueAndFormat(a,o),l=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${Ad(e,o,a).join(`,`)})`,value:L(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},XU=class extends Lp{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i}){super(t),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=r,this.canDispatch=i}import(e){}export(e){}adaptRanges(e,t,n){}garbageCollectExternalResources(){}},ZU=class extends XU{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>b(e)));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Ue.style,color:e.border.color||Ue.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of gt(r))if(e.dimension===`COL`){let n=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{let n=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r=this.borders[e]?.[t]?.[n];return r?.top||r?.bottom||r?.left||r?.right?b(r):null}getBordersColors(e){let t=[],n=this.borders[e];if(n){for(let e of n.filter(C))for(let n of e)if(n)for(let e of[`top`,`bottom`,`left`,`right`]){let r=n[e]?.color;r&&t.push(r)}}return t}ensureColumnBorderContinuity(e,t,n){let r=S(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=S(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&w(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(C);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?S(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n){this.borders[e]&&this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfColumn(e,t,n)})}shiftBordersVertically(e,t,n){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfRow(e,t,n)}))}moveBordersOfRow(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach(a=>{let o=i[a]?.[t+n],s=i[a]?.[t];this.history.update(`borders`,e,a,t+n,r?s:s||o),this.history.update(`borders`,e,a,t,void 0)})}moveBordersOfColumn(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getRowsRange(e).forEach(a=>{let o=i[t+n]?.[a],s=i[t]?.[a];this.history.update(`borders`,e,t+n,a,r?s:s||o),r&&this.history.update(`borders`,e,t,a,void 0)})}setBorder(e,t,n,r,i=!0){let a=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;(i||!this.borders[e]?.[t]?.[n]?.left)&&(this.history.update(`borders`,e,t,n,`left`,r?.left),r?.left&&t>0&&!w(this.borders[e]?.[t-1]?.[n]?.right,r?.left)&&this.history.update(`borders`,e,t-1,n,`right`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.top)&&(this.history.update(`borders`,e,t,n,`top`,r?.top),r?.top&&n>0&&!w(this.borders[e]?.[t]?.[n-1]?.bottom,r?.top)&&this.history.update(`borders`,e,t,n-1,`bottom`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.right)&&(this.history.update(`borders`,e,t,n,`right`,r?.right),r?.right&&t<a&&!w(this.borders[e]?.[t+1]?.[n]?.left,r?.right)&&this.history.update(`borders`,e,t+1,n,`left`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.bottom)&&(this.history.update(`borders`,e,t,n,`bottom`,r?.bottom),r?.bottom&&n<o&&!w(this.borders[e]?.[t]?.[n+1]?.top,r?.bottom)&&this.history.update(`borders`,e,t,n+1,`top`,void 0))}clearBorders(e,t,n=!1){let r=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(let a of ms(t))for(let t=a.top;t<=a.bottom;t++){n&&(a.left>0&&this.history.update(`borders`,e,a.left-1,t,`right`,void 0),a.right<r&&this.history.update(`borders`,e,a.right+1,t,`left`,void 0));for(let r=a.left;r<=a.right;r++)this.history.update(`borders`,e,r,t,void 0),n&&(a.top>0&&this.history.update(`borders`,e,r,a.top-1,`bottom`,void 0),a.bottom<i&&this.history.update(`borders`,e,r,a.bottom+1,`top`,void 0))}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t,!0);for(let i of ms(t)){if(n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r,right:r,bottom:r,left:r});if(n===`h`||n===`hv`){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:r});for(let n=i.top+1;n<i.bottom;n++)this.addBorder(e,t,n,{top:r,bottom:r});this.addBorder(e,t,i.bottom,{top:r})}}if(n===`v`||n===`hv`){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:r});for(let n=i.left+1;n<i.right;n++)this.addBorder(e,n,t,{left:r,right:r});this.addBorder(e,i.right,t,{left:r})}}if(n===`left`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:r});if(n===`top`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||w(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let[n,r]of gc(t.id,t.borders)){let{sheetId:t,col:i,row:a}=n,o=e.borders[r];this.setBorder(t,i,a,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Ts(e))}export(e){let t={};for(let n of e.sheets){let e={};for(let r=0;r<n.colNumber;r++)for(let i=0;i<n.rowNumber;i++){let a=this.getCellBorder({sheetId:n.id,col:r,row:i});if(a){let o=mc(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=hc(e)}e.borders=t}exportForExcel(e){this.export(e)}},QU=class extends XU{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges({applyChange:e},t,n){for(let r of Object.keys(this.cells))for(let i of Object.values(this.cells[r]||{}))if(i.isFormula){for(let a of i.compiledFormula.dependencies)if(a.sheetId===t||a.invalidSheetName===n.old){let t=e(a);t.changeType!==`NONE`&&this.history.update(`cells`,r,i.id,`compiledFormula`,`dependencies`,i.compiledFormula.dependencies.indexOf(a),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&&e.format!==void 0&&this.setFormatter(e.sheetId,e.target,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of ms(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n=this.getters.getCell({sheetId:e,col:t,row:r});(n?.isFormula||n?.content)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}}setFormatter(e,t,n){for(let r of ms(t))for(let t=r.top;t<=r.bottom;t++)for(let i=r.left;i<=r.right;i++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:i,row:t,format:n})}clearFormatting(e,t){for(let n of ms(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=S(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=S(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){for(let t of e.sheets){let n=t.id,r=new LF;for(let e in t.cells)if(t.cells[e]){let{col:n,row:i}=ir(e),a={sheetId:t.id,col:n,row:i};r.set(a,{content:t.cells[e]})}for(let[e,n]of[[`style`,t.styles],[`format`,t.formats]])for(let[i,a]of gc(t.id,n)){let t=r.get(i);t?t[e]=a:r.set(i,{[e]:a})}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}}export(e){let t={},n={};for(let r of e.sheets){let e=[],i=[],a={},o=Object.keys(this.cells[r.id]||{}).map(e=>this.getters.getCellPosition(e)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let r of o){let o=this.getters.getCell(r),s=T(r.col,r.row),c=this.extractCustomStyle(o);if(Object.keys(c).length){let n=mc(c,t);e[n]??=[],e[n].push(r)}if(o.format){let e=mc(o.format,n);i[e]??=[],i[e].push(r)}o.content&&(a[s]=o.content)}r.styles=hc(e),r.formats=hc(i),r.cells=a}e.styles=t,e.formats=n}importCell(e,t,n,r){let i=this.getNextUid();return this.createCell(i,t||``,r,n,e)}exportForExcel(e){this.export(e);let t=[];for(let n in e.formats||[])Qo(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}extractCustomStyle(e){let t={...e.style},n=Hi(e.content,D)?Re:Le;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return this.cells[e]||{}}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){if(!n.length)return Mt(t.map(e=>e.value));let i=0;return Mt(t.map(t=>{if(t.type===`REFERENCE`){let t=n[i++];return this.getters.getRangeString(t,e,{useBoundedReference:r})}return t.value}))}getTranslatedCellFormula(e,t,n,r){let i=this.getters.createAdaptedRanges(iC(r).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t,n){let r=iC(n).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),i=this.getters.removeRangesSheetPrefix(t,r);return this.getFormulaString(t,n,i)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=T(t.left,t.top,n[0]),i=T(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyle(e,t,n){for(let r of ms(t))for(let t=r.left;t<=r.right;t++)for(let i=r.top;i<=r.bottom;i++){let r=this.getters.getCell({sheetId:e,col:t,row:i});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:i,style:n?{...r?.style,...n}:void 0})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextUid(){let e=this.nextId.toString();return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o=a?Wt(r?.content||void 0):i?.content||``,s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextUid(),u=this.createCell(l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}createCell(e,t,n,r,i){return t.startsWith(`=`)?this.createFormulaCell(e,t,n,r,i):this.createLiteralCell(e,t,n,r)}createLiteralCell(e,t,n,r){let i=this.getters.getLocale(),a=ts(t,i);return n||=typeof a==`number`?Io(t,i)||Lo(t):void 0,!$o(n)&&!j(t)&&(t=N(a)),{id:e,content:t,style:r,format:n,isFormula:!1,parsedValue:a}}createFormulaCell(e,t,n,r,i){let a=rC(t);return a.dependencies.length?this.createFormulaCellWithDependencies(e,a,n,r,i):{id:e,content:t,style:r,format:n,isFormula:!0,compiledFormula:{...a,dependencies:[]}}}createFormulaCellWithDependencies(e,t,n,r,i){let a=[];for(let e of t.dependencies)a.push(this.getters.getRangeFromSheetXC(i,e));return new $U(e,t,n,r,a,i,this.getters.getRangeString)}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?Vs(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.content&&!t.style&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.content===e.content)&&(!r||w(t?.style,e.style))&&(!i||t?.format===e.format)?`NoChanges`:`Success`}},$U=class{id;format;style;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,n,r,i,a,o){this.id=e,this.format=n,this.style=r,this.sheetId=a,this.getRangeString=o;let s=0,c=t.tokens.map(e=>e.type===`REFERENCE`?new eW(i,s++,this.sheetId,this.getRangeString):e);this.compiledFormula={...t,dependencies:i,tokens:c}}get content(){return Mt(this.compiledFormula.tokens.map(e=>e.value))}get contentWithFixedReferences(){let e=0;return Mt(this.compiledFormula.tokens.map(t=>{if(t.type===`REFERENCE`){let t=e++;return this.getRangeString(this.compiledFormula.dependencies[t],this.sheetId,{useBoundedReference:!0})}return t.value}))}},eW=class{ranges;rangeIndex;sheetId;getRangeString;type=`REFERENCE`;constructor(e,t,n,r){this.ranges=e,this.rangeIndex=t,this.sheetId=n,this.getRangeString=r}get value(){let e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}},tW=class extends XU{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getFigureIdFromChartId`,`getContextCreationChart`];charts={};createChart=_O(this.getters);validateChartDefinition=e=>yO(this,e.definition);adaptRanges(e){for(let[t,n]of Object.entries(this.charts)){if(!n)continue;let r=n.chart.updateRanges(e);this.history.update(`charts`,t,r?{figureId:n.figureId,chart:r}:void 0)}}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkFigureArguments,this.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`:let{col:t,row:n,offset:r,size:i,sheetId:a,figureId:o}=e;!this.getters.getFigure(a,o)&&r!==void 0&&t!==void 0&&n!==void 0&&this.addFigure(o,a,t,n,r,i),this.addChart(e.figureId,e.chartId,e.definition);break;case`UPDATE_CHART`:this.addChart(e.figureId,e.chartId,e.definition);break;case`DUPLICATE_SHEET`:for(let t of this.getChartIds(e.sheetId)){let{chart:n,figureId:r}=this.charts[t]||{};if(!n||!r)continue;let i=this.getters.getFigure(e.sheetId,r);if(!i)continue;let a=r.split(`??`).pop(),o=`${e.sheetIdTo}??${a}`,s=t.split(`??`).pop(),c=`${e.sheetIdTo}??${s}`,l=n.duplicateInDuplicatedSheet(e.sheetIdTo);l&&this.dispatch(`CREATE_CHART`,{figureId:o,chartId:c,col:i.col,row:i.row,offset:i.offset,size:{width:i.width,height:i.height},definition:l.getDefinition(),sheetId:e.sheetIdTo})}break;case`DELETE_FIGURE`:for(let t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch(`DELETE_CHART`,{chartId:t,sheetId:e.sheetId});break;case`DELETE_CHART`:this.isChartDefined(e.chartId)&&this.history.update(`charts`,e.chartId,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){let t=this.charts[e]?.chart.type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.chart.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.chart.getDefinition();if(!t)throw Error(`There is no chart with the given id: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures){for(let e of t.figures)if(e.tag===`chart`){let n=e.data.chartId,r=this.createChart(e.id,e.data,t.id);this.charts[n]={chart:r,figureId:e.id}}else if(e.tag===`carousel`)for(let n in e.data.chartDefinitions||{}){let r=e.data.chartDefinitions[n],i=this.createChart(e.id,r,t.id);this.charts[n]={chart:i,figureId:e.id}}}}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t,r=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&e.tag===`chart`&&r){let t=this.charts[r]?.chart.getDefinition();t&&(e.data={...t,chartId:r},n.push(e))}else if(e&&e.tag===`carousel`){let r=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),i={};for(let e of r)i[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:i},n.push(e)}else n.push(e)}t.figures=n}}addFigure(e,t,n,r,i,a={width:536,height:335}){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`chart`})}addChart(e,t,n){let r=this.getters.getFigureSheetId(e);if(r){let i=this.createChart(e,n,r);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&&w(this.getChartDefinition(e.chartId),e.definition)?`NoChanges`:`Success`}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||e.offset!==void 0&&e.col!==void 0&&e.row!==void 0?`Success`:`MissingFigureArguments`}};function nW(e){return e===``?NaN:Number(e)}var rW=class extends XU{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};adaptCFFormulas({applyChange:e,adaptFormulaString:t}){for(let n in this.cfRules)for(let r of this.cfRules[n])if(r.rule.type===`DataBarRule`&&r.rule.rangeValues){let t=e(r.rule.rangeValues);switch(t.changeType){case`REMOVE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,t.range);break}}else if(r.rule.type===`CellIsRule`)for(let e=0;e<r.rule.values.length;e++)this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`values`,e,t(n,r.rule.values[e]));else if(r.rule.type===`IconSetRule`)for(let e of[`lowerInflectionPoint`,`upperInflectionPoint`])r.rule[e].type===`formula`&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,r.rule[e].value));else if(r.rule.type===`ColorScaleRule`)for(let e of[`minimum`,`maximum`,`midpoint`]){let i=r.rule[e];i?.type===`formula`&&i?.value&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,i.value))}}adaptCFRanges(e,{applyChange:t}){for(let n of this.cfRules[e])for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}adaptRanges(e,t){let n=t?[t]:Object.keys(this.cfRules);for(let t of n)this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)Vs(t,n,e.zone)&&r.push(i);return new Set(r.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,n,r){if(n.length===0&&r.length===0)return;let i=this.getters.getConditionalFormats(e),a=i.findIndex(e=>e.id===t.id),o=[];a>-1&&(o=i[a].ranges.map(ws));let s=ms(o,r);return ms([...n,...s],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:n}={useBoundedReference:!1}){let r=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:n}));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:n})},ranges:r}:{...t,rule:{...t.rule},ranges:r}}mapToConditionalFormatInternal(e,t){let n=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:n}:{...t,rule:{...t.rule},ranges:n}}addConditionalFormatting(e,t){let n=this.cfRules[t].slice(),r=n.findIndex(t=>t.id===e.id),i=this.mapToConditionalFormatInternal(t,e);r>-1?n.splice(r,1,i):n.push(i),this.history.update(`cfRules`,t,n)}checkValidPriorityChange(e,t,n){if(!this.cfRules[n])return`InvalidSheetId`;let r=this.cfRules[n].findIndex(t=>t.id===e);if(r===-1)return`InvalidConditionalFormatId`;let i=r-t;return i<0||i>=this.cfRules[n].length?`InvalidConditionalFormatId`:`Success`}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}checkCFRule(e){let t=e.cf.rule;switch(t.type){case`CellIsRule`:return Mr.has(t.operator)?this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkCFHasChanged(e){let t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),n=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return n&&w(t,n)?`NoChanges`:`Success`}checkOperatorArgsNumber(e){let t=Y.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(t===void 0||t>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);let n=[],r=e=>e===void 0||e===``;return t>=1&&r(e.values[0])&&n.push(`FirstArgMissing`),t>=2&&r(e.values[1])&&n.push(`SecondArgMissing`),n.length?n:`Success`}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(rC(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){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?`LowerBiggerThanUpper`:`Success`}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&nW(t)>=nW(n)?`MinBiggerThanMax`:`Success`}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&nW(t)>=nW(n)?`MidBiggerThanMax`:`Success`}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&nW(t)>=nW(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&rC(t||``).isBadExpression)return`ValueCellIsInvalidFormula`;return`Success`}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},iW=class extends XU{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e,t){this.adaptDVRanges(t,e),this.adaptDVFormulas(e)}adaptDVFormulas({adaptFormulaString:e}){for(let t in this.rules){let n=this.rules[t];for(let r=n.length-1;r>=0;r--){let n=this.rules[t][r];for(let i=0;i<n.criterion.values.length;i++){let a=e(t,n.criterion.values[i]);this.history.update(`rules`,t,r,`criterion`,`values`,i,a)}}}}adaptDVRanges(e,{applyChange:t}){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return!this.getters.tryGetSheet(e.sheetId)||e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid));case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return`UnknownDataValidationRule`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=b(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>zc(e.sheetId,e.sheetIdTo,t))}));this.history.update(`rules`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.rules};delete t[e.sheetId],this.history.update(`rules`,t);break}case`REMOVE_DATA_VALIDATION_RULE`:this.removeDataValidationRule(e.sheetId,e.id);break;case`ADD_DATA_VALIDATION_RULE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case`DELETE_CONTENT`:{let t=ms(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(e&&(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!this.getters.getCell({sheetId:n,col:r,row:t})?.content)){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,T(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(Vs(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&(t.criterion.displayStyle===`arrow`||t.criterion.displayStyle===`chip`):!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=b(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of Vc(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...b(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return Y.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=Y.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=Y.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||rC(e).isBadExpression:!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}checkValidRange(e){return e.ranges.map(e=>this.getters.getRangeFromRangeData(e)).map(t=>this.getters.getRangeString(t,e.sheetId)).some(e=>!this.getters.isRangeValid(e))?`InvalidRange`:`Success`}},aW=class extends XU{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];adaptRanges({applyChange:e},t){for(let n of this.getFigures(t)){let r=e(this.getters.getRangeFromZone(t,{left:n.col,right:n.col,top:n.row,bottom:n.row}));if(r.changeType===`MOVE`)this.history.update(`figures`,t,n.id,`col`,r.range.zone.right),this.history.update(`figures`,t,n.id,`row`,r.range.zone.bottom);else if(r.changeType===`REMOVE`){let r=e(this.getters.getRangeFromZone(t,{left:0,right:n.col-1,top:0,bottom:n.row-1})),{offset:i,col:a,row:o}=n;r.changeType!==`NONE`&&(a=r.range.zone.right+1,o=r.range.zone.bottom+1),{offset:i,col:a,row:o}=this.getPositionInSheet(t,{...n,col:a,row:o}),this.history.update(`figures`,t,n.id,`offset`,i),this.history.update(`figures`,t,n.id,`col`,a),this.history.update(`figures`,t,n.id,`row`,o)}}}allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case`UPDATE_FIGURE`:return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case`DELETE_FIGURE`:return this.checkFigureExists(e);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{figureId:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:let t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case`UPDATE_FIGURE`:this.updateFigure(e);break;case`DELETE_FIGURE`:this.removeFigure(e.figureId,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case`DUPLICATE_SHEET`:for(let t of this.getFigures(e.sheetId)){let n=t.id,r=this.figures[e.sheetId]?.[n];if(!r)continue;let i=n.split(`??`).pop(),a=`${e.sheetIdTo}??${i}`;this.dispatch(`CREATE_FIGURE`,{figureId:a,...r,size:{width:r.width,height:r.height},sheetId:e.sheetIdTo})}break}}onColRemove(e){let t=this.getters.getNumberCols(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+this.getters.getColSize(e,r);for(let t of this.getFigures(e))if(t.offset.x+t.width>n[t.col]){let r=t.offset.x,i=t.col;for(r=Math.min(r,n[i]-t.width);r<0&&i>0;)i--,r=n[i]-t.width;r!==t.offset.x&&this.history.update(`figures`,e,t.id,`offset`,{x:Math.max(r,0),y:t.offset.y}),i!==t.col&&this.history.update(`figures`,e,t.id,`col`,i)}}onRowRemove(e){let t=this.getters.getNumberRows(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+(this.getters.getUserRowSize(e,r)??23);for(let t of this.getFigures(e))if(t.offset.y+t.height>n[t.row]){let r=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??23;t<r;t=this.getters.getUserRowSize(e,i)??23)i+=1,r-=t;for(r=Math.min(r,n[i]-t.height);r<0&&i>0;)i--,r=n[i]-t.height;r!==t.offset.y&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(0,r)}),i!==t.row&&this.history.update(`figures`,e,t.id,`row`,i)}else t.offset.y+t.height>n[0]&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(n[0]-t.height,0)})}getPositionInSheet(e,t){let{numberOfRows:n,numberOfCols:r}=this.getters.getSheetSize(e),i=0,a=0,o,s,{col:c,row:l}=t,u={...t.offset};for(o=n;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??23;for(l>o?(l=o,u.y=Math.max(i-t.height,0)):l===o&&(u.y=x(u.y,0,Math.max(i-t.height,0))),s=r;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return c>s?(c=s,u.x=Math.max(a-t.width,0)):s===c&&(u.x=x(u.x,0,Math.max(a-t.width,0))),{col:c,row:l,offset:u}}updateFigure(e){if(!(`figureId`in e)||!(`sheetId`in e))return;let{figureId:t,sheetId:n,...r}=e,i={...this.getFigure(n,t),...r};for(let[e,t]of Object.entries(r))switch(e){case`tag`:this.history.update(`figures`,n,i.id,e,t);break;case`offset`:this.history.update(`figures`,n,i.id,e,t);break;case`col`:case`row`:case`width`:case`height`:t!==void 0&&this.history.update(`figures`,n,i.id,e,t);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e){return this.figures[e.sheetId]?.[e.figureId]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?`DuplicatedFigureId`:`Success`}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?`WrongSheetPosition`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){return this.export(e)}},oW=class extends XU{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,b(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=qt(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ft(e.position,e.base),r=t[e.base],i=Jt(t,Array(e.quantity).fill(r),n);this.history.update(`sizes`,e.sheetId,e.dimension,i);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of S(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of S(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},sW=class extends XU{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?`TooManyHiddenElements`:en(e.elements)<0||$t(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,b(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=Ft(e.position,e.base),n=Jt([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return Rt(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=S(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...S(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},cW=class extends XU{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?`InvalidFigureId`:`Success`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.getters.getFigure(e.sheetId,e.figureId)||this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:b(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}garbageCollectExternalResources(){let e=new Set(this.getAllImages().map(e=>e.path));for(let t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,n,r,i,a){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`image`})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:b(e)})}t.images=[...t.images,...n]}}getAllImages(){let e=[];for(let t in this.images)e.push(...Object.values(this.images[t]||{}).filter(C));return e}},lW=class extends XU{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`getSelectionRangeString`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(C))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e,t){this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(C)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(C)}getSelectionRangeString(e,t){let n=this.getters.expandZone(e.sheetId,e.zone),r=Nc({...e,zone:{...n,bottom:Ic(e)?void 0:n.bottom,right:Lc(e)?void 0:n.right}},this.getters.getSheetSize),i=this.getters.getRangeString(r,t);if(this.isSingleCellOrMerge(e.sheetId,e.zone)){let{sheetName:e,xc:t}=jc(i);return Mc(e,t.split(`:`)[0])}return i}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(zs(t,n))return!0;return!1}doesColumnsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(r.id,t,i,n,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(r.id,i,t,i,n))return!0;return!1}expandZone(e,t){let{left:n,right:r,top:i,bottom:a}=t,o={left:n,right:r,top:i,bottom:a};for(let t in this.merges[e]){let n=this.getMergeById(e,parseInt(t));n&&zs(n,o)&&(o=Fs(n,o))}return Rs(o,t)?o:this.expandZone(e,o)}isInSameMerge(e,t,n,r,i){let a=this.getMerge({sheetId:e,col:t,row:n}),o=this.getMerge({sheetId:e,col:r,row:i});return!a||!o?!1:Rs(a,o)}isInMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e];return r?t in r&&!!r[t]?.[n]:!1}getMainCellPosition(e){let t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){let n=this.getters.getHiddenColsGroups(e),r=this.getters.getHiddenRowsGroups(e);for(let e of n)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of r)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){let n=this.getMerge({sheetId:e,col:t.left,row:t.top});if(n)return Rs(t,n);let{numberOfCols:r,numberOfRows:i}=Us(t);return r===1&&i===1}isMainCellPosition(e){return w(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=x(r,0,this.getters.getNumberCols(e)-1),a=x(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&n.content!==``)return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:dW(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?`MergeIsDestructive`:`Success`}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&zs(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);return ic(t,n,r)?`FrozenPaneOverlap`:`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!Rs(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=x(r,0,this.getters.getNumberCols(e)-1),a=x(a,0,this.getters.getNumberRows(e)-1),T(n,i)===T(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,As({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!Rs(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,{applyChange:t}){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=Us(a.range.zone);t===1&&i===1?this.removeMerge(e,n):this.history.update(`merges`,e,parseInt(r,10),a.range);break}}this.history.update(`mergeCellMap`,e,{});for(let t of this.getMerges(e))for(let{col:n,row:r}of Ks(t))this.history.update(`mergeCellMap`,e,n,r,t.id)}import(e){let t=e.sheets||[];for(let e of t)this.history.update(`merges`,e.id,{}),this.history.update(`mergeCellMap`,e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let n of t)this.addMerge(e,Ts(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...uW(e))}}exportForExcel(e){this.export(e)}};function uW(e){return Object.entries(e).map(([e,t])=>t?dW(parseInt(e,10),t):void 0).filter(C).map(e=>T(e.left,e.top)+`:`+T(e.right,e.bottom))}function dW(e,t){return{...t.zone,id:e}}var fW=class{getters;providers=[];isAdaptingRanges=!1;constructor(e){this.getters=e}static getters=[`copyFormulaStringForSheet`,`extendRange`,`getRangeString`,`getRangeFromSheetXC`,`createAdaptedRanges`,`getRangeData`,`getRangeDataFromXc`,`getRangeDataFromZone`,`getRangeFromRangeData`,`getRangeFromZone`,`getRangesUnion`,`recomputeRanges`,`isRangeValid`,`removeRangesSheetPrefix`];allowDispatch(e){return e.type===`MOVE_RANGES`?e.target.length===1?`Success`:`InvalidZones`:`Success`}beforeHandle(e){}handle(e){if(this.isAdaptingRanges)throw Error(`Plugins cannot dispatch commands during adaptRanges phase`);let t=Gc(e);t&&this.executeOnAllRanges(t)}finalize(){}verifyRangeRemoved(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!Os(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}executeOnAllRanges(e){this.isAdaptingRanges=!0;let t={applyChange:this.verifyRangeRemoved(e.applyChange),adaptRangeString:(t,n)=>hC(t,n,e),adaptFormulaString:(t,n)=>mC(t,n,e)};for(let n of this.providers)n(t,e.sheetId,e.sheetName);this.isAdaptingRanges=!1}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,n,r){return e.map(e=>{if(!Os(e.zone))return e;let i=e.prefixSheet?e.sheetId:r,a=Lc(e),o=Ic(e),s={...e.unboundedZone,left:a&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:a?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:o&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:n),bottom:o?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:n)};return Wc(Nc({...e,sheetId:i,zone:s},this.getters.getSheetSize))})}removeRangesSheetPrefix(e,t){return t.map(t=>t.prefixSheet&&t.sheetId===e?{...t,prefixSheet:!1}:t)}extendRange(e,t,n){let r=t===`COL`?e.zone.right+n:e.zone.right,i=t===`ROW`?e.zone.bottom+n:e.zone.bottom,a={left:e.zone.left,top:e.zone.top,right:Lc(e)?void 0:r,bottom:Ic(e)?void 0:i};return Nc({...e,zone:a},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!Tc.test(t)||!this.getters.tryGetSheet(e))return Fc(t);let{sheetName:n}=jc(t);return Pc({xc:t,sheetId:this.getters.getSheetIdByName(n)||e,invalidSheetName:n&&!this.getters.getSheetIdByName(n)?n:void 0},this.getters.getSheetSize)}getRangeString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){return e?e.invalidXc?e.invalidXc:this.getters.tryGetSheet(e.sheetId)?Rc(e,t,this.getters.getSheetName,n):k.InvalidReference:k.InvalidReference}getRangeDataFromXc(e,t){let n=this.getters.getRangeFromSheetXC(e,t);return this.getRangeDataFromZone(n.sheetId,n.unboundedZone)}getRangeDataFromZone(e,t){return t=this.getters.getUnboundedZone(e,t),{_sheetId:e,_zone:t}}getRangeData(e){return this.getRangeDataFromZone(e.sheetId,e.unboundedZone)}getRangeFromZone(e,t){return Nc({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){return ms(e.map(e=>e.unboundedZone),t.map(e=>e.unboundedZone)).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){return this.getters.tryGetSheet(e._sheetId)?Nc({prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]},this.getters.getSheetSize):Fc(k.InvalidReference)}isRangeValid(e){if(!e)return!1;let{xc:t,sheetName:n}=jc(e);return t.match(Tc)!==null&&(!n||this.getters.getSheetIdByName(n)!==void 0)}getRangesUnion(e){let t=Is(...e.map(e=>e.unboundedZone));return this.getRangeFromZone(e[0].sheetId,t)}copyFormulaStringForSheet(e,t,n,r){if(!n.startsWith(`=`))return n;let i=rC(n),a=i.dependencies.map(n=>{let i=this.getters.getRangeFromSheetXC(e,n);return r===`keepSameReference`?i:zc(e,t,i)});return this.getters.getFormulaString(t,i.tokens,a)}},pW=class extends XU{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`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==`Success`)return t;switch(e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?`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{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),`Success`}catch{return`WrongSheetMove`}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||mn(e.color)?`Success`:`InvalidColor`;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?`Success`:`NotEnoughSheets`;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?`InvalidQuantity`:`Success`:`InvalidHeaderIndex`;case`REMOVE_COLUMNS_ROWS`:{let t=en(e.elements),n=$t(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?`InvalidHeaderIndex`:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return`Success`}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,sl(t.name),t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.newName);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`)}}import(e){for(let t of e.sheets)this.sheetIdsMapName[sl(t.name)]=t.id;for(let t of e.sheets){let e=t.name||`Sheet`+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:nl(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(C).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e)return this.sheetIdsMapName[sl(e)]}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(C)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return al(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?Rt(n,S(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&e.col!==void 0&&`row`in e&&e.row!==void 0&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(Os))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>Hs(e,n))?`Success`:`TargetOutOfSheet`}return`Success`}updateCellPosition(e){let{sheetId:t,cellId:n,col:r,row:i}=e;n?this.setNewPosition(n,t,r,i):this.clearPosition(t,r,i)}setNewPosition(e,t,n,r){let i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update(`cellPosition`,e,{row:r,col:n,sheetId:t}),this.history.update(`sheets`,t,`rows`,r,`cells`,n,e)}clearPosition(e,t,n){let r=this.sheets[e]?.rows[n].cells[t];r&&(this.history.update(`cellPosition`,r,void 0),this.history.update(`sheets`,e,`rows`,n,`cells`,t,void 0))}setGridLinesVisibility(e,t){this.history.update(`sheets`,e,`areGridLinesVisible`,t)}createSheet(e,t,n,r,i){let a={id:e,name:t,numberOfCols:n,rows:nl(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(`There is not enough visible sheets`)}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId),n=e.type===`RENAME_SHEET`?e.newName:e.name;if(t!==void 0&&n===t)return`UnchangedSheetName`;let{orderedSheetIds:r,sheets:i}=this,a=n&&n.trim().toLowerCase();return r.find(t=>cl(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:Xe.test(a)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[sl(n)],r[sl(t)]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=b(this.getSheet(e));r.id=t,r.name=n;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[sl(r.name)]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return ol(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[sl(t)],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of gt(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(ir),n=e.rowNumber,r=e.colNumber;for(let{col:e,row:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return`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`}},mW=class extends XU{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};nextTableId=1;adaptRanges({applyChange:e},t){for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return oc(t)?this.checkValidations(e,e=>this.getTablesOverlappingZones(e.sheetId,t).length?`TableOverlap`:`Success`,e=>this.checkTableConfigUpdateIsValid(e.config)):`NonContinuousTargets`;case`UPDATE_TABLE`:return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,e=>this.checkTableConfigUpdateIsValid(e.config)):`TableNotFound`;case`ADD_MERGE`:for(let t of this.getCoreTables(e.sheetId)){let n=t.range.zone;for(let t of e.target)if(zs(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{});break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.consumeNextId(),a=e.config||QA,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!Ls(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t);break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>Hs(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(C):[]}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>Vs(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>zs(e.range.zone,t)))}extendTableDown(e,t){let n=this.getters.extendRange(t.range,`ROW`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}extendTableRight(e,t){let n=this.getters.extendRange(t.range,`COL`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:n,row:r},i){if(!e)return`none`;let a=i.range.zone,o=`none`;if(a.bottom+1===r&&n>=a.left&&n<=a.right?o=`down`:a.right+1===n&&r>=a.top&&r<=a.bottom&&(o=`right`),o===`none`)return`none`;let s=o===`down`?{...a,bottom:a.bottom+1,top:a.bottom+1}:{...a,right:a.right+1,left:a.right+1};for(let e=s.top;e<=s.bottom;e++)for(let n=s.left;n<=s.right;n++){let r={sheetId:t,col:n,row:e};if(this.getters.getCell(r)?.content||this.getters.isInMerge(r)||this.getTablesOverlappingZones(t,[R(r)]).length)return`none`}return o}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return`Success`;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==`Success`)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?`TableOverlap`:`Success`:`TableNotFound`}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?`InvalidTableConfig`:`Success`}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of S(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.consumeNextId();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=$s(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of S(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.consumeNextId();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,$s(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return gI(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return gI(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:b(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:b(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=gI(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<Us(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.consumeNextId(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}consumeNextId(){let e=`${this.nextTableId}`;return this.history.update(`nextTableId`,this.nextTableId+1),e}import(e){for(let t of e.sheets)for(let e of t.tables||[]){let n=this.consumeNextId(),r=e.config||QA,i=this.getters.getRangeFromSheetXC(t.id,e.range),a=e.type||`static`,o=a===`dynamic`?this.createDynamicTable(n,i,r):this.createStaticTable(n,a,i,r);this.history.update(`tables`,t.id,o.id,o)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:As(e.range.zone),type:e.type};w(e.config,QA)||(n.config=e.config),t.tables.push(n)}}exportForExcel(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n=As(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},hW=class extends XU{static getters=[`getCarousel`,`doesCarouselExist`];carousels={};allowDispatch(e){switch(e.type){case`CREATE_CAROUSEL`:return this.getters.getFigure(e.sheetId,e.figureId)?`DuplicatedFigureId`:`Success`;case`UPDATE_CAROUSEL`:return this.carousels[e.sheetId]?.[e.figureId]?`Success`:`InvalidFigureId`}return`Success`}handle(e){switch(e.type){case`CREATE_CAROUSEL`:this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch(`CREATE_FIGURE`,{...e,tag:`carousel`}),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`UPDATE_CAROUSEL`:this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`carousel`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getCarousel(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:{items:i.items.map(t=>{if(t.type===`carouselDataView`)return{...t};let n=t.chartId.split(`??`).pop(),r=`${e.sheetIdTo}??${n}`;return{...t,chartId:r}})}})}}break}case`DELETE_FIGURE`:this.history.update(`carousels`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`carousels`,e.sheetId,void 0);break}}doesCarouselExist(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){let n=new Set(e.definition.items.filter(e=>e.type===`chart`).map(e=>e.chartId));for(let r of t)r.type===`chart`&&!n.has(r.chartId)&&this.dispatch(`DELETE_CHART`,{chartId:r.chartId,sheetId:e.sheetId})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`carousel`);for(let n of e)this.history.update(`carousels`,t.id,n.id,{items:n.data.items,title:n.data.title})}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`carousel`);for(let n of e)this.carousels[t.id]?.[n.id]&&(n.data={...n.data,...this.carousels[t.id]?.[n.id]})}}},gW=class extends XU{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(S(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=b(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=Ft(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&S(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Gt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=rl(n,r,[o.start,o.end]);(s!==o.start||c!==o.end)&&this.history.update(`groups`,e,t,a,{...o,start:s,end:c})}}moveGroupsOnHeaderDeletion(e,t,n){let r=this.getHeaderGroups(e,t),i=[];for(let e of r){let t=il(n,S(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=Uj(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=Uj(t,e,n.end+1);r.collapsed=!0}}}}}},_W=class extends XU{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?w(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`}return`Success`}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new nR(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=b(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,b(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break}}adaptRanges({applyChange:e,adaptFormulaString:t}){for(let t in this.pivots){let n=b(this.pivots[t]?.definition);if(!n)continue;let r=vR.get(n.type)?.adaptRanges?.(this.getters,n,e);r&&!w(n,r)&&this.history.update(`pivots`,t,`definition`,r)}for(let n in this.compiledMeasureFormulas)for(let r in this.compiledMeasureFormulas[n]){let i=this.pivots[n]?.definition.measures.find(e=>e.id===r);if(!i||!i.computedBy)continue;let a=i.computedBy.sheetId,{formula:o,dependencies:s}=this.compiledMeasureFormulas[n][r];this.history.update(`compiledMeasureFormulas`,n,r,`formula`,`dependencies`,o.dependencies.map(t=>e(t).range)),this.history.update(`compiledMeasureFormulas`,n,i.id,`dependencies`,s.map(t=>e(t).range));let c=i.computedBy.formula,l=t(a,c);l!==c&&this.replaceMeasureFormula(n,i,l)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:b(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=this.compileMeasureFormula(n.computedBy.sheetId,n.computedBy.formula);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.tokens){if(o.type!==`SYMBOL`)continue;let a=i.measures.find(e=>mt(e.id)===o.value&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.dependencies.filter(e=>!e.invalidXc)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:Md(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){let n=rC(t),r=n.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return{...n,dependencies:r}}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId})}checkSortedColumnInMeasures(e){let t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?`InvalidDefinition`:`Success`}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}checkCustomFieldsAreValid(e){for(let t in e.customFields){let n=e.customFields[t],r=new Set,i=new Set,a=!1;for(let e of n.groups){if(!e.name||i.has(e.name)||e.values.some(e=>r.has(e))||e.isOtherGroup&&a)return`InvalidPivotCustomField`;e.values.forEach(e=>r.add(e)),i.add(e.name),a||=!!e.isOtherGroup}}return`Success`}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||Td(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},vW=class extends XU{static getters=[`getLocale`];locale=D;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return uu(e.locale)?`Success`:`InvalidLocale`}return`Success`}handle(e){switch(e.type){case`UPDATE_LOCALE`:let t=this.locale,n=e.locale;this.history.update(`locale`,n),this.changeCellsDateFormatWithLocale(t,n);break}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(let n of this.getters.getSheetIds())for(let[r,i]of Object.entries(this.getters.getCells(n))){let n;if(i.format===e.dateFormat&&(n=t.dateFormat),i.format===e.timeFormat&&(n=t.timeFormat),i.format===Du(e)&&(n=Du(t)),n){let{col:e,row:t,sheetId:i}=this.getters.getCellPosition(r);this.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:i,format:n})}}}import(e){this.locale=e.settings?.locale??D}export(e){e.settings={locale:this.locale}}},yW=class extends XU{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return`Success`}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!Os(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},bW=class extends XU{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(!pj[e.templateName])return`InvalidTableStyle`;try{pn(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=mj(e.tableStyleName,e.templateName,e.primaryColor);this.history.update(`styles`,e.tableStyleId,t);break;case`REMOVE_TABLE_STYLE`:let n={...this.styles};delete n[e.tableStyleId],this.history.update(`styles`,n);for(let t of this.getters.getSheetIds())for(let n of this.getters.getCoreTables(t))n.config.styleId===e.tableStyleId&&this.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{styleId:QA.styleId}});break}}getTableStyle(e){if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return an(E(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!fj[e]}import(e){for(let e in fj)this.styles[e]=fj[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=mj(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)fj[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},xW=class extends Lp{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}};let SW=new g;SW.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let CW=zS.mapping;function wW(e,t,n){return new TW(e,t,n).getParameters()}var TW=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(CW),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){let n=this.getRangeError(e);if(n)return n;let r={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};return t?(this.computeCell(r),{value:Mc(this.getters.getSheetName(e.sheetId),As(e.zone))}):this.computeCell(r)}range(e,t){let n=this.getRangeError(e);if(n)return[[n]];let r=e.sheetId,i=e.zone,a=Ls(i,this.getters.getSheetZone(r));if(!a)return[[]];let{top:o,left:s,bottom:c,right:l}=i,u=`${r}-${o}-${s}-${c}-${l}-${t}`;if(u in this.rangeCache)return this.rangeCache[u];let d=a.bottom-a.top+1,f=a.right-a.left+1,p=Array(f),m=this.getters.getSheetName(e.sheetId);for(let e=a.left;e<=a.right;e++){let n=e-a.left;p[n]=Array(d);for(let i=a.top;i<=a.bottom;i++){let o=i-a.top,s=this.computeCell({sheetId:r,col:e,row:i});p[n][o]=t?{value:Mc(m,T(e,i))}:s}}return this.rangeCache[u]=p,p}getRangeError(e){if(!Os(e.zone))return new Yi;if(e.invalidSheetName)return new Yi(E(`Invalid sheet name: %s`,e.invalidSheetName))}},EW=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),DW=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new OW,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new OW),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&w(e.data,t.data)}},OW=class extends EW.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},kW=class e{profilesStartingPosition=[0];profiles=new Map([[0,[]]]);constructor(e=[]){for(let t of e)this.add(t)}isEmpty(){return this.profiles.size===1&&this.profiles.get(0)?.length===0}add(e){hs(this.profilesStartingPosition,this.profiles,[e])}delete(e){hs(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return gs(this.profilesStartingPosition,this.profiles,e)}difference(e){let t=this.copy();for(let n of e)t.delete(n);return t}copy(){let t=new e;t.profilesStartingPosition=[...this.profilesStartingPosition],t.profiles=new Map;for(let[e,n]of this.profiles)t.profiles.set(e,[...n]);return t}[Symbol.iterator](){return bs(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}},AW=class e{setsBySheetId={};constructor(e=[]){for(let t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new kW),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(let t of e)this.add(t)}addPosition(e){this.add(Uc(e))}addManyPositions(e){for(let t of e)this.addPosition(t)}has(e){return this.setsBySheetId[e.sheetId]?this.setsBySheetId[e.sheetId].has(e.zone):!1}hasPosition(e){return this.has(Uc(e))}delete(e){this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].delete(e.zone)}deleteMany(e){for(let t of e)this.delete(t)}deleteManyPositions(e){for(let t of e)this.delete(Uc(t))}difference(t){let n=new e;for(let e in this.setsBySheetId)n.setsBySheetId[e]=this.setsBySheetId[e];for(let e in t.setsBySheetId)n.setsBySheetId[e]&&(n.setsBySheetId[e]=n.setsBySheetId[e].difference(t.setsBySheetId[e]));return n}copy(){let t=new e;for(let e in this.setsBySheetId)t.setsBySheetId[e]=this.setsBySheetId[e].copy();return t}clear(){this.setsBySheetId={}}isEmpty(){for(let e in this.setsBySheetId)if(!this.setsBySheetId[e].isEmpty())return!1;return!0}[Symbol.iterator](){let e=[];for(let t in this.setsBySheetId)for(let n of this.setsBySheetId[t])e.push({sheetId:t,zone:n});return e[Symbol.iterator]()}},jW=class{rTree;constructor(e=[]){let t=MW(e);this.rTree=new DW(t)}insert(e){let t=this.rTree.search(e.boundingBox),n=e.boundingBox,r=t.find(({boundingBox:e})=>e.sheetId===n.sheetId&&e.zone.left===n.zone.left&&e.zone.top===n.zone.top&&e.zone.right===n.zone.right&&e.zone.bottom===n.zone.bottom);r?r.data.add(e.data):this.rTree.insert({...e,data:new AW([e.data])})}search({zone:e,sheetId:t}){let n=new AW;for(let{data:r}of this.rTree.search({zone:e,sheetId:t}))n.addMany(r);return n}remove(e){let t=this.rTree.search(e.boundingBox),n=e.boundingBox,r=t.find(({boundingBox:e})=>e.sheetId===n.sheetId&&e.zone.left===n.zone.left&&e.zone.top===n.zone.top&&e.zone.right===n.zone.right&&e.zone.bottom===n.zone.bottom);r?r.data.delete(e.data):this.rTree.remove({...e,data:new AW([e.data])})}};function MW(e){let t=0,n=0;for(let r=0;r<e.length;r++){let i=e[r].boundingBox.zone;i.right>t&&(t=i.right),i.bottom>n&&(n=i.bottom)}t+=1,n+=1;let r=(((n+1)*t+1)*n+1)*t<=2**53-1;r||console.warn(`Max col/row size exceeded, using slow zone key`);let i={};for(let a of e){let e=a.boundingBox.sheetId;i[e]||(i[e]={});let o=a.boundingBox.zone,s=0;s=r?o.left+o.top*t+o.right*t*n+o.bottom*t*n*t:`${o.left},${o.top},${o.right},${o.bottom}`,i[e][s]?i[e][s].data.add(a.data):i[e][s]={boundingBox:a.boundingBox,data:new AW([a.data])}}let a=[];for(let e in i){let t=i[e];for(let e in t)a.push(t[e])}return a}var NW=class{dependencies=new LF;rTree;constructor(e=[]){this.rTree=new jW(e)}removeAllDependencies(e){let t=this.dependencies.get(e);if(t){for(let e of t)this.rTree.remove(e);this.dependencies.delete(e)}}addDependencies(e,t){let n=t.map(({sheetId:t,zone:n})=>({data:{sheetId:e.sheetId,zone:R(e)},boundingBox:{zone:n,sheetId:t}}));for(let e of n)this.rTree.insert(e);let r=this.dependencies.get(e);r?r.push(...n):this.dependencies.set(e,n)}getCellsDependingOn(e,t=new AW){t=t.copy();let n=Array.from(e).reverse();for(;n.length>0;){let e=n.pop();t.add(e);let r=this.rTree.search(e);n.push(...r.difference(t))}for(let n of e)t.delete(n);return t}},PW=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=FW(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function FW(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var IW=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=PW.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},LW=class{resultsToArrayFormulas=new DW;arrayFormulasToResults=new LF;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||RW}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let RW=[],zW=Object.freeze(ns({...new Ji,origin:void 0})),BW=Object.freeze(ns({value:null}));var VW=class{context;getters;compilationParams;evaluatedCells=new LF;formulaDependencies=Nt(new NW);blockedArrayFormulas=new IW({});spreadingRelations=new LW;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=wW(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||BW}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===`error`&&!(t.ignoreSpillError&&r?.value===k.SpilledBlocked)?R(e):Fs(R(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type!==`empty`)return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,R(e)).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t);for(let e of t)this.compilationParams.ensureRange(e,!1)}updateCompilationParametersForIsolatedFormula(e){this.compilationParams=wW(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.updateDependencies=void 0,this.compilationParams.evalContext.addDependencies=void 0,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParameters(){this.compilationParams=wW(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new IW(e)}evaluateCells(e){let t=performance.now(),n=new AW;n.addManyPositions(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(n)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=new AW;for(let n of e){let e=this.getters.getCell(n)?.content,r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.addPosition(r),e||t.addPosition(n)}for(let e of[...t])t.addMany(this.getArrayFormulasBlockedBy(e.sheetId,e.zone));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new LW,this.formulaDependencies=Nt(()=>{let e=[];for(let t of this.getters.getSheetIds()){let n=this.getters.getCells(t);for(let r in n){let i=n[r];if(i.isFormula){let n=i.compiledFormula.dependencies;for(let i of n)i.invalidSheetName||i.invalidXc||e.push({data:{sheetId:t,zone:R(this.getters.getCellPosition(r))},boundingBox:{sheetId:i.sheetId,zone:i.zone}})}}}return new NW(e)})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new LF;let t=[];for(let e of this.getters.getSheetIds()){let n=this.getters.getSheetZone(e);t.push({sheetId:e,zone:n})}this.evaluate(t),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=rC(t),i=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,{...r,dependencies:i})}evaluateCompiledFormula(e,t,n){try{let r=WW(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return Ir(r)?Ca(r,UW):UW(r)}catch(e){return VS(e,``)}}getArrayFormulasBlockedBy(e,t){let n=new AW,r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addManyPositions(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteManyPositions(i),n.addMany(this.getCellsDependingOn(n)),n}nextRangesToUpdate=new AW;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new AW(e);let t=0;for(;!this.nextRangesToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();let e=[...this.nextRangesToUpdate];this.nextRangesToUpdate.clear(),this.clearEvaluatedRanges(e);for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++){let n={sheetId:t.sheetId,col:a,row:e};if(this.nextRangesToUpdate.hasPosition(n))continue;let r=this.computeCell(n);r!==BW&&this.evaluatedCells.set(n,r)}}SW.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}clearEvaluatedRanges(e){for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++)this.evaluatedCells.delete({sheetId:t.sheetId,col:a,row:e})}}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return BW;let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?zW:(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):es(n,i,e))}catch(t){return t.value=t?.value||k.GenericError,t.message=t?.message||WS,t.origin=e,t.errorOriginPosition=t?.errorOriginPosition,ns(t)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=WW(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!Ir(n)){let r=ns(UW(n),this.getters.getLocale(),t,e);return r.type===`error`&&(r.errorOriginPosition=n.errorOriginPosition??e),r}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return ns({value:0},this.getters.getLocale(),t);if(i===1&&r===1)return ns(UW(n[0][0]),this.getters.getLocale(),t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),HW(r,i,this.checkCollision(e)),HW(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),ns(UW(n[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){let n=this.getCellsDependingOn(Gs(t).map(t=>({sheetId:e,zone:t})));n.delete({sheetId:e,zone:t}),this.nextRangesToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw o?new Qi(E(`Result couldn't be automatically expanded. Please insert more rows.`)):s?new Qi(E(`Result couldn't be automatically expanded. Please insert more columns.`)):new Qi(E(`Result couldn't be automatically expanded. Please insert more columns and rows.`))}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:n},r){if(this.getters.getMergesInZone(e,{top:n,bottom:n+r[0].length-1,left:t,right:t+r.length-1}).length!==0)throw new Qi(E(`Merged cells found in the spill zone. Please unmerge cells before using array formulas.`))}checkCollision(e){let{sheetId:t,col:n,row:r}=e;return(i,a)=>{let o={sheetId:t,col:i+n,row:a+r};if(this.getters.getCell(o)?.content||this.getters.getEvaluatedCell(o).type!==`empty`)throw this.blockedArrayFormulas.add(e),new Qi(E(`Array result was not expanded because it would overwrite data.`),o);this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=ns(UW(r[i][a]),this.getters.getLocale(),s,o);c.type===`error`&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r};this.getters.getCell(t)?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextRangesToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return zW;this.symbolsBeingComputed.add(t);try{return e?.(t)||new qi(E(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}};function HW(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function UW(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function WW(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}var GW=class extends xW{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getRangeFormattedValues`,`getRangeValues`,`getRangeFormats`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new VW(e.custom,this.getters)}beforeHandle(e){(yr.has(e.type)||xr.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:if(e.cellIds)for(let t=0;t<e.cellIds.length;t++)this.positionsToUpdate.push(this.getters.getCellPosition(e.cellIds[t]));else this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return Ir(r)?Ca(r,e=>e.value):r.value}evaluateFormulaResult(e,t,n){return this.evaluator.evaluateFormulaResult(e,t,n)}evaluateCompiledFormula(e,t,n){return this.evaluator.evaluateCompiledFormula(e,t,n)}getRangeFormattedValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).formattedValue)}getRangeValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e).value)}getRangeFormats(e){let t=this.getters.tryGetSheet(e.sheetId);return t===void 0?[]: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 Ks(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return Ks(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return Ks(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=T(t.col,t.row),i=n.value,a=!1,o,s=!0,c=e.sheets.find(e=>e.id===t.sheetId),l=this.getCorrespondingFormulaCell(t);if(l){let u=this.getters.getCell(t);if(s=dC(l.compiledFormula.tokens),a=s&&u?.content===l.content,!s&&i!==``){o=(i??``).toString();let t=n.format;if(t){let n=mc(t,e.formats);c.formats[r]=n}}}let u=c.cells[r],d;d=s&&a&&l instanceof $U?l.contentWithFixedReferences:s?u:o,c.cells[r]=d,c.cellValues[r]=i===k.BadExpression?void 0:i;let f=this.getSpreadZone(t);f&&(c.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,f),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let KW=/"(#[0-9a-fA-F]{6})"/g;function qW(e){let t=[{leadColor:_n(255,0,0),colors:[]},{leadColor:_n(255,128,0),colors:[]},{leadColor:_n(128,128,0),colors:[]},{leadColor:_n(128,255,0),colors:[]},{leadColor:_n(0,255,0),colors:[]},{leadColor:_n(0,255,128),colors:[]},{leadColor:_n(0,255,255),colors:[]},{leadColor:_n(0,127,255),colors:[]},{leadColor:_n(0,0,255),colors:[]},{leadColor:_n(127,0,255),colors:[]},{leadColor:_n(128,0,128),colors:[]},{leadColor:_n(255,0,128),colors:[]}];for(let n of e.map(xn)){let e=500,r=0;t.forEach((t,i)=>{let a=JW(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>Cn(e).s-Cn(t).s)).flat().map(bn)}function JW(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var YW=class extends xW{customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds())for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));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);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return qW(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push(dn(t.minimum.color)),n.push(t.midpoint?dn(t.midpoint.color):void 0),n.push(dn(t.maximum.color)))}return n.filter(C)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getDefinition()).matchAll(KW)].map(e=>e[1])}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(C):[]}tryToAddColors(e){for(let t of e){if(!mn(t))continue;let e=pn(t);t&&!Ie.includes(e)&&this.history.update(`customColors`,e,!0)}}},XW=class extends xW{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};createRuntimeChart=vO(this.getters);handle(e){if(yr.has(e.type)||Sr.has(e.type)||br.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:AC(e)};if(!t)return{background:oe,fontColor:AC(oe)};let n=t.zone.left,r=t.zone.top,i=t.sheetId,a=this.getters.getCellComputedStyle({sheetId:i,col:n,row:r}),o=a.fillColor||`#FFFFFF`;return{background:o,fontColor:a.textColor||AC(o)}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===r.id);if(!e)continue;let i=this.getters.getChart(e),a=i?.getDefinitionForExcel(this.getters);if(a)n.push({...r,data:a});else{if(!i)continue;let n=this.getters.getChartType(e),a=jT(this.getters.getChartRuntime(e),r,n);a&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:a,size:{width:r.width,height:r.height}}})}}t.charts=n}}},ZW=class extends xW{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(yr.has(e.type)||Sr.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=Nt(()=>this.getComputedStyles(e)),this.computedIcons[e]=Nt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=Nt(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(e=>e.startsWith(`=`)?rC(e):void 0);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let s={sheetId:e,col:o,row:i},c=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s.tokens):t});this.getRuleResultForTarget(s,{...n.rule,values:c})&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,t).zone,a=this.getters.getEvaluatedCellsInZone(e,i).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?$t(a):en(a);case`number`:return Number(n.value);case`percentage`:let t=en(a);return t+($t(a)-t)*Number(n.value)/100;case`percentile`:return Gi(a,Number(n.value)/100,!0);case`formula`:let i=n.value&&this.getters.evaluateFormula(e,n.value);return typeof i==`number`?i:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==`number`)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=$t(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===`number`).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!Vs(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:dn(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:n.minimum.color}];n.midpoint&&a&&c.push({value:a,color:n.midpoint.color}),c.push({value:o,color:n.maximum.color});let l=Kn(c);for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let a=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(a.type===`number`){let e=x(a.value,i,o);r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=l(e)}}}getRuleResultForTarget(e,t){let n=this.getters.getEvaluatedCell(e);if(n.type===`error`)return!1;let{sheetId:r}=e,i=Y.get(t.operator),a=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(r,t,e)??``:ts(t,D));if(a.some(Wu))return!1;let o={type:t.operator,values:a.map(Hu)};return i.isValueValid(n.value??``,o,this.getters,r)}};let QW={isValid:!0};var $W=class extends xW{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};handle(e){if(yr.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:`#E7E9ED`}}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=Y.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?E(`The value must not be a formula`):this.isValidFormula(t)?void 0:U.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?E(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}getDataValidationRangeValues(e,t){let n=this.getters.getRangeFromSheetXC(e,String(t.values[0])),r=[],i=new Set;for(let e of Ks(n.zone)){let t=this.getters.getEvaluatedCell({...e,sheetId:n.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),r.push({label:t.formattedValue,value:t.value?.toString()||``}))}return r}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return QW;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:QW}hasChip(e){let t=this.getters.getValidationRuleForCell(e);return(t?.criterion.type===`isValueInList`||t?.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`chip`}getDataValidationStyle(e){let t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;let n=this.getters.getEvaluatedCell(e),r=this.getValueColor(t,n.value);if(r)return{fillColor:r,textColor:Mn(r)}}getValueColor(e,t){if(!(e.criterion.type!==`isValueInList`&&e.criterion.type!==`isValueInRange`)){for(let n in e.criterion.colors)if(n.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[n]}}isValidFormula(e){return!rC(e).isBadExpression}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||QW}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of Vc(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=Nt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?QW:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=Y.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,t,o,i);if(s.some(Wu))return;let c={...i,values:s.map(Hu)};if(!a.isValueValid(e,c,this.getters,r))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>Vs(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n,r){return r.values.map(r=>{if(!r.startsWith(`=`))return ts(r,D);let i=rC(r),a=this.getters.getTranslatedCellFormula(e,n.col,n.row,i.tokens);return this.getters.evaluateFormula(e,a,t)})}};let eG=new g;eG.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value;return{svg:n?Nj:jj,hoverSvg:n?Nj:Mj,priority:2,horizontalAlign:`center`,size:17,margin:2,position:t,type:`data_validation_checkbox`,onClick:(e,t)=>{let r=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||r?.isFormula)return;let i=n?`FALSE`:`TRUE`;t.model.dispatch(`UPDATE_CELL`,{...e,content:i})}}}}),eG.add(`data_validation_chip_icon`,(e,t)=>{let n=e.getDataValidationChipStyle(t);if(n){let r=e.getCellComputedStyle(t);return{svg:kj(n),hoverSvg:Aj(n),priority:10,horizontalAlign:`right`,size:xl(r),margin:4,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_chip_icon`}}}),eG.add(`data_validation_list_icon`,(e,t)=>{if(!e.isReadonly()&&e.cellHasListDataValidationIcon(t)){let n=e.getCellComputedStyle(t);return{svg:Tj(n),hoverSvg:Dj(n),priority:2,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_list_icon`}}}),eG.add(`filter_icon`,(e,t)=>{if(e.isFilterHeader(t)){let n=e.isFilterActive(t),r=vn(e.getCellComputedStyle(t).fillColor||`#fff`)<.45;return{type:`filter_icon`,svg:Fj(n,r,!1),hoverSvg:Fj(n,r,!0),priority:3,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let n=t.getStore(TA),r=n.persistentCellPopover;if(r.isOpen&&r.col===e.col&&r.row===e.row&&r.type===`FilterMenu`){n.close();return}n.open(e,`FilterMenu`)}}}}),eG.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:Ij[n].svg,priority:1,horizontalAlign:`left`,size:xl(r),margin:4,position:t}}}),eG.add(`pivot_collapse`,(e,t)=>{if(!e.isSpillPivotFormula(t))return;let n=e.getPivotCellFromPosition(t),r=e.getPivotIdFromPosition(t);if(n.type===`HEADER`&&r&&n.domain.length){let i=e.getPivotCoreDefinition(r),a=e.isDashboard(),o=n.dimension===`COL`?i.columns:i.rows,s=!a&&n.domain.length!==o.length,c=(i.collapsedDomains?.[n.dimension]??[]).some(e=>w(e,n.domain)),l=n.dimension===`ROW`?(n.domain.length-1)*15:0;return{type:`pivot_collapse`,priority:4,horizontalAlign:`left`,size:s||!a&&n.dimension===`ROW`&&i.rows.length>1?12:0,margin:s?4+l:l,svg:s?Pj(c,!1):void 0,hoverSvg:s?Pj(c,!0):void 0,position:t,onClick:tG}}});function tG(e,t){let n=t.model.getters.getPivotCellFromPosition(e),r=t.model.getters.getPivotIdFromPosition(e);if(!r||n.type!==`HEADER`)return;let i=t.model.getters.getPivotCoreDefinition(r),a=i.collapsedDomains?.[n.dimension]?[...i.collapsedDomains[n.dimension]]:[],o=a.findIndex(e=>w(e,n.domain));o===-1?a.push(n.domain):a.splice(o,1);let s=i.collapsedDomains?{...i.collapsedDomains}:{COL:[],ROW:[]};s[n.dimension]=a,t.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...i,collapsedDomains:s}})}eG.add(`pivot_dashboard_sorting`,(e,t)=>{if(!e.isDashboard()||e.getPivotCellFromPosition(t).type!==`MEASURE_HEADER`)return;let n=e.getPivotCellSortDirection(t);if(n!==`asc`&&n!==`desc`)return;let r=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${n}`,priority:5,horizontalAlign:`right`,size:17,margin:2,svg:n===`asc`?Ej(r):Tj(r),position:t,onClick:void 0}});var nG=class extends xW{static getters=[`doesCellHaveGridIcon`,`getCellIcons`,`getCellIconRect`];cellIconsCache={};handle(e){e.type!==`SET_VIEWPORT_OFFSET`&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){let n=e.position,r=this.getters.getCell(n);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,r?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,n){let r=e.x,i=e.x+e.width;switch(t){case`right`:return i-n.margin-n.size;case`left`:return r+n.margin;default:let e=Math.floor((i-r-n.size)/2);return i-n.size-e}}computeCellIcons(e){let t={left:void 0,right:void 0,center:void 0},n=eG.getAll();for(let r of n){let n=r(this.getters,e);n&&(!t[n.horizontalAlign]||n.priority>t[n.horizontalAlign].priority)&&(t[n.horizontalAlign]=n)}if(t.center&&(t.left||t.right)){let e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(C)}doesCellHaveGridIcon(e){return!!this.getCellIcons(e).length}},rG=class extends xW{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(yr.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tables={};return}switch(e.type){case`CREATE_TABLE`:case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`DELETE_CONTENT`:this.tables={};break}}finalize(){for(let e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){let t=[],n=this.getters.getCoreTables(e);for(let e of n)e.type!==`dynamic`&&t.push(e);let r=[...t];for(let i of n){if(i.type!==`dynamic`)continue;let n=this.coreTableToTable(e,i),a=n.range.zone;for(let e of r){let t=e.range.zone;zs(a,t)&&(a=t.left>a.left?{...a,right:Math.min(a.right,t.left-1)}:{...a,bottom:Math.min(a.bottom,t.top-1)})}t.push({...n,range:this.getters.getRangeFromZone(e,a)})}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){let t=this.getTable(e);if(!(!t||!t.config.hasFilters))return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:n}){return this.getTables(e).find(e=>Vs(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>zs(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){let t=[];for(let n of this.getTables(e)){if(!n.config.hasFilters)continue;let r=n.range.zone,i=r.top;for(let n=r.left;n<=r.right;n++)t.push({sheetId:e,col:n,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:n}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===n)}canCreateDynamicTableOnZones(e,t){if(!oc(t))return!1;let n=Fs(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);if(!i){let e=this.getters.getEvaluatedCell(r);return e.value===k.SpilledBlocked&&!e.errorOriginPosition}else if(w(i,r)&&nc(n)===1)return!0;return w(n,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=gI(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!Ks(t.range.zone).some(t=>this.getters.getArrayFormulaSpreadingOn({sheetId:e,...t}))}exportForExcel(e){for(let t of e.sheets){let n=[];for(let r of t.tables){let i=Ts(r.range),a={sheetId:t.id,col:i.left,row:i.top},o=this.getters.getCoreTable(a),s=this.getTable(a);if(!o||!s||this.isTableExcelExportable(t.id,o)){n.push(r);continue}t.styles=t.styles||{},t.borders=t.borders||{};for(let n of Ks(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=T(n.col,n.row);if(!kt(i)){let n=mc(i,e.styles);t.styles[o]=n}if(a){let n=mc(a,e.borders);t.borders[o]=n}}}t.tables=n}}},iG=class extends xW{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=document.createElement(`canvas`).getContext(`2d`);beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=Ft(e.position,e.base),n=Array(e.quantity).fill(void 0),r=Jt(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=b(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=qt(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of S(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of Ks(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getMaxAnchorOffset(e,t,n){let{numberOfRows:r,numberOfCols:i}=this.getters.getSheetSize(e),a=0;for(;a<t&&r>0;r--)a+=this.getRowSize(e,r-1);let o=0;for(;o<n&&i>0;i--)o+=this.getters.getColSize(e,i-1);return{col:i,row:r,offset:{x:o-n,y:a-t}}}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return ul(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCells(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let aG=`0.00%`;function oG(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=wd[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return VS(t,e.aggregator.toUpperCase())}}let i=this.getters.getMeasureCompiledFormula(this.pivotId,e),a=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,e=>{let{columns:n,rows:r}=this.definition;if(n.find(t=>t.nameWithGranularity===e)){let{colDomain:n}=LL(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Xi:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=LL(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Xi:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return Ir(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=LL(this,t),i=super.getExpandedTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=Nd(this.definition.getDimension(r.field),t[n]?.value);if(r.field===t[n]?.field&&r.value===e)return this.getSubTreeMatchingDomain(r.children,t,n+1)}return[]}treeToLeafDomains(e,t=[]){let n=[];for(let r of e){let e=this.definition.getDimension(r.field),i=[...t,{field:r.field,value:r.value,type:e.type}];r.children.length===0?n.push(i):n.push(...this.treeToLeafDomains(r.children,i))}return n}getMeasureDisplayValue(e,t){let n=this.getMeasure(e),r=this._getPivotCellValueAndFormat(e,t);if(!n.display||n.display.type===`no_calculations`||r.message)return r;let i=n.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:k.NotAvailable,message:E(`Field "%s" not found in pivot for measure display calculation`,i)};try{let e=n.display;switch(e.type){case`%_of_grand_total`:return this.asPercentOfGrandTotal(r,n);case`%_of_col_total`:return this.asPercentOfColumnTotal(r,n,t);case`%_of_row_total`:return this.asPercentOfRowTotal(r,n,t);case`%_of_parent_row_total`:return this.asPercentOfParentRowTotal(r,n,t);case`%_of_parent_col_total`:return this.asPercentOfParentColumnTotal(r,n,t);case`index`:return this.asIndex(r,n,t);case`%_of_parent_total`:return this.asPercentOfParentTotal(r,n,t,e);case`running_total`:return this.asRunningTotal(r,n,t,e,`running_total`);case`%_running_total`:return this.asRunningTotal(r,n,t,e,`%_running_total`);case`rank_asc`:return this.asRank(r,n,t,e,`asc`);case`rank_desc`:return this.asRank(r,n,t,e,`desc`);case`%_of`:return this.asPercentOf(r,n,t,e);case`difference_from`:return this.asDifferenceFrom(r,n,t,e);case`%_difference_from`:return this.asDifferenceFromInPercent(r,n,t,e)}return r}catch(e){return VS(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:k.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:aG}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:k.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:aG}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:k.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:aG}}asPercentOfParentRowTotal(e,t,n){let r=FL(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:aG}}asPercentOfParentColumnTotal(e,t,n){let r=IL(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:aG}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!GL(i,n))return{value:``};let a=UL(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:aG}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value:k.DivisionByZero}:{value:r*o/(a*i),format:void 0}}asRunningTotal(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;let o=i===`running_total`?this.runningTotal:this.runningTotalInPercent,s=o[t.id]?.[a];s||(s=this.computeRunningTotal(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=LL(this,n),u=JL(l),d=JL(c);return{value:s[u]?.[d]??``,format:i===`running_total`?e.format:aG}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!GL(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:k.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:aG}:s===void 0?{value:k.NullError}:{value:s/o,format:aG}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!GL(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a)||0;return o===`sameValue`?{value:``}:{value:this.measureValueToNumber(e)-o,format:e.format}}asDifferenceFromInPercent(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!GL(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:k.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:k.NullError}:{value:(s-o)/o,format:aG}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!GL(a,n))return{value:``};let o=i===`asc`?this.rankAsc:this.rankDesc,s=o[t.id]?.[a];s||(s=this.computeRank(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=LL(this,n),u=JL(l),d=JL(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=KL(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=Ta(o));for(let s of o){let o=JL(RL(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:RL(this,i,t.domain)})).filter(e=>GL(t,e.rowDomain)),l=Object.groupBy(c,e=>XL(e.rowDomain,t));for(let e in l)l[e]=nn(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=JL(RL(this,i,e.domain)),a=l[XL(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:rn(r)}computeRunningTotal(e,t,n){let r={},i=KL(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=Ta(o));for(let s of o){let o=JL(RL(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:RL(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>GL(t,e.rowDomain));for(let e of l){let n=JL(e.rowDomain),i=ZL(e.rowDomain,t),a=(c[i]||0)+e.value;c[i]=a,r[o][n]=a}if(n===`%_running_total`)for(let e of l){let n=e.rowDomain,i=JL(n),a=ZL(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:rn(r)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=LL(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=LL(this,t).colDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,n,r){let i=r===`(previous)`||r===`(next)`?qL(this,t,n,r):WL(t,n,r);if(w(i,t))return`sameValue`;if(!i||!BL(this,i))throw new Xi;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){let e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){let e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;let t=this.definition.sortedColumn.measure;Vd(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let sG=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function cG(e){return sG.includes(e.type)}var lG=class extends xW{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotCellSortDirection`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`];pivots={};unusedPivots;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(yr.has(e.type))for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0});switch(e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.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;let t=e.commands.filter(cG);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:gR();break}}getPivotIdFromPosition(e){return this.getPivotIdsFromPosition(e)[0]}getPivotIdsFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getPivotIdsFromFormula(e.sheetId,t.compiledFormula):[]}getPivotIdsFromFormula(e,t){return this.getPivotFunctions(e,t.tokens).map(e=>{let t=e.args[0]?.toString();return t&&this.getters.getPivotId(t)}).filter(C)}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens)?.functionName===`PIVOT`:!1}getPivotFunctions(e,t){let n=gU(t);if(!n.length)return[];let r=[];for(let t of n){let{functionName:n,args:i}=t,a=i.map(t=>{if(t.type===`EMPTY`)return;if(t.type===`STRING`||t.type===`BOOLEAN`||t.type===`NUMBER`)return t.value;let n=PB(t);return this.getters.evaluateFormula(e,n)});r.push({functionName:n,args:a})}return r}getFirstPivotFunction(e,t){return this.getPivotFunctions(e,t)[0]}getPivotCellFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||_U(t.compiledFormula.tokens)===0)return rR;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!r)return rR;let{functionName:i,args:a}=r,o=a[0];if(!o)return rR;let s=this.getters.getPivotId(o.toString());if(!s)return rR;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!t.content.replaceAll(` `,``).toUpperCase().startsWith(`=PIVOT`))return rR;try{if(i===`PIVOT`){let t=Hu(a[2]),r=t===void 0?!0:P(t),i=Hu(a[3]),o=Hu(a[5]),s=o===void 0?!0:P(o),l={displayColumnHeaders:i===void 0?!0:P(i),displayTotals:r,displayMeasuresRow:s},u=c.getCollapsedTableStructure().getPivotCells(l),d=e.col-n.col,f=e.row-n.row;return u[d][f]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>Ir(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`){let e=c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})));return{type:`HEADER`,domain:e,dimension:LL(c,e).colDomain.length?`COL`:`ROW`}}let[o,...s]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(s.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return rR}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return an(E(`Calculated measure 1`),t,{compute:(e,t)=>E(`Calculated measure %s`,t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){return this._getUnusedPivots().includes(e)}getPivotCellSortDirection(e){let t=this.getters.getPivotIdFromPosition(e),n=this.getters.getPivotCellFromPosition(e);if(n.type===`EMPTY`||n.type===`HEADER`||!t)return;let r=this.getters.getPivot(t),i=LL(r,n.domain).colDomain,a=r.definition.sortedColumn;return a?.measure===n.measure&&w(a.domain,i)?a.order:`none`}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=b(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=oG(vR.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivots(){if(this.unusedPivots!==void 0)return this.unusedPivots;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n in this.getters.getCells(t)){let t=this.getters.getCellPosition(n),r=this.getPivotIdsFromPosition(t);for(let t of r)if(e.delete(t),!e.size)return this.unusedPivots=[],[]}for(let t of this.getters.getPivotIds()){let n=this.getters.getPivot(t);for(let r of n.definition.measures)if(r.computedBy){let{sheetId:n}=r.computedBy,i=this.getters.getMeasureCompiledFormula(t,r),a=this.getPivotIdsFromFormula(n,i);for(let t of a)if(e.delete(t),!e.size)return this.unusedPivots=[],[]}}return this.unusedPivots=[...e],this.unusedPivots}};let uG=new g;uG.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=Math.abs(e.current).toString();n=`0`.repeat(Math.max(e.numberPostfixLength-n.length,0))+n;let r=`${e.prefix}${n}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:{props:{content:r}}}}}).add(`INCREMENT_MODIFIER`,{apply:(e,t,n)=>{e.current+=e.increment;let r=e.current.toString(),i=n.getLocale(),a=L(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=F(e.current,n.getLocale());r.setFullYear(r.getFullYear()+e.increment.years||0),r.setMonth(r.getMonth()+e.increment.months||0),r.setDate(r.getDate()+e.increment.days||0);let i=wi(r);e.current=i;let a=n.getLocale(),o=L(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:o}}:void 0}}}).add(`COPY_MODIFIER`,{apply:(e,t,n)=>{let r=t.cell?.content||``,i={locale:n.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:t.cell?es(t.cell,i).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula.tokens);return{cellData:{border:t.border,style:o.style,format:o.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let dG=new g,fG=/(\d+)$/,pG=/^(.*\D+)/,mG=/^(.*\D+)(\d+)$/,hG=/^0*/;function gG(e,t,n){let r=[],i=!1;for(let a of t){a===e&&(i=!0);let t=a===void 0||a.isFormula?void 0:es(a,{locale:D,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function _G(e){let t=[],n=e[0];for(let r=1;r<e.length;r++){let i=e[r];t.push(i-n),n=i}return t.reduce((e,t)=>e+t,0)/t.length}function vG(e){let t=1;return e.length>=2&&(t=_G(e)*e.length),t}function yG(e){return e.length<2?e[0]||{years:0,months:0,days:0}:e.every(t=>t.years===e[0].years&&t.months===e[0].months&&t.days===e[0].days)?e[0]:void 0}function bG(e){if(e.length<2)return 1;let t=e.map(e=>F(e,D)),n=yG(xG(t));if(n===void 0)return;let r=Object.values(n).filter(e=>e!==0).length===1,i=Object.values(n).every(e=>e===0);if(!r||i){let n=t.map((e,n)=>{if(n===0)return 0;let r=t[n-1];return Math.floor(e.getTime())-Math.floor(r.getTime())}).slice(1);if(n.every(e=>e===n[0]))return e.length*(e[1]-e[0])}return{years:n.years*e.length,months:n.months*e.length,days:n.days*e.length}}dG.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&jo(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&es(e,{locale:D}).type===`text`&&mG.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(fG)[0]),i=e.content.match(pG)[0],a=gG(e,t,e=>e.type===`text`&&mG.test(e.value)).filter(e=>i===(e.value??``).toString().match(pG)[0]).map(e=>(e.value??``).toString().match(fG)[0]),o=a.reduce((e,t)=>{let n=t.match(hG)[0].length;return n>e[1]?[t,n]:e},[a[0],0]),s=o[1]?o[0].length:0,c=vG(a.map(e=>parseInt(e)));return[`up`,`left`].includes(n)&&a.length===1&&(c=-c),{type:`ALPHANUMERIC_INCREMENT_MODIFIER`,prefix:i,current:r,increment:c,numberPostfixLength:s}},sequence:15}).add(`copy_text`,{condition:e=>!e.isFormula&&es(e,{locale:D}).type===`text`,generateRule:()=>({type:`COPY_MODIFIER`}),sequence:20}).add(`update_formula`,{condition:e=>e.isFormula,generateRule:(e,t)=>({type:`FORMULA_MODIFIER`,increment:t.length,current:0}),sequence:30}).add(`increment_dates`,{condition:(e,t)=>!e.isFormula&&es(e,{locale:D}).type===`number`&&!!e.format&&jo(e.format),generateRule:(e,t)=>{let n=bG(gG(e,t,e=>e.type===`number`&&!!e.format&&jo(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=es(e,{locale:D});return typeof n==`object`?{type:`DATE_INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}:{type:`INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}},sequence:25}).add(`increment_number`,{condition:e=>!e.isFormula&&es(e,{locale:D}).type===`number`,generateRule:(e,t,n)=>{let r=gG(e,t,e=>e.type===`number`&&!jo(e.format||``)).map(e=>Number(e.value)),i=vG(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=es(e,{locale:D});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function xG(e){return e.length<2?[{years:0,months:0,days:0}]:e.map((t,n)=>{if(n===0)return{years:0,months:0,days:0};let r=O.fromTimestamp(e[n-1].getTime()),i=Mi(r,t),a=Ai(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:ji(r,t)}}).slice(1)}var SG=class{cells;getters;index=0;direction;constructor(e,t,n){this.cells=e,this.getters=t,this.direction=n}next(){let e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:n,tooltip:r}=uG.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:n,tooltip:r,origin:{col:e.data.col,row:e.data.row}}}},CG=class extends Rp{static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:x(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:x(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(T(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(T(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(T(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(T(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(R({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s=this.getters.getRulesByCell(e,r,i),c=T(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(R({col:a,row:o})))}autofillCell(e,t){this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t.col,row:t.row,content:t.content||``,style:t.style||null,format:t.format||``}),this.dispatch(`AUTOFILL_CELL`,t)}autofillBorders(e,t){for(let n in t){let r=n===`undefined`?void 0:JSON.parse(n);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,border:r,target:ms(t[n])})}}autofillConditionalFormats(e,t){for(let n in t){let r=t[n],i=this.getters.getConditionalFormats(e).find(e=>e.id===n);if(!i)continue;let a=this.getters.getAdaptedCfRanges(e,i,r.map(Ts),[]);a&&this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:a,sheetId:e})}}autofillDataValidations(e,t){for(let n in t){let r=t[n],i=this.getters.getDataValidationRule(e,n);if(!i)continue;let a=ms(i.ranges.map(e=>e.zone).concat(r),[]);this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:i,ranges:a.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){let n=this.getters.getSelectedZone();if(Vs(e,t,n)){this.autofillZone=void 0;return}switch(this.direction=this.getDirection(e,t),this.direction){case`up`:this.saveZone(t,n.top-1,n.left,n.right),this.steps=n.top-t;break;case`down`:this.saveZone(n.bottom+1,t,n.left,n.right),this.steps=t-n.bottom;break;case`left`:this.saveZone(n.top,n.bottom,e,n.left-1),this.steps=n.left-e;break;case`right`:this.saveZone(n.top,n.bottom,n.right+1,e),this.steps=e-n.right;break}this.autofill(!1)}autofillAuto(){let e=this.getters.getActivePosition(),t=this.getters.getTable(e),n=t?t.range.zone.bottom:this.getAutofillAutoLastRow(),r=this.getters.getSelectedZone();for(let t=r.bottom+1;t<=n;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==`empty`){n=t-1;break}n>r.bottom&&(this.select(e.col,n),this.autofill(!0))}getAutofillAutoLastRow(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId(),n=e.left,r=e.bottom;if(n>0){let e={sheetId:t,col:n-1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n-1,row:r}}if(r===e.bottom&&(n=e.right,n<=this.getters.getNumberCols(t))){let e={sheetId:t,col:n+1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n+1,row:r}}return r-1}computeNewCell(e,t,n){let{cellData:r,tooltip:i,origin:a}=e.next(),{content:o,style:s,border:c,format:l}=r;return this.tooltip=i,{originCol:a.col,originRow:a.row,col:t,row:n,content:o,style:s,border:c,format:l}}getRule(e,t){let n=dG.getAll().sort((e,t)=>e.sequence-t.sequence).find(n=>n.condition(e,t));return n&&this.direction&&n.generateRule(e,t,this.direction)}createGenerator(e){let t=[],n=[],r=this.getters.getActiveSheetId();for(let t of e){let{col:e,row:i}=ir(t),a=this.getters.getCell({sheetId:r,col:e,row:i});n.push({col:e,row:i,cell:a,sheetId:r})}let i=n.map(e=>e.cell);for(let e of n){let n={type:`COPY_MODIFIER`};e&&e.cell&&(n=this.getRule(e.cell,i)||n);let r=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:r},rule:n})}return new SG(t,this.getters,this.direction)}saveZone(e,t,n,r){this.autofillZone={top:e,bottom:t,left:n,right:r}}getDirection(e,t){let n=this.getters.getSelectedZone(),r={up:{number:n.top-t,value:`up`},down:{number:t-n.bottom,value:`down`},left:{number:n.left-e,value:`left`},right:{number:e-n.right,value:`right`}};if(Object.values(r).map(e=>+(e.number>0)).reduce((e,t)=>e+t)===1)return Object.values(r).find(e=>+(e.number>0)).value;let i=r.up.number>0?`up`:`down`,a=r.left.number>0?`left`:`right`;return Math.abs(r[i].number)>=Math.abs(r[a].number)?r[i].value:r[a].value}autofillMerge(e,t){let{originCol:n,originRow:r,col:i,row:a}=t,o={sheetId:e,col:i,row:a},s={sheetId:e,col:n,row:r};if(this.getters.isInMerge(o)&&!this.getters.isInMerge(s)){let t=this.getters.getMerge(o);t&&this.dispatch(`REMOVE_MERGE`,{sheetId:e,target:[t]})}let c=this.getters.getMerge(s);c?.left===n&&c?.top===r&&this.dispatch(`ADD_MERGE`,{sheetId:e,target:[{top:a,bottom:a+c.bottom-c.top,left:i,right:i+c.right-c.left}]})}drawLayer(e){if(!this.autofillZone)return;let{ctx:t,thinLineWidth:n}=e,{x:r,y:i,width:a,height:o}=this.getters.getVisibleRect(this.autofillZone);a>0&&o>0&&(t.strokeStyle=`black`,t.lineWidth=n,t.setLineDash([3]),t.strokeRect(r,i,a,o),t.setLineDash([]))}},wG=class extends Rp{static getters=[`getAutomaticSums`];handle(e){switch(e.type){case`SUM_SELECTION`:let e=this.getters.getActiveSheetId(),{zones:t,anchor:n}=this.getters.getSelection();for(let r of t){let t=this.getAutomaticSums(e,r,n.cell);this.dispatchCellUpdates(e,t)}break}}getAutomaticSums(e,t,n){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,n):this.sumData(e,t)}sumData(e,t){let n=this.dimensionsToSum(e,t),r=this.sumDimensions(e,t,n).filter(({zone:t})=>!this.getters.isEmpty(e,t));return n.has(`ROW`)&&n.has(`COL`)&&r.push(this.sumTotal(t)),r}sumAdjacentData(e,t,n){let{col:r,row:i}=Vs(n.col,n.row,t)?n:{col:t.left,row:t.top},a=this.findAdjacentData(e,r,i);return a?this.getters.isSingleCellOrMerge(e,t)||Ws(Fs(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,Fs(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=S(n,-1,-1),a=$t(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=gt(i.filter(e=>this.isNumber(r[e])))[0]||[];return $t(o)<a?1/0:en(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&jo(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){let n=new Set;return Ws(t)?(n.add(Us(t).numberOfCols===1?`COL`:`ROW`),n):(this.lastColIsEmpty(e,t)&&n.add(`ROW`),this.lastRowIsEmpty(e,t)&&n.add(`COL`),n.size===0&&n.add(`COL`),n)}sumDimensions(e,t,n){return[...n.has(`COL`)?this.sumColumns(t,e):[],...n.has(`ROW`)?this.sumRows(t,e):[]]}sumTotal(e){let{bottom:t,right:n}=e;return{position:{col:n,row:t},zone:{...e,top:t,right:n-1}}}sumColumns(e,t){let n=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,n.bottom-1)},Ks(n).map(t=>({position:t,zone:{...e,right:t.col,left:t.col}}))}sumRows(e,t){let n=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,n.right-1)},Ks(n).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(let n of t){let{col:t,row:r}=n.position;this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:`=SUM(${this.getters.zoneToXC(e,n.zone)})`})}}nextEmptyRow(e,t){let n=t.bottom+1,{left:r,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:n,top:n,left:r,right:i});)n++;return{...t,top:n,bottom:n}}nextEmptyCol(e,t){let n=t.right+1,{top:r,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:n,right:n,top:r,bottom:i});)n++;return{...t,left:n,right:n}}transpose(e){return new Set([...e.values()].map(e=>e===`COL`?`ROW`:`COL`))}};let TG=new class extends g{addTransformation(e,t,n){this.content[e]||(this.content[e]=new Map);for(let r of t)this.content[e].set(r,n);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}},EG=new class extends g{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};TG.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],zG),TG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],zG),TG.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],AG),TG.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`,`UPDATE_CAROUSEL`],jG),TG.addTransformation(`DELETE_CHART`,[`UPDATE_CHART`],MG),TG.addTransformation(`DELETE_CHART`,[`UPDATE_CAROUSEL`],NG),TG.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],PG),TG.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],FG),TG.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],IG),TG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],IG),TG.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],LG),TG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],LG),TG.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],RG),TG.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],BG),TG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],BG),TG.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],kG),TG.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],OG),TG.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],DG),TG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],DG);function DG(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=of(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function OG(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function kG(e,t){if(e.pivotId!==t.pivotId)return e}function AG(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function jG(e,t){if(e.figureId!==t.figureId)return e}function MG(e,t){if(e.chartId!==t.chartId)return e}function NG(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!(e.type===`chart`&&e.chartId===t.chartId))}}}function PG(e,t){return e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`}),e.name===t.name?{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1}:e}function FG(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!zs(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function IG(e,t){if(e.sheetId!==t.sheetId||(e.type===`FREEZE_COLUMNS`?`COL`:`ROW`)!==t.dimension)return e;let n=e.quantity;if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);for(let t of e)n>t&&n--}if(t.type===`ADD_COLUMNS_ROWS`){let e=t.position===`before`?t.base-1:t.base;n=n>e?n+t.quantity:n}return n>0?{...e,quantity:n}:void 0}function LG(e,t){if(e.sheetId!==t.sheetId)return e;let n=of(e.zone,t);if(!n)return;let r=e.newTableRange?sf(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function RG(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:QA.styleId}}:e}function zG(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=il(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=rl(Ft(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function BG(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=S(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=il(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=rl(Ft(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function VG(e,t){let n=e.content&&mC(e.sheetId,e.content,t);return{...e,content:n}}EG.add(`UPDATE_CELL`,VG);function HG(e,t){let n=e.cf.rule;if(e={...e,cf:{...e.cf}},n.type===`CellIsRule`)e.cf.rule={...n,values:n.values.map(n=>mC(e.sheetId,n,t))};else if(n.type===`ColorScaleRule`){let{minimum:r,maximum:i,midpoint:a}=n;e.cf.rule={...n,minimum:{...r,value:r.value&&mC(e.sheetId,r.value,t)},maximum:{...i,value:i.value&&mC(e.sheetId,i.value,t)},midpoint:a?{...a,value:mC(e.sheetId,a.value,t)}:void 0}}else if(n.type===`IconSetRule`){let{upperInflectionPoint:r,lowerInflectionPoint:i}=n;e.cf.rule={...n,upperInflectionPoint:{...r,value:mC(e.sheetId,r.value,t)},lowerInflectionPoint:{...i,value:mC(e.sheetId,i.value,t)}}}else n.type===`DataBarRule`&&(e.cf.rule={...n,rangeValues:n.rangeValues?hC(e.sheetId,n.rangeValues,t).range:void 0});return e}EG.add(`ADD_CONDITIONAL_FORMAT`,HG);function UG(e,t){return e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}},e.rule.criterion.values=e.rule.criterion.values.map(n=>mC(e.sheetId,n,t)),e}EG.add(`ADD_DATA_VALIDATION_RULE`,UG);function WG(e,t){return e=b(e),e.pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=mC(e.computedBy.sheetId,e.computedBy.formula,t))}),e}EG.add(`ADD_PIVOT`,WG),EG.add(`UPDATE_PIVOT`,WG),EG.add(`CREATE_CHART`,GG),EG.add(`UPDATE_CHART`,GG);function GG(e,t){return{...e,definition:bO(e.sheetId,e.definition,t)}}let KG=[{match:pr,fn:ZG},{match:hr,fn:QG},{match:vr,fn:$G},{match:_r,fn:nK},{match:mr,fn:tK},{match:gr,fn:eK}];function qG(e,t){let n=TG.getTransformation(e.type,t.type),r=n?n(e,t):XG(e,t);return r&&JG(r,t)}function JG(e,t){let n=EG.get(e.type);if(!n)return e;let r=Gc(t);return r?n(e,r):e}function YG(e,t){let n=[...e],r=new Set(TG.getKeys());for(let e of t)(r.has(e.type)||Kc.contains(e.type))&&(n=n.reduce((t,n)=>{let r=qG(n,e);return r&&t.push(r),t},[]));return n}function XG(e,t){for(let{match:n,fn:r}of KG)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function ZG(e,t){if(!(`sheetId`in t))return e;let n=t.type===`DELETE_SHEET`&&t.sheetId;return e.sheetId===n?`IGNORE_COMMAND`:e.type===`CREATE_SHEET`||t.type===`CREATE_SHEET`||e.sheetId!==t.sheetId?e:`SKIP_TRANSFORMATION`}function QG(e,t){let n=ZG(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=of(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function $G(e,t){let n=ZG(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=of(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function eK(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>sf(e,t)).filter(C);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function tK(e,t){let n=ZG(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;if(t.type!==`ADD_COLUMNS_ROWS`&&t.type!==`REMOVE_COLUMNS_ROWS`)return`SKIP_TRANSFORMATION`;if(t.dimension!==e.dimension)return e;let r=[];return t.type===`REMOVE_COLUMNS_ROWS`?r=il(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=rl(Ft(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function nK(e,t){let n=ZG(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?rK(e,t):t.type===`ADD_MERGE`?iK(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function rK(e,t){let n=t.dimension===`COL`?`col`:`row`,r=e[n];if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);if(e.includes(r))return`IGNORE_COMMAND`;for(let t of e)r>=t&&r--}return t.type===`ADD_COLUMNS_ROWS`&&(r>t.base||r===t.base&&t.position===`before`)&&(r+=t.quantity),{...e,[n]:r}}function iK(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&Vs(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var aK=class{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,n,r,i,a){this.rootCommand=r,this.timestamp=a,this.id=e,this.clientId=t,this._commands=[...n],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}},oK=class extends Error{},sK=class extends cf{revisions;transportService;serverRevisionId;clients={};clientId=`local`;debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new jl;lastLocalOperation;constructor(e,t,n=We){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.debouncedMove=At(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new aK(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}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),void 0)}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.sendToTransport({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.sendToTransport({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){let t=this.clients[e];if(!t)throw new oK(`The client left the session`);return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(C))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId]){this.awaitingClientPosition=e;return}let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getCurrentClient();this.clients[this.clientId]={...r,position:e},this.sendToTransport({type:n,version:1,client:{...r,position:e}}).then(()=>{this.pendingMessages.length>0&&!this.waitingAck&&this.sendPendingMessage()})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){if(this.isWrongServerRevisionId(e)){this.trigger(`unexpected-revision-id`);return}switch(e.type){case`CLIENT_MOVED`:this.onClientMoved(e);break;case`CLIENT_JOINED`:this.onClientJoined(e);break;case`CLIENT_LEFT`:this.onClientLeft(e);break;case`REVISION_REDONE`:this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-redone`,{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case`REVISION_UNDONE`:this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-undone`,{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case`REMOTE_REVISION`:let{clientId:t,commands:n,timestamp:r}=e,i=new aK(e.nextRevisionId,t,n,void 0,void 0,r);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);let t=this.pendingMessages.filter(e=>e.type===`REMOTE_REVISION`).map(e=>e.commands).flat();this.trigger(`remote-revision-received`,{commands:YG(n,t)})}break;case`SNAPSHOT_CREATED`:{let t=new aK(e.nextRevisionId,`server`,[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger(`snapshot`),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger(`collaborative-event-received`)}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;let t=this.clients[this.clientId];if(t){let{position:e}=t;e&&this.sendToTransport({type:`CLIENT_MOVED`,version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),!this.waitingAck&&this.sendPendingMessage()}async sendToTransport(e){return this.transportService.sendMessage(e)}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if(e.type===`REMOTE_REVISION`){let t=this.revisions.get(e.nextRevisionId);t.commands.length===0&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.
1930
+ ${JSON.stringify(e)}`);this.waitingAck=!0,this.sendToTransport({...e,serverRevisionId:this.serverRevisionId}).catch(e=>{if(!(e instanceof oK))throw e.cause||e;this.waitingAck=!1})}}acknowledge(e){switch((e.type===`REVISION_UNDONE`||e.type===`REVISION_REDONE`)&&(this.waitingUndoRedoAck=!1),e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`SNAPSHOT_CREATED`:this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case`REVISION_UNDONE`:{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId);let t=this.pendingMessages.findIndex(e=>e.type===`REMOTE_REVISION`);t!==-1&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if(e.type===`CLIENT_MOVED`&&e.client.id===this.clientId)return!0;switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter(({type:e})=>e!==`REVISION_REDONE`&&e!==`REVISION_UNDONE`)}},cK=class extends Rp{static getters=[`getClientsToDisplay`,`getClient`,`getCurrentClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];colors=new Gn(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 oK)return[];throw e}let e=this.getters.getActiveSheetId(),t=[];for(let n of this.getters.getConnectedClients())n.id!==this.getters.getCurrentClient().id&&n.position&&n.position.sheetId===e&&this.isPositionValid(n.position)&&t.push({...n,position:n.position});return t}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getters.getActiveSheetId();for(let e of this.getClientsToDisplay()){let{row:i,col:a}=e.position,o=this.getters.expandZone(r,{top:i,bottom:i,left:a,right:a}),{x:s,y:c,width:l,height:u}=this.getters.getVisibleRect(o);if(l<=0||u<=0)continue;let d=e.color;t.fillStyle=`${d}10`,t.lineWidth=4*n,t.strokeStyle=d,t.globalCompositeOperation=`multiply`,t.fillRect(s,c,l,u),t.globalCompositeOperation=`source-over`,t.strokeRect(s,c,l,u),t.font=`bold ${Ve+1}px ${He}`}}},lK=class extends Rp{allowDispatch(e){switch(e.type){case`REMOVE_DUPLICATES`:return this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique))}return`Success`}handle(e){switch(e.type){case`REMOVE_DUPLICATES`:this.removeDuplicates(e.columns,e.hasHeader);break;case`TRIM_WHITESPACE`:this.trimWhitespace();break}}removeDuplicates(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getSelectedZone();t&&(r.top+=1);let i=this.getUniqueRowsIndexes(n,r.top,r.bottom,e),a=i.length;if(a===Us(r).numberOfRows){this.notifyRowsRemovedAndRemaining(0,a);return}let o=i.map(e=>({left:r.left,top:e,right:r.right,bottom:e})),s=new Yd(this.getters,this.dispatch),c=s.copy(Nl(n,o),!1);if(!c)return;this.dispatch(`CLEAR_CELLS`,{target:[r],sheetId:n});let l={left:r.left,top:r.top,right:r.left,bottom:r.top};s.paste({zones:[l],sheetId:n},c,{isCutOperation:!1});let u={left:r.left,top:r.top-+!!t,right:r.right,bottom:r.top+a-1};this.selection.selectZone({cell:{col:u.left,row:u.top},zone:u});let d=r.bottom-r.top+1-a;this.notifyRowsRemovedAndRemaining(d,a)}getUniqueRowsIndexes(e,t,n,r){let i=new Map;for(let a of S(t,n+1)){let t=r.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:a}).value);Object.values(i).some(e=>w(e,t))||(i[a]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:`info`,text:E(`%s duplicate rows found and removed.
1931
+ %s unique rows remain.`,e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return this.getters.getSelectedZones().length===1?`Success`:`MoreThanOneRangeSelected`}checkNoMergeInZone(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?`WillRemoveExistingMerge`:`Success`}checkRangeContainsValues(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedZone();return e.hasHeader&&(n.top+=1),this.getters.getEvaluatedCellsInZone(t,n).every(e=>e.type===`empty`)?`EmptyTarget`:`Success`}checkNoColumnProvided(e){return e.columns.length===0?`NoColumnsProvided`:`Success`}checkColumnsIncludedInZone(e){let t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?`ColumnsNotIncludedInZone`:`Success`}checkColumnsAreUnique(e){return e.columns.length===new Set(e.columns).size?`Success`:`DuplicatesColumnsSelected`}trimWhitespace(){let e=ms(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(Ks).flat()){let e=this.getters.getCell({col:r,row:i,sheetId:t});if(!e)continue;let a=Xt(e.content);a!==e.content&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:a}))}let r=n?E(`Trimmed whitespace from %s cells.`,n):E(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}},uK=class extends Rp{handle(e){switch(e.type){case`SET_DECIMAL`:this.setDecimal(e.sheetId,e.target,e.step);break;case`SET_FORMATTING_WITH_PIVOT`:this.setContextualFormat(e.sheetId,e.target,e.format);break}}setContextualFormat(e,t,n){let r=[],i={};for(let n of ms(t))for(let t=n.left;t<=n.right;t++)for(let a=n.top;a<=n.bottom;a++){let n={sheetId:e,col:t,row:a},o=this.getters.getPivotCellFromPosition(n);if(this.isSpilledPivotValueFormula(n,o)){r.push(n);let e=this.getters.getPivotIdFromPosition(n)||``;i[e]??=new Set,i[e].add(o.measure)}}let a=ms(r.map(R));for(let e in i){let t=i[e],r=this.getters.getPivotCoreDefinition(e);this.dispatch(`UPDATE_PIVOT`,{pivotId:e,pivot:{...r,measures:r.measures.map(e=>t.has(e.id)?{...e,format:n}:e)}})}this.dispatch(`SET_FORMATTING`,{sheetId:e,target:a,format:``}),this.dispatch(`SET_FORMATTING`,{sheetId:e,target:ms(t,a),format:n})}isSpilledPivotValueFormula(e,t){let n=this.getters.getCell(e);return t.type===`VALUE`&&!n?.isFormula}setDecimal(e,t,n){let r={};for(let i of ms(t))for(let t of Ks(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=Jo(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=ms(r[t].map(e=>R(e)));this.setContextualFormat(e,n,t)}}getCellNumberFormat(e){for(let t of[e]){let e=this.getters.getEvaluatedCell(t);if(e.type===`number`&&!(e.format&&jo(e.format)))return e.format||Fo(e.value)}}},dK=class extends Rp{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){console.error(`No geoJsonService provided to the model`);return}let t=this.geoJsonCache[e];if(!(t instanceof Promise)){if(t!==void 0)return t??void 0;this.geoJsonCache[e]=new Promise(async t=>{let n=await this.geoJsonService?.getTopoJson(e);this.geoJsonCache[e]=this.convertToGeoJson(n),this.dispatch(`EVALUATE_CHARTS`),t()})}}geoFeatureNameToId(e,t){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}return this.geoJsonService.geoFeatureNameToId(e,t)}convertToGeoJson(e){if(!e)return null;if(e.type===`Topology`){let t=window.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return t.type===`FeatureCollection`?t.features:[t]}else if(e.type===`FeatureCollection`)return e.features;throw Error(`Invalid TopoJSON`)}},fK=class extends Rp{static getters=[`getNextVisibleCellPosition`,`findVisibleHeader`,`findLastVisibleColRowIndex`,`findFirstVisibleColRowIndex`,`isRowHidden`,`isColHidden`,`isHeaderHidden`];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,n){return t===`COL`?this.isColHidden(e,n):this.isRowHidden(e,n)}getNextVisibleCellPosition({sheetId:e,col:t,row:n}){return{sheetId:e,col:this.findVisibleHeader(e,`COL`,t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,n,r){if(n<=r){for(let i=n;i<=r;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}if(n>r){for(let i=n;i>=r;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}}findLastVisibleColRowIndex(e,t,{last:n,first:r}){return S(n,r,-1).find(n=>!this.isHeaderHidden(e,t,n))||r}findFirstVisibleColRowIndex(e,t){let n=this.getters.getNumberHeaders(e,t);for(let r=0;r<n;r++)if(t===`COL`&&!this.isColHidden(e,r)||t===`ROW`&&!this.isRowHidden(e,r))return r}exportForExcel(e){for(let t of e.sheets)for(let[e,n]of Object.entries(t.rows))n.isHidden=this.isRowHidden(t.id,Number(e))}},pK=class extends Rp{static getters=[];allowDispatch(e){switch(e.type){case`DUPLICATE_PIVOT_IN_NEW_SHEET`:if(!this.getters.isExistingPivot(e.pivotId))return`PivotIdNotFound`;if(!this.getters.getPivot(e.pivotId).isValid())return`PivotInError`;break}return`Success`}handle(e){switch(e.type){case`INSERT_NEW_PIVOT`:this.insertNewPivot(e.pivotId,e.newSheetId);break;case`DUPLICATE_PIVOT_IN_NEW_SHEET`:this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case`INSERT_PIVOT_WITH_TABLE`:this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case`SPLIT_PIVOT_FORMULA`:this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){nc(this.getters.getSelectedZone())===1&&this.selection.selectTableAroundSelection();let n=this.getters.getActiveSheetId();this.dispatch(`ADD_PIVOT`,{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:n},columns:[],rows:[],measures:[],name:E(`New pivot`),type:`SPREADSHEET`}});let r=this.getters.getSheetIds().findIndex(e=>e===n)+1,i=this.getters.getPivotFormulaId(e);this.dispatch(`CREATE_SHEET`,{sheetId:t,name:E(`Pivot #%(formulaId)s`,{formulaId:i}),position:r}),this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:t});let a=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,a.getCollapsedTableStructure().export(),`dynamic`)}duplicatePivotInNewSheet(e,t,n){this.dispatch(`DUPLICATE_PIVOT`,{pivotId:e,newPivotId:t,duplicatedPivotName:E(`%s (copy)`,this.getters.getPivotCoreDefinition(e).name)});let r=this.getters.getActiveSheetId(),i=this.getters.getSheetIds().indexOf(r)+1,a=this.getters.getPivotFormulaId(t),o=this.getters.getPivotName(t);if(this.dispatch(`CREATE_SHEET`,{sheetId:n,name:this.getPivotDuplicateSheetName(E(`%(newPivotName)s (Pivot #%(formulaId)s)`,{newPivotName:o,formulaId:a})),position:i}).isSuccessful){this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:r,sheetIdTo:n});let i=this.getters.getPivot(e);this.insertPivotWithTable(n,0,0,t,i.getCollapsedTableStructure().export(),`dynamic`)}}getPivotDuplicateSheetName(e){let t=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e));return an(ht(e),t)}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new nR(o,s,c,l||{}),d=u.columns.length-1;this.resizeSheet(e,t,n,u);let f=this.getters.getPivotFormulaId(r),p;a===`dynamic`?(this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:n,content:`=PIVOT(${f})`}),p={left:t,right:t,top:n,bottom:n}):(this.dispatch(`INSERT_PIVOT`,{sheetId:e,col:t,row:n,pivotId:r,table:u.export()}),p={left:t,right:t+u.getNumberOfDataColumns(),top:n,bottom:n+d+u.rows.length}),this.dispatch(`CREATE_TABLE`,{tableType:a,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,p)],config:{...tt,numberOfHeaders:d}})}resizeSheet(e,t,n,r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}splitPivotFormula(e,t,n,r){let i=this.getters.getSpreadZone({sheetId:e,col:t,row:n});if(!i)return;let a=this.getters.getPivotFormulaId(r),o=new Map;for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++){let r={sheetId:e,col:t,row:n};o.set(r,this.getters.getPivotCellFromPosition(r))}for(let[e,t]of o)this.dispatch(`UPDATE_CELL`,{...e,content:Md(a,t)});if(this.getters.getCoreTable({sheetId:e,col:t,row:n})?.type===`dynamic`){let r=R({col:t,row:n}),a=this.getters.getRangeDataFromZone(e,i);this.dispatch(`UPDATE_TABLE`,{sheetId:e,zone:r,newTableRange:a,tableType:`static`})}}},mK=class extends Rp{allowDispatch(e){switch(e.type){case`SORT_CELLS`:return Vs(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):`InvalidSortAnchor`}return`Success`}handle(e){switch(e.type){case`SORT_CELLS`:this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{});break}}checkMerge({sheetId:e,zone:t}){return this.getters.doesIntersectMerge(e,t)&&Ks(t).some(({col:t,row:n})=>!this.getters.isInMerge({sheetId:e,col:t,row:n}))?`InvalidSortZone`:`Success`}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return`Success`;let n=this.getters.getMerges(e).filter(e=>zs(e,t)),r=Us(n[0]),[i,a]=[r.numberOfCols,r.numberOfRows];return n.every(e=>{let[t,n]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&n===a})?`Success`:`InvalidSortZone`}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return Ks(t).some(({col:t,row:n})=>{let r=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:n});return r&&!w(r,{sheetId:e,col:t,row:n})})?`SortZoneWithArrayFormulas`:`Success`}hasHeader(e,t){if(t[0].length===1)return!1;let n=t.map(t=>t.map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).type));return n[0][0]===`empty`&&(n=n.slice(1)),n.some(e=>e[0]===`empty`)?!1:!!n.some(e=>e[1]!==`empty`&&e[0]!==e[1])}sortZone(e,t,n,r,i){let[a,o]=this.mainCellsSteps(e,n),s=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,c=Object.assign({},n),l=this.mainCells(e,n);!i.sortHeaders&&this.hasHeader(e,l)&&(c.top+=o),l=this.mainCells(e,c);let u=l[s-c.left],d=vv(u.map(e=>this.getters.getEvaluatedCell(e)),r,!!i.emptyCellAsZero).map(e=>e.index),[f,p]=[l.length,l[0].length],m=[];for(let e=0;e<f;e++)for(let t=0;t<p;t++){let{col:n,row:r,sheetId:i}=l[e][d[t]],s=this.getters.getCell({sheetId:i,col:n,row:r}),u=c.left+e*a,f=c.top+t*o,p={sheetId:i,col:u,row:f,content:``};if(s){let e=s.content;if(s.isFormula){let t=this.getters.getCellPosition(s.id);e=this.getters.getTranslatedCellFormula(i,0,f-t.row,s.compiledFormula.tokens)}p.style=s.style,p.content=e,p.format=s.format}m.push(p)}m.forEach(e=>this.dispatch(`UPDATE_CELL`,e))}mainCellsSteps(e,t){let n=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[n?n.right-n.left+1:1,n?n.bottom-n.top+1:1]}mainCells(e,t){let[n,r]=this.mainCellsSteps(e,t),i=[],a=S(t.left,t.right+1,n),o=S(t.top,t.bottom+1,r);for(let t of a){let n=[];i.push(n);for(let r of o)n.push({sheetId:e,col:t,row:r})}return i}},hK=class extends Rp{static getters=[`shouldShowFormulas`];showFormulas=!1;handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.showFormulas=e.show;break}}shouldShowFormulas(){return this.showFormulas}},gK=class extends Rp{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(let t of e.cols){let n=this.getColMaxWidth(e.sheetId,t);n!==0&&this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:[t],dimension:`COL`,size:n,sheetId:e.sheetId})}break;case`AUTORESIZE_ROWS`:this.autoResizeRows(e.sheetId,e.rows);break;case`DELETE_UNFILTERED_CONTENT`:let t=[];for(let n of e.target){let r=gt(S(n.top,n.bottom+1).filter(t=>!this.getters.isRowFiltered(e.sheetId,t)));for(let e of r)t.push({...n,top:e[0],bottom:e[e.length-1]})}this.dispatch(`DELETE_CONTENT`,{sheetId:e.sheetId,target:t});break}}getCellWidth(e){let t=this.getters.getCellComputedStyle(e),n=0,r=this.getters.getEvaluatedCell(e).formattedValue;if(r){let e=Cl(this.ctx,r,t,void 0);n+=Math.max(...e.map(e=>ml(this.ctx,e,t)))}for(let t of this.getters.getCellIcons(e))n+=t.margin+t.size;if(this.getters.getDataValidationChipStyle(e)&&(n+=10),n===0)return 0;if(n+=8,t.wrapping===`wrap`){let t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,n)}return n}getTextWidth(e,t){return ml(this.ctx,e,t)}getCellText(e,t){let n=this.getters.getCell(e),r=this.getters.getLocale();if(t?.showFormula&&n?.isFormula)return gu(n.content,r);if(t?.showFormula&&!n?.content)return``;{let i=this.getters.getEvaluatedCell(e),a=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>ml(this.ctx,e,n?.style||{})}:void 0;return L(i.value,{format:i.format,locale:r,formatWidth:a})}}getCellMultiLineText(e,t){let n=this.getters.getCellStyle(e),r=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.formatWidth});return Cl(this.ctx,r,n,t.wrapText?t.maxWidth:void 0)}computeTextYCoordinate(e,t,n=ze,r=1){let i=e.y+1,a=ll(t,r);if(e.height>a+8){if(n===`middle`)return Math.ceil(i+(e.height-a)/2);if(n===`bottom`)return i+e.height-a-4}return i+4}getContiguousZone(e,t){let n=t=>{for(let n of S(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:n,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:n,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(let n of S(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:n}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:n}))return{...t,right:t.right+1}}return t},r=!1,i=t;do{r=!1;let e=n(i);Rs(i,e)||(r=!0,i=e)}while(r);return i}isCellEmpty(e){let t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===`empty`}getColMaxWidth(e,t){let n=Ks(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,$t(n))}checkSheetExists(e){return`sheetId`in e&&this.getters.tryGetSheet(e.sheetId)===void 0?`InvalidSheetId`:`Success`}checkZonesAreInSheet(e){let t=`sheetId`in e?e.sheetId:this.getters.tryGetActiveSheetId();if(`ranges`in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId)))return`InvalidSheetId`;let n=this.getters.getCommandZones(e);return!t&&n.length>0?`NoActiveSheet`:t&&n.length>0?this.getters.checkZonesExistInSheet(t,n):`Success`}autoResizeRows(e,t){let n=[];for(let r of t){let t=0;for(let n of this.getters.getRowCells(e,r)){let r=this.getters.getCellById(n);if(!r)continue;let i=this.getters.getCellPosition(r.id),a=this.getters.getColSize(e,i.col);if(r.isFormula||this.getters.getArrayFormulaSpreadingOn(i)){let e=this.getters.getEvaluatedCell(i).formattedValue,n=dl(this.ctx,e,r?.style,a);n>t&&n>23&&(t=n)}else{let e=r.content,n=dl(this.ctx,e,r?.style,a);n>=t&&n>23&&(t=0)}}n.push(t||null)}let r=new Map(n.map(e=>[e,[]]));for(let e=0;e<n.length;e++)r.get(n[e])?.push(t[e]);for(let[t,n]of r)this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:n,dimension:`ROW`,size:t,sheetId:e})}},_K=class extends Rp{static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(yr.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(yK(e)){`sheetId`in e?delete this.tableStyles[e.sheetId]:this.tableStyles={};return}}finalize(){for(let e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(let t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}computeTableStyle(e,t){return Nt(()=>{let{config:n,numberOfCols:r,numberOfRows:i}=this.getTableRuntimeConfig(e,t),a=vI(n,this.getters.getTableStyle(t.config.styleId),r,i),o=this.getTableMapping(e,t),s={borders:{},styles:{}};for(let e=0;e<r;e++){let t=o.colMapping[e];s.borders[t]={},s.styles[t]={};for(let n=0;n<i;n++){let r=o.rowMapping[n];s.borders[t][r]=a.borders[e][n],s.styles[t][r]=a.styles[e][n]}}return s})}getTableRuntimeConfig(e,t){let n=t.range.zone,r={...t.config},i=n.right-n.left+1,a=n.bottom-n.top+1;for(let i=n.top;i<=n.bottom;i++)this.getters.isRowHidden(e,i)&&(a--,i-n.top<t.config.numberOfHeaders&&(r.numberOfHeaders--,r.numberOfHeaders<0&&(r.numberOfHeaders=0)),i===n.bottom&&(r.totalRow=!1));for(let t=n.left;t<=n.right;t++)this.getters.isColHidden(e,t)&&(i--,t===n.left&&(r.firstColumn=!1),t===n.right&&(r.lastColumn=!1));return{config:r,numberOfCols:i,numberOfRows:a}}getTableMapping(e,t){let n={},r={},i=0,a=0,o=t.range.zone;for(let t=o.left;t<=o.right;t++)if(!this.getters.isColHidden(e,t)){n[i]=t,i++;for(let t=o.top;t<=o.bottom;t++)this.getters.isRowHidden(e,t)||(r[a]=t,a++)}return{colMapping:n,rowMapping:r}}};let vK=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 yK(e){return vK.has(e.type)}var bK=class extends Rp{static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles=new LF;borders=new LF;handle(e){if(yr.has(e.type)||e.type===`UPDATE_CELL`||e.type===`SET_FORMATTING`||e.type===`CLEAR_FORMATTING`||e.type===`ADD_DATA_VALIDATION_RULE`||e.type===`REMOVE_DATA_VALIDATION_RULE`||e.type===`EVALUATE_CELLS`){this.styles=new LF,this.borders=new LF;return}if(yK(e)){`sheetId`in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new LF,this.borders=new LF);return}if(Sr.has(e.type)){this.styles=new LF;return}if(Cr.has(e.type)){this.borders=new LF;return}}getCellComputedBorder(e){let t=this.borders.get(e);return t===void 0&&(t=this.computeCellBorder(e),this.borders.set(e,t)),t}getCellComputedStyle(e){let t=this.styles.get(e);return t===void 0&&(t=this.computeCellStyle(e),this.styles.set(e,t)),t}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...zt(this.getters.getCellTableBorder(e)||{}),...zt(t)};return kt(n)?null:n}computeCellStyle(e){let t=this.getters.getCell(e),n=this.getters.getCellConditionalFormatStyle(e),r=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e),a={...zt(r),...zt(i),...zt(t?.style),...zt(n)};return this.getters.getEvaluatedCell(e).link&&!a.textColor&&(a.textColor=le),a}},xK=class extends Rp{static getters=[`hasBooleanValidationInZones`];handle(e){switch(e.type){case`TOGGLE_CHECKBOX`:this.toggleCheckbox(e.sheetId,e.target);break}}hasBooleanValidationInZones(e){let t=this.getters.getActiveSheetId();for(let n of e)for(let e=n.left;e<=n.right;e++)for(let r=n.top;r<=n.bottom;r++)if(this.getters.isCellValidCheckbox({col:e,row:r,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n={col:t,row:r,sheetId:e};if(this.getters.isCellValidCheckbox(n)){let e=this.getters.getEvaluatedCell(n).value?`FALSE`:`TRUE`;this.dispatch(`UPDATE_CELL`,{...n,content:e})}}}},SK=class extends Rp{handle(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:if(e.rule.criterion.type===`isBoolean`){let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));for(let e of Vc(t)){let t=this.getters.getCell(e),n=this.getters.getEvaluatedCell(e);if(!t?.content)this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`});else if(t?.content&&n.type===`empty`){let n;if(t.content.startsWith(`=`)){let r=this.getters.evaluateFormula(e.sheetId,t.content);n=(Ir(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!vt(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==`boolean`&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}},CK=class extends Rp{static getters=[`dynamicTranslate`];dynamicTranslate(e){return e}};let wK=[TK,EK,OK,kK];function TK(e,t){return`sheetId`in t?{...b(t),sheetId:e.getActiveSheetId()}:t}function EK(e,t){return!(`target`in t)||!Array.isArray(t.target)?t:{...b(t),target:e.getSelectedZones()}}function DK(e,t){return`zone`in t?{...b(t),zone:e.getSelectedZone()}:t}function OK(e,t){if(!(`row`in t)||!(`col`in t))return t;let{col:n,row:r}=e.getActivePosition();return{...b(t),col:n,row:r}}function kK(e,t){return`ranges`in t?{...b(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}let AK=new jl;function jK(e,t){let n=AK.smallUuid();return{...TK(e,t),figureId:n,chartId:n}}function MK(e,t){return{...TK(e,t),figureId:AK.smallUuid()}}function NK(e,t){let n=OK(e,TK(e,t));return n.figureId=AK.smallUuid(),n}function PK(e,t){let n=b(t);n.sheetId=AK.smallUuid();let r=t.name||e.getSheet(e.getActiveSheetId()).name,i=r.match(/(.+?)\d*$/)?.[1]||r;return n.name=e.getNextSheetName(i),n}function FK(e,t){let n=e.getActivePosition();return{...TK(e,t),base:t.dimension===`COL`?n.col:n.row}}function IK(e,t){let n=e.getSelectedZone();return{...TK(e,t),elements:t.dimension===`COL`?S(n.left,n.right+1):S(n.top,n.bottom+1)}}function LK(e,t){let n=e.getSelectedZone();return{...b(t),zone:n}}function RK(e,t){let n=b(t),{top:r,bottom:i,left:a,right:o}=e.getSelectedZone();return`cols`in n?n.cols=S(a,o+1):`rows`in n&&(n.rows=S(r,i+1)),n}function zK(e,t){let n=e.getSelectedZone();return{...TK(e,t),col:n.left,row:n.top,zone:n}}function BK(e,t){return{type:`REPEAT_PASTE`,pasteOption:b(t.pasteOption),target:e.getSelectedZones()}}function VK(e,t){let n=e.getSelectedZone();return{...TK(e,t),start:t.dimension===`COL`?n.left:n.top,end:t.dimension===`COL`?n.right:n.bottom}}let HK=new g;HK.add(`UPDATE_CELL`,WK),HK.add(`CLEAR_CELL`,WK),HK.add(`CLEAR_CELLS`,WK),HK.add(`DELETE_CONTENT`,WK),HK.add(`ADD_MERGE`,WK),HK.add(`REMOVE_MERGE`,WK),HK.add(`SET_FORMATTING`,WK),HK.add(`CLEAR_FORMATTING`,WK),HK.add(`SET_BORDER`,WK),HK.add(`CREATE_TABLE`,WK),HK.add(`REMOVE_TABLE`,WK),HK.add(`HIDE_SHEET`,WK),HK.add(`ADD_COLUMNS_ROWS`,FK),HK.add(`REMOVE_COLUMNS_ROWS`,IK),HK.add(`HIDE_COLUMNS_ROWS`,IK),HK.add(`RESIZE_COLUMNS_ROWS`,IK),HK.add(`CREATE_SHEET`,PK),HK.add(`CREATE_FIGURE`,NK),HK.add(`CREATE_CHART`,jK),HK.add(`CREATE_IMAGE`,MK),HK.add(`GROUP_HEADERS`,VK),HK.add(`UNGROUP_HEADERS`,VK),HK.add(`UNFOLD_HEADER_GROUPS_IN_ZONE`,DK),HK.add(`FOLD_HEADER_GROUPS_IN_ZONE`,DK);let UK=new g;UK.add(`PASTE`,BK),UK.add(`INSERT_CELL`,LK),UK.add(`DELETE_CELL`,LK),UK.add(`AUTORESIZE_COLUMNS`,RK),UK.add(`AUTORESIZE_ROWS`,RK),UK.add(`SORT_CELLS`,zK),UK.add(`SUM_SELECTION`,WK),UK.add(`SET_DECIMAL`,WK),UK.add(`DELETE_UNFILTERED_CONTENT`,WK);function WK(e,t){let n=b(t);for(let t of wK)n=t(e,n);return n}function GK(e,t){if(t&&HK.contains(t.type))return HK.get(t.type)(e,t)}function KK(e,t,n){if(UK.contains(t.type))return UK.get(t.type)(e,t,n)}function qK(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:Dr(e.rootCommand)?HK.contains(e.rootCommand.type):UK.contains(e.rootCommand.type)}function JK(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return Dr(e.rootCommand)?GK(t,e.rootCommand):KK(t,e.rootCommand,e.commands)}var YK=class extends Rp{static getters=[`canUndo`,`canRedo`];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on(`new-local-state-update`,this,this.onNewLocalStateUpdate),this.session.on(`snapshot`,this,()=>{this.undoStack=[],this.redoStack=[]})}allowDispatch(e){switch(e.type){case`REQUEST_UNDO`:if(!this.canUndo())return`EmptyUndoStack`;break;case`REQUEST_REDO`:if(!this.canRedo())return`EmptyRedoStack`;break}return`Success`}handle(e){switch(e.type){case`REQUEST_UNDO`:case`REQUEST_REDO`:this.requestHistoryChange(e.type===`REQUEST_UNDO`?`UNDO`:`REDO`)}}finalize(){}requestHistoryChange(e){let t=e===`UNDO`?this.undoStack.pop():this.redoStack.pop();if(!t){let e=this.getPossibleRevisionToRepeat();if(!e)return;let t=JK(e,this.getters);if(!t)return;if(!Array.isArray(t)){this.dispatch(t.type,t);return}for(let e of t)this.dispatch(e.type,e);return}e===`UNDO`?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0?!0:qK(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},XK=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,N(e.value)])}isValuePresent(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(n)}isHeaderPresent(e){let t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(n)}trackHeader(e){let t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}},ZK=class extends Rp{static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new XK,this.trackPresencePivotId=e.pivotId;break;case`PIVOT_STOP_PRESENCE_TRACKING`:this.trackPresencePivotId=void 0;break}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw Error(`Tracker not initialized`);return this.tracker}}},QK=class extends Rp{static getters=[`getAutomaticSeparator`];allowDispatch(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:return this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e)}return`Success`}handle(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:this.splitIntoColumns(e);break}}getAutomaticSeparator(){let e=this.getters.getSelectedCells();for(let t of e)if(t.value&&t.type===`text`){let e=this.getAutoSeparatorForString(t.value);if(e)return e}return` `}getAutoSeparatorForString(e){for(let t of[`
1932
+ `,`;`,`,`,` `,`.`])if(e.includes(t))return t}splitIntoColumns({separator:e,addNewColumns:t}){let n=this.getters.getSelectedZone(),r=this.getters.getActiveSheetId(),i=this.getSplittedCols(n,e);t&&this.addColsToAvoidCollisions(n,i),this.removeMergesInSplitZone(n,i),this.addColumnsToNotOverflowSheet(n,i);for(let e=0;e<i.length;e++){let t=n.top+e,a=i[e],o=n.left,s=this.getters.getCell({sheetId:r,col:o,row:t});if(!(a.length===1&&a[0]===s?.content))for(let[e,n]of a.entries())this.dispatch(`UPDATE_CELL`,{sheetId:r,col:o+e,row:t,content:du(n,this.getters.getLocale()),format:``,style:s?.style||null})}}getSplittedCols(e,t){if(!t)throw Error(`Separator cannot be empty`);let n=this.getters.getActiveSheetId(),r=[];for(let i of S(e.top,e.bottom+1)){let a=this.getters.getEvaluatedCell({sheetId:n,col:e.left,row:i}).formattedValue;r.push(this.splitAndRemoveTrailingEmpty(a,t))}return r}splitAndRemoveTrailingEmpty(e,t){let n=e.split(t);for(;n.length>1&&n[n.length-1]===``;)n.pop();return n}willSplittedColsOverwriteContent(e,t){let n=this.getters.getActiveSheetId();for(let r of S(e.top,e.bottom+1)){let i=t[r-e.top];for(let t=1;t<i.length;t++){let i=this.getters.getCell({sheetId:n,col:e.left+t,row:r});if(i&&i.content)return!0}}return!1}removeMergesInSplitZone(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length)),i={...e,right:e.left+r-1},a=this.getters.getMergesInZone(n,i);this.dispatch(`REMOVE_MERGE`,{sheetId:n,target:a})}addColsToAvoidCollisions(e,t){let n=this.getters.getActiveSheetId(),r=0;for(let i of S(e.top,e.bottom+1)){let a={sheetId:n,col:e.left,row:i},o=t[i-e.top],s=this.getColsToAddToAvoidCollision(a,o);r=Math.max(r,s)}r&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:e.left,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:r,position:`after`})}getColsToAddToAvoidCollision(e,t){let n=t.length;for(let t=1;t<n;t++){let r=e.col+t,i=this.getters.getCell({...e,col:r});if(i&&i.content)return n-t}return 0}addColumnsToNotOverflowSheet(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length-1)),i=this.getters.getNumberCols(n)-1;e.left+r>i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:i,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:e.left+r-i,position:`after`})}checkSingleColSelected(){return this.getters.isSingleColSelected()?`Success`:`MoreThanOneColumnSelected`}checkNonEmptySelector(e){return e.separator===``?`EmptySplitSeparator`:`Success`}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return`Success`;let t=this.getters.getSelectedZones()[0],n=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,n)?`SplitWillOverwriteContent`:`Success`}checkSeparatorInSelection({separator:e}){let t=this.getters.getSelectedCells();for(let n of t)if(n.formattedValue.includes(e))return`Success`;return`NoSplitSeparatorInSelection`}},$K=class extends Rp{handle(e){switch(e.type){case`AUTOFILL_TABLE_COLUMN`:let t=this.getters.getCoreTable(e),n=this.getters.getCell(e);if(!t?.config.automaticAutofill||t.type===`dynamic`||!n?.isFormula)return;let{col:r,row:i}=e,a=mI(t.range.zone,t.config);if(a&&Vs(r,i,a)){let t=e.autofillRowStart??a.top,n=e.autofillRowEnd??a.bottom,r={...a,top:t,bottom:n};this.autofillTableZone(e,r)}break}}autofillTableZone(e,t){if(t.top===t.bottom)return;let{col:n,row:r,sheetId:i}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==r&&this.getters.getEvaluatedCell({col:n,row:e,sheetId:i}).type!==`empty`)return;let a={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.bottom}),this.dispatch(`AUTOFILL`),this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.top}),this.dispatch(`AUTOFILL`),this.selection.selectZone(a)}},eq=class extends Rp{allowDispatch(e){switch(e.type){case`RESIZE_TABLE`:let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return`TableNotFound`;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;return r.top!==n.top||r.left!==n.left?`InvalidTableResize`:this.canDispatch(`UPDATE_TABLE`,{...e}).reasons}return`Success`}handle(e){switch(e.type){case`RESIZE_TABLE`:{let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch(`UPDATE_TABLE`,{...e}),!t)return;let n=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(n.right,n.bottom),!t.config.automaticAutofill)return;let r=t.range.zone;if(n.bottom>=r.bottom){for(let t=n.left;t<=n.right;t++){let i={col:t,row:r.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.content.startsWith(`=`)&&this.dispatch(`AUTOFILL_TABLE_COLUMN`,{...i,autofillRowStart:r.bottom,autofillRowEnd:n.bottom})}break}}}}},tq=class extends Rp{static layers=[`Clipboard`];static getters=[`getClipboardTextAndImageContent`,`getClipboardId`,`getClipboardTextContent`,`isCutOperation`];status=`invisible`;originSheetId;copiedData;_isCutOperation=!1;clipboardId=new jl().uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new jl}allowDispatch(e){switch(e.type){case`CUT`:let t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case`PASTE_FROM_OS_CLIPBOARD`:{let t=this.convertTextToClipboardData(e.clipboardContent.text??``),n=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:n,isCutOperation:!1})}case`PASTE`:{if(!this.copiedData)return`EmptyClipboard`;let t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].top===0&&e[0].bottom===0)return`InvalidCopyPasteSelection`;break}case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].left===0&&e[0].right===0)return`InvalidCopyPasteSelection`;break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}}return`Success`}handle(e){switch(e.type){case`COPY`:case`CUT`:let t=this.getters.getSelectedZones();this.status=`visible`,this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation=e.type===`CUT`,this.copiedData=this.copy(t);break;case`PASTE_FROM_OS_CLIPBOARD`:{this._isCutOperation=!1;let t=e.clipboardContent;if(t.data?.version!==bP()&&(t={...t},delete t.data),t.imageData){let n=this.getters.getActiveSheetId(),r=this.uuidGenerator.uuidv4(),i=t.imageData,a=CO(this.getters,i.size);this.dispatch(`CREATE_IMAGE`,{definition:i,size:a,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:n,figureId:r})}t.data?this.copiedData=t.data:this.copiedData=this.convertTextToClipboardData(t.text??``);let n=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:n,selectTarget:!0,isCutOperation:!1}),this.status=`invisible`,this.copiedData=void 0;break}case`PASTE`:{let t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status=`invisible`,this._isCutOperation&&=(this.copiedData=void 0,!1);break}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZone(),t=e.top!==e.bottom,n={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZone(),t=e.left!==e.right,n={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`CLEAN_CLIPBOARD_HIGHLIGHT`:this.status=`invisible`;break;case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Os(t[0])){this.dispatch(`CLEAR_CELLS`,{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}let r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`ADD_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard(e.position===`before`?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case`REMOVE_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;for(let t of e.elements)if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}this.status=`invisible`;break;case`REPEAT_PASTE`:this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case`DELETE_SHEET`:if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status=`invisible`);break;default:Dr(e)&&(this.status=`invisible`)}}convertTextToClipboardData(e){let t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),n={};for(let{handlerName:r,handler:i}of t){let t=i.convertTextToClipboardData(e);n[r]=t;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])t&&e in t&&(n[e]=t[e])}return n}selectClipboardHandlers(e){let t=`figureId`in e?af.figureHandlers:af.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){let t=this.getClipboardData(e);for(let{handler:e}of this.selectClipboardHandlers(t)){let n=e.isCutAllowed(t);if(n!==`Success`)return n}return`Success`}isPasteAllowed(e,t,n){for(let{handler:r}of this.selectClipboardHandlers(t)){let i=r.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...n});if(i!==`Success`)return i}return`Success`}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;let{zones:n}=this.copiedData;for(let r of n)if(t===`COL`&&e<=r.right||t===`ROW`&&e<=r.bottom)return!0;return!1}copy(e,t=`copyPaste`){let n={},r=this.getClipboardData(e);for(let{handlerName:e,handler:i}of this.selectClipboardHandlers(r)){let a=i.copy(r,this._isCutOperation,t);n[e]=a;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])a&&e in a&&(n[e]=a[e])}return n}paste(e,t,n){if(!t)return;let r=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:a,zone:o,selectedZones:s}=zl(r,e,t,i,n);o!==void 0&&this.addMissingDimensions(r,o.right-o.left+1,o.bottom-o.top+1,o.left,o.top),Rl(i,t,a,n),n?.selectTarget&&Bl(this.selection,e,s)}addMissingDimensions(e,t,n,r,i){let a=n+i-this.getters.getNumberRows(e);a>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a,position:`after`});let o=t+r-this.getters.getNumberCols(e);o>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:o,position:`after`})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){let e=await this.getImageContent(),t=e?.type,n={"text/plain":this.getPlainTextContent(),"text/html":await this.getHTMLContent()};return t&&e&&(n[t]=e),n}getSheetData(){let e={version:bP(),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(` `)).join(`
1933
1933
  `)||` `}async getHTMLContent(){let e=``,t=this.copiedData?.cells;if(!t)if(this.copiedData?.figureId){let t=this.copiedData.figureId,n=this.getters.getFigureSheetId(t);e=this.getters.getFigure(n,t).tag===`image`?await this.craftImageHTML(t):` `}else e=` `;else if(t.length===1&&t[0].length===1)e=`${this.getters.getCellText(t[0][0].position)}`;else if(t[0][0]){let n=`<table border="1" style="border-collapse:collapse">`;for(let e of t){n+=`<tr>`;for(let t of e){if(!t)continue;let e=V(kf(this.getters.getCellComputedStyle(t.position))),r=this.getters.getCellText(t.position);n+=`<td style="${e}">`+DO(r)+`</td>`}n+=`</tr>`}n+=`</table>`,e=n}else return``;return`<div data-osheet-clipboard='${DO(JSON.stringify(this.getSheetData()))}'>${e}</div>`}readFileAsDataURL(e){return new Promise(t=>{let n=new FileReader;n.onload=()=>t(n.result),n.readAsDataURL(e)})}async craftImageHTML(e){if(!this.fileStore)return` `;let t=this.getters.getImage(e).path,n=await this.fileStore?.getFile(t)||null;return n?`<img src="${DO(await this.readFileAsDataURL(n))}" />`:` `}async getImageContent(){let e=this.copiedData?.figureId;if(!e)return;let t=this.getters.getFigureSheetId(e),n=this.getters.getFigure(t,e),r;if(n.tag===`image`){if(!this.fileStore)return;let t=this.getters.getImage(e).path;if(r=await this.fileStore?.getFile(t),r.type!==`image/png`){if(r.size>5242880){this.ui.notifyUI({text:E(`The file you are trying to copy is too large (>%sMB).
1934
1934
  It will not be added to your OS clipboard.
1935
- You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=await oT(t)}}if(r)return r instanceof File?r:new File([r],`image.png`,{type:`image/png`})}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r;return r=t===`COL`?{...e,left:e.right+1,right:this.getters.getNumberCols(n)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1},{cut:[r],paste:[e]}}getInsertCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r,i;return t===`COL`?(r={...e,right:this.getters.getNumberCols(n)-1},i={...e,left:e.right+1,right:e.right+1}):(r={...e,bottom:this.getters.getNumberRows(n)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1}),{cut:[r],paste:[i]}}getClipboardData(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedFigureId();if(n)return{figureId:n,sheetId:t};let r=Nl(t,e);return this._isCutOperation||(r.rowsIndexes=r.rowsIndexes.filter(e=>!this.getters.isRowFiltered(t,e))),r}drawLayer(e){if(this.status!==`visible`||!this.copiedData)return;let{sheetId:t,zones:n}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!n||!n.length)return;let{ctx:r,thinLineWidth:i}=e;r.setLineDash([8,5]),r.strokeStyle=ae,r.lineWidth=3.3*i;for(let e of n){let{x:t,y:n,width:i,height:a}=this.getters.getVisibleRect(e);i>0&&a>0&&r.strokeRect(t,n,i,a)}}};let tq={filterType:`criterion`,type:`none`,values:[]};var nq=class extends Rp{static getters=[`getFilterValue`,`getFilterHiddenValues`,`getFilterCriterionValue`,`getFirstTableInSelection`,`isRowFiltered`,`isFilterActive`];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){switch(e.type){case`UPDATE_FILTER`:if(!this.getters.getFilterId(e))return`FilterNotFound`;break}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(let 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]=b(this.filterValues[e.sheetId]);break}}finalize(){if(this.isEvaluationDirty){for(let e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterValue(e){let t=this.getters.getFilterId(e),n=e.sheetId;return t?this.filterValues[n]?.[t]:void 0}getFilterHiddenValues(e){let t=this.getters.getFilterId(e),n=e.sheetId;if(!t||!this.filterValues[n])return[];let r=this.filterValues[n][t]||[];return r.filterType===`values`?r.hiddenValues:[]}getFilterCriterionValue(e){let t=this.getters.getFilterId(e),n=e.sheetId;if(!t||!this.filterValues[n])return tq;let r=this.filterValues[n][t];return r&&r.filterType===`criterion`?r:tq}isFilterActive(e){let t=this.getters.getFilterId(e);if(!t)return!1;let n=e.sheetId,r=this.filterValues[n]?.[t];return r?r.filterType===`values`?r.hiddenValues.length>0:r.type!==`none`:!1}getFirstTableInSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,value:n,sheetId:r}){let i=this.getters.getFilterId({sheetId:r,col:e,row:t});i&&(this.filterValues[r]||(this.filterValues[r]={}),this.filterValues[r][i]=n)}updateHiddenRows(e){let t=this.getters.getFilters(e).sort((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top),n=new Set;for(let r of t){let t=this.filterValues[e]?.[r.id],i=r.filteredRange?.zone;if(!(!t||!i||n.has(r.rangeWithHeaders.zone.top)||this.getters.isRowHiddenByUser(e,r.rangeWithHeaders.zone.top)))if(t.filterType===`values`){let a=t.hiddenValues?.map(Tl);if(!a)continue;let o=new Set(a);for(let t=i.top;t<=i.bottom;t++){let i=this.getCellValueAsString(e,r.col,t);o.has(i)&&n.add(t)}}else{if(t.type===`none`)continue;let a=Y.get(t.type),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(e,t)??``:ts(t,D));if(o.some(Wu))continue;let s={type:t.type,values:o.map(Hu),dateValue:t.dateValue};for(let t=i.top;t<=i.bottom;t++){let i={sheetId:e,col:r.col,row:t},o=this.getters.getEvaluatedCell(i).value??``;a.isValueValid(o,s,this.getters,e)||n.add(t)}}}this.hiddenRows[e]=n}getCellValueAsString(e,t,n){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).formattedValue.toLowerCase()}exportForExcel(e){for(let t of e.sheets){let e=t.id;for(let n of t.tables){let r=Ts(n.range),i=[],a=[];for(let n of S(0,Us(r).numberOfCols)){let o={sheetId:t.id,col:r.left+n,row:r.top},s=this.getFilterHiddenValues(o),c=this.getters.getFilter(o),l=c?.filteredRange?Ks(c.filteredRange.zone).map(t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue):[];if(s.length){let e=l.filter(e=>e).filter(e=>!s.includes(e));i.push({colId:n,displayedValues:[...new Set(e)],displayBlanks:!s.includes(``)&&l.some(e=>!e)})}let u=this.getters.getEvaluatedCell(o).formattedValue,d=this.getUniqueColNameForExcel(n,u,a);a.push(d);let f=T(o.col,o.row);t.cells[f]=d,t.cellValues[f]=d}n.filters=i}}}getUniqueColNameForExcel(e,t,n){return t||=`Column${e}`,an(t,n,{compute:(e,n)=>t+String(n),start:2})}},rq=class extends Rp{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{return`InvalidSheetId`}case`MOVE_COLUMNS_ROWS`:return this.isMoveElementAllowed(e)}return`Success`}handleEvent(e){let t=e.anchor,n=[];switch(this.isUnbounded=e.options?.unbounded||!1,e.mode){case`overrideSelection`:n=[t.zone];break;case`updateAnchor`:n=[...this.gridSelection.zones];let r=n.findIndex(t=>Rs(t,e.previousAnchor.zone));r>=0&&(n[r]=t.zone);break;case`newAnchor`:n=[...this.gridSelection.zones,t.zone];break}this.setSelectionMixin(e.anchor,n),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor));let{col:r,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:r,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);break}switch(e.type){case`START`:let t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);let{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(n,r),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`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`ADD_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}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`:let i=Object.keys(this.sheetsData).filter(e=>!this.getters.tryGetSheet(e));for(let e of i)delete this.sheetsData[e];for(let e in this.sheetsData){let t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:b(t)}}this.fallbackToVisibleSheet();let a=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map(e=>this.getters.expandZone(a,e)),this.gridSelection.anchor.zone=this.getters.expandZone(a,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null;break}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,b(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(){let e=new Set;for(let t of this.gridSelection.zones)if(t.top===0&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let n=t.left;n<=t.right;n++)e.add(n);return e}getActiveRows(){let e=new Set,t=this.getters.getActiveSheetId();for(let n of this.gridSelection.zones)if(n.left===0&&n.right===this.getters.getNumberCols(t)-1)for(let t=n.top;t<=n.bottom;t++)e.add(t);return e}getCurrentStyle(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return b(this.gridSelection.zones)}getSelectedZone(){return b(this.gridSelection.anchor.zone)}getSelectecUnboundedZone(){return b(this.isUnbounded?this.getters.getUnboundedZone(this.activeSheet.id,this.gridSelection.anchor.zone):this.gridSelection.anchor.zone)}getSelection(){return b(this.gridSelection)}getSelectedCells(){let e=this.getters.getActiveSheetId(),t=[];for(let n of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,n));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();{let 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(){let e=this.getters.getSelectedZones();return!(e.length!==1||e[0].left!==e[0].right)}getElementsFromSelection(e){if(e===`COL`&&this.getters.getActiveCols().size===0||e===`ROW`&&this.getters.getActiveRows().size===0)return[];let t=this.getters.getSelectedZones(),n=[],r=e===`COL`?`left`:`top`,i=e===`COL`?`right`:`bottom`;for(let e of t){let t=Array.from({length:e[i]-e[r]+1},(t,n)=>e[r]+n);n=n.concat(t)}return[...new Set(n)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:b(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor));else{let{col:e,row:n}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,n)}let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:n,row:r})}setSelectionMixin(e,t){let{anchor:n,zones:r}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=n,this.gridSelection.zones=Xs(r)}selectCell(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.expandZone(n,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:r,cell:{col:e,row:t}},[r])}setActiveSheet(e){this.activeSheet=this.getters.getSheet(e)}activateNextSheet(e){let t=this.getters.getSheetIds(),n=(t.findIndex(e=>e===this.activeSheet.id)+(e===`left`?t.length-1:1))%t.length;this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[n]})}onColumnsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=Ns(n,`left`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=Ns(i,`left`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>Ns(t,`left`,[...e.elements]));this.setSelectionMixin(a,o)}onRowsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=Ns(n,`top`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=Ns(i,`top`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>Ns(t,`top`,[...e.elements]));this.setSelectionMixin(a,o)}onAddElements(e){let t=e.dimension===`COL`?`left`:`top`,n=Ms(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),r=this.gridSelection.zones.map(n=>Ms(n,t,e.base,e.position,e.quantity)),i={cell:{col:n.left,row:n.top},zone:n};this.setSelectionMixin(i,r)}onMoveElements(e){let t=e.elements.length,n=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});let r=e.dimension===`COL`,i=e.elements[0],a=e.elements[t-1],o=e.base<i,s=o&&r?t:0,c=o&&!r?t:0,l=o?e.elements.map(e=>e+t):e.elements,u={};for(let t of l)u[t]=this.getters.getHeaderSize(e.sheetId,e.dimension,t);let d=[{left:r?i+s:0,right:r?a+s:this.getters.getNumberCols(e.sheetId)-1,top:r?0:i+c,bottom:r?this.getters.getNumberRows(e.sheetId)-1:a+c}],f=this.getActiveSheetId(),p=o?e.base:e.base+1,m=[{left:r?p:0,right:r?p+t-1:this.getters.getNumberCols(e.sheetId)-1,top:r?0:p,bottom:r?this.getters.getNumberRows(e.sheetId)-1:p+t-1}],h=af.cellHandlers.getKeys().map(e=>[e,new(af.cellHandlers.get(e))(this.getters,this.dispatch)]),g={};for(let[e,t]of h)g[e]=t.copy(Nl(f,d),!1,`shiftCells`);for(let[e,t]of h)g[e]&&t.paste({zones:m,sheetId:f},g[e],{isCutOperation:!0});let _=m[0],v=_.left,y=_.top;this.setSelectionMixin({zone:_,cell:{col:v,row:y}},[_]);let ee=o?e.base:e.base+1,te={};for(let t of l){let n=u[t];n!==this.getters.getHeaderSize(e.sheetId,e.dimension,ee)&&(te[n]??=[],te[n].push(ee)),ee+=1}for(let t in te)this.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,size:parseInt(t,10),elements:te[t]});this.dispatch(`REMOVE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,elements:l}),this.applyFigureUpdates(n)}getFiguresUpdates(e){let t=[],n={},r=e.elements[0]<e.base?e.base-e.elements.length+1:e.base;for(let t=0;t<e.elements.length;t++)n[e.elements[t]]=r+t;for(let r of this.getters.getFigures(e.sheetId))e.dimension===`COL`&&r.col in n&&t.push({type:`UPDATE_FIGURE`,sheetId:e.sheetId,figureId:r.id,col:n[r.col],row:r.row}),e.dimension===`ROW`&&r.row in n&&t.push({type:`UPDATE_FIGURE`,sheetId:e.sheetId,figureId:r.id,row:n[r.row],col:r.col});return t}applyFigureUpdates(e){for(let t of e)this.dispatch(t.type,{...t})}isMoveElementAllowed(e){let t=e.dimension===`COL`,n=e.elements[0],r=e.elements[e.elements.length-1],i=e.sheetId,a=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(a(i,n-1,n)||a(i,r,r+1)||a(i,e.base-1,e.base))return`WillRemoveExistingMerge`;let o=[e.base,...e.elements],s=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return o.some(e=>e<0||e>=s)?`InvalidHeaderIndex`:!t&&!this.isTableRowMoveAllowed(i,e.elements)?`CannotMoveTableHeader`:`Success`}isTableRowMoveAllowed(e,t){let n=this.getters.getCoreTables(e);if(n.length===0)return!0;let r=new Set(t);return n.every(({range:{zone:e},config:n})=>{let{top:i,bottom:a}=e;if(n.numberOfHeaders===0)return!0;let o=i+n.numberOfHeaders-1;return t.some(e=>e>=i&&e<=o)?S(i,a+1).every(e=>r.has(e)):!0})}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){let e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){let{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);let{col:t,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:n})}}clipSelection(e,t){let n=this.getters.getNumberCols(e)-1,r=this.getters.getNumberRows(e)-1,i=t.zones.map(e=>({left:x(e.left,0,n),right:x(e.right,0,n),top:x(e.top,0,r),bottom:x(e.bottom,0,r)})),a=x(t.anchor.cell.col,0,n),o=x(t.anchor.cell.row,0,r),s={left:x(t.anchor.zone.left,0,n),right:x(t.anchor.zone.right,0,n),top:x(t.anchor.zone.top,0,r),bottom:x(t.anchor.zone.bottom,0,r)};return{zones:i,anchor:{cell:{col:a,row:o},zone:s}}}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getSelectedZones();t.fillStyle=`#f3f7fe`,t.fillStyle=r.length===1&&r[0].left===r[0].right&&r[0].top===r[0].bottom?`#f3f7fe`:`#e9f0ff`,t.strokeStyle=ae,t.lineWidth=1.5*n;for(let e of r){let{x:n,y:r,width:i,height:a}=this.getters.getVisibleRect(e);t.globalCompositeOperation=`multiply`,t.fillRect(n,r,i,a),t.globalCompositeOperation=`source-over`,t.strokeRect(n,r,i,a)}t.globalCompositeOperation=`source-over`;let i=this.getActivePosition();t.strokeStyle=ae,t.lineWidth=3*n;let a;a=this.getters.isInMerge(i)?this.getters.getMerge(i):R(i);let{x:o,y:s,width:c,height:l}=this.getters.getVisibleRect(a);c>0&&l>0&&t.strokeRect(o,s,c,l)}},iq=class{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,n,r,i,a){if(this.getters=e,this.sheetId=t,this.boundaries=n,r.width<0||r.height<0)throw Error(`Viewport size cannot be negative`);this.viewportWidth=r.height&&r.width,this.viewportHeight=r.width&&r.height,this.top=n.top,this.bottom=n.bottom,this.left=n.left,this.right=n.right,this.offsetX=a.x,this.offsetY=a.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(){let 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:n}=this.getters.getColDimensions(this.sheetId,e),{end:r}=this.getters.getRowDimensions(this.sheetId,t),i=n-this.offsetCorrectionX;this.canScrollHorizontally&&(i=Math.max(i,this.viewportWidth));let a=r-this.offsetCorrectionY;return this.canScrollVertically&&(a=Math.max(a,this.viewportHeight),r+46>a&&!this.getters.isReadonly()&&(a+=46)),{width:i,height:a}}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){let t=this.sheetId,n=this.getters.getMainCellPosition({sheetId:t,...e}),{col:r,row:i}=this.getters.getNextVisibleCellPosition(n);Vs(r,this.boundaries.top,this.boundaries)&&this.adjustPositionX(r),Vs(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){let t=this.sheetId,{start:n,end:r}=this.getters.getColDimensions(t,e);this.offsetX+this.viewportWidth+this.offsetCorrectionX<r?this.offsetX=r-this.viewportWidth:this.offsetX+this.offsetCorrectionX>n&&(this.offsetX=n-this.offsetCorrectionX),this.adjustViewportZoneX()}adjustPositionY(e){let t=this.sheetId,{start:n,end:r}=this.getters.getRowDimensions(t,e);this.offsetY+this.viewportHeight+this.offsetCorrectionY<r?this.offsetY=r-this.viewportHeight:this.offsetY+this.offsetCorrectionY>n&&(this.offsetY=n-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){let t=Ls(e,this),n=this.snapCorrection.x,r=this.snapCorrection.y;if(t)return{x:this.getters.getColRowOffset(`COL`,this.left,t.left)+this.offsetCorrectionX-(this.left===t.left?0:n),y:this.getters.getColRowOffset(`ROW`,this.top,t.top)+this.offsetCorrectionY-(this.top===t.top?0:r),width:Math.min(this.getters.getColRowOffset(`COL`,t.left,t.right+1)-(this.left===t.left?n:0),this.viewportWidth),height:Math.min(this.getters.getColRowOffset(`ROW`,t.top,t.bottom+1)-(this.top===t.top?r:0),this.viewportHeight)}}getFullRect(e){let t=Ls(e,this.boundaries),n=this.snapCorrection.x,r=this.snapCorrection.y;if(t){let t=this.getters.getColRowOffset(`COL`,this.left,e.left)+this.offsetCorrectionX,i=this.getters.getColRowOffset(`ROW`,this.top,e.top)+this.offsetCorrectionY,a=this.getters.getColRowOffset(`COL`,e.left,e.right+1),o=this.getters.getColRowOffset(`ROW`,e.top,e.bottom+1);return{x:t-n,y:i-r,width:a,height:o}}}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,n=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;let r=this.sheetId,i=this.getters.getNumberHeaders(r,e),a=n,o=i;for(;a<=o&&a!==i&&o!==-1;){let i=Math.floor((a+o)/2),s=this.getters.getColRowOffset(e,n,i),c=this.getters.getHeaderSize(r,e,i);if(t>=s&&t<s+c)return i;t>=s+c?a=i+1:o=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){let{width:e}=this.getMaxSize();this.viewportWidth+this.offsetX>e&&(this.offsetX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){let{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&&(this.left===-1&&(this.left=this.boundaries.left),this.right===-1&&(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&&(this.top===-1&&(this.top=this.boundaries.top),this.bottom===-1&&(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)))}}},aq=class extends Rp{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.getMaximumSheetOffset`.split(`.`);viewports={};sheetViewWidth=Qe();sheetViewHeight=Qe();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){let t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:n,row:r}=Qs(e.previousAnchor.zone,e.anchor.zone);if(e.mode===`updateAnchor`){let i=e.previousAnchor.zone,a=e.anchor.zone,{top:o,bottom:s,left:c,right:l}=this.getMainInternalViewport(t);i.left===a.left&&i.right===a.right&&(n=c>n||n>l?c:n),i.top===a.top&&i.bottom===a.bottom&&(r=o>r||r>s?o:r)}n=Math.min(n,this.getters.getNumberCols(t)-1),r=Math.min(r,this.getters.getNumberRows(t)-1),this.sheetsWithDirtyViewports.has(t)||this.refreshViewport(this.getters.getActiveSheetId(),{col:n,row:r})}}handle(e){if(yr.has(e.type))for(let 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(let 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`:let t=this.getters.getActiveSheetId(),{top:n,viewportHeight:r,offsetCorrectionY:i}=this.getMainInternalViewport(t),a=this.getters.getRowDimensions(t,n);this.shiftVertically(a.start+r-i);break;case`SHIFT_VIEWPORT_UP`:{let e=this.getters.getActiveSheetId(),{top:t,viewportHeight:n,offsetCorrectionY:r}=this.getMainInternalViewport(e),i=this.getters.getRowDimensions(e,t);this.shiftVertically(i.end-r-n);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`:for(let 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});break}}finalize(){for(let e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){let t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach(e=>{e.adjustPosition(t)})}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){let e=this.getters.getSheetIds();for(let t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getColIndex(e)))}getRowIndex(e){let 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(){let e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getSheetViewVisibleCols(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>S(e.left,e.right+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`COL`,t))}getSheetViewVisibleRows(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>S(e.top,e.bottom+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`ROW`,t))}getVisibleCellPositions(){let e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),n=this.getters.getActiveSheetId(),r=[];for(let i of e)for(let e of t){let t={sheetId:n,col:i,row:e},a=this.getters.getMainCellPosition(t);a.row!==e||a.col!==i||r.push(t)}return r}getMainViewportRect(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e),{width:i,height:a}=t.getMaxSize();return{x:this.getters.getColDimensions(e,n).start,y:this.getters.getRowDimensions(e,r).start,width:i,height:a}}getMaximumSheetOffset(){let e=this.getters.getActiveSheetId(),{width:t,height:n}=this.getMainViewportRect(),r=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-r.viewportWidth),maxOffsetY:Math.max(0,n-r.viewportHeight)}}getColRowOffsetInViewport(e,t,n){if(n<t)return-this.getColRowOffsetInViewport(e,n,t);let r=this.getters.getActiveSheetId(),i=e===`COL`?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),a=i.findIndex(e=>t>=e),o=i.findIndex(e=>n<=e);o=o===-1?i.length:o;let s=i.slice(a,o),c=0;for(let t of s)c+=this.getters.getHeaderSize(r,e,t);return c}isVisibleInViewport({sheetId:e,col:t,row:n}){return this.getSubViewports(e).some(e=>e.isVisible(t,n))}getEdgeScrollCol(e,t,n){let r=!1,i=0,a=0,{xSplit:o}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:s}=this.getSheetViewDimension(),{x:c}=this.getMainViewportCoordinates(),l=this.getActiveSheetScrollInfo().scrollX;return e>s?(r=!0,a=vc(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=vc(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=vc(e),i=`reset`),{canEdgeScroll:r,direction:i,delay:a}}getEdgeScrollRow(e,t,n){let r=!1,i=0,a=0,{ySplit:o}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:s}=this.getSheetViewDimension(),{y:c}=this.getMainViewportCoordinates(),l=this.getActiveSheetScrollInfo().scrollY;return e>s?(r=!0,a=vc(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=vc(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=vc(e),i=`reset`),{canEdgeScroll:r,direction:i,delay:a}}getVisibleRect(e){let t=this.getVisibleRectWithoutHeaders(e);return{...t,x:t.x+this.gridOffsetX,y:t.y+this.gridOffsetY}}getVisibleRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getVisibleRect(e))}getRect(e){let t=this.getters.getActiveSheetId(),n=this.mapViewportsToRect(t,t=>t.getFullRect(e));return{...n,x:n.x+this.gridOffsetX,y:n.y+this.gridOffsetY}}getRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getFullRect(e))}getMainViewportCoordinates(){let e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,n).start}}getColDimensionsInViewport(e,t){let{top:n}=this.getMainInternalViewport(e),r={left:t,right:t,top:n,bottom:n},{x:i,width:a}=this.getVisibleRect(r),o=i-this.gridOffsetX;return{start:o,size:a,end:o+a}}getRowDimensionsInViewport(e,t){let{left:n}=this.getMainInternalViewport(e),r={left:0,right:n,top:t,bottom:t},{y:i,height:a}=this.getVisibleRect(r),o=i-this.gridOffsetY;return{start:o,size:a,end:o+a}}getAllActiveViewportsZonesAndRect(){let 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(C)}checkPositiveDimension(e){return e.width<0||e.height<0?`InvalidViewportSize`:`Success`}checkValuesAreDifferent(e){let{height:t,width:n}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===n&&e.height===t?`ValuesNotChanged`:`Success`}checkScrollingDirection({offsetX:e,offsetY:t}){let n=this.getMainInternalViewport(this.getters.getActiveSheetId());return!n.canScrollHorizontally&&e>0||!n.canScrollVertically&&t>0?`InvalidScrollingDirection`:`Success`}checkIfViewportsWillChange({offsetX:e,offsetY:t}){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();return this.getSubViewports(n).some(n=>n.willNewOffsetScrollViewport(x(e,0,r),x(t,0,i)))?`Success`:`ViewportScrollLimitsReached`}getMainViewport(e){let 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(){let e={};for(let t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,n=0,r=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=n,this.gridOffsetY=r,this.recomputeViewports()}recomputeViewports(){for(let e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();this.getSubViewports(n).forEach(n=>n.setViewportOffset(x(e,0,r),x(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;let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),a=Math.min(this.getters.getColRowOffset(`COL`,0,t,e),this.sheetViewWidth),o=Math.min(this.getters.getColRowOffset(`ROW`,0,n,e),this.sheetViewHeight),s=Math.max(this.sheetViewWidth-a,0),c=Math.max(this.sheetViewHeight-o,0),{xRatio:l,yRatio:u}=this.getFrozenSheetViewRatio(e),d=l<1,f=u<1,p=this.getViewportOffset(e),m={topLeft:n&&t&&new iq(this.getters,e,{left:0,right:t-1,top:0,bottom:n-1},{width:a,height:o},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:n&&new iq(this.getters,e,{left:t,right:r-1,top:0,bottom:n-1},{width:s,height:o},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?p.x:0,y:0})||void 0,bottomLeft:t&&new iq(this.getters,e,{left:0,right:t-1,top:n,bottom:i-1},{width:a,height:c},{canScrollHorizontally:!1,canScrollVertically:f},{x:0,y:f?p.y:0})||void 0,bottomRight:new iq(this.getters,e,{left:t,right:r-1,top:n,bottom:i-1},{width:s,height:c},{canScrollHorizontally:d,canScrollVertically:f},{x:d?p.x:0,y:f?p.y:0})};this.viewports[e]=m}refreshViewport(e,t){this.getSubViewports(e).forEach(e=>{e.adjustViewportZone(),e.adjustPosition(t)})}shiftVertically(e){let t=this.getters.getActiveSheetId(),{top:n}=this.getMainInternalViewport(t),{scrollX:r}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(r,e);let{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){let e=this.getMainInternalViewport(t).top-n;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getColIndexLeftOfMainViewport(e){if(e>=0)return-1;let t=this.getters.getActiveSheetId(),n=this.getActiveMainViewport().left,r=-this.getActiveSheetScrollInfo().scrollX-this.getters.getColRowOffset(`COL`,n,0);for(;e<r;n--)r-=this.getters.getColSize(t,n-1);return Math.max(n,0)}getRowIndexTopOfMainViewport(e){if(e>=0)return-1;let t=this.getters.getActiveSheetId(),n=this.getActiveMainViewport().top,r=-this.getActiveSheetScrollInfo().scrollY-this.getters.getColRowOffset(`ROW`,n,0);for(;e<r;n--)r-=this.getters.getRowSize(t,n-1);return Math.max(n,0)}getVisibleFigures(){let e=this.getters.getActiveSheetId(),t=[],n=this.getters.getFigures(e),{scrollX:r,scrollY:i}=this.getters.getActiveSheetScrollInfo(),{x:a,y:o}=this.getMainViewportCoordinates(),{width:s,height:c}=this.getters.getSheetViewDimensionWithHeaders();for(let l of n){let n=this.getFigureUI(e,l),{x:u,y:d}=n;u>=a&&(u+l.width<r+a||u>s+r+a)||d>=o&&(d+l.height<i+o||d>c+i+o)||t.push(n)}return t}getFigureUI(e,t){let n=t.offset.x+this.getters.getColDimensions(e,t.col).start,r=t.offset.y+this.getters.getRowDimensions(e,t.row).start;return{...t,x:n,y:r}}getPositionAnchorOffset(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),r=e.x-t,i=e.y-n,a=r>=0?this.getColIndex(r):this.getColIndexLeftOfMainViewport(r),o=i>=0?this.getRowIndex(i):this.getRowIndexTopOfMainViewport(i),{x:s,y:c}=this.getRect(R({col:a,row:o}));return{col:a,row:o,offset:{x:Math.max(r-s+this.gridOffsetX,0),y:Math.max(i-c+this.gridOffsetY,0)}}}isPixelPositionVisible(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),{x:r,y:i}=this.getters.getMainViewportCoordinates(),{width:a,height:o}=this.getters.getSheetViewDimension();return!(e.x>=r&&(e.x<r+t||e.x>a+t+r)||e.y>=i&&(e.y<i+n||e.y>o+n+i))}getFrozenSheetViewRatio(e){let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,n).start,a=this.sheetViewWidth+this.gridOffsetX,o=this.sheetViewHeight+this.gridOffsetY;return{xRatio:r/a,yRatio:i/o}}mapViewportsToRect(e,t){let n=1/0,r=1/0,i=0,a=0,o=!1;for(let s of this.getSubViewports(e)){let e=t(s);e&&(o=!0,n=Math.min(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.x+e.width),a=Math.max(a,e.y+e.height))}return o?{x:n,y:r,width:i-n,height:a-r}:{x:0,y:0,width:0,height:0}}},oq=class extends Rp{static getters=[`getSelectedCarouselItem`,`getChartFromFigureId`,`getChartIdFromFigureId`];uuidGenerator=new jl;carouselStates={};allowDispatch(e){switch(e.type){case`ADD_FIGURE_CHART_TO_CAROUSEL`:return!this.getters.doesCarouselExist(e.carouselFigureId)||this.getters.getFigure(e.sheetId,e.chartFigureId)?.tag!==`chart`?`InvalidFigureId`:`Success`;case`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=>w(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(let e in this.carouselStates)this.fixWrongCarouselState(e);break}}popOutChartFromCarousel(e,t,n){let r=this.getters.getCarousel(e);if(!r)return;let i=this.getters.getFigure(n,e),a=this.getters.getChartDefinition(t);if(!a||!i)return;let o=this.getters.getFigureUI(n,i),s=this.getters.getPositionAnchorOffset({x:o.x+50,y:o.y+50}),c=this.uuidGenerator.smallUuid();this.dispatch(`CREATE_CHART`,{...s,chartId:this.uuidGenerator.smallUuid(),figureId:c,sheetId:n,size:{width:i.width,height:i.height},definition:{...a}});let l=r.items.filter(e=>e.type!==`chart`||e.chartId!==t);this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:{...r,items:l}}),this.dispatch(`SELECT_FIGURE`,{figureId:c})}getSelectedCarouselItem(e){let t=this.getters.getCarousel(e);if(t.items.length)return this.carouselStates[e]?t.items.find(t=>this.getCarouselItemId(t)===this.carouselStates[e]):t.items[0]}getChartFromFigureId(e){if(!this.getters.getFigureSheetId(e))return;let t=this.getChartIdFromFigureId(e);return t?this.getters.getChart(t):void 0}getChartIdFromFigureId(e){let t=this.getters.getFigureSheetId(e);if(!t)return;let n=this.getters.getFigure(t,e);if(!(!n||n.tag!==`chart`&&n.tag!==`carousel`)){if(n.tag===`carousel`){let t=this.getSelectedCarouselItem(e);return t?.type===`chart`?t.chartId:void 0}return this.getters.getChartIds(t).find(t=>this.getters.getFigureIdFromChartId(t)===e)}}fixWrongCarouselState(e){if(!this.getters.doesCarouselExist(e)){delete this.carouselStates[e];return}let t=this.getters.getCarousel(e);t.items.length===0?delete this.carouselStates[e]:this.carouselStates[e]&&t.items.some(t=>this.getCarouselItemId(t)===this.carouselStates[e])||(this.carouselStates[e]=this.getCarouselItemId(t.items[0]))}addNewChartToCarousel(e,t){let n=this.getters.getCarousel(e),r=this.uuidGenerator.smallUuid();this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:t,definition:WO});let i={...n,items:[...n.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:t,figureId:e,definition:i})}addFigureChartToCarousel(e,t,n){let r=this.getChartIdFromFigureId(t);if(!r)return;let i=this.getters.getCarousel(e),a={...i,items:[...i.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:a}),this.dispatch(`UPDATE_CHART`,{sheetId:n,chartId:r,figureId:e,definition:this.getters.getChartDefinition(r)}),this.dispatch(`DELETE_FIGURE`,{sheetId:n,figureId:t})}getCarouselItemId(e){return e.type===`chart`?e.chartId:`carouselDataView`}},sq=class extends Rp{static getters=[`getColDimensions`,`getRowDimensions`,`getColRowOffset`];headerPositions={};isDirty=!0;handle(e){switch(yr.has(e.type)&&(this.headerPositions={},this.isDirty=!0),e.type){case`START`:for(let e of this.getters.getSheetIds())this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e);break;case`UPDATE_CELL`:this.headerPositions={},this.isDirty=!0;break;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]=b(this.headerPositions[e.sheetId]);break}}finalize(){for(let e of this.getters.getSheetIds())(this.isDirty||!this.headerPositions[e])&&(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){let n=this.headerPositions[e].COL[t],r=this.getters.getColSize(e,t);return{start:n,size:r,end:n+(this.getters.isColHidden(e,t)?0:r)}}getRowDimensions(e,t){let n=this.headerPositions[e].ROW[t],r=this.getters.getRowSize(e,t);return{start:n,size:r,end:n+(this.getters.isRowHidden(e,t)?0:r)}}getColRowOffset(e,t,n,r=this.getters.getActiveSheetId()){let i=this.headerPositions[r][e][t];return this.headerPositions[r][e][n]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,`COL`),ROW:this.computePositions(e,`ROW`)}}computePositions(e,t){let n={},r=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)n[i]=r,!this.getters.isHeaderHidden(e,t,i)&&(r+=this.getters.getHeaderSize(e,t,i));return n}};let cq=new g().add(`settings`,_W).add(`sheet`,fW).add(`header grouping`,hW).add(`header visibility`,oW).add(`tables`,pW).add(`dataValidation`,rW).add(`cell`,ZU).add(`merge`,cW).add(`headerSize`,aW).add(`borders`,XU).add(`conditional formatting`,nW).add(`figures`,iW).add(`chart`,eW).add(`carousel`,mW).add(`image`,sW).add(`pivot_core`,gW).add(`spreadsheet_pivot_core`,vW).add(`tableStyle`,yW),lq=new g().add(`ui_sheet`,hK).add(`ui_options`,mK).add(`autofill`,SG).add(`sort`,pK).add(`automatic_sum`,CG).add(`format`,lK).add(`insert_pivot`,fK).add(`pivot_presence`,XK).add(`split_to_columns`,ZK).add(`subtotal_evaluation`,zp).add(`collaborative`,sK).add(`history`,JK).add(`data_cleanup`,cK).add(`table_autofill`,QK).add(`table_ui_resize`,$K).add(`datavalidation_insert`,xK).add(`checkbox_toggle`,bK).add(`dynamic_translate`,SK).add(`geo_features`,uK),uq=new g().add(`selection`,rq).add(`evaluation_filter`,nq).add(`header_visibility_ui`,dK).add(`cell_computed_style`,yK).add(`table_computed_style`,gK).add(`header_positions`,sq).add(`viewport`,aq).add(`clipboard`,eq).add(`carousel_ui`,oq),dq=new g().add(`evaluation`,WW).add(`evaluation_chart`,YW).add(`evaluation_cf`,XW).add(`row_size`,rG).add(`data_validation_ui`,QW).add(`dynamic_tables`,nG).add(`custom_colors`,JW).add(`pivot_ui`,cG).add(`cell_icon`,tG);up.add(`dataValidation`,{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(on(t)||!this.composer.currentEditedCell)return[];let n=this.composer.currentEditedCell,r=this.getters.getValidationRuleForCell(n);if(!r||r.criterion.type!==`isValueInList`&&r.criterion.type!==`isValueInRange`)return[];let i=this.composer.currentEditedCell.sheetId,a=r.criterion.type===`isValueInRange`?this.getters.getDataValidationRangeValues(i,r.criterion):r.criterion.values.map(e=>({label:e,value:e}));if(r.criterion.displayStyle!==`chip`)return a.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));let o=r.criterion.colors;return a.map(e=>{let t=o?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:t?Mn(t):void 0,backgroundColor:t||`#E7E9ED`,classes:[`badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start`]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t),this.composer.stopEdition()}}),up.add(`functions`,{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if(e.type!==`SYMBOL`)return[];let t=e.value;return on(this.composer.currentContent)?Object.entries(zS.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:n}])=>({text:e,description:n,htmlContent:$H(t,e,ge,`o-semi-bold`)})).sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text)):[]},selectProposal(e,t){let n=e.end,r=e.end;[`SYMBOL`,`FUNCTION`].includes(e.type)&&(n=e.start);let i=this.composer.currentTokens;t+=`(`;let a=i.map(e=>e.start).indexOf(e.start);a+1<i.length&&i[a+1]?.type===`LEFT_PAREN`&&r++,this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}}),up.add(`pivot_ids`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||![`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`].includes(t.parent.toUpperCase())||t.argPosition!==0)return;let n=this.getters.getPivotIds();if(!n.includes(e.value))return n.map(e=>{let t=this.getters.getPivotCoreDefinition(e),n=`${this.getters.getPivotFormulaId(e)}`;return{text:n,description:t.name,htmlContent:[{value:n,color:ot.NUMBER}],fuzzySearchKey:n+t.name,alwaysExpanded:!0}}).filter(C)},selectProposal:qS}),up.add(`pivot_measures`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(t?.parent.toUpperCase()!==`PIVOT.VALUE`||t.argPosition!==1)return[];let n=mU(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return[];let i=this.getters.getPivot(r);return i.init(),i.isValid()?i.definition.measures.map(e=>{if(e.fieldName===`__count`){let e=`"__count"`;return{text:e,description:E(`Count`),htmlContent:[{value:e,color:ot.STRING}],fuzzySearchKey:E(`Count`)+e}}return dU(e)}).filter(C):[]},selectProposal:qS}),up.add(`pivot_group_fields`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!fq(e)&&!pq(e))return;let n=mU(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);i.init();let a=i.getFields(),{columns:o,rows:s}=i.definition,c=t.args;t?.parent.toUpperCase()===`PIVOT.VALUE`?(c=c.filter((e,t)=>t%2==0),c=c.slice(1,t.argPosition)):c=c.filter((e,t)=>t%2==1);let l=c.map(e=>e?.value).filter(C),u=o.map(e=>e.nameWithGranularity),d=s.map(e=>e.nameWithGranularity),f=[],p=[`ARG_SEPARATOR`,`SPACE`].includes(e.type)?l.at(-1):l.at(-2),m=GU.get(i.type);if(m&&p?.startsWith(`#`)&&(p=p.slice(1)),p===void 0&&(f.push(u[0]),f.push(d[0])),d.includes(p)){let e=d[d.indexOf(p)+1];f.push(e),f.push(u[0])}if(u.includes(p)){let e=u[u.indexOf(p)+1];f.push(e)}let h=f.filter(C);return h.map(e=>{let[t,n]=e.split(`:`),r=a[t];return r?uU(r,n):void 0}).concat(h.map(e=>{if(!m)return;let t=a[e.split(`:`)[0]];if(!t)return;let n=`"#${e}"`;return{text:n,description:E(`%s (positional)`,t.string)+(t.help?` (${t.help})`:``),htmlContent:[{value:n,color:ot.STRING}],fuzzySearchKey:t.string+n}})).filter(C)},selectProposal:qS});function fq(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==0}function pq(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==1}up.add(`pivot_group_values`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!e||!mq(e)&&!hq(e))return;let n=mU(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);if(!i.isValid())return;let a=t.argPosition,o=e.functionContext?.args[a-1]?.value;if(!o)return;let s;try{s=i.definition.getDimension(o)}catch{return}return s.granularity===`month_number`?Object.values(go).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:ot.NUMBER}]})):s.granularity===`quarter_number`?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:E(`Quarter %s`,e),htmlContent:[{value:`${e}`,color:ot.NUMBER}]})):s.granularity===`day_of_month`?S(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:ot.NUMBER}]})):s.granularity===`iso_week_number`?S(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:ot.NUMBER}]})):s.granularity===`day_of_week`?S(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:ot.NUMBER}]})):s.granularity===`hour_number`?S(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:ot.NUMBER}]})):s.granularity===`minute_number`?S(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:ot.NUMBER}]})):s.granularity===`second_number`?S(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:ot.NUMBER}]})):i.getPossibleFieldValues(s).map(({value:e,label:t})=>{let n=typeof e==`string`,r=n?`"${e}"`:e.toString(),i=n?ot.STRING:ot.NUMBER,a=t===e?``:t;return{text:r,description:a,htmlContent:[{value:r,color:i}],fuzzySearchKey:r+a}})},selectProposal:qS});function mq(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==1}function hq(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==0}up.add(`sheet_names`,{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return e.type===`SYMBOL`||e.type===`UNKNOWN`&&e.value.startsWith(`'`)?this.getters.getSheetIds().map(e=>{let t=mt(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith(`'`)?t:`'`+t}}):[]},selectProposal(e,t){let n=e.start,r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t+`!`)}});let gq=new g;gq.add(`link`,{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,n)=>Yr(t.model.getters.getEvaluatedCell(e).link,t,n),title:(e,t)=>{let n=t.getEvaluatedCell(e).link;return n?n.isExternal?E(`Go to url: %(url)s`,{url:n.url}):E(`Go to %(label)s`,{label:n.label}):``},sequence:5}),gq.add(`dashboard_pivot_sorting`,{condition:(e,t)=>{if(!t.isDashboard())return!1;let n=t.getPivotCellFromPosition(e);return AR(t,e)&&n.type===`MEASURE_HEADER`},execute:(e,t)=>{jR(t,e,vq(t.model.getters,e))},component:KU,componentProps:(e,t)=>({position:e,sortDirection:t.getPivotCellSortDirection(e)}),sequence:2});let _q={none:`asc`,asc:`desc`,desc:`none`};function vq(e,t){return _q[e.getPivotCellSortDirection(t)??`none`]}let yq=new g().add(`ADD_COLUMNS_ROWS`,Sq).add(`REMOVE_COLUMNS_ROWS`,Dq).add(`ADD_MERGE`,Cq).add(`REMOVE_MERGE`,wq).add(`CREATE_SHEET`,Tq).add(`DELETE_SHEET`,Oq).add(`DUPLICATE_SHEET`,Eq).add(`CREATE_FIGURE`,kq).add(`CREATE_CHART`,Aq).add(`HIDE_COLUMNS_ROWS`,jq).add(`UNHIDE_COLUMNS_ROWS`,Mq).add(`CREATE_TABLE_STYLE`,Nq).add(`ADD_PIVOT`,xq).add(`RENAME_SHEET`,Pq);for(let e of Er.values())yq.contains(e)||yq.add(e,bq);function bq(e){return[e]}function xq(e){return[{type:`REMOVE_PIVOT`,pivotId:e.pivotId}]}function Sq(e){let t=[],n=e.base;e.position===`after`&&n++;for(let r=0;r<e.quantity;r++)t.push(r+n);return[{type:`REMOVE_COLUMNS_ROWS`,dimension:e.dimension,elements:t,sheetId:e.sheetId,sheetName:e.sheetName}]}function Cq(e){return[{type:`REMOVE_MERGE`,sheetId:e.sheetId,target:e.target}]}function wq(e){return[{type:`ADD_MERGE`,sheetId:e.sheetId,target:e.target}]}function Tq(e){return[{type:`DELETE_SHEET`,sheetId:e.sheetId,sheetName:e.name}]}function Eq(e){return[{type:`DELETE_SHEET`,sheetId:e.sheetIdTo,sheetName:``}]}function Dq(e){let t=[],n=[...e.elements].sort((e,t)=>e-t);for(let r of gt(n)){let n=r[0]===0?0:r[0]-1,i=r[0]===0?`before`:`after`;t.push({type:`ADD_COLUMNS_ROWS`,dimension:e.dimension,quantity:r.length,base:n,sheetId:e.sheetId,sheetName:e.sheetName,position:i})}return t}function Oq(e){return[{type:`CREATE_SHEET`,sheetId:e.sheetId,position:1,name:e.sheetName}]}function kq(e){return[{type:`DELETE_FIGURE`,figureId:e.figureId,sheetId:e.sheetId}]}function Aq(e){return[{type:`DELETE_FIGURE`,figureId:e.figureId,sheetId:e.sheetId}]}function jq(e){return[{type:`UNHIDE_COLUMNS_ROWS`,sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}function Mq(e){return[{type:`HIDE_COLUMNS_ROWS`,sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}function Nq(e){return[{type:`REMOVE_TABLE_STYLE`,tableStyleId:e.tableStyleId}]}function Pq(e){return[{type:`RENAME_SHEET`,sheetId:e.sheetId,oldName:e.newName,newName:e.oldName}]}let Fq=new g;Fq.add(`format_number_automatic`,{...QR,id:`format_number_automatic`,sequence:10}).add(`format_number_plain_text`,{...$R,id:`format_number_plain_text`,sequence:15,separator:!0}).add(`format_number_number`,{...ez,id:`format_number_number`,sequence:20}).add(`format_number_percent`,{...nz,id:`format_number_percent`,sequence:30,separator:!0}).add(`format_number_currency`,{...rz,id:`format_number_currency`,sequence:40}).add(`format_number_accounting`,{...az,id:`format_number_accounting`,sequence:45}).add(`format_number_currency_rounded`,{...iz,id:`format_number_currency_rounded`,sequence:50}).add(`format_custom_currency`,{...sz,id:`format_custom_currency`,sequence:60,separator:!0}).add(`format_number_date`,{...cz,id:`format_number_date`,sequence:70}).add(`format_number_time`,{...lz,id:`format_number_time`,sequence:80}).add(`format_number_date_time`,{...uz,id:`format_number_date_time`,sequence:90}).add(`format_number_duration`,{...dz,id:`format_number_duration`,sequence:100,separator:!0}).add(`more_formats`,{...mz,id:`more_formats`,sequence:120});function Iq(e){let t=new Set(Fq.getAll().map(t=>typeof t.format==`function`?t.format(e):t.format)),n=new Map;for(let r of e.model.getters.getSheetIds()){let i=e.model.getters.getEvaluatedCells(r);for(let e in i){let r=i[e];if(r.format&&!n.has(r.format)&&!t.has(r.format)){let e=Lq(r.format);(e===`date`||e===`currency`)&&n.set(r.format,ZR({descriptionValue:e===`currency`?1e3:oz,format:r.format,name:r.format}))}}}return[...n.values()]}let Lq=Kt(e=>jo(e)?`date`:e.includes(`[$`)?`currency`:`number`),Rq={name:E(`More formats`),icon:`o-spreadsheet-Icon.NUMBER_FORMATS`,children:[e=>{let t=Iq(e).map(e=>({...e,sequence:110}));return t.length>0&&(t[t.length-1].separator=!0),f([...Fq.getAll(),...t])}]};function zq(e){let t=new IA;return t.add(`delete`,{...kA,sequence:10}).add(`hide_sheet`,{...FA,sequence:20}).add(`duplicate`,{...AA,sequence:30,separator:!0}).add(`rename`,{...jA(e),sequence:40}).add(`change_color`,{...MA(e),sequence:50,separator:!0}).add(`move_right`,{...NA,sequence:60}).add(`move_left`,{...PA,sequence:70}),t}let Bq=new IA;Bq.add(`file`,{name:E(`File`),sequence:10,isReadonlyAllowed:!0}).addChild(`settings`,[`file`],{name:E(`Settings`),sequence:200,execute:e=>e.openSidePanel(`Settings`),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.COG`}).add(`edit`,{name:E(`Edit`),sequence:20,isReadonlyAllowed:!0}).addChild(`undo`,[`edit`],{...DI,sequence:10}).addChild(`redo`,[`edit`],{...OI,sequence:20,separator:!0}).addChild(`copy`,[`edit`],{...kI,sequence:30}).addChild(`cut`,[`edit`],{...AI,sequence:40}).addChild(`paste`,[`edit`],{...jI,sequence:50}).addChild(`paste_special`,[`edit`],{...MI,sequence:60,separator:!0}).addChild(`paste_special_value`,[`edit`,`paste_special`],{...NI,sequence:10}).addChild(`paste_special_format`,[`edit`,`paste_special`],{...PI,sequence:20}).addChild(`edit_table`,[`edit`],{...qI,isVisible:DF,sequence:60}).addChild(`find_and_replace`,[`edit`],{...FI,sequence:65,separator:!0}).addChild(`delete`,[`edit`],{name:E(`Delete`),icon:`o-spreadsheet-Icon.TRASH`,sequence:70}).addChild(`edit_delete_cell_values`,[`edit`,`delete`],{...II,sequence:10}).addChild(`edit_delete_row`,[`edit`,`delete`],{...LI,sequence:20}).addChild(`edit_delete_column`,[`edit`,`delete`],{...BI,sequence:30}).addChild(`edit_delete_cell_shift_up`,[`edit`,`delete`],{...WI,sequence:40}).addChild(`edit_delete_cell_shift_left`,[`edit`,`delete`],{...GI,sequence:50}).addChild(`edit_unhide_columns`,[`edit`],{...UF,sequence:80}).addChild(`edit_unhide_rows`,[`edit`],{...KF,sequence:80}).add(`view`,{name:E(`View`),sequence:30,isReadonlyAllowed:!0}).addChild(`unfreeze_panes`,[`view`],{...qF,sequence:4}).addChild(`freeze_panes`,[`view`],{...JF,sequence:5}).addChild(`unfreeze_rows`,[`view`,`freeze_panes`],{...YF,sequence:5}).addChild(`freeze_first_row`,[`view`,`freeze_panes`],{...XF,sequence:10}).addChild(`freeze_second_row`,[`view`,`freeze_panes`],{...ZF,sequence:15}).addChild(`freeze_current_row`,[`view`,`freeze_panes`],{...QF,sequence:20,separator:!0}).addChild(`unfreeze_columns`,[`view`,`freeze_panes`],{...$F,sequence:25}).addChild(`freeze_first_col`,[`view`,`freeze_panes`],{...eI,sequence:30}).addChild(`freeze_second_col`,[`view`,`freeze_panes`],{...tI,sequence:35}).addChild(`freeze_current_col`,[`view`,`freeze_panes`],{...nI,sequence:40}).addChild(`group_headers`,[`view`],{name:E(`Group`),sequence:15,separator:!0,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,isVisible:NF}).addChild(`group_columns`,[`view`,`group_headers`],{...oI,sequence:5}).addChild(`ungroup_columns`,[`view`,`group_headers`],{...cI,isVisible:e=>fI(e,`COL`),sequence:10}).addChild(`group_rows`,[`view`,`group_headers`],{...sI,sequence:15}).addChild(`ungroup_rows`,[`view`,`group_headers`],{...lI,isVisible:e=>fI(e,`ROW`),sequence:20}).addChild(`show`,[`view`],{name:E(`Show`),sequence:1,icon:`o-spreadsheet-Icon.SHOW`}).addChild(`view_gridlines`,[`view`,`show`],{...rI,sequence:5}).addChild(`view_formulas`,[`view`,`show`],{...aI,sequence:10}).addChild(`view_irregularity_map`,[`view`],{...iI,sequence:40,separator:!0}).add(`insert`,{name:E(`Insert`),sequence:40,isReadonlyAllowed:!0}).addChild(`insert_row`,[`insert`],{...QI,sequence:10}).addChild(`insert_row_before`,[`insert`,`insert_row`],{...eL,sequence:10}).addChild(`insert_row_after`,[`insert`,`insert_row`],{...rL,sequence:20}).addChild(`insert_column`,[`insert`],{...iL,sequence:20}).addChild(`insert_column_before`,[`insert`,`insert_column`],{...oL,sequence:10}).addChild(`insert_column_after`,[`insert`,`insert_column`],{...lL,sequence:20}).addChild(`insert_cell`,[`insert`],{...uL,sequence:30}).addChild(`insert_cell_down`,[`insert`,`insert_cell`],{...dL,name:E(`Shift down`),sequence:10}).addChild(`insert_cell_right`,[`insert`,`insert_cell`],{...fL,name:E(`Shift right`),sequence:20}).addChild(`insert_sheet`,[`insert`],{...AL,sequence:40,separator:!0}).addChild(`insert_chart`,[`insert`],{...pL,sequence:50}).addChild(`insert_carousel`,[`insert`],{...mL,sequence:51}).addChild(`insert_pivot`,[`insert`],{...hL,sequence:52}).addChild(`insert_image`,[`insert`],{...gL,sequence:55}).addChild(`insert_table`,[`insert`],{..._L,sequence:57}).addChild(`insert_function`,[`insert`],{...vL,sequence:60}).addChild(`insert_function_sum`,[`insert`,`insert_function`],{...yL,sequence:0}).addChild(`insert_function_average`,[`insert`,`insert_function`],{...bL,sequence:10}).addChild(`insert_function_count`,[`insert`,`insert_function`],{...xL,sequence:20}).addChild(`insert_function_max`,[`insert`,`insert_function`],{...SL,sequence:30}).addChild(`insert_function_min`,[`insert`,`insert_function`],{...CL,sequence:40,separator:!0}).addChild(`categorie_function_all`,[`insert`,`insert_function`],{...wL,sequence:50}).addChild(`categories_function_list`,[`insert`,`insert_function`],EL).addChild(`insert_link`,[`insert`],{...DL,separator:!0,sequence:70}).addChild(`insert_checkbox`,[`insert`],{...OL,sequence:80}).addChild(`insert_dropdown`,[`insert`],{...kL,separator:!0,sequence:90}).add(`format`,{name:E(`Format`),sequence:50,isReadonlyAllowed:!0}).addChild(`format_number`,[`format`],{...Rq,name:E(`Number`),sequence:10,separator:!0}).addChild(`format_bold`,[`format`],{...Ez,sequence:20}).addChild(`format_italic`,[`format`],{...Dz,sequence:30}).addChild(`format_underline`,[`format`],{...Oz,sequence:40}).addChild(`format_strikethrough`,[`format`],{...kz,sequence:50,separator:!0}).addChild(`format_font_size`,[`format`],{...Az,sequence:60,separator:!0}).addChild(`format_alignment`,[`format`],{...jz,sequence:70}).addChild(`format_alignment_left`,[`format`,`format_alignment`],{...Nz,sequence:10}).addChild(`format_alignment_center`,[`format`,`format_alignment`],{...Pz,sequence:20}).addChild(`format_alignment_right`,[`format`,`format_alignment`],{...Fz,sequence:30,separator:!0}).addChild(`format_alignment_top`,[`format`,`format_alignment`],{...Lz,sequence:40}).addChild(`format_alignment_middle`,[`format`,`format_alignment`],{...Rz,sequence:50}).addChild(`format_alignment_bottom`,[`format`,`format_alignment`],{...zz,sequence:60,separator:!0}).addChild(`format_wrapping`,[`format`],{...Bz,sequence:80,separator:!0}).addChild(`format_wrapping_overflow`,[`format`,`format_wrapping`],{...Hz,sequence:10}).addChild(`format_wrapping_wrap`,[`format`,`format_wrapping`],{...Uz,sequence:20}).addChild(`format_wrapping_clip`,[`format`,`format_wrapping`],{...Wz,sequence:30}).addChild(`format_cf`,[`format`],{...Gz,sequence:90,separator:!0}).addChild(`format_clearFormat`,[`format`],{...Kz,sequence:100,separator:!0}).add(`data`,{name:E(`Data`),sequence:60,isReadonlyAllowed:!0}).addChild(`sort_range`,[`data`],{...BR,sequence:10,separator:!0}).addChild(`sort_ascending`,[`data`,`sort_range`],{...VR,sequence:10}).addChild(`sort_descending`,[`data`,`sort_range`],{...GR,sequence:20}).addChild(`data_cleanup`,[`data`],{...HR,sequence:15}).addChild(`remove_duplicates`,[`data`,`data_cleanup`],{...UR,sequence:10}).addChild(`trim_whitespace`,[`data`,`data_cleanup`],{...WR,sequence:20}).addChild(`split_to_columns`,[`data`],{...JR,sequence:20}).addChild(`data_validation`,[`data`],{name:E(`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`],{...KR,sequence:40,separator:!0}).addChild(`pivot_data_sources`,[`data`],e=>{let t=e.model.getters.getPivotIds().length;return e.model.getters.getPivotIds().map((n,r)=>{let i={get highlights(){return YH(e.model.getters,n)}};return{id:`item_pivot_${e.model.getters.getPivotFormulaId(n)}`,name:e.model.getters.getPivotDisplayName(n),sequence:50+r/t,isReadonlyAllowed:!0,execute:e=>e.openSidePanel(`PivotSidePanel`,{pivotId:n}),isEnabled:e=>!e.isSmall,onStartHover:e=>e.getStore(Kk).register(i),onStopHover:e=>e.getStore(Kk).unRegister(i),icon:`o-spreadsheet-Icon.PIVOT`,separator:r===e.model.getters.getPivotIds().length-1,secondaryIcon:e=>e.model.getters.isPivotUnused(n)?`o-spreadsheet-Icon.UNUSED_PIVOT_WARNING`:void 0}})}).addChild(`reinsert_dynamic_pivot`,[`data`],YR).addChild(`reinsert_static_pivot`,[`data`],XR);let Vq=new class extends g{mapping={};uuidGenerator=new jl;replace(e,t){let n={...t,id:this.uuidGenerator.uuidv4()};return super.replace(e,n)}getAllOrdered(){return this.getAll().sort((e,t)=>e.sequence-t.sequence)}};var Hq=class{listeners=[];async sendMessage(e){for(let{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)}},Uq=class{fileStore;constructor(e){this.fileStore=e}async requestImage(){let e=await this.userImageUpload(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}async uploadFile(e){let t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}userImageUpload(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.setAttribute(`type`,`file`),n.setAttribute(`accept`,`image/*`),n.addEventListener(`change`,async()=>{n.files===null||n.files.length!==1?t():e(n.files[0])}),n.click()})}getImageOriginalSize(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{t({width:r.width,height:r.height})}),r.addEventListener(`error`,n),r.src=e})}};let Wq=[{transform:`scale(0)`},{transform:`scale(0.8)`,offset:.33},{opacity:`0`,transform:`scale(1)`,offset:1}];B`
1935
+ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=await oT(t)}}if(r)return r instanceof File?r:new File([r],`image.png`,{type:`image/png`})}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r;return r=t===`COL`?{...e,left:e.right+1,right:this.getters.getNumberCols(n)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1},{cut:[r],paste:[e]}}getInsertCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r,i;return t===`COL`?(r={...e,right:this.getters.getNumberCols(n)-1},i={...e,left:e.right+1,right:e.right+1}):(r={...e,bottom:this.getters.getNumberRows(n)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1}),{cut:[r],paste:[i]}}getClipboardData(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedFigureId();if(n)return{figureId:n,sheetId:t};let r=Nl(t,e);return this._isCutOperation||(r.rowsIndexes=r.rowsIndexes.filter(e=>!this.getters.isRowFiltered(t,e))),r}drawLayer(e){if(this.status!==`visible`||!this.copiedData)return;let{sheetId:t,zones:n}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!n||!n.length)return;let{ctx:r,thinLineWidth:i}=e;r.setLineDash([8,5]),r.strokeStyle=ae,r.lineWidth=3.3*i;for(let e of n){let{x:t,y:n,width:i,height:a}=this.getters.getVisibleRect(e);i>0&&a>0&&r.strokeRect(t,n,i,a)}}};let nq={filterType:`criterion`,type:`none`,values:[]};var rq=class extends Rp{static getters=[`getFilterValue`,`getFilterHiddenValues`,`getFilterCriterionValue`,`getFirstTableInSelection`,`isRowFiltered`,`isFilterActive`];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){switch(e.type){case`UPDATE_FILTER`:if(!this.getters.getFilterId(e))return`FilterNotFound`;break}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(let 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]=b(this.filterValues[e.sheetId]);break}}finalize(){if(this.isEvaluationDirty){for(let e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterValue(e){let t=this.getters.getFilterId(e),n=e.sheetId;return t?this.filterValues[n]?.[t]:void 0}getFilterHiddenValues(e){let t=this.getters.getFilterId(e),n=e.sheetId;if(!t||!this.filterValues[n])return[];let r=this.filterValues[n][t]||[];return r.filterType===`values`?r.hiddenValues:[]}getFilterCriterionValue(e){let t=this.getters.getFilterId(e),n=e.sheetId;if(!t||!this.filterValues[n])return nq;let r=this.filterValues[n][t];return r&&r.filterType===`criterion`?r:nq}isFilterActive(e){let t=this.getters.getFilterId(e);if(!t)return!1;let n=e.sheetId,r=this.filterValues[n]?.[t];return r?r.filterType===`values`?r.hiddenValues.length>0:r.type!==`none`:!1}getFirstTableInSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,value:n,sheetId:r}){let i=this.getters.getFilterId({sheetId:r,col:e,row:t});i&&(this.filterValues[r]||(this.filterValues[r]={}),this.filterValues[r][i]=n)}updateHiddenRows(e){let t=this.getters.getFilters(e).sort((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top),n=new Set;for(let r of t){let t=this.filterValues[e]?.[r.id],i=r.filteredRange?.zone;if(!(!t||!i||n.has(r.rangeWithHeaders.zone.top)||this.getters.isRowHiddenByUser(e,r.rangeWithHeaders.zone.top)))if(t.filterType===`values`){let a=t.hiddenValues?.map(Tl);if(!a)continue;let o=new Set(a);for(let t=i.top;t<=i.bottom;t++){let i=this.getCellValueAsString(e,r.col,t);o.has(i)&&n.add(t)}}else{if(t.type===`none`)continue;let a=Y.get(t.type),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(e,t)??``:ts(t,D));if(o.some(Wu))continue;let s={type:t.type,values:o.map(Hu),dateValue:t.dateValue};for(let t=i.top;t<=i.bottom;t++){let i={sheetId:e,col:r.col,row:t},o=this.getters.getEvaluatedCell(i).value??``;a.isValueValid(o,s,this.getters,e)||n.add(t)}}}this.hiddenRows[e]=n}getCellValueAsString(e,t,n){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).formattedValue.toLowerCase()}exportForExcel(e){for(let t of e.sheets){let e=t.id;for(let n of t.tables){let r=Ts(n.range),i=[],a=[];for(let n of S(0,Us(r).numberOfCols)){let o={sheetId:t.id,col:r.left+n,row:r.top},s=this.getFilterHiddenValues(o),c=this.getters.getFilter(o),l=c?.filteredRange?Ks(c.filteredRange.zone).map(t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue):[];if(s.length){let e=l.filter(e=>e).filter(e=>!s.includes(e));i.push({colId:n,displayedValues:[...new Set(e)],displayBlanks:!s.includes(``)&&l.some(e=>!e)})}let u=this.getters.getEvaluatedCell(o).formattedValue,d=this.getUniqueColNameForExcel(n,u,a);a.push(d);let f=T(o.col,o.row);t.cells[f]=d,t.cellValues[f]=d}n.filters=i}}}getUniqueColNameForExcel(e,t,n){return t||=`Column${e}`,an(t,n,{compute:(e,n)=>t+String(n),start:2})}},iq=class extends Rp{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{return`InvalidSheetId`}case`MOVE_COLUMNS_ROWS`:return this.isMoveElementAllowed(e)}return`Success`}handleEvent(e){let t=e.anchor,n=[];switch(this.isUnbounded=e.options?.unbounded||!1,e.mode){case`overrideSelection`:n=[t.zone];break;case`updateAnchor`:n=[...this.gridSelection.zones];let r=n.findIndex(t=>Rs(t,e.previousAnchor.zone));r>=0&&(n[r]=t.zone);break;case`newAnchor`:n=[...this.gridSelection.zones,t.zone];break}this.setSelectionMixin(e.anchor,n),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor));let{col:r,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:r,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);break}switch(e.type){case`START`:let t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);let{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(n,r),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`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`ADD_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}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`:let i=Object.keys(this.sheetsData).filter(e=>!this.getters.tryGetSheet(e));for(let e of i)delete this.sheetsData[e];for(let e in this.sheetsData){let t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:b(t)}}this.fallbackToVisibleSheet();let a=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map(e=>this.getters.expandZone(a,e)),this.gridSelection.anchor.zone=this.getters.expandZone(a,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null;break}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,b(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(){let e=new Set;for(let t of this.gridSelection.zones)if(t.top===0&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let n=t.left;n<=t.right;n++)e.add(n);return e}getActiveRows(){let e=new Set,t=this.getters.getActiveSheetId();for(let n of this.gridSelection.zones)if(n.left===0&&n.right===this.getters.getNumberCols(t)-1)for(let t=n.top;t<=n.bottom;t++)e.add(t);return e}getCurrentStyle(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return b(this.gridSelection.zones)}getSelectedZone(){return b(this.gridSelection.anchor.zone)}getSelectecUnboundedZone(){return b(this.isUnbounded?this.getters.getUnboundedZone(this.activeSheet.id,this.gridSelection.anchor.zone):this.gridSelection.anchor.zone)}getSelection(){return b(this.gridSelection)}getSelectedCells(){let e=this.getters.getActiveSheetId(),t=[];for(let n of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,n));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();{let 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(){let e=this.getters.getSelectedZones();return!(e.length!==1||e[0].left!==e[0].right)}getElementsFromSelection(e){if(e===`COL`&&this.getters.getActiveCols().size===0||e===`ROW`&&this.getters.getActiveRows().size===0)return[];let t=this.getters.getSelectedZones(),n=[],r=e===`COL`?`left`:`top`,i=e===`COL`?`right`:`bottom`;for(let e of t){let t=Array.from({length:e[i]-e[r]+1},(t,n)=>e[r]+n);n=n.concat(t)}return[...new Set(n)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:b(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor));else{let{col:e,row:n}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,n)}let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:n,row:r})}setSelectionMixin(e,t){let{anchor:n,zones:r}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=n,this.gridSelection.zones=Xs(r)}selectCell(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.expandZone(n,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:r,cell:{col:e,row:t}},[r])}setActiveSheet(e){this.activeSheet=this.getters.getSheet(e)}activateNextSheet(e){let t=this.getters.getSheetIds(),n=(t.findIndex(e=>e===this.activeSheet.id)+(e===`left`?t.length-1:1))%t.length;this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[n]})}onColumnsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=Ns(n,`left`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=Ns(i,`left`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>Ns(t,`left`,[...e.elements]));this.setSelectionMixin(a,o)}onRowsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=Ns(n,`top`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=Ns(i,`top`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>Ns(t,`top`,[...e.elements]));this.setSelectionMixin(a,o)}onAddElements(e){let t=e.dimension===`COL`?`left`:`top`,n=Ms(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),r=this.gridSelection.zones.map(n=>Ms(n,t,e.base,e.position,e.quantity)),i={cell:{col:n.left,row:n.top},zone:n};this.setSelectionMixin(i,r)}onMoveElements(e){let t=e.elements.length,n=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});let r=e.dimension===`COL`,i=e.elements[0],a=e.elements[t-1],o=e.base<i,s=o&&r?t:0,c=o&&!r?t:0,l=o?e.elements.map(e=>e+t):e.elements,u={};for(let t of l)u[t]=this.getters.getHeaderSize(e.sheetId,e.dimension,t);let d=[{left:r?i+s:0,right:r?a+s:this.getters.getNumberCols(e.sheetId)-1,top:r?0:i+c,bottom:r?this.getters.getNumberRows(e.sheetId)-1:a+c}],f=this.getActiveSheetId(),p=o?e.base:e.base+1,m=[{left:r?p:0,right:r?p+t-1:this.getters.getNumberCols(e.sheetId)-1,top:r?0:p,bottom:r?this.getters.getNumberRows(e.sheetId)-1:p+t-1}],h=af.cellHandlers.getKeys().map(e=>[e,new(af.cellHandlers.get(e))(this.getters,this.dispatch)]),g={};for(let[e,t]of h)g[e]=t.copy(Nl(f,d),!1,`shiftCells`);for(let[e,t]of h)g[e]&&t.paste({zones:m,sheetId:f},g[e],{isCutOperation:!0});let _=m[0],v=_.left,y=_.top;this.setSelectionMixin({zone:_,cell:{col:v,row:y}},[_]);let ee=o?e.base:e.base+1,te={};for(let t of l){let n=u[t];n!==this.getters.getHeaderSize(e.sheetId,e.dimension,ee)&&(te[n]??=[],te[n].push(ee)),ee+=1}for(let t in te)this.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,size:parseInt(t,10),elements:te[t]});this.dispatch(`REMOVE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,elements:l}),this.applyFigureUpdates(n)}getFiguresUpdates(e){let t=[],n={},r=e.elements[0]<e.base?e.base-e.elements.length+1:e.base;for(let t=0;t<e.elements.length;t++)n[e.elements[t]]=r+t;for(let r of this.getters.getFigures(e.sheetId))e.dimension===`COL`&&r.col in n&&t.push({type:`UPDATE_FIGURE`,sheetId:e.sheetId,figureId:r.id,col:n[r.col],row:r.row}),e.dimension===`ROW`&&r.row in n&&t.push({type:`UPDATE_FIGURE`,sheetId:e.sheetId,figureId:r.id,row:n[r.row],col:r.col});return t}applyFigureUpdates(e){for(let t of e)this.dispatch(t.type,{...t})}isMoveElementAllowed(e){let t=e.dimension===`COL`,n=e.elements[0],r=e.elements[e.elements.length-1],i=e.sheetId,a=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(a(i,n-1,n)||a(i,r,r+1)||a(i,e.base-1,e.base))return`WillRemoveExistingMerge`;let o=[e.base,...e.elements],s=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return o.some(e=>e<0||e>=s)?`InvalidHeaderIndex`:!t&&!this.isTableRowMoveAllowed(i,e.elements)?`CannotMoveTableHeader`:`Success`}isTableRowMoveAllowed(e,t){let n=this.getters.getCoreTables(e);if(n.length===0)return!0;let r=new Set(t);return n.every(({range:{zone:e},config:n})=>{let{top:i,bottom:a}=e;if(n.numberOfHeaders===0)return!0;let o=i+n.numberOfHeaders-1;return t.some(e=>e>=i&&e<=o)?S(i,a+1).every(e=>r.has(e)):!0})}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){let e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){let{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);let{col:t,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:n})}}clipSelection(e,t){let n=this.getters.getNumberCols(e)-1,r=this.getters.getNumberRows(e)-1,i=t.zones.map(e=>({left:x(e.left,0,n),right:x(e.right,0,n),top:x(e.top,0,r),bottom:x(e.bottom,0,r)})),a=x(t.anchor.cell.col,0,n),o=x(t.anchor.cell.row,0,r),s={left:x(t.anchor.zone.left,0,n),right:x(t.anchor.zone.right,0,n),top:x(t.anchor.zone.top,0,r),bottom:x(t.anchor.zone.bottom,0,r)};return{zones:i,anchor:{cell:{col:a,row:o},zone:s}}}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getSelectedZones();t.fillStyle=`#f3f7fe`,t.fillStyle=r.length===1&&r[0].left===r[0].right&&r[0].top===r[0].bottom?`#f3f7fe`:`#e9f0ff`,t.strokeStyle=ae,t.lineWidth=1.5*n;for(let e of r){let{x:n,y:r,width:i,height:a}=this.getters.getVisibleRect(e);t.globalCompositeOperation=`multiply`,t.fillRect(n,r,i,a),t.globalCompositeOperation=`source-over`,t.strokeRect(n,r,i,a)}t.globalCompositeOperation=`source-over`;let i=this.getActivePosition();t.strokeStyle=ae,t.lineWidth=3*n;let a;a=this.getters.isInMerge(i)?this.getters.getMerge(i):R(i);let{x:o,y:s,width:c,height:l}=this.getters.getVisibleRect(a);c>0&&l>0&&t.strokeRect(o,s,c,l)}},aq=class{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,n,r,i,a){if(this.getters=e,this.sheetId=t,this.boundaries=n,r.width<0||r.height<0)throw Error(`Viewport size cannot be negative`);this.viewportWidth=r.height&&r.width,this.viewportHeight=r.width&&r.height,this.top=n.top,this.bottom=n.bottom,this.left=n.left,this.right=n.right,this.offsetX=a.x,this.offsetY=a.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(){let 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:n}=this.getters.getColDimensions(this.sheetId,e),{end:r}=this.getters.getRowDimensions(this.sheetId,t),i=n-this.offsetCorrectionX;this.canScrollHorizontally&&(i=Math.max(i,this.viewportWidth));let a=r-this.offsetCorrectionY;return this.canScrollVertically&&(a=Math.max(a,this.viewportHeight),r+46>a&&!this.getters.isReadonly()&&(a+=46)),{width:i,height:a}}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){let t=this.sheetId,n=this.getters.getMainCellPosition({sheetId:t,...e}),{col:r,row:i}=this.getters.getNextVisibleCellPosition(n);Vs(r,this.boundaries.top,this.boundaries)&&this.adjustPositionX(r),Vs(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){let t=this.sheetId,{start:n,end:r}=this.getters.getColDimensions(t,e);this.offsetX+this.viewportWidth+this.offsetCorrectionX<r?this.offsetX=r-this.viewportWidth:this.offsetX+this.offsetCorrectionX>n&&(this.offsetX=n-this.offsetCorrectionX),this.adjustViewportZoneX()}adjustPositionY(e){let t=this.sheetId,{start:n,end:r}=this.getters.getRowDimensions(t,e);this.offsetY+this.viewportHeight+this.offsetCorrectionY<r?this.offsetY=r-this.viewportHeight:this.offsetY+this.offsetCorrectionY>n&&(this.offsetY=n-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){let t=Ls(e,this),n=this.snapCorrection.x,r=this.snapCorrection.y;if(t)return{x:this.getters.getColRowOffset(`COL`,this.left,t.left)+this.offsetCorrectionX-(this.left===t.left?0:n),y:this.getters.getColRowOffset(`ROW`,this.top,t.top)+this.offsetCorrectionY-(this.top===t.top?0:r),width:Math.min(this.getters.getColRowOffset(`COL`,t.left,t.right+1)-(this.left===t.left?n:0),this.viewportWidth),height:Math.min(this.getters.getColRowOffset(`ROW`,t.top,t.bottom+1)-(this.top===t.top?r:0),this.viewportHeight)}}getFullRect(e){let t=Ls(e,this.boundaries),n=this.snapCorrection.x,r=this.snapCorrection.y;if(t){let t=this.getters.getColRowOffset(`COL`,this.left,e.left)+this.offsetCorrectionX,i=this.getters.getColRowOffset(`ROW`,this.top,e.top)+this.offsetCorrectionY,a=this.getters.getColRowOffset(`COL`,e.left,e.right+1),o=this.getters.getColRowOffset(`ROW`,e.top,e.bottom+1);return{x:t-n,y:i-r,width:a,height:o}}}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,n=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;let r=this.sheetId,i=this.getters.getNumberHeaders(r,e),a=n,o=i;for(;a<=o&&a!==i&&o!==-1;){let i=Math.floor((a+o)/2),s=this.getters.getColRowOffset(e,n,i),c=this.getters.getHeaderSize(r,e,i);if(t>=s&&t<s+c)return i;t>=s+c?a=i+1:o=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){let{width:e}=this.getMaxSize();this.viewportWidth+this.offsetX>e&&(this.offsetX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){let{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&&(this.left===-1&&(this.left=this.boundaries.left),this.right===-1&&(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&&(this.top===-1&&(this.top=this.boundaries.top),this.bottom===-1&&(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)))}}},oq=class extends Rp{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.getMaximumSheetOffset`.split(`.`);viewports={};sheetViewWidth=Qe();sheetViewHeight=Qe();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){let t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:n,row:r}=Qs(e.previousAnchor.zone,e.anchor.zone);if(e.mode===`updateAnchor`){let i=e.previousAnchor.zone,a=e.anchor.zone,{top:o,bottom:s,left:c,right:l}=this.getMainInternalViewport(t);i.left===a.left&&i.right===a.right&&(n=c>n||n>l?c:n),i.top===a.top&&i.bottom===a.bottom&&(r=o>r||r>s?o:r)}n=Math.min(n,this.getters.getNumberCols(t)-1),r=Math.min(r,this.getters.getNumberRows(t)-1),this.sheetsWithDirtyViewports.has(t)||this.refreshViewport(this.getters.getActiveSheetId(),{col:n,row:r})}}handle(e){if(yr.has(e.type))for(let 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(let 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`:let t=this.getters.getActiveSheetId(),{top:n,viewportHeight:r,offsetCorrectionY:i}=this.getMainInternalViewport(t),a=this.getters.getRowDimensions(t,n);this.shiftVertically(a.start+r-i);break;case`SHIFT_VIEWPORT_UP`:{let e=this.getters.getActiveSheetId(),{top:t,viewportHeight:n,offsetCorrectionY:r}=this.getMainInternalViewport(e),i=this.getters.getRowDimensions(e,t);this.shiftVertically(i.end-r-n);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`:for(let 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});break}}finalize(){for(let e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){let t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach(e=>{e.adjustPosition(t)})}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){let e=this.getters.getSheetIds();for(let t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getColIndex(e)))}getRowIndex(e){let 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(){let e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getSheetViewVisibleCols(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>S(e.left,e.right+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`COL`,t))}getSheetViewVisibleRows(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>S(e.top,e.bottom+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`ROW`,t))}getVisibleCellPositions(){let e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),n=this.getters.getActiveSheetId(),r=[];for(let i of e)for(let e of t){let t={sheetId:n,col:i,row:e},a=this.getters.getMainCellPosition(t);a.row!==e||a.col!==i||r.push(t)}return r}getMainViewportRect(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e),{width:i,height:a}=t.getMaxSize();return{x:this.getters.getColDimensions(e,n).start,y:this.getters.getRowDimensions(e,r).start,width:i,height:a}}getMaximumSheetOffset(){let e=this.getters.getActiveSheetId(),{width:t,height:n}=this.getMainViewportRect(),r=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-r.viewportWidth),maxOffsetY:Math.max(0,n-r.viewportHeight)}}getColRowOffsetInViewport(e,t,n){if(n<t)return-this.getColRowOffsetInViewport(e,n,t);let r=this.getters.getActiveSheetId(),i=e===`COL`?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),a=i.findIndex(e=>t>=e),o=i.findIndex(e=>n<=e);o=o===-1?i.length:o;let s=i.slice(a,o),c=0;for(let t of s)c+=this.getters.getHeaderSize(r,e,t);return c}isVisibleInViewport({sheetId:e,col:t,row:n}){return this.getSubViewports(e).some(e=>e.isVisible(t,n))}getEdgeScrollCol(e,t,n){let r=!1,i=0,a=0,{xSplit:o}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:s}=this.getSheetViewDimension(),{x:c}=this.getMainViewportCoordinates(),l=this.getActiveSheetScrollInfo().scrollX;return e>s?(r=!0,a=vc(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=vc(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=vc(e),i=`reset`),{canEdgeScroll:r,direction:i,delay:a}}getEdgeScrollRow(e,t,n){let r=!1,i=0,a=0,{ySplit:o}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:s}=this.getSheetViewDimension(),{y:c}=this.getMainViewportCoordinates(),l=this.getActiveSheetScrollInfo().scrollY;return e>s?(r=!0,a=vc(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=vc(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=vc(e),i=`reset`),{canEdgeScroll:r,direction:i,delay:a}}getVisibleRect(e){let t=this.getVisibleRectWithoutHeaders(e);return{...t,x:t.x+this.gridOffsetX,y:t.y+this.gridOffsetY}}getVisibleRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getVisibleRect(e))}getRect(e){let t=this.getters.getActiveSheetId(),n=this.mapViewportsToRect(t,t=>t.getFullRect(e));return{...n,x:n.x+this.gridOffsetX,y:n.y+this.gridOffsetY}}getRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getFullRect(e))}getMainViewportCoordinates(){let e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,n).start}}getColDimensionsInViewport(e,t){let{top:n}=this.getMainInternalViewport(e),r={left:t,right:t,top:n,bottom:n},{x:i,width:a}=this.getVisibleRect(r),o=i-this.gridOffsetX;return{start:o,size:a,end:o+a}}getRowDimensionsInViewport(e,t){let{left:n}=this.getMainInternalViewport(e),r={left:0,right:n,top:t,bottom:t},{y:i,height:a}=this.getVisibleRect(r),o=i-this.gridOffsetY;return{start:o,size:a,end:o+a}}getAllActiveViewportsZonesAndRect(){let 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(C)}checkPositiveDimension(e){return e.width<0||e.height<0?`InvalidViewportSize`:`Success`}checkValuesAreDifferent(e){let{height:t,width:n}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===n&&e.height===t?`ValuesNotChanged`:`Success`}checkScrollingDirection({offsetX:e,offsetY:t}){let n=this.getMainInternalViewport(this.getters.getActiveSheetId());return!n.canScrollHorizontally&&e>0||!n.canScrollVertically&&t>0?`InvalidScrollingDirection`:`Success`}checkIfViewportsWillChange({offsetX:e,offsetY:t}){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();return this.getSubViewports(n).some(n=>n.willNewOffsetScrollViewport(x(e,0,r),x(t,0,i)))?`Success`:`ViewportScrollLimitsReached`}getMainViewport(e){let 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(){let e={};for(let t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,n=0,r=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=n,this.gridOffsetY=r,this.recomputeViewports()}recomputeViewports(){for(let e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();this.getSubViewports(n).forEach(n=>n.setViewportOffset(x(e,0,r),x(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;let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),a=Math.min(this.getters.getColRowOffset(`COL`,0,t,e),this.sheetViewWidth),o=Math.min(this.getters.getColRowOffset(`ROW`,0,n,e),this.sheetViewHeight),s=Math.max(this.sheetViewWidth-a,0),c=Math.max(this.sheetViewHeight-o,0),{xRatio:l,yRatio:u}=this.getFrozenSheetViewRatio(e),d=l<1,f=u<1,p=this.getViewportOffset(e),m={topLeft:n&&t&&new aq(this.getters,e,{left:0,right:t-1,top:0,bottom:n-1},{width:a,height:o},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:n&&new aq(this.getters,e,{left:t,right:r-1,top:0,bottom:n-1},{width:s,height:o},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?p.x:0,y:0})||void 0,bottomLeft:t&&new aq(this.getters,e,{left:0,right:t-1,top:n,bottom:i-1},{width:a,height:c},{canScrollHorizontally:!1,canScrollVertically:f},{x:0,y:f?p.y:0})||void 0,bottomRight:new aq(this.getters,e,{left:t,right:r-1,top:n,bottom:i-1},{width:s,height:c},{canScrollHorizontally:d,canScrollVertically:f},{x:d?p.x:0,y:f?p.y:0})};this.viewports[e]=m}refreshViewport(e,t){this.getSubViewports(e).forEach(e=>{e.adjustViewportZone(),e.adjustPosition(t)})}shiftVertically(e){let t=this.getters.getActiveSheetId(),{top:n}=this.getMainInternalViewport(t),{scrollX:r}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(r,e);let{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){let e=this.getMainInternalViewport(t).top-n;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getColIndexLeftOfMainViewport(e){if(e>=0)return-1;let t=this.getters.getActiveSheetId(),n=this.getActiveMainViewport().left,r=-this.getActiveSheetScrollInfo().scrollX-this.getters.getColRowOffset(`COL`,n,0);for(;e<r;n--)r-=this.getters.getColSize(t,n-1);return Math.max(n,0)}getRowIndexTopOfMainViewport(e){if(e>=0)return-1;let t=this.getters.getActiveSheetId(),n=this.getActiveMainViewport().top,r=-this.getActiveSheetScrollInfo().scrollY-this.getters.getColRowOffset(`ROW`,n,0);for(;e<r;n--)r-=this.getters.getRowSize(t,n-1);return Math.max(n,0)}getVisibleFigures(){let e=this.getters.getActiveSheetId(),t=[],n=this.getters.getFigures(e),{scrollX:r,scrollY:i}=this.getters.getActiveSheetScrollInfo(),{x:a,y:o}=this.getMainViewportCoordinates(),{width:s,height:c}=this.getters.getSheetViewDimensionWithHeaders();for(let l of n){let n=this.getFigureUI(e,l),{x:u,y:d}=n;u>=a&&(u+l.width<r+a||u>s+r+a)||d>=o&&(d+l.height<i+o||d>c+i+o)||t.push(n)}return t}getFigureUI(e,t){let n=t.offset.x+this.getters.getColDimensions(e,t.col).start,r=t.offset.y+this.getters.getRowDimensions(e,t.row).start;return{...t,x:n,y:r}}getPositionAnchorOffset(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),r=e.x-t,i=e.y-n,a=r>=0?this.getColIndex(r):this.getColIndexLeftOfMainViewport(r),o=i>=0?this.getRowIndex(i):this.getRowIndexTopOfMainViewport(i),{x:s,y:c}=this.getRect(R({col:a,row:o}));return{col:a,row:o,offset:{x:Math.max(r-s+this.gridOffsetX,0),y:Math.max(i-c+this.gridOffsetY,0)}}}isPixelPositionVisible(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),{x:r,y:i}=this.getters.getMainViewportCoordinates(),{width:a,height:o}=this.getters.getSheetViewDimension();return!(e.x>=r&&(e.x<r+t||e.x>a+t+r)||e.y>=i&&(e.y<i+n||e.y>o+n+i))}getFrozenSheetViewRatio(e){let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,n).start,a=this.sheetViewWidth+this.gridOffsetX,o=this.sheetViewHeight+this.gridOffsetY;return{xRatio:r/a,yRatio:i/o}}mapViewportsToRect(e,t){let n=1/0,r=1/0,i=0,a=0,o=!1;for(let s of this.getSubViewports(e)){let e=t(s);e&&(o=!0,n=Math.min(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.x+e.width),a=Math.max(a,e.y+e.height))}return o?{x:n,y:r,width:i-n,height:a-r}:{x:0,y:0,width:0,height:0}}},sq=class extends Rp{static getters=[`getSelectedCarouselItem`,`getChartFromFigureId`,`getChartIdFromFigureId`];uuidGenerator=new jl;carouselStates={};allowDispatch(e){switch(e.type){case`ADD_FIGURE_CHART_TO_CAROUSEL`:return!this.getters.doesCarouselExist(e.carouselFigureId)||this.getters.getFigure(e.sheetId,e.chartFigureId)?.tag!==`chart`?`InvalidFigureId`:`Success`;case`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=>w(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(let e in this.carouselStates)this.fixWrongCarouselState(e);break}}popOutChartFromCarousel(e,t,n){let r=this.getters.getCarousel(e);if(!r)return;let i=this.getters.getFigure(n,e),a=this.getters.getChartDefinition(t);if(!a||!i)return;let o=this.getters.getFigureUI(n,i),s=this.getters.getPositionAnchorOffset({x:o.x+50,y:o.y+50}),c=this.uuidGenerator.smallUuid();this.dispatch(`CREATE_CHART`,{...s,chartId:this.uuidGenerator.smallUuid(),figureId:c,sheetId:n,size:{width:i.width,height:i.height},definition:{...a}});let l=r.items.filter(e=>e.type!==`chart`||e.chartId!==t);this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:{...r,items:l}}),this.dispatch(`SELECT_FIGURE`,{figureId:c})}getSelectedCarouselItem(e){let t=this.getters.getCarousel(e);if(t.items.length)return this.carouselStates[e]?t.items.find(t=>this.getCarouselItemId(t)===this.carouselStates[e]):t.items[0]}getChartFromFigureId(e){if(!this.getters.getFigureSheetId(e))return;let t=this.getChartIdFromFigureId(e);return t?this.getters.getChart(t):void 0}getChartIdFromFigureId(e){let t=this.getters.getFigureSheetId(e);if(!t)return;let n=this.getters.getFigure(t,e);if(!(!n||n.tag!==`chart`&&n.tag!==`carousel`)){if(n.tag===`carousel`){let t=this.getSelectedCarouselItem(e);return t?.type===`chart`?t.chartId:void 0}return this.getters.getChartIds(t).find(t=>this.getters.getFigureIdFromChartId(t)===e)}}fixWrongCarouselState(e){if(!this.getters.doesCarouselExist(e)){delete this.carouselStates[e];return}let t=this.getters.getCarousel(e);t.items.length===0?delete this.carouselStates[e]:this.carouselStates[e]&&t.items.some(t=>this.getCarouselItemId(t)===this.carouselStates[e])||(this.carouselStates[e]=this.getCarouselItemId(t.items[0]))}addNewChartToCarousel(e,t){let n=this.getters.getCarousel(e),r=this.uuidGenerator.smallUuid();this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:t,definition:WO});let i={...n,items:[...n.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:t,figureId:e,definition:i})}addFigureChartToCarousel(e,t,n){let r=this.getChartIdFromFigureId(t);if(!r)return;let i=this.getters.getCarousel(e),a={...i,items:[...i.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:a}),this.dispatch(`UPDATE_CHART`,{sheetId:n,chartId:r,figureId:e,definition:this.getters.getChartDefinition(r)}),this.dispatch(`DELETE_FIGURE`,{sheetId:n,figureId:t})}getCarouselItemId(e){return e.type===`chart`?e.chartId:`carouselDataView`}},cq=class extends Rp{static getters=[`getColDimensions`,`getRowDimensions`,`getColRowOffset`];headerPositions={};isDirty=!0;handle(e){switch(yr.has(e.type)&&(this.headerPositions={},this.isDirty=!0),e.type){case`START`:for(let e of this.getters.getSheetIds())this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e);break;case`UPDATE_CELL`:this.headerPositions={},this.isDirty=!0;break;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]=b(this.headerPositions[e.sheetId]);break}}finalize(){for(let e of this.getters.getSheetIds())(this.isDirty||!this.headerPositions[e])&&(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){let n=this.headerPositions[e].COL[t],r=this.getters.getColSize(e,t);return{start:n,size:r,end:n+(this.getters.isColHidden(e,t)?0:r)}}getRowDimensions(e,t){let n=this.headerPositions[e].ROW[t],r=this.getters.getRowSize(e,t);return{start:n,size:r,end:n+(this.getters.isRowHidden(e,t)?0:r)}}getColRowOffset(e,t,n,r=this.getters.getActiveSheetId()){let i=this.headerPositions[r][e][t];return this.headerPositions[r][e][n]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,`COL`),ROW:this.computePositions(e,`ROW`)}}computePositions(e,t){let n={},r=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)n[i]=r,!this.getters.isHeaderHidden(e,t,i)&&(r+=this.getters.getHeaderSize(e,t,i));return n}};let lq=new g().add(`settings`,vW).add(`sheet`,pW).add(`header grouping`,gW).add(`header visibility`,sW).add(`tables`,mW).add(`dataValidation`,iW).add(`cell`,QU).add(`merge`,lW).add(`headerSize`,oW).add(`borders`,ZU).add(`conditional formatting`,rW).add(`figures`,aW).add(`chart`,tW).add(`carousel`,hW).add(`image`,cW).add(`pivot_core`,_W).add(`spreadsheet_pivot_core`,yW).add(`tableStyle`,bW),uq=new g().add(`ui_sheet`,gK).add(`ui_options`,hK).add(`autofill`,CG).add(`sort`,mK).add(`automatic_sum`,wG).add(`format`,uK).add(`insert_pivot`,pK).add(`pivot_presence`,ZK).add(`split_to_columns`,QK).add(`subtotal_evaluation`,zp).add(`collaborative`,cK).add(`history`,YK).add(`data_cleanup`,lK).add(`table_autofill`,$K).add(`table_ui_resize`,eq).add(`datavalidation_insert`,SK).add(`checkbox_toggle`,xK).add(`dynamic_translate`,CK).add(`geo_features`,dK),dq=new g().add(`selection`,iq).add(`evaluation_filter`,rq).add(`header_visibility_ui`,fK).add(`cell_computed_style`,bK).add(`table_computed_style`,_K).add(`header_positions`,cq).add(`viewport`,oq).add(`clipboard`,tq).add(`carousel_ui`,sq),fq=new g().add(`evaluation`,GW).add(`evaluation_chart`,XW).add(`evaluation_cf`,ZW).add(`row_size`,iG).add(`data_validation_ui`,$W).add(`dynamic_tables`,rG).add(`custom_colors`,YW).add(`pivot_ui`,lG).add(`cell_icon`,nG);up.add(`dataValidation`,{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(on(t)||!this.composer.currentEditedCell)return[];let n=this.composer.currentEditedCell,r=this.getters.getValidationRuleForCell(n);if(!r||r.criterion.type!==`isValueInList`&&r.criterion.type!==`isValueInRange`)return[];let i=this.composer.currentEditedCell.sheetId,a=r.criterion.type===`isValueInRange`?this.getters.getDataValidationRangeValues(i,r.criterion):r.criterion.values.map(e=>({label:e,value:e}));if(r.criterion.displayStyle!==`chip`)return a.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));let o=r.criterion.colors;return a.map(e=>{let t=o?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:t?Mn(t):void 0,backgroundColor:t||`#E7E9ED`,classes:[`badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start`]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t),this.composer.stopEdition()}}),up.add(`functions`,{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if(e.type!==`SYMBOL`)return[];let t=e.value;return on(this.composer.currentContent)?Object.entries(zS.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:n}])=>({text:e,description:n,htmlContent:$H(t,e,ge,`o-semi-bold`)})).sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text)):[]},selectProposal(e,t){let n=e.end,r=e.end;[`SYMBOL`,`FUNCTION`].includes(e.type)&&(n=e.start);let i=this.composer.currentTokens;t+=`(`;let a=i.map(e=>e.start).indexOf(e.start);a+1<i.length&&i[a+1]?.type===`LEFT_PAREN`&&r++,this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}}),up.add(`pivot_ids`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||![`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`].includes(t.parent.toUpperCase())||t.argPosition!==0)return;let n=this.getters.getPivotIds();if(!n.includes(e.value))return n.map(e=>{let t=this.getters.getPivotCoreDefinition(e),n=`${this.getters.getPivotFormulaId(e)}`;return{text:n,description:t.name,htmlContent:[{value:n,color:ot.NUMBER}],fuzzySearchKey:n+t.name,alwaysExpanded:!0}}).filter(C)},selectProposal:qS}),up.add(`pivot_measures`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(t?.parent.toUpperCase()!==`PIVOT.VALUE`||t.argPosition!==1)return[];let n=mU(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return[];let i=this.getters.getPivot(r);return i.init(),i.isValid()?i.definition.measures.map(e=>{if(e.fieldName===`__count`){let e=`"__count"`;return{text:e,description:E(`Count`),htmlContent:[{value:e,color:ot.STRING}],fuzzySearchKey:E(`Count`)+e}}return dU(e)}).filter(C):[]},selectProposal:qS}),up.add(`pivot_group_fields`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!pq(e)&&!mq(e))return;let n=mU(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);i.init();let a=i.getFields(),{columns:o,rows:s}=i.definition,c=t.args;t?.parent.toUpperCase()===`PIVOT.VALUE`?(c=c.filter((e,t)=>t%2==0),c=c.slice(1,t.argPosition)):c=c.filter((e,t)=>t%2==1);let l=c.map(e=>e?.value).filter(C),u=o.map(e=>e.nameWithGranularity),d=s.map(e=>e.nameWithGranularity),f=[],p=[`ARG_SEPARATOR`,`SPACE`].includes(e.type)?l.at(-1):l.at(-2),m=KU.get(i.type);if(m&&p?.startsWith(`#`)&&(p=p.slice(1)),p===void 0&&(f.push(u[0]),f.push(d[0])),d.includes(p)){let e=d[d.indexOf(p)+1];f.push(e),f.push(u[0])}if(u.includes(p)){let e=u[u.indexOf(p)+1];f.push(e)}let h=f.filter(C);return h.map(e=>{let[t,n]=e.split(`:`),r=a[t];return r?uU(r,n):void 0}).concat(h.map(e=>{if(!m)return;let t=a[e.split(`:`)[0]];if(!t)return;let n=`"#${e}"`;return{text:n,description:E(`%s (positional)`,t.string)+(t.help?` (${t.help})`:``),htmlContent:[{value:n,color:ot.STRING}],fuzzySearchKey:t.string+n}})).filter(C)},selectProposal:qS});function pq(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==0}function mq(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==1}up.add(`pivot_group_values`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!e||!hq(e)&&!gq(e))return;let n=mU(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);if(!i.isValid())return;let a=t.argPosition,o=e.functionContext?.args[a-1]?.value;if(!o)return;let s;try{s=i.definition.getDimension(o)}catch{return}return s.granularity===`month_number`?Object.values(go).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:ot.NUMBER}]})):s.granularity===`quarter_number`?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:E(`Quarter %s`,e),htmlContent:[{value:`${e}`,color:ot.NUMBER}]})):s.granularity===`day_of_month`?S(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:ot.NUMBER}]})):s.granularity===`iso_week_number`?S(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:ot.NUMBER}]})):s.granularity===`day_of_week`?S(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:ot.NUMBER}]})):s.granularity===`hour_number`?S(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:ot.NUMBER}]})):s.granularity===`minute_number`?S(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:ot.NUMBER}]})):s.granularity===`second_number`?S(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:ot.NUMBER}]})):i.getPossibleFieldValues(s).map(({value:e,label:t})=>{let n=typeof e==`string`,r=n?`"${e}"`:e.toString(),i=n?ot.STRING:ot.NUMBER,a=t===e?``:t;return{text:r,description:a,htmlContent:[{value:r,color:i}],fuzzySearchKey:r+a}})},selectProposal:qS});function hq(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==1}function gq(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==0}up.add(`sheet_names`,{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return e.type===`SYMBOL`||e.type===`UNKNOWN`&&e.value.startsWith(`'`)?this.getters.getSheetIds().map(e=>{let t=mt(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith(`'`)?t:`'`+t}}):[]},selectProposal(e,t){let n=e.start,r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t+`!`)}});let _q=new g;_q.add(`link`,{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,n)=>Yr(t.model.getters.getEvaluatedCell(e).link,t,n),title:(e,t)=>{let n=t.getEvaluatedCell(e).link;return n?n.isExternal?E(`Go to url: %(url)s`,{url:n.url}):E(`Go to %(label)s`,{label:n.label}):``},sequence:5}),_q.add(`dashboard_pivot_sorting`,{condition:(e,t)=>{if(!t.isDashboard())return!1;let n=t.getPivotCellFromPosition(e);return AR(t,e)&&n.type===`MEASURE_HEADER`},execute:(e,t)=>{jR(t,e,yq(t.model.getters,e))},component:qU,componentProps:(e,t)=>({position:e,sortDirection:t.getPivotCellSortDirection(e)}),sequence:2});let vq={none:`asc`,asc:`desc`,desc:`none`};function yq(e,t){return vq[e.getPivotCellSortDirection(t)??`none`]}let bq=new g().add(`ADD_COLUMNS_ROWS`,Cq).add(`REMOVE_COLUMNS_ROWS`,Oq).add(`ADD_MERGE`,wq).add(`REMOVE_MERGE`,Tq).add(`CREATE_SHEET`,Eq).add(`DELETE_SHEET`,kq).add(`DUPLICATE_SHEET`,Dq).add(`CREATE_FIGURE`,Aq).add(`CREATE_CHART`,jq).add(`HIDE_COLUMNS_ROWS`,Mq).add(`UNHIDE_COLUMNS_ROWS`,Nq).add(`CREATE_TABLE_STYLE`,Pq).add(`ADD_PIVOT`,Sq).add(`RENAME_SHEET`,Fq);for(let e of Er.values())bq.contains(e)||bq.add(e,xq);function xq(e){return[e]}function Sq(e){return[{type:`REMOVE_PIVOT`,pivotId:e.pivotId}]}function Cq(e){let t=[],n=e.base;e.position===`after`&&n++;for(let r=0;r<e.quantity;r++)t.push(r+n);return[{type:`REMOVE_COLUMNS_ROWS`,dimension:e.dimension,elements:t,sheetId:e.sheetId,sheetName:e.sheetName}]}function wq(e){return[{type:`REMOVE_MERGE`,sheetId:e.sheetId,target:e.target}]}function Tq(e){return[{type:`ADD_MERGE`,sheetId:e.sheetId,target:e.target}]}function Eq(e){return[{type:`DELETE_SHEET`,sheetId:e.sheetId,sheetName:e.name}]}function Dq(e){return[{type:`DELETE_SHEET`,sheetId:e.sheetIdTo,sheetName:``}]}function Oq(e){let t=[],n=[...e.elements].sort((e,t)=>e-t);for(let r of gt(n)){let n=r[0]===0?0:r[0]-1,i=r[0]===0?`before`:`after`;t.push({type:`ADD_COLUMNS_ROWS`,dimension:e.dimension,quantity:r.length,base:n,sheetId:e.sheetId,sheetName:e.sheetName,position:i})}return t}function kq(e){return[{type:`CREATE_SHEET`,sheetId:e.sheetId,position:1,name:e.sheetName}]}function Aq(e){return[{type:`DELETE_FIGURE`,figureId:e.figureId,sheetId:e.sheetId}]}function jq(e){return[{type:`DELETE_FIGURE`,figureId:e.figureId,sheetId:e.sheetId}]}function Mq(e){return[{type:`UNHIDE_COLUMNS_ROWS`,sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}function Nq(e){return[{type:`HIDE_COLUMNS_ROWS`,sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}function Pq(e){return[{type:`REMOVE_TABLE_STYLE`,tableStyleId:e.tableStyleId}]}function Fq(e){return[{type:`RENAME_SHEET`,sheetId:e.sheetId,oldName:e.newName,newName:e.oldName}]}let Iq=new g;Iq.add(`format_number_automatic`,{...QR,id:`format_number_automatic`,sequence:10}).add(`format_number_plain_text`,{...$R,id:`format_number_plain_text`,sequence:15,separator:!0}).add(`format_number_number`,{...ez,id:`format_number_number`,sequence:20}).add(`format_number_percent`,{...nz,id:`format_number_percent`,sequence:30,separator:!0}).add(`format_number_currency`,{...rz,id:`format_number_currency`,sequence:40}).add(`format_number_accounting`,{...az,id:`format_number_accounting`,sequence:45}).add(`format_number_currency_rounded`,{...iz,id:`format_number_currency_rounded`,sequence:50}).add(`format_custom_currency`,{...sz,id:`format_custom_currency`,sequence:60,separator:!0}).add(`format_number_date`,{...cz,id:`format_number_date`,sequence:70}).add(`format_number_time`,{...lz,id:`format_number_time`,sequence:80}).add(`format_number_date_time`,{...uz,id:`format_number_date_time`,sequence:90}).add(`format_number_duration`,{...dz,id:`format_number_duration`,sequence:100,separator:!0}).add(`more_formats`,{...mz,id:`more_formats`,sequence:120});function Lq(e){let t=new Set(Iq.getAll().map(t=>typeof t.format==`function`?t.format(e):t.format)),n=new Map;for(let r of e.model.getters.getSheetIds()){let i=e.model.getters.getEvaluatedCells(r);for(let e in i){let r=i[e];if(r.format&&!n.has(r.format)&&!t.has(r.format)){let e=Rq(r.format);(e===`date`||e===`currency`)&&n.set(r.format,ZR({descriptionValue:e===`currency`?1e3:oz,format:r.format,name:r.format}))}}}return[...n.values()]}let Rq=Kt(e=>jo(e)?`date`:e.includes(`[$`)?`currency`:`number`),zq={name:E(`More formats`),icon:`o-spreadsheet-Icon.NUMBER_FORMATS`,children:[e=>{let t=Lq(e).map(e=>({...e,sequence:110}));return t.length>0&&(t[t.length-1].separator=!0),f([...Iq.getAll(),...t])}]};function Bq(e){let t=new IA;return t.add(`delete`,{...kA,sequence:10}).add(`hide_sheet`,{...FA,sequence:20}).add(`duplicate`,{...AA,sequence:30,separator:!0}).add(`rename`,{...jA(e),sequence:40}).add(`change_color`,{...MA(e),sequence:50,separator:!0}).add(`move_right`,{...NA,sequence:60}).add(`move_left`,{...PA,sequence:70}),t}let Vq=new IA;Vq.add(`file`,{name:E(`File`),sequence:10,isReadonlyAllowed:!0}).addChild(`settings`,[`file`],{name:E(`Settings`),sequence:200,execute:e=>e.openSidePanel(`Settings`),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.COG`}).add(`edit`,{name:E(`Edit`),sequence:20,isReadonlyAllowed:!0}).addChild(`undo`,[`edit`],{...DI,sequence:10}).addChild(`redo`,[`edit`],{...OI,sequence:20,separator:!0}).addChild(`copy`,[`edit`],{...kI,sequence:30}).addChild(`cut`,[`edit`],{...AI,sequence:40}).addChild(`paste`,[`edit`],{...jI,sequence:50}).addChild(`paste_special`,[`edit`],{...MI,sequence:60,separator:!0}).addChild(`paste_special_value`,[`edit`,`paste_special`],{...NI,sequence:10}).addChild(`paste_special_format`,[`edit`,`paste_special`],{...PI,sequence:20}).addChild(`edit_table`,[`edit`],{...qI,isVisible:DF,sequence:60}).addChild(`find_and_replace`,[`edit`],{...FI,sequence:65,separator:!0}).addChild(`delete`,[`edit`],{name:E(`Delete`),icon:`o-spreadsheet-Icon.TRASH`,sequence:70}).addChild(`edit_delete_cell_values`,[`edit`,`delete`],{...II,sequence:10}).addChild(`edit_delete_row`,[`edit`,`delete`],{...LI,sequence:20}).addChild(`edit_delete_column`,[`edit`,`delete`],{...BI,sequence:30}).addChild(`edit_delete_cell_shift_up`,[`edit`,`delete`],{...WI,sequence:40}).addChild(`edit_delete_cell_shift_left`,[`edit`,`delete`],{...GI,sequence:50}).addChild(`edit_unhide_columns`,[`edit`],{...UF,sequence:80}).addChild(`edit_unhide_rows`,[`edit`],{...KF,sequence:80}).add(`view`,{name:E(`View`),sequence:30,isReadonlyAllowed:!0}).addChild(`unfreeze_panes`,[`view`],{...qF,sequence:4}).addChild(`freeze_panes`,[`view`],{...JF,sequence:5}).addChild(`unfreeze_rows`,[`view`,`freeze_panes`],{...YF,sequence:5}).addChild(`freeze_first_row`,[`view`,`freeze_panes`],{...XF,sequence:10}).addChild(`freeze_second_row`,[`view`,`freeze_panes`],{...ZF,sequence:15}).addChild(`freeze_current_row`,[`view`,`freeze_panes`],{...QF,sequence:20,separator:!0}).addChild(`unfreeze_columns`,[`view`,`freeze_panes`],{...$F,sequence:25}).addChild(`freeze_first_col`,[`view`,`freeze_panes`],{...eI,sequence:30}).addChild(`freeze_second_col`,[`view`,`freeze_panes`],{...tI,sequence:35}).addChild(`freeze_current_col`,[`view`,`freeze_panes`],{...nI,sequence:40}).addChild(`group_headers`,[`view`],{name:E(`Group`),sequence:15,separator:!0,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,isVisible:NF}).addChild(`group_columns`,[`view`,`group_headers`],{...oI,sequence:5}).addChild(`ungroup_columns`,[`view`,`group_headers`],{...cI,isVisible:e=>fI(e,`COL`),sequence:10}).addChild(`group_rows`,[`view`,`group_headers`],{...sI,sequence:15}).addChild(`ungroup_rows`,[`view`,`group_headers`],{...lI,isVisible:e=>fI(e,`ROW`),sequence:20}).addChild(`show`,[`view`],{name:E(`Show`),sequence:1,icon:`o-spreadsheet-Icon.SHOW`}).addChild(`view_gridlines`,[`view`,`show`],{...rI,sequence:5}).addChild(`view_formulas`,[`view`,`show`],{...aI,sequence:10}).addChild(`view_irregularity_map`,[`view`],{...iI,sequence:40,separator:!0}).add(`insert`,{name:E(`Insert`),sequence:40,isReadonlyAllowed:!0}).addChild(`insert_row`,[`insert`],{...QI,sequence:10}).addChild(`insert_row_before`,[`insert`,`insert_row`],{...eL,sequence:10}).addChild(`insert_row_after`,[`insert`,`insert_row`],{...rL,sequence:20}).addChild(`insert_column`,[`insert`],{...iL,sequence:20}).addChild(`insert_column_before`,[`insert`,`insert_column`],{...oL,sequence:10}).addChild(`insert_column_after`,[`insert`,`insert_column`],{...lL,sequence:20}).addChild(`insert_cell`,[`insert`],{...uL,sequence:30}).addChild(`insert_cell_down`,[`insert`,`insert_cell`],{...dL,name:E(`Shift down`),sequence:10}).addChild(`insert_cell_right`,[`insert`,`insert_cell`],{...fL,name:E(`Shift right`),sequence:20}).addChild(`insert_sheet`,[`insert`],{...AL,sequence:40,separator:!0}).addChild(`insert_chart`,[`insert`],{...pL,sequence:50}).addChild(`insert_carousel`,[`insert`],{...mL,sequence:51}).addChild(`insert_pivot`,[`insert`],{...hL,sequence:52}).addChild(`insert_image`,[`insert`],{...gL,sequence:55}).addChild(`insert_table`,[`insert`],{..._L,sequence:57}).addChild(`insert_function`,[`insert`],{...vL,sequence:60}).addChild(`insert_function_sum`,[`insert`,`insert_function`],{...yL,sequence:0}).addChild(`insert_function_average`,[`insert`,`insert_function`],{...bL,sequence:10}).addChild(`insert_function_count`,[`insert`,`insert_function`],{...xL,sequence:20}).addChild(`insert_function_max`,[`insert`,`insert_function`],{...SL,sequence:30}).addChild(`insert_function_min`,[`insert`,`insert_function`],{...CL,sequence:40,separator:!0}).addChild(`categorie_function_all`,[`insert`,`insert_function`],{...wL,sequence:50}).addChild(`categories_function_list`,[`insert`,`insert_function`],EL).addChild(`insert_link`,[`insert`],{...DL,separator:!0,sequence:70}).addChild(`insert_checkbox`,[`insert`],{...OL,sequence:80}).addChild(`insert_dropdown`,[`insert`],{...kL,separator:!0,sequence:90}).add(`format`,{name:E(`Format`),sequence:50,isReadonlyAllowed:!0}).addChild(`format_number`,[`format`],{...zq,name:E(`Number`),sequence:10,separator:!0}).addChild(`format_bold`,[`format`],{...Ez,sequence:20}).addChild(`format_italic`,[`format`],{...Dz,sequence:30}).addChild(`format_underline`,[`format`],{...Oz,sequence:40}).addChild(`format_strikethrough`,[`format`],{...kz,sequence:50,separator:!0}).addChild(`format_font_size`,[`format`],{...Az,sequence:60,separator:!0}).addChild(`format_alignment`,[`format`],{...jz,sequence:70}).addChild(`format_alignment_left`,[`format`,`format_alignment`],{...Nz,sequence:10}).addChild(`format_alignment_center`,[`format`,`format_alignment`],{...Pz,sequence:20}).addChild(`format_alignment_right`,[`format`,`format_alignment`],{...Fz,sequence:30,separator:!0}).addChild(`format_alignment_top`,[`format`,`format_alignment`],{...Lz,sequence:40}).addChild(`format_alignment_middle`,[`format`,`format_alignment`],{...Rz,sequence:50}).addChild(`format_alignment_bottom`,[`format`,`format_alignment`],{...zz,sequence:60,separator:!0}).addChild(`format_wrapping`,[`format`],{...Bz,sequence:80,separator:!0}).addChild(`format_wrapping_overflow`,[`format`,`format_wrapping`],{...Hz,sequence:10}).addChild(`format_wrapping_wrap`,[`format`,`format_wrapping`],{...Uz,sequence:20}).addChild(`format_wrapping_clip`,[`format`,`format_wrapping`],{...Wz,sequence:30}).addChild(`format_cf`,[`format`],{...Gz,sequence:90,separator:!0}).addChild(`format_clearFormat`,[`format`],{...Kz,sequence:100,separator:!0}).add(`data`,{name:E(`Data`),sequence:60,isReadonlyAllowed:!0}).addChild(`sort_range`,[`data`],{...BR,sequence:10,separator:!0}).addChild(`sort_ascending`,[`data`,`sort_range`],{...VR,sequence:10}).addChild(`sort_descending`,[`data`,`sort_range`],{...GR,sequence:20}).addChild(`data_cleanup`,[`data`],{...HR,sequence:15}).addChild(`remove_duplicates`,[`data`,`data_cleanup`],{...UR,sequence:10}).addChild(`trim_whitespace`,[`data`,`data_cleanup`],{...WR,sequence:20}).addChild(`split_to_columns`,[`data`],{...JR,sequence:20}).addChild(`data_validation`,[`data`],{name:E(`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`],{...KR,sequence:40,separator:!0}).addChild(`pivot_data_sources`,[`data`],e=>{let t=e.model.getters.getPivotIds().length;return e.model.getters.getPivotIds().map((n,r)=>{let i={get highlights(){return YH(e.model.getters,n)}};return{id:`item_pivot_${e.model.getters.getPivotFormulaId(n)}`,name:e.model.getters.getPivotDisplayName(n),sequence:50+r/t,isReadonlyAllowed:!0,execute:e=>e.openSidePanel(`PivotSidePanel`,{pivotId:n}),isEnabled:e=>!e.isSmall,onStartHover:e=>e.getStore(Kk).register(i),onStopHover:e=>e.getStore(Kk).unRegister(i),icon:`o-spreadsheet-Icon.PIVOT`,separator:r===e.model.getters.getPivotIds().length-1,secondaryIcon:e=>e.model.getters.isPivotUnused(n)?`o-spreadsheet-Icon.UNUSED_PIVOT_WARNING`:void 0}})}).addChild(`reinsert_dynamic_pivot`,[`data`],YR).addChild(`reinsert_static_pivot`,[`data`],XR);let Hq=new class extends g{mapping={};uuidGenerator=new jl;replace(e,t){let n={...t,id:this.uuidGenerator.uuidv4()};return super.replace(e,n)}getAllOrdered(){return this.getAll().sort((e,t)=>e.sequence-t.sequence)}};var Uq=class{listeners=[];async sendMessage(e){for(let{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)}},Wq=class{fileStore;constructor(e){this.fileStore=e}async requestImage(){let e=await this.userImageUpload(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}async uploadFile(e){let t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}userImageUpload(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.setAttribute(`type`,`file`),n.setAttribute(`accept`,`image/*`),n.addEventListener(`change`,async()=>{n.files===null||n.files.length!==1?t():e(n.files[0])}),n.click()})}getImageOriginalSize(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{t({width:r.width,height:r.height})}),r.addEventListener(`error`,n),r.src=e})}};let Gq=[{transform:`scale(0)`},{transform:`scale(0.8)`,offset:.33},{opacity:`0`,transform:`scale(1)`,offset:1}];B`
1936
1936
  .o-ripple {
1937
1937
  z-index: 1;
1938
1938
  }
1939
- `;var Gq=class 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=(0,t.useRef)(`ripple`);setup(){let e;(0,t.onMounted)(()=>{let t=this.rippleRef.el;!t||!t.animate||(e=t.animate(Wq,{duration:this.props.duration,easing:`ease-out`}),e.addEventListener(`finish`,this.props.onAnimationEnd))}),(0,t.onWillUnmount)(()=>{e?.removeEventListener(`finish`,this.props.onAnimationEnd)})}get rippleStyle(){let{x:e,y:t,width:n,height:r}=this.props,i=this.props.offsetX||0,a=this.props.offsetY||0;return V({transform:`scale(0)`,left:e,top:t,"margin-left":`${-n/2+i}px`,"margin-top":`${-r/2+a}px`,width:`${n}px`,height:`${r}px`,background:this.props.color,"border-radius":`100%`,opacity:`${this.props.opacity}`})}},Kq=class 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:Gq};static defaultProps={color:`#aaaaaa`,opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:``};childContainer=(0,t.useRef)(`childContainer`);state=(0,t.useState)({ripples:[]});currentId=1;onClick(e){if(!this.props.enabled||!this.childContainer.el)return;let{x:t,y:n,width:r,height:i}=this.getRippleChildRectInfo(),a=Math.max(r,i),o={x:e.clientX-t,y:e.clientY-n,width:this.props.width||a*2.85,height:this.props.height||a*2.85};this.state.ripples.push({rippleRect:o,id:this.currentId++})}getRippleStyle(){let e=this.childContainer.el;if(!e||e.childElementCount!==1||!e.firstElementChild)return``;let t=this.getRippleChildRectInfo();return V({top:t.marginTop+`px`,left:t.marginLeft+`px`,width:t.width+`px`,height:t.height+`px`})}getRippleChildRectInfo(){let e=this.childContainer.el;if(!e)throw Error(`No child container element found`);if(e.childElementCount!==1||!e.firstElementChild)return{...Yw(e),marginLeft:0,marginTop:0};let t=e.firstElementChild,n=jf(t);return{...Yw(t),marginLeft:n.left,marginTop:n.top}}removeRipple(e){let t=this.state.ripples.findIndex(t=>t.id===e);t!==-1&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){let t=this.state.ripples.find(t=>t.id===e)?.rippleRect;if(!t)throw 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)}}};function qq(e,t,n,r){let i=e.model.dispatch(`RENAME_SHEET`,{sheetId:t,newName:n,oldName:e.model.getters.getSheetName(t)});i.reasons.includes(`MissingSheetName`)?e.raiseError(E(`The sheet name cannot be empty.`),r):i.reasons.includes(`DuplicatedSheetName`)?e.raiseError(E(`A sheet with the name %s already exists. Please select another name.`,n),r):i.reasons.includes(`ForbiddenCharactersInSheetName`)&&e.raiseError(E(`Some used characters are not allowed in a sheet name (Forbidden characters are %s).`,Ye.join(` `)),r)}B`
1939
+ `;var Kq=class 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=(0,t.useRef)(`ripple`);setup(){let e;(0,t.onMounted)(()=>{let t=this.rippleRef.el;!t||!t.animate||(e=t.animate(Gq,{duration:this.props.duration,easing:`ease-out`}),e.addEventListener(`finish`,this.props.onAnimationEnd))}),(0,t.onWillUnmount)(()=>{e?.removeEventListener(`finish`,this.props.onAnimationEnd)})}get rippleStyle(){let{x:e,y:t,width:n,height:r}=this.props,i=this.props.offsetX||0,a=this.props.offsetY||0;return V({transform:`scale(0)`,left:e,top:t,"margin-left":`${-n/2+i}px`,"margin-top":`${-r/2+a}px`,width:`${n}px`,height:`${r}px`,background:this.props.color,"border-radius":`100%`,opacity:`${this.props.opacity}`})}},qq=class 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:Kq};static defaultProps={color:`#aaaaaa`,opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:``};childContainer=(0,t.useRef)(`childContainer`);state=(0,t.useState)({ripples:[]});currentId=1;onClick(e){if(!this.props.enabled||!this.childContainer.el)return;let{x:t,y:n,width:r,height:i}=this.getRippleChildRectInfo(),a=Math.max(r,i),o={x:e.clientX-t,y:e.clientY-n,width:this.props.width||a*2.85,height:this.props.height||a*2.85};this.state.ripples.push({rippleRect:o,id:this.currentId++})}getRippleStyle(){let e=this.childContainer.el;if(!e||e.childElementCount!==1||!e.firstElementChild)return``;let t=this.getRippleChildRectInfo();return V({top:t.marginTop+`px`,left:t.marginLeft+`px`,width:t.width+`px`,height:t.height+`px`})}getRippleChildRectInfo(){let e=this.childContainer.el;if(!e)throw Error(`No child container element found`);if(e.childElementCount!==1||!e.firstElementChild)return{...Yw(e),marginLeft:0,marginTop:0};let t=e.firstElementChild,n=jf(t);return{...Yw(t),marginLeft:n.left,marginTop:n.top}}removeRipple(e){let t=this.state.ripples.findIndex(t=>t.id===e);t!==-1&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){let t=this.state.ripples.find(t=>t.id===e)?.rippleRect;if(!t)throw 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)}}};function Jq(e,t,n,r){let i=e.model.dispatch(`RENAME_SHEET`,{sheetId:t,newName:n,oldName:e.model.getters.getSheetName(t)});i.reasons.includes(`MissingSheetName`)?e.raiseError(E(`The sheet name cannot be empty.`),r):i.reasons.includes(`DuplicatedSheetName`)?e.raiseError(E(`A sheet with the name %s already exists. Please select another name.`,n),r):i.reasons.includes(`ForbiddenCharactersInSheetName`)&&e.raiseError(E(`Some used characters are not allowed in a sheet name (Forbidden characters are %s).`,Ye.join(` `)),r)}B`
1940
1940
  .o-sheet {
1941
1941
  padding: 0 15px;
1942
1942
  padding-right: 10px;
@@ -1988,7 +1988,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
1988
1988
  .o-spreadshet-mobile .o-sheet {
1989
1989
  height: ${44}px;
1990
1990
  }
1991
- `;var Jq=class 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:Kq,ColorPicker:iA};static defaultProps={onMouseDown:()=>{},style:``};state=(0,t.useState)({isEditing:!1,pickerOpened:!1});sheetDivRef=(0,t.useRef)(`sheetDiv`);sheetNameRef=(0,t.useRef)(`sheetNameSpan`);editionState=`initializing`;DOMFocusableElementStore;setup(){(0,t.onPatched)(()=>{this.sheetNameRef.el&&this.state.isEditing&&this.editionState===`initializing`&&(this.editionState=`editing`,this.focusInputAndSelectContent())}),this.DOMFocusableElementStore=z(Dk),(0,t.useExternalListener)(window,`click`,()=>this.state.pickerOpened=!1),(0,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();let 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&&this.editionState!==`initializing`&&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&&(e.key===`Enter`&&(e.preventDefault(),this.stopEdition(),this.DOMFocusableElementStore.focus()),e.key===`Escape`&&(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();let e=this.getInputContent()||``;qq(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(){let e=this.sheetDivRef.el;return Yw(e)}get contextMenuRegistry(){return zq({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 V({background:this.env.model.getters.getSheet(this.props.sheetId).color||``})}};let Yq=[{name:E(`Sum`),types:[`number`],compute:(e,t)=>Au([[e]],t)},{name:E(`Avg`),types:[`number`],compute:(e,t)=>Ku([[e]],t)},{name:E(`Min`),types:[`number`],compute:(e,t)=>Xu([[e]],t).value},{name:E(`Max`),types:[`number`],compute:(e,t)=>Yu([[e]],t).value},{name:E(`Count`),types:[`number`,`text`,`boolean`,`error`],compute:e=>Ju([[e]])},{name:E(`Count Numbers`),types:[`number`,`text`,`boolean`,`error`],compute:(e,t)=>qu([[e]],t)}];var Xq=class extends bf{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)})}handle(e){switch((yr.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isDirty=!0),e.type){case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`GROUP_HEADERS`:case`UNGROUP_HEADERS`:case`ACTIVATE_SHEET`:case`ACTIVATE_NEXT_SHEET`:case`ACTIVATE_PREVIOUS_SHEET`:case`EVALUATE_CELLS`:case`UNDO`:case`REDO`:this.isDirty=!0}}finalize(){this.isDirty&&(this.isDirty=!1,this.statisticFnResults=this._computeStatisticFnResults())}handleEvent(){this.getters.isGridSelectionActive()&&(this.statisticFnResults=this._computeStatisticFnResults())}_computeStatisticFnResults(){let e=this.getters,t=e.getActiveSheetId(),n=[],r=ms(e.getSelectedZones(),[]),i=this.getters.getSheetSize(t).numberOfRows-1,a=this.getters.getSheetSize(t).numberOfCols-1;for(let o of r)for(let r=o.left;r<=(o.right??a);r++)for(let a=o.top;a<=(o.bottom??i);a++){if(e.isRowHidden(t,a)||e.isColHidden(t,r))continue;let i=e.getEvaluatedCell({sheetId:t,col:r,row:a});i.type!==`empty`&&n.push(i)}let o=e.getLocale(),s={},c=Kt(e=>{let t=e.split(`,`);return n.filter(e=>t.includes(e.type))});for(let e of Yq){let t,n=c(e.types.sort().join(`,`));n.length&&(t=Nt(()=>e.compute(n,o))),s[e.name]=t}return s}};B`
1991
+ `;var Yq=class 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:qq,ColorPicker:iA};static defaultProps={onMouseDown:()=>{},style:``};state=(0,t.useState)({isEditing:!1,pickerOpened:!1});sheetDivRef=(0,t.useRef)(`sheetDiv`);sheetNameRef=(0,t.useRef)(`sheetNameSpan`);editionState=`initializing`;DOMFocusableElementStore;setup(){(0,t.onPatched)(()=>{this.sheetNameRef.el&&this.state.isEditing&&this.editionState===`initializing`&&(this.editionState=`editing`,this.focusInputAndSelectContent())}),this.DOMFocusableElementStore=z(Dk),(0,t.useExternalListener)(window,`click`,()=>this.state.pickerOpened=!1),(0,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();let 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&&this.editionState!==`initializing`&&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&&(e.key===`Enter`&&(e.preventDefault(),this.stopEdition(),this.DOMFocusableElementStore.focus()),e.key===`Escape`&&(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();let e=this.getInputContent()||``;Jq(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(){let e=this.sheetDivRef.el;return Yw(e)}get contextMenuRegistry(){return Bq({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 V({background:this.env.model.getters.getSheet(this.props.sheetId).color||``})}};let Xq=[{name:E(`Sum`),types:[`number`],compute:(e,t)=>Au([[e]],t)},{name:E(`Avg`),types:[`number`],compute:(e,t)=>Ku([[e]],t)},{name:E(`Min`),types:[`number`],compute:(e,t)=>Xu([[e]],t).value},{name:E(`Max`),types:[`number`],compute:(e,t)=>Yu([[e]],t).value},{name:E(`Count`),types:[`number`,`text`,`boolean`,`error`],compute:e=>Ju([[e]])},{name:E(`Count Numbers`),types:[`number`,`text`,`boolean`,`error`],compute:(e,t)=>qu([[e]],t)}];var Zq=class extends bf{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)})}handle(e){switch((yr.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isDirty=!0),e.type){case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`GROUP_HEADERS`:case`UNGROUP_HEADERS`:case`ACTIVATE_SHEET`:case`ACTIVATE_NEXT_SHEET`:case`ACTIVATE_PREVIOUS_SHEET`:case`EVALUATE_CELLS`:case`UNDO`:case`REDO`:this.isDirty=!0}}finalize(){this.isDirty&&(this.isDirty=!1,this.statisticFnResults=this._computeStatisticFnResults())}handleEvent(){this.getters.isGridSelectionActive()&&(this.statisticFnResults=this._computeStatisticFnResults())}_computeStatisticFnResults(){let e=this.getters,t=e.getActiveSheetId(),n=[],r=ms(e.getSelectedZones(),[]),i=this.getters.getSheetSize(t).numberOfRows-1,a=this.getters.getSheetSize(t).numberOfCols-1;for(let o of r)for(let r=o.left;r<=(o.right??a);r++)for(let a=o.top;a<=(o.bottom??i);a++){if(e.isRowHidden(t,a)||e.isColHidden(t,r))continue;let i=e.getEvaluatedCell({sheetId:t,col:r,row:a});i.type!==`empty`&&n.push(i)}let o=e.getLocale(),s={},c=Kt(e=>{let t=e.split(`,`);return n.filter(e=>t.includes(e.type))});for(let e of Xq){let t,n=c(e.types.sort().join(`,`));n.length&&(t=Nt(()=>e.compute(n,o))),s[e.name]=t}return s}};B`
1992
1992
  .o-selection-statistic {
1993
1993
  margin-right: 20px;
1994
1994
  padding: 4px 4px 4px 8px;
@@ -1998,7 +1998,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
1998
1998
  background-color: rgba(0, 0, 0, 0.08) !important;
1999
1999
  }
2000
2000
  }
2001
- `;var Zq=class extends t.Component{static template=`o-spreadsheet-BottomBarStatistic`;static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:Kq};selectedStatisticFn=``;store;setup(){this.store=z(Xq),(0,t.onWillUpdateProps)(()=>{Object.values(this.store.statisticFnResults).every(e=>e===void 0)&&this.props.closeContextMenu()})}getSelectedStatistic(){if(!Object.values(this.store.statisticFnResults).every(e=>e===void 0))return this.selectedStatisticFn===``&&(this.selectedStatisticFn=Object.keys(this.store.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn)}listSelectionStatistics(e){let t=new IA,n=0;for(let[e]of Object.entries(this.store.statisticFnResults))t.add(e,{name:()=>this.getComposedFnName(e),sequence:n,isReadonlyAllowed:!0,execute:()=>{this.selectedStatisticFn=e}}),n++;let{top:r,left:i,width:a}=e.currentTarget.getBoundingClientRect();this.props.openContextMenu(i+a,r,t)}getComposedFnName(e){let t=this.env.model.getters.getLocale(),n=this.store.statisticFnResults[e];return e+`: `+(n===void 0?`__`:L(n(),{locale:t}))}};B`
2001
+ `;var Qq=class extends t.Component{static template=`o-spreadsheet-BottomBarStatistic`;static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:qq};selectedStatisticFn=``;store;setup(){this.store=z(Zq),(0,t.onWillUpdateProps)(()=>{Object.values(this.store.statisticFnResults).every(e=>e===void 0)&&this.props.closeContextMenu()})}getSelectedStatistic(){if(!Object.values(this.store.statisticFnResults).every(e=>e===void 0))return this.selectedStatisticFn===``&&(this.selectedStatisticFn=Object.keys(this.store.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn)}listSelectionStatistics(e){let t=new IA,n=0;for(let[e]of Object.entries(this.store.statisticFnResults))t.add(e,{name:()=>this.getComposedFnName(e),sequence:n,isReadonlyAllowed:!0,execute:()=>{this.selectedStatisticFn=e}}),n++;let{top:r,left:i,width:a}=e.currentTarget.getBoundingClientRect();this.props.openContextMenu(i+a,r,t)}getComposedFnName(e){let t=this.env.model.getters.getLocale(),n=this.store.statisticFnResults[e];return e+`: `+(n===void 0?`__`:L(n(),{locale:t}))}};B`
2002
2002
  .o-spreadsheet-bottom-bar {
2003
2003
  background-color: ${y};
2004
2004
  padding-left: ${48}px;
@@ -2068,12 +2068,12 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2068
2068
  max-width: none;
2069
2069
  }
2070
2070
  }
2071
- `;var Qq=class extends t.Component{static template=`o-spreadsheet-BottomBar`;static props={onClick:Function};static components={MenuPopover:ck,Ripple:Kq,BottomBarSheet:Jq,BottomBarStatistic:Zq};bottomBarRef=(0,t.useRef)(`bottomBar`);sheetListRef=(0,t.useRef)(`sheetList`);dragAndDrop=sA();targetScroll=void 0;state=(0,t.useState)({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=(0,t.useState)({isOpen:!1,menuId:void 0,anchorRect:null,menuItems:[]});sheetList=this.getVisibleSheets();setup(){(0,t.onWillUpdateProps)(()=>{this.updateScrollState();let e=this.getVisibleSheets();w(this.sheetList,e)||this.dragAndDrop.cancel(),this.sheetList=e})}clickAddSheet(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSheetIds().findIndex(e=>e===t)+1,r=this.env.model.uuidGenerator.smallUuid(),i=this.env.model.getters.getNextSheetName(E(`Sheet`));this.env.model.dispatch(`CREATE_SHEET`,{sheetId:r,position:n,name:i}),this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:r})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map(e=>{let t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}})}clickListSheets(e){let t=new IA,n=this.env.model.getters.getActiveSheetId(),r=0;for(let e of this.env.model.getters.getSheetIds()){let i=this.env.model.getters.getSheet(e);t.add(e,{name:i.name,sequence:r,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:n,sheetIdTo:e})},isEnabled:e=>e.model.getters.isReadonly()?i.isVisible:!0,icon:i.color?`o-spreadsheet-Icon.SMALL_DOT_RIGHT_ALIGN`:void 0,iconColor:i.color}),r++}let{left:i}=e.currentTarget.getBoundingClientRect(),a=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(i,a,`listSheets`,t)}openContextMenu(e,t,n,r){this.menuState.isOpen=!0,this.menuState.menuId=n,this.menuState.menuItems=r.getMenuItems(),this.menuState.anchorRect={x:e,y:t,width:0,height:0}}onSheetContextMenu(e,t,n){let{top:r,left:i}=n.currentTarget.getBoundingClientRect();if(n.closedMenuId===e){this.closeMenu();return}this.openContextMenu(i,r,e,t)}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;let t=e.currentTarget;t.scrollLeft+=e.deltaY*.5}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||=this.sheetListCurrentScroll;let t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||=this.sheetListCurrentScroll;let 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(t.button!==0||this.env.model.getters.isReadonly()||(this.closeMenu(),this.env.isMobile()))return;let n=this.getVisibleSheets(),r=this.getSheetItemRects(),i=n.map((e,t)=>({id:e.id,size:r[t].width,position:r[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){let n=t-this.getVisibleSheets().findIndex(t=>t.id===e);e&&n!==0&&this.env.model.dispatch(`MOVE_SHEET`,{sheetId:e,delta:n})}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}},$q=class extends bf{_clickableCells=(0,t.markRaw)({});_registryItems=(0,t.markRaw)(gq.getAll().sort((e,t)=>e.sequence-t.sequence));handle(e){(yr.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this._clickableCells=(0,t.markRaw)({}),this._registryItems=(0,t.markRaw)(gq.getAll().sort((e,t)=>e.sequence-t.sequence)))}getClickableItem(e){let{sheetId:t,col:n,row:r}=e,i=this._clickableCells,a=T(n,r);if(i[t]||(i[t]={}),!(a in i[t])){let n=this.findClickableItem(e);i[t][a]=n}return i[t][a]}findClickableItem(e){let t=this.getters;for(let n of this._registryItems)if(n.condition(e,t))return n}get clickableCells(){let e=[],t=this.getters;for(let n of this.getters.getVisibleCellPositions()){let r=this.getClickableItem(n);if(!r)continue;let i=typeof r.title==`function`?r.title(n,t):r.title,a=this.getClickableCellRect(n);a&&e.push({coordinates:a,position:n,action:r.execute,title:i||``,component:r.component,componentProps:r.componentProps?.(n,t)??{}})}return e}getClickableCellRect(e){let t=this.getters.expandZone(e.sheetId,R(e)),n=this.getters.getVisibleRect(t),r=this.getters.getCellIcons(e),i={center:r.find(e=>e.horizontalAlign===`center`),left:r.find(e=>e.horizontalAlign===`left`),right:r.find(e=>e.horizontalAlign===`right`)};if(!i.center?.onClick){if(i.right?.onClick){let e=this.getters.getRect(t),r=this.getters.getCellIconRect(i.right,e);n.width-=r.width+i.right.margin}if(i.left?.onClick){let e=this.getters.getRect(t),r=this.getters.getCellIconRect(i.left,e);n.x+=r.width+i.left.margin,n.width-=r.width+i.left.margin}return n}}};B`
2071
+ `;var $q=class extends t.Component{static template=`o-spreadsheet-BottomBar`;static props={onClick:Function};static components={MenuPopover:ck,Ripple:qq,BottomBarSheet:Yq,BottomBarStatistic:Qq};bottomBarRef=(0,t.useRef)(`bottomBar`);sheetListRef=(0,t.useRef)(`sheetList`);dragAndDrop=sA();targetScroll=void 0;state=(0,t.useState)({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=(0,t.useState)({isOpen:!1,menuId:void 0,anchorRect:null,menuItems:[]});sheetList=this.getVisibleSheets();setup(){(0,t.onWillUpdateProps)(()=>{this.updateScrollState();let e=this.getVisibleSheets();w(this.sheetList,e)||this.dragAndDrop.cancel(),this.sheetList=e})}clickAddSheet(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSheetIds().findIndex(e=>e===t)+1,r=this.env.model.uuidGenerator.smallUuid(),i=this.env.model.getters.getNextSheetName(E(`Sheet`));this.env.model.dispatch(`CREATE_SHEET`,{sheetId:r,position:n,name:i}),this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:r})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map(e=>{let t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}})}clickListSheets(e){let t=new IA,n=this.env.model.getters.getActiveSheetId(),r=0;for(let e of this.env.model.getters.getSheetIds()){let i=this.env.model.getters.getSheet(e);t.add(e,{name:i.name,sequence:r,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:n,sheetIdTo:e})},isEnabled:e=>e.model.getters.isReadonly()?i.isVisible:!0,icon:i.color?`o-spreadsheet-Icon.SMALL_DOT_RIGHT_ALIGN`:void 0,iconColor:i.color}),r++}let{left:i}=e.currentTarget.getBoundingClientRect(),a=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(i,a,`listSheets`,t)}openContextMenu(e,t,n,r){this.menuState.isOpen=!0,this.menuState.menuId=n,this.menuState.menuItems=r.getMenuItems(),this.menuState.anchorRect={x:e,y:t,width:0,height:0}}onSheetContextMenu(e,t,n){let{top:r,left:i}=n.currentTarget.getBoundingClientRect();if(n.closedMenuId===e){this.closeMenu();return}this.openContextMenu(i,r,e,t)}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;let t=e.currentTarget;t.scrollLeft+=e.deltaY*.5}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||=this.sheetListCurrentScroll;let t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||=this.sheetListCurrentScroll;let 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(t.button!==0||this.env.model.getters.isReadonly()||(this.closeMenu(),this.env.isMobile()))return;let n=this.getVisibleSheets(),r=this.getSheetItemRects(),i=n.map((e,t)=>({id:e.id,size:r[t].width,position:r[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){let n=t-this.getVisibleSheets().findIndex(t=>t.id===e);e&&n!==0&&this.env.model.dispatch(`MOVE_SHEET`,{sheetId:e,delta:n})}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}},eJ=class extends bf{_clickableCells=(0,t.markRaw)({});_registryItems=(0,t.markRaw)(_q.getAll().sort((e,t)=>e.sequence-t.sequence));handle(e){(yr.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this._clickableCells=(0,t.markRaw)({}),this._registryItems=(0,t.markRaw)(_q.getAll().sort((e,t)=>e.sequence-t.sequence)))}getClickableItem(e){let{sheetId:t,col:n,row:r}=e,i=this._clickableCells,a=T(n,r);if(i[t]||(i[t]={}),!(a in i[t])){let n=this.findClickableItem(e);i[t][a]=n}return i[t][a]}findClickableItem(e){let t=this.getters;for(let n of this._registryItems)if(n.condition(e,t))return n}get clickableCells(){let e=[],t=this.getters;for(let n of this.getters.getVisibleCellPositions()){let r=this.getClickableItem(n);if(!r)continue;let i=typeof r.title==`function`?r.title(n,t):r.title,a=this.getClickableCellRect(n);a&&e.push({coordinates:a,position:n,action:r.execute,title:i||``,component:r.component,componentProps:r.componentProps?.(n,t)??{}})}return e}getClickableCellRect(e){let t=this.getters.expandZone(e.sheetId,R(e)),n=this.getters.getVisibleRect(t),r=this.getters.getCellIcons(e),i={center:r.find(e=>e.horizontalAlign===`center`),left:r.find(e=>e.horizontalAlign===`left`),right:r.find(e=>e.horizontalAlign===`right`)};if(!i.center?.onClick){if(i.right?.onClick){let e=this.getters.getRect(t),r=this.getters.getCellIconRect(i.right,e);n.width-=r.width+i.right.margin}if(i.left?.onClick){let e=this.getters.getRect(t),r=this.getters.getCellIconRect(i.left,e);n.x+=r.width+i.left.margin,n.width-=r.width+i.left.margin}return n}}};B`
2072
2072
  .o-dashboard-clickable-cell {
2073
2073
  position: absolute;
2074
2074
  cursor: pointer;
2075
2075
  }
2076
- `;var eJ=class extends t.Component{static template=`o-spreadsheet-SpreadsheetDashboard`;static props={getGridSize:Function};static components={GridOverlay:oV,GridPopover:sV,Popover:ik,VerticalScrollBar:EV,HorizontalScrollBar:TV};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;gridRef;setup(){this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=z(hk),this.clickableCellsStore=z($q),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),hV(`canvas`,this.env.model,()=>this.env.model.getters.getSheetViewDimension()),this.onMouseWheel=vV((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=z(TA),_V(this.gridRef,this.moveCanvas.bind(this),()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e})}get gridContainer(){return V({"max-width":`${this.getMaxSheetWidth()}px`})}get gridOverlayDimensions(){return V({height:`100%`,width:`100%`})}getCellClickableStyle(e){return V({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){return(0,t.toRaw)(this.clickableCellsStore.clickableCells)}selectClickableCell(e,t){let{position:n,action:r}=t;r(n,this.env,aT(e))}onClosePopover(){this.cellPopovers.close()}onGridResized(){let{height:e,width:t}=this.props.getGridSize(),n=this.getMaxSheetWidth();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:Math.min(n,t),height:e,gridOffsetX:0,gridOffsetY:0})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}getGridRect(){return{...Jw(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}getMaxSheetWidth(){let e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e);return this.env.model.getters.getColDimensions(e,t).end}};B`
2076
+ `;var tJ=class extends t.Component{static template=`o-spreadsheet-SpreadsheetDashboard`;static props={getGridSize:Function};static components={GridOverlay:oV,GridPopover:sV,Popover:ik,VerticalScrollBar:EV,HorizontalScrollBar:TV};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;gridRef;setup(){this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=z(hk),this.clickableCellsStore=z(eJ),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),hV(`canvas`,this.env.model,()=>this.env.model.getters.getSheetViewDimension()),this.onMouseWheel=vV((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=z(TA),_V(this.gridRef,this.moveCanvas.bind(this),()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e})}get gridContainer(){return V({"max-width":`${this.getMaxSheetWidth()}px`})}get gridOverlayDimensions(){return V({height:`100%`,width:`100%`})}getCellClickableStyle(e){return V({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){return(0,t.toRaw)(this.clickableCellsStore.clickableCells)}selectClickableCell(e,t){let{position:n,action:r}=t;r(n,this.env,aT(e))}onClosePopover(){this.cellPopovers.close()}onGridResized(){let{height:e,width:t}=this.props.getGridSize(),n=this.getMaxSheetWidth();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:Math.min(n,t),height:e,gridOffsetX:0,gridOffsetY:0})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}getGridRect(){return{...Jw(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}getMaxSheetWidth(){let e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e);return this.env.model.getters.getColDimensions(e,t).end}};B`
2077
2077
  .o-header-group {
2078
2078
  .o-header-group-header {
2079
2079
  z-index: ${6};
@@ -2093,7 +2093,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2093
2093
  }
2094
2094
  }
2095
2095
  }
2096
- `;var tJ=class extends t.Component{static template=`o-spreadsheet-HeaderGroup`;static props={group:Object,layerOffset:Number,openContextMenu:Function};toggleGroup(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group;aB(this.env,e,this.dimension,t,n)}get groupBoxStyle(){let e=this.groupBox;return V({top:`${e.groupRect.y}px`,left:`${e.groupRect.x}px`,width:`${e.groupRect.width}px`,height:`${e.groupRect.height}px`})}get groupButtonStyle(){return V({"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(){let 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){let t=this.env.model.getters.getActiveSheetId(),n={x:e.clientX,y:e.clientY},r=this.props.group,i=sB(t,this.dimension,r.start,r.end);this.props.openContextMenu(n,i)}},nJ=class extends tJ{dimension=`ROW`;get groupBorderStyle(){let e=this.groupBox;return this.groupBox.groupRect.height===0?``:V({top:`${e.headerRect.height/2}px`,left:`calc(50% - 1px)`,width:`30%`,height:`calc(100% - ${e.headerRect.height/2}px)`,"border-left":`1px solid ${pe}`,"border-bottom":e.isEndHidden?``:`1px solid ${pe}`})}get groupHeaderStyle(){return V({width:`100%`,height:`${this.groupBox.headerRect.height}px`})}get groupBox(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group,r=this.env.model.getters.getRowDimensions(e,t).start,i=this.env.model.getters.getRowDimensions(e,n).end,a=0,o=26;if(t!==0){let n=this.env.model.getters.getRowDimensions(e,t-1);a=26+n.start,o=n.end-n.start}let s={x:this.props.layerOffset,y:a,width:21,height:o};return{headerRect:s,groupRect:{x:this.props.layerOffset,y:s.y,width:21,height:s.height+(i-r)},isEndHidden:this.env.model.getters.isRowHidden(e,n)}}},rJ=class extends tJ{dimension=`COL`;get groupBorderStyle(){let e=this.groupBox;return e.groupRect.width===0?``:V({top:`calc(50% - 1px)`,left:`${e.headerRect.width/2}px`,width:`calc(100% - ${e.headerRect.width/2}px)`,height:`30%`,"border-top":`1px solid ${pe}`,"border-right":e.isEndHidden?``:`1px solid ${pe}`})}get groupHeaderStyle(){return V({width:`${this.groupBox.headerRect.width}px`,height:`100%`})}get groupBox(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group,r=this.env.model.getters.getColDimensions(e,t).start,i=this.env.model.getters.getColDimensions(e,n).end,a=0,o=48;if(t!==0){let n=this.env.model.getters.getColDimensions(e,t-1);a=48+n.start,o=n.end-n.start}let s={x:a,y:this.props.layerOffset,width:o,height:21};return{headerRect:s,groupRect:{x:s.x,y:this.props.layerOffset,width:s.width+(i-r),height:21},isEndHidden:this.env.model.getters.isColHidden(e,n)}}};B`
2096
+ `;var nJ=class extends t.Component{static template=`o-spreadsheet-HeaderGroup`;static props={group:Object,layerOffset:Number,openContextMenu:Function};toggleGroup(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group;aB(this.env,e,this.dimension,t,n)}get groupBoxStyle(){let e=this.groupBox;return V({top:`${e.groupRect.y}px`,left:`${e.groupRect.x}px`,width:`${e.groupRect.width}px`,height:`${e.groupRect.height}px`})}get groupButtonStyle(){return V({"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(){let 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){let t=this.env.model.getters.getActiveSheetId(),n={x:e.clientX,y:e.clientY},r=this.props.group,i=sB(t,this.dimension,r.start,r.end);this.props.openContextMenu(n,i)}},rJ=class extends nJ{dimension=`ROW`;get groupBorderStyle(){let e=this.groupBox;return this.groupBox.groupRect.height===0?``:V({top:`${e.headerRect.height/2}px`,left:`calc(50% - 1px)`,width:`30%`,height:`calc(100% - ${e.headerRect.height/2}px)`,"border-left":`1px solid ${pe}`,"border-bottom":e.isEndHidden?``:`1px solid ${pe}`})}get groupHeaderStyle(){return V({width:`100%`,height:`${this.groupBox.headerRect.height}px`})}get groupBox(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group,r=this.env.model.getters.getRowDimensions(e,t).start,i=this.env.model.getters.getRowDimensions(e,n).end,a=0,o=26;if(t!==0){let n=this.env.model.getters.getRowDimensions(e,t-1);a=26+n.start,o=n.end-n.start}let s={x:this.props.layerOffset,y:a,width:21,height:o};return{headerRect:s,groupRect:{x:this.props.layerOffset,y:s.y,width:21,height:s.height+(i-r)},isEndHidden:this.env.model.getters.isRowHidden(e,n)}}},iJ=class extends nJ{dimension=`COL`;get groupBorderStyle(){let e=this.groupBox;return e.groupRect.width===0?``:V({top:`calc(50% - 1px)`,left:`${e.headerRect.width/2}px`,width:`calc(100% - ${e.headerRect.width/2}px)`,height:`30%`,"border-top":`1px solid ${pe}`,"border-right":e.isEndHidden?``:`1px solid ${pe}`})}get groupHeaderStyle(){return V({width:`${this.groupBox.headerRect.width}px`,height:`100%`})}get groupBox(){let e=this.env.model.getters.getActiveSheetId(),{start:t,end:n}=this.props.group,r=this.env.model.getters.getColDimensions(e,t).start,i=this.env.model.getters.getColDimensions(e,n).end,a=0,o=48;if(t!==0){let n=this.env.model.getters.getColDimensions(e,t-1);a=48+n.start,o=n.end-n.start}let s={x:a,y:this.props.layerOffset,width:o,height:21};return{headerRect:s,groupRect:{x:s.x,y:this.props.layerOffset,width:s.width+(i-r),height:21},isEndHidden:this.env.model.getters.isColHidden(e,n)}}};B`
2097
2097
  .o-header-group-frozen-pane-border {
2098
2098
  &.o-group-rows {
2099
2099
  margin-top: -1px;
@@ -2113,7 +2113,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2113
2113
  margin-left: -2px;
2114
2114
  }
2115
2115
  }
2116
- `;var iJ=class extends t.Component{static template=`o-spreadsheet-HeaderGroupContainer`;static props={dimension:String,layers:Array};static components={RowGroup:nJ,ColGroup:rJ,MenuPopover:ck};menu=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});getLayerOffset(e){return e*21}onContextMenu(e){let t=this.env.model.getters.getActiveSheetId(),n={x:e.clientX,y:e.clientY},r=oB(t,this.props.dimension);this.openContextMenu(n,r)}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 this.props.dimension===`ROW`?nJ:rJ}get hasFrozenPane(){let e=this.env.model.getters.getMainViewportCoordinates();return this.props.dimension===`COL`?e.x>0:e.y>0}get scrollContainerStyle(){let{scrollX:e,scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo(),n={};return this.props.dimension===`COL`?n.left=`${-e-this.frozenPaneContainerSize}px`:n.top=`${-t-this.frozenPaneContainerSize}px`,V(n)}get frozenPaneContainerStyle(){let e={};return this.props.dimension===`COL`?e.width=`${this.frozenPaneContainerSize}px`:e.height=`${this.frozenPaneContainerSize}px`,V(e)}get frozenPaneContainerSize(){if(!this.hasFrozenPane)return 0;let e=this.env.model.getters.getMainViewportCoordinates();return this.props.dimension===`COL`?48+e.x:26+e.y}};function aJ(){let e=nk();return{get isSmall(){return e.width<768}}}B`
2116
+ `;var aJ=class extends t.Component{static template=`o-spreadsheet-HeaderGroupContainer`;static props={dimension:String,layers:Array};static components={RowGroup:rJ,ColGroup:iJ,MenuPopover:ck};menu=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});getLayerOffset(e){return e*21}onContextMenu(e){let t=this.env.model.getters.getActiveSheetId(),n={x:e.clientX,y:e.clientY},r=oB(t,this.props.dimension);this.openContextMenu(n,r)}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 this.props.dimension===`ROW`?rJ:iJ}get hasFrozenPane(){let e=this.env.model.getters.getMainViewportCoordinates();return this.props.dimension===`COL`?e.x>0:e.y>0}get scrollContainerStyle(){let{scrollX:e,scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo(),n={};return this.props.dimension===`COL`?n.left=`${-e-this.frozenPaneContainerSize}px`:n.top=`${-t-this.frozenPaneContainerSize}px`,V(n)}get frozenPaneContainerStyle(){let e={};return this.props.dimension===`COL`?e.width=`${this.frozenPaneContainerSize}px`:e.height=`${this.frozenPaneContainerSize}px`,V(e)}get frozenPaneContainerSize(){if(!this.hasFrozenPane)return 0;let e=this.env.model.getters.getMainViewportCoordinates();return this.props.dimension===`COL`?48+e.x:26+e.y}};function oJ(){let e=nk();return{get isSmall(){return e.width<768}}}B`
2117
2117
  .o-sidePanel {
2118
2118
  display: flex;
2119
2119
  flex-direction: column;
@@ -2227,11 +2227,11 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2227
2227
  .o-fw-bold {
2228
2228
  font-weight: 500;
2229
2229
  }
2230
- `;var oJ=class 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=nk();getTitle(){let e=this.props.panelContent;return typeof e.title==`function`?e.title(this.env,this.props.panelProps):e.title}get pinInfoMessage(){return E(`Pin this panel to allow to open another side panel beside it.`)}},sJ=class extends t.Component{static template=`o-spreadsheet-SidePanels`;static props={};static components={SidePanel:oJ};sidePanelStore;spreadsheetRect=nk();setup(){this.sidePanelStore=z(BU),(0,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){let n=document.body.style.cursor,r=e===`mainPanel`?this.sidePanelStore.mainPanel:this.sidePanelStore.secondaryPanel;if(!r)return;let i=r.size,a=t.clientX;rA(t=>{document.body.style.cursor=`col-resize`;let n=i+a-t.clientX;this.sidePanelStore.changePanelSize(e,n)},()=>{document.body.style.cursor=n})}get mainPanelProps(){let e=this.sidePanelStore.mainPanelProps;if(!(!this.sidePanelStore.mainPanel||!e))return{panelContent:RU.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(){let e=this.sidePanelStore.secondaryPanelProps;if(!(!this.sidePanelStore.secondaryPanel||!e))return{panelContent:RU.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?V({width:`${this.sidePanelStore.secondaryPanel.size}px`}):``},{key:this.sidePanelStore.mainPanelKey,props:this.mainPanelProps,style:this.sidePanelStore.mainPanel?V({width:`${this.sidePanelStore.mainPanel.size}px`}):``}].filter(e=>e.key&&e.props)}},cJ=class extends t.Component{static template=`o-spreadsheet-RibbonMenu`;static props={onClose:Function};static components={Menu:XO};rootItems=Bq.getMenuItems();menuRef=(0,t.useRef)(`menu`);containerRef=(0,t.useRef)(`container`);state=(0,t.useState)({menuItems:this.rootItems,title:E(`Menu Bar`),parentState:void 0});setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0}),(0,t.onMounted)(this.updateShadows)}onExternalClick(e){this.menuRef.el?.contains(e.target)||this.props.onClose()}onClickMenu(e){let t=e.children(this.env);t.length?(this.state.parentState={...this.state},this.state.menuItems=t,this.state.title=e.name(this.env),this.containerRef.el?.scrollTo({top:0})):(this.state.menuItems=this.rootItems,this.state.title=void 0,this.state.parentState=void 0,e.execute?.(this.env),this.props.onClose())}get menuProps(){return{menuItems:h(this.env,this.state.menuItems),onClose:this.props.onClose,onClickMenu:this.onClickMenu.bind(this)}}get style(){return V({height:`${this.props.height}px`})}updateShadows(){if(!this.containerRef.el)return;this.containerRef.el.classList.remove(`scroll-top`,`scroll-bottom`);let e=this.containerRef.el.scrollHeight-this.containerRef.el.clientHeight||0;this.containerRef.el.scrollTop<e-1&&this.containerRef.el.classList.add(`scroll-bottom`),this.containerRef.el.scrollTop>0&&this.containerRef.el.classList.add(`scroll-top`)}onClickBack(){if(!this.state.parentState){this.props.onClose();return}this.state.menuItems=this.state.parentState.menuItems,this.state.title=this.state.parentState.title,this.state.parentState=this.state.parentState.parentState,this.containerRef.el?.scrollTo({top:0})}get backTitle(){return this.state.parentState?E(`Go to previous menu`):E(`Close menu bar`)}};B`
2230
+ `;var sJ=class 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=nk();getTitle(){let e=this.props.panelContent;return typeof e.title==`function`?e.title(this.env,this.props.panelProps):e.title}get pinInfoMessage(){return E(`Pin this panel to allow to open another side panel beside it.`)}},cJ=class extends t.Component{static template=`o-spreadsheet-SidePanels`;static props={};static components={SidePanel:sJ};sidePanelStore;spreadsheetRect=nk();setup(){this.sidePanelStore=z(VU),(0,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){let n=document.body.style.cursor,r=e===`mainPanel`?this.sidePanelStore.mainPanel:this.sidePanelStore.secondaryPanel;if(!r)return;let i=r.size,a=t.clientX;rA(t=>{document.body.style.cursor=`col-resize`;let n=i+a-t.clientX;this.sidePanelStore.changePanelSize(e,n)},()=>{document.body.style.cursor=n})}get mainPanelProps(){let e=this.sidePanelStore.mainPanelProps;if(!(!this.sidePanelStore.mainPanel||!e))return{panelContent:zU.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(){let e=this.sidePanelStore.secondaryPanelProps;if(!(!this.sidePanelStore.secondaryPanel||!e))return{panelContent:zU.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?V({width:`${this.sidePanelStore.secondaryPanel.size}px`}):``},{key:this.sidePanelStore.mainPanelKey,props:this.mainPanelProps,style:this.sidePanelStore.mainPanel?V({width:`${this.sidePanelStore.mainPanel.size}px`}):``}].filter(e=>e.key&&e.props)}},lJ=class extends t.Component{static template=`o-spreadsheet-RibbonMenu`;static props={onClose:Function};static components={Menu:XO};rootItems=Vq.getMenuItems();menuRef=(0,t.useRef)(`menu`);containerRef=(0,t.useRef)(`container`);state=(0,t.useState)({menuItems:this.rootItems,title:E(`Menu Bar`),parentState:void 0});setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0}),(0,t.onMounted)(this.updateShadows)}onExternalClick(e){this.menuRef.el?.contains(e.target)||this.props.onClose()}onClickMenu(e){let t=e.children(this.env);t.length?(this.state.parentState={...this.state},this.state.menuItems=t,this.state.title=e.name(this.env),this.containerRef.el?.scrollTo({top:0})):(this.state.menuItems=this.rootItems,this.state.title=void 0,this.state.parentState=void 0,e.execute?.(this.env),this.props.onClose())}get menuProps(){return{menuItems:h(this.env,this.state.menuItems),onClose:this.props.onClose,onClickMenu:this.onClickMenu.bind(this)}}get style(){return V({height:`${this.props.height}px`})}updateShadows(){if(!this.containerRef.el)return;this.containerRef.el.classList.remove(`scroll-top`,`scroll-bottom`);let e=this.containerRef.el.scrollHeight-this.containerRef.el.clientHeight||0;this.containerRef.el.scrollTop<e-1&&this.containerRef.el.classList.add(`scroll-bottom`),this.containerRef.el.scrollTop>0&&this.containerRef.el.classList.add(`scroll-top`)}onClickBack(){if(!this.state.parentState){this.props.onClose();return}this.state.menuItems=this.state.parentState.menuItems,this.state.title=this.state.parentState.title,this.state.parentState=this.state.parentState.parentState,this.containerRef.el?.scrollTo({top:0})}get backTitle(){return this.state.parentState?E(`Go to previous menu`):E(`Close menu bar`)}};B`
2231
2231
  .o-small-composer {
2232
2232
  z-index: ${30};
2233
2233
  }
2234
- `;var lJ=class extends t.Component{static components={Composer:Uk,BottomBar:Qq,Ripple:Kq,RibbonMenu:cJ};static template=`o-spreadsheet-SmallBottomBar`;static props={onClick:Function};composerFocusStore;composerStore;composerInterface;composerRef=(0,t.useRef)(`bottombarComposer`);menuState=(0,t.useState)({isOpen:!1});setup(){this.composerFocusStore=z(Sf);let e=z(RB);this.composerStore=e,this.composerInterface={id:`bottombarComposer`,get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},(0,t.useEffect)(()=>{this.env.isMobile()&&!this.menuState.isOpen&&this.composerStore.editionMode!==`inactive`&&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 this.focus===`inactive`&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get rect(){return this.composerRef.el?Yw(this.composerRef.el):{x:0,y:0,width:0,height:0}}get composerProps(){let{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,composerStore:this.composerStore,onComposerContentFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`,selection:e}),isDefaultFocus:!1,inputStyle:V({height:this.focus===`inactive`?`26px`:`fit-content`,"max-height":`130px`}),showAssistant:!1,placeholder:this.composerStore.placeholder}}get symbols(){return[`=`,`(`,`)`,`:`,`-`,`/`,`*`,`,`,`+`,`$`,`.`]}insertSymbol(e){this.composerStore.replaceComposerCursorSelection(e),this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`})}toggleRibbon(){this.composerStore.cancelEdition(),this.menuState.isOpen=!this.menuState.isOpen}};B`
2234
+ `;var uJ=class extends t.Component{static components={Composer:Uk,BottomBar:$q,Ripple:qq,RibbonMenu:lJ};static template=`o-spreadsheet-SmallBottomBar`;static props={onClick:Function};composerFocusStore;composerStore;composerInterface;composerRef=(0,t.useRef)(`bottombarComposer`);menuState=(0,t.useState)({isOpen:!1});setup(){this.composerFocusStore=z(Sf);let e=z(RB);this.composerStore=e,this.composerInterface={id:`bottombarComposer`,get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},(0,t.useEffect)(()=>{this.env.isMobile()&&!this.menuState.isOpen&&this.composerStore.editionMode!==`inactive`&&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 this.focus===`inactive`&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get rect(){return this.composerRef.el?Yw(this.composerRef.el):{x:0,y:0,width:0,height:0}}get composerProps(){let{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,composerStore:this.composerStore,onComposerContentFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`,selection:e}),isDefaultFocus:!1,inputStyle:V({height:this.focus===`inactive`?`26px`:`fit-content`,"max-height":`130px`}),showAssistant:!1,placeholder:this.composerStore.placeholder}}get symbols(){return[`=`,`(`,`)`,`:`,`-`,`/`,`*`,`,`,`+`,`$`,`.`]}insertSymbol(e){this.composerStore.replaceComposerCursorSelection(e),this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`})}toggleRibbon(){this.composerStore.cancelEdition(),this.menuState.isOpen=!this.menuState.isOpen}};B`
2235
2235
  .o-topbar-composer-container {
2236
2236
  height: ${34}px;
2237
2237
  }
@@ -2247,7 +2247,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2247
2247
  .user-select-text {
2248
2248
  user-select: text;
2249
2249
  }
2250
- `;var uJ=class extends t.Component{static template=`o-spreadsheet-TopBarComposer`;static props={};static components={Composer:Uk};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=z(Sf);let e=z(RB);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 this.focus===`inactive`&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get composerStyle(){let e={padding:`5px 0px 5px 8px`,"max-height":`300px`,"line-height":`24px`};return e.height=this.focus===`inactive`?`34px`:`fit-content`,V(e)}get containerStyle(){return this.focus===`inactive`?V({"border-color":de,"border-right":`none`}):V({"border-color":ae,"z-index":`30`})}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}},dJ=class{mutators=[`closeDropdowns`,`openDropdown`];_currentDropdown=null;closeDropdowns(){this._currentDropdown=null}openDropdown(e){this._currentDropdown=e}get currentDropdown(){return this._currentDropdown}},fJ=class{content={};add(e){if(e in this.content)throw 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)}};function pJ(){let e=(0,t.useComponent)(),n=z(dJ);return(0,t.onWillUnmount)(()=>{e===n.currentDropdown&&n.closeDropdowns()}),{closeDropdowns:()=>n.closeDropdowns(),openDropdown:()=>{n.openDropdown(e)},get isActive(){return n.currentDropdown===e}}}let mJ=[[[`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`]]];B`
2250
+ `;var dJ=class extends t.Component{static template=`o-spreadsheet-TopBarComposer`;static props={};static components={Composer:Uk};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=z(Sf);let e=z(RB);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 this.focus===`inactive`&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get composerStyle(){let e={padding:`5px 0px 5px 8px`,"max-height":`300px`,"line-height":`24px`};return e.height=this.focus===`inactive`?`34px`:`fit-content`,V(e)}get containerStyle(){return this.focus===`inactive`?V({"border-color":de,"border-right":`none`}):V({"border-color":ae,"z-index":`30`})}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}},fJ=class{mutators=[`closeDropdowns`,`openDropdown`];_currentDropdown=null;closeDropdowns(){this._currentDropdown=null}openDropdown(e){this._currentDropdown=e}get currentDropdown(){return this._currentDropdown}},pJ=class{content={};add(e){if(e in this.content)throw 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)}};function mJ(){let e=(0,t.useComponent)(),n=z(fJ);return(0,t.onWillUnmount)(()=>{e===n.currentDropdown&&n.closeDropdowns()}),{closeDropdowns:()=>n.closeDropdowns(),openDropdown:()=>{n.openDropdown(e)},get isActive(){return n.currentDropdown===e}}}let hJ=[[[`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`]]];B`
2251
2251
  .o-border-selector {
2252
2252
  padding: 4px;
2253
2253
  background-color: white;
@@ -2319,7 +2319,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2319
2319
  height: 25px !important;
2320
2320
  }
2321
2321
  }
2322
- `;var hJ=class 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:jV,Popover:ik};BORDER_POSITIONS=mJ;lineStyleButtonRef=(0,t.useRef)(`lineStyleButton`);borderStyles=Fr;state=(0,t.useState)({activeTool:void 0});toggleDropdownTool(e){let 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(){let e=this.lineStyleButtonRef.el;if(e===null)return{x:0,y:0,width:0,height:0};let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}},gJ=class 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:hJ};topBarToolStore;borderEditorButtonRef=(0,t.useRef)(`borderEditorButton`);state=(0,t.useState)({currentColor:Ue.color,currentStyle:Ue.style,currentPosition:void 0});setup(){this.topBarToolStore=pJ(),(0,t.onWillUpdateProps)(()=>{this.isActive||(this.state.currentPosition=void 0)})}get dropdownMaxHeight(){return this.env.model.getters.getSheetViewDimension().height}get borderEditorAnchorRect(){let 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(){this.state.currentPosition!==void 0&&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}})}},_J=class extends t.Component{static template=`o-spreadsheet-PaintFormatButton`;static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=z(nV)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}},vJ=class extends t.Component{static template=`o-spreadsheet-TableDropdownButton`;static components={TableStylesPopover:NU,ActionButton:AV};static props={class:{type:String,optional:!0}};topBarToolStore;state=(0,t.useState)({popoverProps:void 0});setup(){this.topBarToolStore=pJ()}onStylePicked(e){let t=this.env.model.getters.getActiveSheetId(),n={...this.tableConfig,styleId:e};GP(this.env,t,n).isSuccessful&&this.env.openSidePanel(`TableSidePanel`,{}),this.closePopover()}onClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps){this.closePopover();return}if(this.env.model.getters.getFirstTableInSelection()){this.topBarToolStore.closeDropdowns(),this.env.toggleSidePanel(`TableSidePanel`,{});return}let{left:t,bottom:n}=e.currentTarget.getBoundingClientRect();this.topBarToolStore.openDropdown(),this.state.popoverProps={anchorRect:{x:t,y:n,width:0,height:0},positioning:`bottom-left`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}get action(){return{name:e=>e.model.getters.getFirstTableInSelection()?E(`Edit table`):E(`Insert table`),icon:e=>e.model.getters.getFirstTableInSelection()?`o-spreadsheet-Icon.EDIT_TABLE`:`o-spreadsheet-Icon.PAINT_TABLE`}}get tableConfig(){return{...QA,numberOfHeaders:1,bandedRows:!0}}},yJ=class extends t.Component{static components={ColorPickerWidget:jV};static props={class:String,style:String,icon:String,title:String};static template=`o-spreadsheet-ColorEditor`;topBarToolStore;state=(0,t.useState)({isOpen:!1});setup(){this.topBarToolStore=pJ()}get currentColor(){return this.env.model.getters.getCurrentStyle()[this.props.style]||(this.props.style===`textColor`?`#000000`:`#ffffff`)}setColor(e){qP(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()}},bJ=class extends t.Component{static template=`o-spreadsheet-DropdownAction`;static components={ActionButton:AV,Popover:ik};static props={parentAction:Object,childActions:Array,class:String,childClass:String};topBarToolStore;actionRef=(0,t.useRef)(`actionRef`);setup(){this.topBarToolStore=pJ()}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`}}},xJ=class extends t.Component{static components={FontSizeEditor:MV};static props={class:String};static template=`o-spreadsheet-TopBarFontSizeEditor`;topBarToolStore;setup(){this.topBarToolStore=pJ()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Ve}setFontSize(e){qP(this.env,{fontSize:e})}onToggle(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}},SJ=class extends t.Component{static template=`o-spreadsheet-NumberFormatsTool`;static components={MenuPopover:ck,ActionButton:AV};static props={class:String};formatNumberMenuItemSpec=Rq;topBarToolStore;buttonRef=(0,t.useRef)(`buttonRef`);state=(0,t.useState)({anchorRect:{x:0,y:0,width:0,height:0},menuItems:[]});setup(){this.topBarToolStore=pJ()}toggleMenu(){if(this.isActive)this.topBarToolStore.closeDropdowns();else{let e=m(this.formatNumberMenuItemSpec);this.state.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.anchorRect=Yw(this.buttonRef.el),this.topBarToolStore.openDropdown()}}get isActive(){return this.topBarToolStore.isActive}};let CJ=new fJ;CJ.add(`edit`).addChild(`edit`,{component:AV,props:{action:DI,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`edit`,{component:AV,props:{action:OI,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`edit`,{component:_J,props:{class:`o-hoverable-button o-toolbar-button o-mobile-disabled`},sequence:3}).addChild(`edit`,{component:AV,props:{action:Kz,class:`o-hoverable-button o-toolbar-button`},sequence:4}).add(`numberFormat`).addChild(`numberFormat`,{component:AV,props:{action:tz,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`numberFormat`,{component:AV,props:{action:Tz,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`numberFormat`,{component:AV,props:{action:wz,class:`o-hoverable-button o-toolbar-button`},sequence:3}).addChild(`numberFormat`,{component:SJ,props:{class:`o-menu-item-button o-hoverable-button o-toolbar-button`},sequence:4}).add(`fontSize`).addChild(`fontSize`,{component:xJ,props:{class:`o-hoverable-button o-toolbar-button`},sequence:3}).add(`textStyle`).addChild(`textStyle`,{component:AV,props:{action:Ez,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`textStyle`,{component:AV,props:{action:Dz,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`textStyle`,{component:AV,props:{action:kz,class:`o-hoverable-button o-toolbar-button`},sequence:3}).addChild(`textStyle`,{component:yJ,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`,style:`textColor`,icon:`o-spreadsheet-Icon.TEXT_COLOR`,title:E(`Text Color`)},sequence:4}).add(`cellStyle`).addChild(`cellStyle`,{component:yJ,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`,style:`fillColor`,icon:`o-spreadsheet-Icon.FILL_COLOR`,title:E(`Fill Color`)},sequence:1}).addChild(`cellStyle`,{component:gJ,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:2}).addChild(`cellStyle`,{component:AV,props:{action:KI,class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:3}).add(`alignment`).addChild(`alignment`,{component:bJ,props:{parentAction:Mz,childActions:[Nz,Pz,Fz],class:`o-hoverable-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:1}).addChild(`alignment`,{component:bJ,props:{parentAction:Iz,childActions:[Lz,Rz,zz],class:`o-hoverable-button o-menu-item-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:2}).addChild(`alignment`,{component:bJ,props:{parentAction:Vz,childActions:[Hz,Uz,Wz],class:`o-hoverable-button o-menu-item-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:3}).add(`misc`).addChild(`misc`,{component:vJ,props:{class:`o-toolbar-button o-hoverable-button o-menu-item-button o-mobile-disabled`},sequence:1}).addChild(`misc`,{component:AV,props:{action:qR,class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:2}),B`
2322
+ `;var gJ=class 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:jV,Popover:ik};BORDER_POSITIONS=hJ;lineStyleButtonRef=(0,t.useRef)(`lineStyleButton`);borderStyles=Fr;state=(0,t.useState)({activeTool:void 0});toggleDropdownTool(e){let 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(){let e=this.lineStyleButtonRef.el;if(e===null)return{x:0,y:0,width:0,height:0};let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}},_J=class 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:gJ};topBarToolStore;borderEditorButtonRef=(0,t.useRef)(`borderEditorButton`);state=(0,t.useState)({currentColor:Ue.color,currentStyle:Ue.style,currentPosition:void 0});setup(){this.topBarToolStore=mJ(),(0,t.onWillUpdateProps)(()=>{this.isActive||(this.state.currentPosition=void 0)})}get dropdownMaxHeight(){return this.env.model.getters.getSheetViewDimension().height}get borderEditorAnchorRect(){let 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(){this.state.currentPosition!==void 0&&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}})}},vJ=class extends t.Component{static template=`o-spreadsheet-PaintFormatButton`;static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=z(nV)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}},yJ=class extends t.Component{static template=`o-spreadsheet-TableDropdownButton`;static components={TableStylesPopover:PU,ActionButton:AV};static props={class:{type:String,optional:!0}};topBarToolStore;state=(0,t.useState)({popoverProps:void 0});setup(){this.topBarToolStore=mJ()}onStylePicked(e){let t=this.env.model.getters.getActiveSheetId(),n={...this.tableConfig,styleId:e};GP(this.env,t,n).isSuccessful&&this.env.openSidePanel(`TableSidePanel`,{}),this.closePopover()}onClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps){this.closePopover();return}if(this.env.model.getters.getFirstTableInSelection()){this.topBarToolStore.closeDropdowns(),this.env.toggleSidePanel(`TableSidePanel`,{});return}let{left:t,bottom:n}=e.currentTarget.getBoundingClientRect();this.topBarToolStore.openDropdown(),this.state.popoverProps={anchorRect:{x:t,y:n,width:0,height:0},positioning:`bottom-left`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}get action(){return{name:e=>e.model.getters.getFirstTableInSelection()?E(`Edit table`):E(`Insert table`),icon:e=>e.model.getters.getFirstTableInSelection()?`o-spreadsheet-Icon.EDIT_TABLE`:`o-spreadsheet-Icon.PAINT_TABLE`}}get tableConfig(){return{...QA,numberOfHeaders:1,bandedRows:!0}}},bJ=class extends t.Component{static components={ColorPickerWidget:jV};static props={class:String,style:String,icon:String,title:String};static template=`o-spreadsheet-ColorEditor`;topBarToolStore;state=(0,t.useState)({isOpen:!1});setup(){this.topBarToolStore=mJ()}get currentColor(){return this.env.model.getters.getCurrentStyle()[this.props.style]||(this.props.style===`textColor`?`#000000`:`#ffffff`)}setColor(e){qP(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()}},xJ=class extends t.Component{static template=`o-spreadsheet-DropdownAction`;static components={ActionButton:AV,Popover:ik};static props={parentAction:Object,childActions:Array,class:String,childClass:String};topBarToolStore;actionRef=(0,t.useRef)(`actionRef`);setup(){this.topBarToolStore=mJ()}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`}}},SJ=class extends t.Component{static components={FontSizeEditor:MV};static props={class:String};static template=`o-spreadsheet-TopBarFontSizeEditor`;topBarToolStore;setup(){this.topBarToolStore=mJ()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Ve}setFontSize(e){qP(this.env,{fontSize:e})}onToggle(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}},CJ=class extends t.Component{static template=`o-spreadsheet-NumberFormatsTool`;static components={MenuPopover:ck,ActionButton:AV};static props={class:String};formatNumberMenuItemSpec=zq;topBarToolStore;buttonRef=(0,t.useRef)(`buttonRef`);state=(0,t.useState)({anchorRect:{x:0,y:0,width:0,height:0},menuItems:[]});setup(){this.topBarToolStore=mJ()}toggleMenu(){if(this.isActive)this.topBarToolStore.closeDropdowns();else{let e=m(this.formatNumberMenuItemSpec);this.state.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.anchorRect=Yw(this.buttonRef.el),this.topBarToolStore.openDropdown()}}get isActive(){return this.topBarToolStore.isActive}};let wJ=new pJ;wJ.add(`edit`).addChild(`edit`,{component:AV,props:{action:DI,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`edit`,{component:AV,props:{action:OI,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`edit`,{component:vJ,props:{class:`o-hoverable-button o-toolbar-button o-mobile-disabled`},sequence:3}).addChild(`edit`,{component:AV,props:{action:Kz,class:`o-hoverable-button o-toolbar-button`},sequence:4}).add(`numberFormat`).addChild(`numberFormat`,{component:AV,props:{action:tz,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`numberFormat`,{component:AV,props:{action:Tz,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`numberFormat`,{component:AV,props:{action:wz,class:`o-hoverable-button o-toolbar-button`},sequence:3}).addChild(`numberFormat`,{component:CJ,props:{class:`o-menu-item-button o-hoverable-button o-toolbar-button`},sequence:4}).add(`fontSize`).addChild(`fontSize`,{component:SJ,props:{class:`o-hoverable-button o-toolbar-button`},sequence:3}).add(`textStyle`).addChild(`textStyle`,{component:AV,props:{action:Ez,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`textStyle`,{component:AV,props:{action:Dz,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`textStyle`,{component:AV,props:{action:kz,class:`o-hoverable-button o-toolbar-button`},sequence:3}).addChild(`textStyle`,{component:bJ,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`,style:`textColor`,icon:`o-spreadsheet-Icon.TEXT_COLOR`,title:E(`Text Color`)},sequence:4}).add(`cellStyle`).addChild(`cellStyle`,{component:bJ,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`,style:`fillColor`,icon:`o-spreadsheet-Icon.FILL_COLOR`,title:E(`Fill Color`)},sequence:1}).addChild(`cellStyle`,{component:_J,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:2}).addChild(`cellStyle`,{component:AV,props:{action:KI,class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:3}).add(`alignment`).addChild(`alignment`,{component:xJ,props:{parentAction:Mz,childActions:[Nz,Pz,Fz],class:`o-hoverable-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:1}).addChild(`alignment`,{component:xJ,props:{parentAction:Iz,childActions:[Lz,Rz,zz],class:`o-hoverable-button o-menu-item-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:2}).addChild(`alignment`,{component:xJ,props:{parentAction:Vz,childActions:[Hz,Uz,Wz],class:`o-hoverable-button o-menu-item-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:3}).add(`misc`).addChild(`misc`,{component:yJ,props:{class:`o-toolbar-button o-hoverable-button o-menu-item-button o-mobile-disabled`},sequence:1}).addChild(`misc`,{component:AV,props:{action:qR,class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:2}),B`
2323
2323
  .o-topbar-divider {
2324
2324
  border-right: 1px solid ${de};
2325
2325
  width: 0;
@@ -2402,7 +2402,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2402
2402
  cursor: not-allowed;
2403
2403
  }
2404
2404
  }
2405
- `;var wJ=class extends t.Component{static template=`o-spreadsheet-TopBar`;static props={onClick:Function,dropdownMaxHeight:Number};static components={MenuPopover:ck,TopBarComposer:uJ,Popover:ik};toolsCategories=CJ.getCategories();state=(0,t.useState)({menuState:{isOpen:!1,anchorRect:null,menuItems:[]},invisibleToolsCategories:[],toolsPopoverState:{isOpen:!1}});isSelectingMenu=!1;openedEl=null;menus=[];toolbarMenuRegistry=CJ;formatNumberMenuItemSpec=Rq;isntToolbarMenu=!1;composerFocusStore;fingerprints;topBarToolStore;toolBarContainerRef=(0,t.useRef)(`toolBarContainer`);toolbarRef=(0,t.useRef)(`toolBar`);moreToolsContainerRef=(0,t.useRef)(`moreToolsContainer`);moreToolsButtonRef=(0,t.useRef)(`moreToolsButton`);spreadsheetRect=nk();setup(){this.composerFocusStore=z(Sf),this.fingerprints=z(RF),this.topBarToolStore=z(dJ),(0,t.useExternalListener)(window,`click`,this.onExternalClick),(0,t.onWillStart)(()=>this.updateCellState()),(0,t.onWillUpdateProps)(()=>this.updateCellState()),(0,t.useEffect)(()=>{this.state.toolsPopoverState.isOpen=!1,this.setVisibilityToolsGroups()},()=>[this.spreadsheetRect.width])}setVisibilityToolsGroups(){if(this.env.model.getters.isReadonly())return;let e=[],{x:t}=this.toolbarRef.el.getBoundingClientRect(),{x:n}=this.toolBarContainerRef.el.getBoundingClientRect();this.moreToolsContainerRef.el?.classList.remove(`d-none`);let r=this.moreToolsButtonRef.el?.getBoundingClientRect().width||0,i=Math.round(this.spreadsheetRect.width)-r-(t-n)-16,a=document.querySelectorAll(`.tool-container`),o=0;for(let t=0;t<a.length;t++){let n=a[t];n.classList.remove(`d-none`);let{width:r}=n.getBoundingClientRect();o+=r,o>i&&(n.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 Vq.getAllOrdered().filter(e=>!e.isVisible||e.isVisible(this.env))}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Ve}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=Yw(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=Bq.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){qP(this.env,{[e]:t}),this.onClick()}setFontSize(e){qP(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?Yw(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}};function TJ(){return new EJ(navigator.clipboard)}var EJ=class{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({"text/plain":this.getBlob(e,`text/plain`),"text/html":this.getBlob(e,`text/html`)})])}catch{}}else await this.writeText(e[`text/plain`]??``)}async writeText(e){try{this.clipboard?.writeText(e)}catch{}}async read(){let e;try{e=await navigator.permissions.query({name:`clipboard-read`})}catch{}if(this.clipboard?.read)try{let e=await this.clipboard.read(),t={};for(let n of e)for(let e of n.types){let r=await n.getType(e);Ml.includes(e)?t[e]=r:t[e]=await r.text()}return{status:`ok`,content:t}}catch{return{status:e?.state===`denied`?`permissionDenied`:`notImplemented`}}else return{status:`ok`,content:{"text/plain":await this.clipboard?.readText()}}}getClipboardItems(e){let t={};for(let n of Object.keys(e))t[n]=this.getBlob(e,n);return[new ClipboardItem(t)]}getBlob(e,t){let n=e[t];return n instanceof Blob||n instanceof File?n:new Blob([e[t]||``],{type:t})}};B`
2405
+ `;var TJ=class extends t.Component{static template=`o-spreadsheet-TopBar`;static props={onClick:Function,dropdownMaxHeight:Number};static components={MenuPopover:ck,TopBarComposer:dJ,Popover:ik};toolsCategories=wJ.getCategories();state=(0,t.useState)({menuState:{isOpen:!1,anchorRect:null,menuItems:[]},invisibleToolsCategories:[],toolsPopoverState:{isOpen:!1}});isSelectingMenu=!1;openedEl=null;menus=[];toolbarMenuRegistry=wJ;formatNumberMenuItemSpec=zq;isntToolbarMenu=!1;composerFocusStore;fingerprints;topBarToolStore;toolBarContainerRef=(0,t.useRef)(`toolBarContainer`);toolbarRef=(0,t.useRef)(`toolBar`);moreToolsContainerRef=(0,t.useRef)(`moreToolsContainer`);moreToolsButtonRef=(0,t.useRef)(`moreToolsButton`);spreadsheetRect=nk();setup(){this.composerFocusStore=z(Sf),this.fingerprints=z(RF),this.topBarToolStore=z(fJ),(0,t.useExternalListener)(window,`click`,this.onExternalClick),(0,t.onWillStart)(()=>this.updateCellState()),(0,t.onWillUpdateProps)(()=>this.updateCellState()),(0,t.useEffect)(()=>{this.state.toolsPopoverState.isOpen=!1,this.setVisibilityToolsGroups()},()=>[this.spreadsheetRect.width])}setVisibilityToolsGroups(){if(this.env.model.getters.isReadonly())return;let e=[],{x:t}=this.toolbarRef.el.getBoundingClientRect(),{x:n}=this.toolBarContainerRef.el.getBoundingClientRect();this.moreToolsContainerRef.el?.classList.remove(`d-none`);let r=this.moreToolsButtonRef.el?.getBoundingClientRect().width||0,i=Math.round(this.spreadsheetRect.width)-r-(t-n)-16,a=document.querySelectorAll(`.tool-container`),o=0;for(let t=0;t<a.length;t++){let n=a[t];n.classList.remove(`d-none`);let{width:r}=n.getBoundingClientRect();o+=r,o>i&&(n.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 Hq.getAllOrdered().filter(e=>!e.isVisible||e.isVisible(this.env))}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Ve}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=Yw(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=Vq.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){qP(this.env,{[e]:t}),this.onClick()}setFontSize(e){qP(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?Yw(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}};function EJ(){return new DJ(navigator.clipboard)}var DJ=class{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({"text/plain":this.getBlob(e,`text/plain`),"text/html":this.getBlob(e,`text/html`)})])}catch{}}else await this.writeText(e[`text/plain`]??``)}async writeText(e){try{this.clipboard?.writeText(e)}catch{}}async read(){let e;try{e=await navigator.permissions.query({name:`clipboard-read`})}catch{}if(this.clipboard?.read)try{let e=await this.clipboard.read(),t={};for(let n of e)for(let e of n.types){let r=await n.getType(e);Ml.includes(e)?t[e]=r:t[e]=await r.text()}return{status:`ok`,content:t}}catch{return{status:e?.state===`denied`?`permissionDenied`:`notImplemented`}}else return{status:`ok`,content:{"text/plain":await this.clipboard?.readText()}}}getClipboardItems(e){let t={};for(let n of Object.keys(e))t[n]=this.getBlob(e,n);return[new ClipboardItem(t)]}getBlob(e,t){let n=e[t];return n instanceof Blob||n instanceof File?n:new Blob([e[t]||``],{type:t})}};B`
2406
2406
  .o-spreadsheet {
2407
2407
  position: relative;
2408
2408
  display: grid;
@@ -2634,12 +2634,12 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2634
2634
  .o-spreadsheet-bottombar-wrapper {
2635
2635
  z-index: ${16};
2636
2636
  }
2637
- `;var DJ=class 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:wJ,Grid:WU,BottomBar:Qq,SmallBottomBar:lJ,SidePanels:sJ,SpreadsheetDashboard:eJ,HeaderGroupContainer:iJ,FullScreenFigure:qU};sidePanel;spreadsheetRef=(0,t.useRef)(`spreadsheet`);spreadsheetRect=nk();_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){let e={};return this.env.isDashboard()?e[`grid-template-rows`]=`auto`:e[`grid-template-rows`]=`min-content auto min-content`,e[`grid-template-columns`]=`auto ${this.sidePanel.mainPanel?`${this.sidePanel.totalPanelSize||350}px`:`auto`}`,V(e)}setup(){if(!(`isSmall`in this.env)){let e=aJ();(0,t.useSubEnv)({get isSmall(){return e.isSmall}})}let e=pf();e.inject(vf,this.model);let n=this.env;e.get(zU).setSmallThreshhold(()=>n.isSmall),this.notificationStore=z(qk),this.composerFocusStore=z(Sf),this.sidePanel=z(BU);let r=this.model.config.external.fileStore;(0,t.useSubEnv)({model:this.model,imageProvider:r?new Uq(r):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||TJ(),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,n)=>this.notificationStore.askConfirmation(e,t,n),raiseError:(e,t)=>this.notificationStore.raiseError(e,t),isMobile:pT}),this.notificationStore.updateNotificationCallbacks({...this.props}),(0,t.useEffect)(()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()}),(0,t.useExternalListener)(window,`resize`,()=>this.render(!0)),(0,t.useExternalListener)(document.body,`wheel`,()=>{}),this.bindModelEvents(),(0,t.onWillUpdateProps)(e=>{if(e.model!==this.props.model)throw 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})});let i=jt(this.render.bind(this,!0));(0,t.onMounted)(()=>{this.checkViewportSize(),e.on(`store-updated`,this,i),a.observe(this.spreadsheetRef.el)}),(0,t.onWillUnmount)(()=>{this.unbindModelEvents(),e.off(`store-updated`,this),a.disconnect(),Ff()}),(0,t.onPatched)(()=>{this.checkViewportSize()});let a=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(){let{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:E(`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(){let e=21*this.rowLayers.length,t=21*this.colLayers.length;return V({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`})}get rowLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`ROW`)}get colLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`COL`)}getGridSize(){let e=this.spreadsheetRef.el;if(!e)return{width:0,height:0};let t=t=>e.querySelector(t)?.getBoundingClientRect().height||0,n=t=>e.querySelector(t)?.getBoundingClientRect().width||0,r=e.getBoundingClientRect(),i=t(`.o-spreadsheet-topbar-wrapper`),a=t(`.o-spreadsheet-bottombar-wrapper`),o=t(`.o-column-groups`),s=n(`.o-grid`);return{width:Math.max(s-15,0),height:Math.max(r.height-i-a-o-15,0)}}},OJ=class{transportService;constructor(e){this.transportService=e}async sendMessage(e){(e.type===`CLIENT_JOINED`||e.type===`CLIENT_LEFT`||e.type===`CLIENT_MOVED`)&&await this.transportService.sendMessage(e)}onNewMessage(e,t){this.transportService.onNewMessage(e,t)}leave(e){this.transportService.leave(e)}};function kJ(e){return yq.get(e.type)(e)}var AJ=class e{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){let t=this.operations.find(t=>t.id===e);if(!t)throw Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(let n of this.operations){if(n.id===e)return e;if(n.id===t)return t}throw Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find(t=>t.id===e)}prepend(e){let t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map(e=>e.transformed(t))]}insert(e,t){let n=this.buildTransformation.with(e.data),{before:r,operation:i,after:a}=this.locateOperation(t);this.operations=[...r,i,e,...a.map(e=>e.transformed(n))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(t){let{after:n}=this.locateOperation(t);return new e(this.buildTransformation,n)}transform(e){this.operations=this.operations.map(t=>t.transformed(e))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){let{before:t,operation:n}=this.locateOperation(e);this.operations=t.concat([n])}locateOperation(e){let t=this.operations.findIndex(t=>t.id===e);if(t===-1)throw Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}},jJ=class{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new MJ(this.id,Nt(()=>e(this.data)))}},MJ=class e{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(t){return new e(this.id,this.lazyData.map(t))}},NJ=class e{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(t){function*n(e,t){for(let n of e)if(yield n,n.operation.id===t)return}return new e(n(this.operations,t))}stopBefore(t){function*n(e,t){for(let n of e){if(n.operation.id===t)return;yield n}}return new e(n(this.operations,t))}startAfter(t){function*n(e,t){let n=!0;for(let r of e)n||(yield r),r.operation.id===t&&(n=!1)}return new e(n(this.operations,t))}},PJ=class{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 NJ(_t(this._execution(e),this._execution(e)))}revertedExecution(e){return new NJ(_t(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){let n=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),n&&this.insertPrevious(e,t,n)}insertOperationAfter(e,t,n){e.insert(t,n),this.updateNextWith(e,t,n),this.insertPrevious(e,t,n)}undo(e,t){let n=this.buildTransformation.without(t.data),r=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);let i=e.fork(t.id);r&&this.branchingOperationIds.set(i,r),this.insertBranchAfter(e,i),this.transform(i,n)}redo(e){let t=this.nextBranch(e);if(!t)return;let n=this.nextBranch(t);this.removeBranchFromTree(t);let r=this.branchingOperationIds.get(t);r?this.branchingOperationIds.set(e,r):this.branchingOperationIds.delete(e),n&&this.rebaseUp(n)}drop(e){for(let t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(let n of this.revertedExecution(e))if(n.operation.id===t)return n;throw Error(`Operation ${t} not found`)}rebaseUp(e){let{previousBranch:t,branchingOperation:n}=this.findPreviousBranchingOperation(e);if(!t||!n)return;let r=this.buildTransformation.without(n.data),i=t.fork(n.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(r);let a=this.nextBranch(i);a&&this.rebaseUp(a)}removeBranchFromTree(e){let t=this.branches.findIndex(t=>t===e);this.branches.splice(t,1)}insertBranchAfter(e,t){let n=this.branches.findIndex(t=>t===e);this.branches.splice(n+1,0,t)}updateNextWith(e,t,n){let r=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(!(!r||!i))if(e.getFirstOperationAmong(n,r)===r){let a=this.addToNextBranch(e,i,r,t,n);this.updateNextWith(i,a,n)}else{let e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,n,r,i){let a=r;return i===n?(a=this.getTransformedOperation(e,n,r),t.prepend(a)):t.contains(i)?(a=this.getTransformedOperation(e,n,r),t.insert(a,i)):t.append(r),a}getTransformedOperation(e,t,n){let r=e.getOperation(t),i=this.buildTransformation.without(r.data);return n.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);let n=this.nextBranch(e);n&&this.transform(n,t)}insertPrevious(e,t,n){let{previousBranch:r,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!r||!i)return;let a=this.buildTransformation.with(i.data),o=e.fork(n);o.transform(a),r.cutAfter(n),r.appendBranch(o);let s=t.transformed(a);this.insertPrevious(r,s,n)}findPreviousBranchingOperation(e){let t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};let n=this.branchingOperationIds.get(t);return n?{previousBranch:t,branchingOperation:t.getOperation(n)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){let t=this.branches.findIndex(t=>t===e);if(t!==-1)return this.branches[t+1]}previousBranch(e){let t=this.branches.findIndex(t=>t===e);if(t!==-1)return this.branches[t-1]}*_revertedExecution(e){let t=this.branchingOperationIds.get(e),n=!!t,r=e.getOperations();for(let i=r.length-1;i>=0;i--){let a=r[i];a.id===t&&(n=!1),n||(yield{operation:a,branch:e,isCancelled:!this.shouldExecute(e,a)})}let i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(let t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){let t=this.nextBranch(e);yield*t?this._execution(t):[];return}if(!this.branchingOperationIds.get(e)){let t=this.nextBranch(e);yield*t?this._execution(t):[]}}},FJ=class{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 AJ(this.buildTransformation),this.tree=new PJ(this.buildTransformation,this.HEAD_BRANCH);let t=e.initialOperationId,n=new jJ(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,n),this.HEAD_OPERATION=n}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){let n=new jJ(e,t),r=this.tree.getLastBranch();this.tree.insertOperationLast(r,n),this.HEAD_BRANCH=r,this.HEAD_OPERATION=n}insert(e,t,n){let r=new jJ(e,t);this.revertTo(n),this.tree.insertOperationAfter(this.HEAD_BRANCH,r,n),this.fastForward()}undo(e,t,n){let{branch:r,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(r,i),this.fastForward(),this.insert(t,this.buildEmpty(t),n)}redo(e,t,n){let{branch:r}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(r),this.fastForward(),this.insert(t,this.buildEmpty(t),n)}rebase(e){let t=this.get(e),n=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);let r=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,r);for(let{operation:e}of n)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){let t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){let t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(let{next:t,operation:n,isCancelled:r}of e)r||this.revertOperation(n.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){let e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(let{operation:t,branch:n,isCancelled:r}of e)r||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=n}};function IJ(e){return new FJ({initialOperationId:e.initialRevisionId,applyOperation:t=>{let n=t.commands.slice(),{changes:r}=e.recordChanges(()=>{for(let t of n)e.dispatch(t)});t.setChanges(r)},revertOperation:e=>LJ([e]),buildEmpty:e=>new iK(e,`empty`,[]),buildTransformation:{with:e=>t=>new iK(t.id,t.clientId,JG(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new iK(t.id,t.clientId,JG(t.commands,e.commands.map(kJ).flat()),t.rootCommand,void 0,t.timestamp)}})}function LJ(e){for(let t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){let n=t.changes[e];RJ(n)}}function RJ(e){let t=e.target,n=e.key,r=e.before;r===void 0?delete t[n]:t[n]=r}var zJ=class{observers=new Map;defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||=this.defaultSubscription}observe(e,t){this.observers.set(e,{owner:e,callbacks:t})}capture(e,t){if(this.observers.get(e))throw 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))}},BJ=class{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new zJ,this.anchor={cell:{col:0,row:0},zone:R({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,n){this.stream.capture(e,n),this.anchor=t}registerAsDefault(e,t,n){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,n),this.defaultAnchor=t,this.capture(e,t,n)}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,n){let r=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(r,e.zone)},this.processEvent({options:n,anchor:e,mode:t})}selectZone(e,t={scrollIntoView:!0}){return this.modifyAnchor(e,`overrideSelection`,t)}selectCell(e,t){let n=R({col:e,row:t});return this.selectZone({zone:n,cell:{col:e,row:t}},{scrollIntoView:!0})}moveAnchorCell(e,t=1){if(t!==`end`&&t<=0)return new kr(`InvalidSelectionStep`);let{col:n,row:r}=this.getNextAvailablePosition(e,t);return this.selectCell(n,r)}setAnchorCorner(e,t){let n=this.getters.getActiveSheetId(),{col:r,row:i}=this.anchor.cell,a={left:Math.min(r,e),top:Math.min(i,t),right:Math.max(r,e),bottom:Math.max(i,t)},o={zone:this.getters.expandZone(n,a),cell:{col:r,row:i}};return this.processEvent({mode:`updateAnchor`,anchor:o,options:{scrollIntoView:!1}})}addCellToSelection(e,t){let n=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:n,col:e,row:t}));let r=this.getters.expandZone(n,R({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:r,cell:{col:e,row:t}},mode:`newAnchor`})}resizeAnchorZone(e,t=1){if(t!==`end`&&t<=0)return new kr(`InvalidSelectionStep`);let n=this.getters.getActiveSheetId(),r=this.anchor,{col:i,row:a}=r.cell,{left:o,right:s,top:c,bottom:l}=r.zone,u=this.getStartingPosition(e),[d,f]=this.deltaToTarget(u,e,t);if(d===0&&f===0)return kr.Success;let p=r.zone,m=e=>{e=Js(e);let{left:t,right:r,top:i,bottom:a}=this.getters.expandZone(n,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(n)-1,r),top:Math.max(0,i),bottom:Math.min(this.getters.getNumberRows(n)-1,a)}},{cell:h,zone:g}=this.getReferenceAnchor(),{col:_,row:v}=h,y=0;for(;p!==null;){if(y++,d<0){let e=this.getNextAvailableCol(d,s-(y-1),v);p=g.right<=s-y?m({top:c,left:o,bottom:l,right:e}):null}if(d>0){let e=this.getNextAvailableCol(d,o+(y-1),v);p=o+y<=g.left?m({top:c,left:e,bottom:l,right:s}):null}if(f<0){let e=this.getNextAvailableRow(f,_,l-(y-1));p=g.bottom<=l-y?m({top:c,left:o,bottom:e,right:s}):null}if(f>0){let e=this.getNextAvailableRow(f,_,c+(y-1));p=c+y<=g.top?m({top:e,left:o,bottom:l,right:s}):null}if(p&&=Js(p),p&&!Rs(p,r.zone))return this.processEvent({options:{scrollIntoView:!0},mode:`updateAnchor`,anchor:{zone:p,cell:{col:i,row:a}}})}p=m(Fs({top:a,bottom:a,left:i,right:i},Js({top:this.getNextAvailableRow(f,_,c),left:this.getNextAvailableCol(d,o,v),bottom:this.getNextAvailableRow(f,_,l),right:this.getNextAvailableCol(d,s,v)})));let ee={zone:p,cell:{col:i,row:a}};return this.processEvent({anchor:ee,mode:`updateAnchor`,options:{scrollIntoView:!0}})}selectColumn(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberRows(n)-1,i={left:e,right:e,top:0,bottom:r},a=this.getters.findFirstVisibleColRowIndex(n,`ROW`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=e,s=a;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=Fs(i,{left:o,right:o,top:a,bottom:r});break}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:o,row:s}},mode:t})}selectRow(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberCols(n)-1,i={top:e,bottom:e,left:0,right:r},a=this.getters.findFirstVisibleColRowIndex(n,`COL`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=a,s=e;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=Fs(i,{left:a,right:r,top:s,bottom:s});break}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:o,row:s}},mode:t})}loopSelection(){let e=this.getters.getActiveSheetId(),t=this.anchor;if(Rs(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:R(t.cell)},`updateAnchor`,{scrollIntoView:!1});let n=this.getters.getContiguousZone(e,t.zone);return w(n,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:n},`updateAnchor`,{scrollIntoView:!1})}selectTableAroundSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getContiguousZone(e,this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:t},`updateAnchor`,{scrollIntoView:!1})}selectAll(){let 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){let t={...e,previousAnchor:b(this.anchor)},n=this.checkEventAnchorZone(t);return n===`Success`?(this.anchor=t.anchor,this.stream.send(t),kr.Success):new kr(n)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){let{cell:t,zone:n}=e;if(!Vs(t.col,t.row,n))return`InvalidAnchorZone`;let{left:r,right:i,top:a,bottom:o}=n,s=this.getters.getActiveSheetId(),c=this.getters.findVisibleHeader(s,`COL`,r,i);return this.getters.findVisibleHeader(s,`ROW`,a,o)===void 0||c===void 0?`SelectionOutOfBound`:`Success`}checkAnchorZoneOrThrow(e){if(this.checkAnchorZone(e)===`InvalidAnchorZone`)throw Error(`The provided anchor is invalid. The cell must be part of the zone.`)}getNextAvailablePosition(e,t=1){let{col:n,row:r}=this.anchor.cell,i=this.deltaToTarget({col:n,row:r},e,t);return{col:this.getNextAvailableCol(i[0],n,r),row:this.getNextAvailableRow(i[1],n,r)}}getNextAvailableCol(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`COL`,t,i,e=>this.getters.isInSameMerge(r,t,n,e,n))}getNextAvailableRow(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`ROW`,n,i,e=>this.getters.isInSameMerge(r,t,n,t,e))}getNextAvailableHeader(e,t,n,r,i){let a=this.getters.getActiveSheetId();if(e===0)return n;let o=Math.sign(e),s=n+e;for(;i(s);)s+=o;for(;this.getters.isHeaderHidden(a,t,s);)s+=o;return s<0||s>this.getters.getNumberHeaders(a,t)-1?this.getters.isHeaderHidden(a,t,n)?this.getNextAvailableHeader(-o,t,n,r,i):n:s}getReferenceAnchor(){let e=this.getters.getActiveSheetId(),t=this.anchor,{left:n,right:r,top:i,bottom:a}=t.zone,{col:o,row:s}=t.cell,c=this.getters.isColHidden(e,o)&&this.getters.findVisibleHeader(e,`COL`,n,r)||o,l=this.getters.isRowHidden(e,s)&&this.getters.findVisibleHeader(e,`ROW`,i,a)||s,u=this.getters.expandZone(e,{left:c,right:c,top:l,bottom:l});return{cell:{col:c,row:l},zone:u}}deltaToTarget(e,t,n){switch(t){case`up`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,-1)-e.row]:[0,-n];case`down`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,1)-e.row]:[0,n];case`left`:return n===`end`?[this.getEndOfCluster(e,`cols`,-1)-e.col,0]:[-n,0];case`right`:return n===`end`?[this.getEndOfCluster(e,`cols`,1)-e.col,0]:[n,0]}}getStartingPosition(e){let{col:t,row:n}=this.getPosition(),r=this.anchor.zone;switch(e){case`down`:case`up`:n=n===r.top?r.bottom:r.top;break;case`left`:case`right`:t=t===r.right?r.left:r.right;break}return{col:t,row:n}}getEndOfCluster(e,t,n){let r=this.getters.getActiveSheetId(),i=e,a=this.getNextCellPosition(e,t,n),o=!this.isCellSkippableInCluster({...i,sheetId:r})&&!this.isCellSkippableInCluster({...a,sheetId:r})?`endOfCluster`:`nextCluster`;for(;;){let e=this.getNextCellPosition(i,t,n);if(i.col===e.col&&i.row===e.row)break;let a=this.isCellSkippableInCluster({...e,sheetId:r});if(o===`endOfCluster`&&a)break;if(o===`nextCluster`&&!a){i=e;break}i=e}return t===`cols`?i.col:i.row}getNextCellPosition(e,t,n){let r=t===`cols`?`col`:`row`,i={...e};return i[r]=t===`cols`?this.getNextAvailableCol(n,i.col,i.row):this.getNextAvailableRow(n,i.col,i.row),{col:i.col,row:i.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){let t=this.getters.getMainCellPosition(e),n=this.getters.getEvaluatedCell(t);return n.type===`empty`||n.type===`text`&&n.value===``}};function VJ(e){if(typeof e==`string`)return{};if(typeof e==`number`)return[];throw Error(`Cannot create new node`)}var HJ=class{changes;commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){let t=e.pop(),n=e[0],r=e.at(-1),i=e.length-2;for(let t=1;t<=i;t++){let r=e[t];if(n[r]===void 0){let i=e[t+1];n[r]=VJ(i)}n=n[r]}n[r]!==t&&(this.changes?.push({key:r,target:n,before:n[r]}),t===void 0?delete n[r]:n[r]=t)}};let UJ=17781237,WJ=17781238,GJ=88853993,KJ=88853994;function qJ(e,t,n){let r=[[`xmlns:r`,Jf],[`xmlns:a`,Wf],[`xmlns:c`,Gf]],i=JJ({backgroundColor:e.data.backgroundColor,line:{color:`000000`}}),a=J``;if(e.data.title?.text){let t=G(jC(e.data.backgroundColor)),n=e.data.title.fontSize??16;a=J`
2637
+ `;var OJ=class 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:TJ,Grid:GU,BottomBar:$q,SmallBottomBar:uJ,SidePanels:cJ,SpreadsheetDashboard:tJ,HeaderGroupContainer:aJ,FullScreenFigure:JU};sidePanel;spreadsheetRef=(0,t.useRef)(`spreadsheet`);spreadsheetRect=nk();_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){let e={};return this.env.isDashboard()?e[`grid-template-rows`]=`auto`:e[`grid-template-rows`]=`min-content auto min-content`,e[`grid-template-columns`]=`auto ${this.sidePanel.mainPanel?`${this.sidePanel.totalPanelSize||350}px`:`auto`}`,V(e)}setup(){if(!(`isSmall`in this.env)){let e=oJ();(0,t.useSubEnv)({get isSmall(){return e.isSmall}})}let e=pf();e.inject(vf,this.model);let n=this.env;e.get(BU).setSmallThreshhold(()=>n.isSmall),this.notificationStore=z(qk),this.composerFocusStore=z(Sf),this.sidePanel=z(VU);let r=this.model.config.external.fileStore;(0,t.useSubEnv)({model:this.model,imageProvider:r?new Wq(r):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||EJ(),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,n)=>this.notificationStore.askConfirmation(e,t,n),raiseError:(e,t)=>this.notificationStore.raiseError(e,t),isMobile:pT}),this.notificationStore.updateNotificationCallbacks({...this.props}),(0,t.useEffect)(()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()}),(0,t.useExternalListener)(window,`resize`,()=>this.render(!0)),(0,t.useExternalListener)(document.body,`wheel`,()=>{}),this.bindModelEvents(),(0,t.onWillUpdateProps)(e=>{if(e.model!==this.props.model)throw 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})});let i=jt(this.render.bind(this,!0));(0,t.onMounted)(()=>{this.checkViewportSize(),e.on(`store-updated`,this,i),a.observe(this.spreadsheetRef.el)}),(0,t.onWillUnmount)(()=>{this.unbindModelEvents(),e.off(`store-updated`,this),a.disconnect(),Ff()}),(0,t.onPatched)(()=>{this.checkViewportSize()});let a=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(){let{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:E(`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(){let e=21*this.rowLayers.length,t=21*this.colLayers.length;return V({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`})}get rowLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`ROW`)}get colLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`COL`)}getGridSize(){let e=this.spreadsheetRef.el;if(!e)return{width:0,height:0};let t=t=>e.querySelector(t)?.getBoundingClientRect().height||0,n=t=>e.querySelector(t)?.getBoundingClientRect().width||0,r=e.getBoundingClientRect(),i=t(`.o-spreadsheet-topbar-wrapper`),a=t(`.o-spreadsheet-bottombar-wrapper`),o=t(`.o-column-groups`),s=n(`.o-grid`);return{width:Math.max(s-15,0),height:Math.max(r.height-i-a-o-15,0)}}},kJ=class{transportService;constructor(e){this.transportService=e}async sendMessage(e){(e.type===`CLIENT_JOINED`||e.type===`CLIENT_LEFT`||e.type===`CLIENT_MOVED`)&&await this.transportService.sendMessage(e)}onNewMessage(e,t){this.transportService.onNewMessage(e,t)}leave(e){this.transportService.leave(e)}};function AJ(e){return bq.get(e.type)(e)}var jJ=class e{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){let t=this.operations.find(t=>t.id===e);if(!t)throw Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(let n of this.operations){if(n.id===e)return e;if(n.id===t)return t}throw Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find(t=>t.id===e)}prepend(e){let t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map(e=>e.transformed(t))]}insert(e,t){let n=this.buildTransformation.with(e.data),{before:r,operation:i,after:a}=this.locateOperation(t);this.operations=[...r,i,e,...a.map(e=>e.transformed(n))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(t){let{after:n}=this.locateOperation(t);return new e(this.buildTransformation,n)}transform(e){this.operations=this.operations.map(t=>t.transformed(e))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){let{before:t,operation:n}=this.locateOperation(e);this.operations=t.concat([n])}locateOperation(e){let t=this.operations.findIndex(t=>t.id===e);if(t===-1)throw Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}},MJ=class{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new NJ(this.id,Nt(()=>e(this.data)))}},NJ=class e{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(t){return new e(this.id,this.lazyData.map(t))}},PJ=class e{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(t){function*n(e,t){for(let n of e)if(yield n,n.operation.id===t)return}return new e(n(this.operations,t))}stopBefore(t){function*n(e,t){for(let n of e){if(n.operation.id===t)return;yield n}}return new e(n(this.operations,t))}startAfter(t){function*n(e,t){let n=!0;for(let r of e)n||(yield r),r.operation.id===t&&(n=!1)}return new e(n(this.operations,t))}},FJ=class{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 PJ(_t(this._execution(e),this._execution(e)))}revertedExecution(e){return new PJ(_t(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){let n=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),n&&this.insertPrevious(e,t,n)}insertOperationAfter(e,t,n){e.insert(t,n),this.updateNextWith(e,t,n),this.insertPrevious(e,t,n)}undo(e,t){let n=this.buildTransformation.without(t.data),r=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);let i=e.fork(t.id);r&&this.branchingOperationIds.set(i,r),this.insertBranchAfter(e,i),this.transform(i,n)}redo(e){let t=this.nextBranch(e);if(!t)return;let n=this.nextBranch(t);this.removeBranchFromTree(t);let r=this.branchingOperationIds.get(t);r?this.branchingOperationIds.set(e,r):this.branchingOperationIds.delete(e),n&&this.rebaseUp(n)}drop(e){for(let t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(let n of this.revertedExecution(e))if(n.operation.id===t)return n;throw Error(`Operation ${t} not found`)}rebaseUp(e){let{previousBranch:t,branchingOperation:n}=this.findPreviousBranchingOperation(e);if(!t||!n)return;let r=this.buildTransformation.without(n.data),i=t.fork(n.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(r);let a=this.nextBranch(i);a&&this.rebaseUp(a)}removeBranchFromTree(e){let t=this.branches.findIndex(t=>t===e);this.branches.splice(t,1)}insertBranchAfter(e,t){let n=this.branches.findIndex(t=>t===e);this.branches.splice(n+1,0,t)}updateNextWith(e,t,n){let r=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(!(!r||!i))if(e.getFirstOperationAmong(n,r)===r){let a=this.addToNextBranch(e,i,r,t,n);this.updateNextWith(i,a,n)}else{let e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,n,r,i){let a=r;return i===n?(a=this.getTransformedOperation(e,n,r),t.prepend(a)):t.contains(i)?(a=this.getTransformedOperation(e,n,r),t.insert(a,i)):t.append(r),a}getTransformedOperation(e,t,n){let r=e.getOperation(t),i=this.buildTransformation.without(r.data);return n.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);let n=this.nextBranch(e);n&&this.transform(n,t)}insertPrevious(e,t,n){let{previousBranch:r,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!r||!i)return;let a=this.buildTransformation.with(i.data),o=e.fork(n);o.transform(a),r.cutAfter(n),r.appendBranch(o);let s=t.transformed(a);this.insertPrevious(r,s,n)}findPreviousBranchingOperation(e){let t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};let n=this.branchingOperationIds.get(t);return n?{previousBranch:t,branchingOperation:t.getOperation(n)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){let t=this.branches.findIndex(t=>t===e);if(t!==-1)return this.branches[t+1]}previousBranch(e){let t=this.branches.findIndex(t=>t===e);if(t!==-1)return this.branches[t-1]}*_revertedExecution(e){let t=this.branchingOperationIds.get(e),n=!!t,r=e.getOperations();for(let i=r.length-1;i>=0;i--){let a=r[i];a.id===t&&(n=!1),n||(yield{operation:a,branch:e,isCancelled:!this.shouldExecute(e,a)})}let i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(let t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){let t=this.nextBranch(e);yield*t?this._execution(t):[];return}if(!this.branchingOperationIds.get(e)){let t=this.nextBranch(e);yield*t?this._execution(t):[]}}},IJ=class{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 jJ(this.buildTransformation),this.tree=new FJ(this.buildTransformation,this.HEAD_BRANCH);let t=e.initialOperationId,n=new MJ(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,n),this.HEAD_OPERATION=n}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){let n=new MJ(e,t),r=this.tree.getLastBranch();this.tree.insertOperationLast(r,n),this.HEAD_BRANCH=r,this.HEAD_OPERATION=n}insert(e,t,n){let r=new MJ(e,t);this.revertTo(n),this.tree.insertOperationAfter(this.HEAD_BRANCH,r,n),this.fastForward()}undo(e,t,n){let{branch:r,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(r,i),this.fastForward(),this.insert(t,this.buildEmpty(t),n)}redo(e,t,n){let{branch:r}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(r),this.fastForward(),this.insert(t,this.buildEmpty(t),n)}rebase(e){let t=this.get(e),n=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);let r=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,r);for(let{operation:e}of n)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){let t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){let t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(let{next:t,operation:n,isCancelled:r}of e)r||this.revertOperation(n.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){let e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(let{operation:t,branch:n,isCancelled:r}of e)r||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=n}};function LJ(e){return new IJ({initialOperationId:e.initialRevisionId,applyOperation:t=>{let n=t.commands.slice(),{changes:r}=e.recordChanges(()=>{for(let t of n)e.dispatch(t)});t.setChanges(r)},revertOperation:e=>RJ([e]),buildEmpty:e=>new aK(e,`empty`,[]),buildTransformation:{with:e=>t=>new aK(t.id,t.clientId,YG(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new aK(t.id,t.clientId,YG(t.commands,e.commands.map(AJ).flat()),t.rootCommand,void 0,t.timestamp)}})}function RJ(e){for(let t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){let n=t.changes[e];zJ(n)}}function zJ(e){let t=e.target,n=e.key,r=e.before;r===void 0?delete t[n]:t[n]=r}var BJ=class{observers=new Map;defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||=this.defaultSubscription}observe(e,t){this.observers.set(e,{owner:e,callbacks:t})}capture(e,t){if(this.observers.get(e))throw 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))}},VJ=class{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new BJ,this.anchor={cell:{col:0,row:0},zone:R({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,n){this.stream.capture(e,n),this.anchor=t}registerAsDefault(e,t,n){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,n),this.defaultAnchor=t,this.capture(e,t,n)}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,n){let r=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(r,e.zone)},this.processEvent({options:n,anchor:e,mode:t})}selectZone(e,t={scrollIntoView:!0}){return this.modifyAnchor(e,`overrideSelection`,t)}selectCell(e,t){let n=R({col:e,row:t});return this.selectZone({zone:n,cell:{col:e,row:t}},{scrollIntoView:!0})}moveAnchorCell(e,t=1){if(t!==`end`&&t<=0)return new kr(`InvalidSelectionStep`);let{col:n,row:r}=this.getNextAvailablePosition(e,t);return this.selectCell(n,r)}setAnchorCorner(e,t){let n=this.getters.getActiveSheetId(),{col:r,row:i}=this.anchor.cell,a={left:Math.min(r,e),top:Math.min(i,t),right:Math.max(r,e),bottom:Math.max(i,t)},o={zone:this.getters.expandZone(n,a),cell:{col:r,row:i}};return this.processEvent({mode:`updateAnchor`,anchor:o,options:{scrollIntoView:!1}})}addCellToSelection(e,t){let n=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:n,col:e,row:t}));let r=this.getters.expandZone(n,R({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:r,cell:{col:e,row:t}},mode:`newAnchor`})}resizeAnchorZone(e,t=1){if(t!==`end`&&t<=0)return new kr(`InvalidSelectionStep`);let n=this.getters.getActiveSheetId(),r=this.anchor,{col:i,row:a}=r.cell,{left:o,right:s,top:c,bottom:l}=r.zone,u=this.getStartingPosition(e),[d,f]=this.deltaToTarget(u,e,t);if(d===0&&f===0)return kr.Success;let p=r.zone,m=e=>{e=Js(e);let{left:t,right:r,top:i,bottom:a}=this.getters.expandZone(n,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(n)-1,r),top:Math.max(0,i),bottom:Math.min(this.getters.getNumberRows(n)-1,a)}},{cell:h,zone:g}=this.getReferenceAnchor(),{col:_,row:v}=h,y=0;for(;p!==null;){if(y++,d<0){let e=this.getNextAvailableCol(d,s-(y-1),v);p=g.right<=s-y?m({top:c,left:o,bottom:l,right:e}):null}if(d>0){let e=this.getNextAvailableCol(d,o+(y-1),v);p=o+y<=g.left?m({top:c,left:e,bottom:l,right:s}):null}if(f<0){let e=this.getNextAvailableRow(f,_,l-(y-1));p=g.bottom<=l-y?m({top:c,left:o,bottom:e,right:s}):null}if(f>0){let e=this.getNextAvailableRow(f,_,c+(y-1));p=c+y<=g.top?m({top:e,left:o,bottom:l,right:s}):null}if(p&&=Js(p),p&&!Rs(p,r.zone))return this.processEvent({options:{scrollIntoView:!0},mode:`updateAnchor`,anchor:{zone:p,cell:{col:i,row:a}}})}p=m(Fs({top:a,bottom:a,left:i,right:i},Js({top:this.getNextAvailableRow(f,_,c),left:this.getNextAvailableCol(d,o,v),bottom:this.getNextAvailableRow(f,_,l),right:this.getNextAvailableCol(d,s,v)})));let ee={zone:p,cell:{col:i,row:a}};return this.processEvent({anchor:ee,mode:`updateAnchor`,options:{scrollIntoView:!0}})}selectColumn(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberRows(n)-1,i={left:e,right:e,top:0,bottom:r},a=this.getters.findFirstVisibleColRowIndex(n,`ROW`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=e,s=a;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=Fs(i,{left:o,right:o,top:a,bottom:r});break}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:o,row:s}},mode:t})}selectRow(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberCols(n)-1,i={top:e,bottom:e,left:0,right:r},a=this.getters.findFirstVisibleColRowIndex(n,`COL`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=a,s=e;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=Fs(i,{left:a,right:r,top:s,bottom:s});break}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:o,row:s}},mode:t})}loopSelection(){let e=this.getters.getActiveSheetId(),t=this.anchor;if(Rs(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:R(t.cell)},`updateAnchor`,{scrollIntoView:!1});let n=this.getters.getContiguousZone(e,t.zone);return w(n,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:n},`updateAnchor`,{scrollIntoView:!1})}selectTableAroundSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getContiguousZone(e,this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:t},`updateAnchor`,{scrollIntoView:!1})}selectAll(){let 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){let t={...e,previousAnchor:b(this.anchor)},n=this.checkEventAnchorZone(t);return n===`Success`?(this.anchor=t.anchor,this.stream.send(t),kr.Success):new kr(n)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){let{cell:t,zone:n}=e;if(!Vs(t.col,t.row,n))return`InvalidAnchorZone`;let{left:r,right:i,top:a,bottom:o}=n,s=this.getters.getActiveSheetId(),c=this.getters.findVisibleHeader(s,`COL`,r,i);return this.getters.findVisibleHeader(s,`ROW`,a,o)===void 0||c===void 0?`SelectionOutOfBound`:`Success`}checkAnchorZoneOrThrow(e){if(this.checkAnchorZone(e)===`InvalidAnchorZone`)throw Error(`The provided anchor is invalid. The cell must be part of the zone.`)}getNextAvailablePosition(e,t=1){let{col:n,row:r}=this.anchor.cell,i=this.deltaToTarget({col:n,row:r},e,t);return{col:this.getNextAvailableCol(i[0],n,r),row:this.getNextAvailableRow(i[1],n,r)}}getNextAvailableCol(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`COL`,t,i,e=>this.getters.isInSameMerge(r,t,n,e,n))}getNextAvailableRow(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`ROW`,n,i,e=>this.getters.isInSameMerge(r,t,n,t,e))}getNextAvailableHeader(e,t,n,r,i){let a=this.getters.getActiveSheetId();if(e===0)return n;let o=Math.sign(e),s=n+e;for(;i(s);)s+=o;for(;this.getters.isHeaderHidden(a,t,s);)s+=o;return s<0||s>this.getters.getNumberHeaders(a,t)-1?this.getters.isHeaderHidden(a,t,n)?this.getNextAvailableHeader(-o,t,n,r,i):n:s}getReferenceAnchor(){let e=this.getters.getActiveSheetId(),t=this.anchor,{left:n,right:r,top:i,bottom:a}=t.zone,{col:o,row:s}=t.cell,c=this.getters.isColHidden(e,o)&&this.getters.findVisibleHeader(e,`COL`,n,r)||o,l=this.getters.isRowHidden(e,s)&&this.getters.findVisibleHeader(e,`ROW`,i,a)||s,u=this.getters.expandZone(e,{left:c,right:c,top:l,bottom:l});return{cell:{col:c,row:l},zone:u}}deltaToTarget(e,t,n){switch(t){case`up`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,-1)-e.row]:[0,-n];case`down`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,1)-e.row]:[0,n];case`left`:return n===`end`?[this.getEndOfCluster(e,`cols`,-1)-e.col,0]:[-n,0];case`right`:return n===`end`?[this.getEndOfCluster(e,`cols`,1)-e.col,0]:[n,0]}}getStartingPosition(e){let{col:t,row:n}=this.getPosition(),r=this.anchor.zone;switch(e){case`down`:case`up`:n=n===r.top?r.bottom:r.top;break;case`left`:case`right`:t=t===r.right?r.left:r.right;break}return{col:t,row:n}}getEndOfCluster(e,t,n){let r=this.getters.getActiveSheetId(),i=e,a=this.getNextCellPosition(e,t,n),o=!this.isCellSkippableInCluster({...i,sheetId:r})&&!this.isCellSkippableInCluster({...a,sheetId:r})?`endOfCluster`:`nextCluster`;for(;;){let e=this.getNextCellPosition(i,t,n);if(i.col===e.col&&i.row===e.row)break;let a=this.isCellSkippableInCluster({...e,sheetId:r});if(o===`endOfCluster`&&a)break;if(o===`nextCluster`&&!a){i=e;break}i=e}return t===`cols`?i.col:i.row}getNextCellPosition(e,t,n){let r=t===`cols`?`col`:`row`,i={...e};return i[r]=t===`cols`?this.getNextAvailableCol(n,i.col,i.row):this.getNextAvailableRow(n,i.col,i.row),{col:i.col,row:i.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){let t=this.getters.getMainCellPosition(e),n=this.getters.getEvaluatedCell(t);return n.type===`empty`||n.type===`text`&&n.value===``}};function HJ(e){if(typeof e==`string`)return{};if(typeof e==`number`)return[];throw Error(`Cannot create new node`)}var UJ=class{changes;commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){let t=e.pop(),n=e[0],r=e.at(-1),i=e.length-2;for(let t=1;t<=i;t++){let r=e[t];if(n[r]===void 0){let i=e[t+1];n[r]=HJ(i)}n=n[r]}n[r]!==t&&(this.changes?.push({key:r,target:n,before:n[r]}),t===void 0?delete n[r]:n[r]=t)}};let WJ=17781237,GJ=17781238,KJ=88853993,qJ=88853994;function JJ(e,t,n){let r=[[`xmlns:r`,Jf],[`xmlns:a`,Wf],[`xmlns:c`,Gf]],i=YJ({backgroundColor:e.data.backgroundColor,line:{color:`000000`}}),a=J``;if(e.data.title?.text){let t=G(jC(e.data.backgroundColor)),n=e.data.title.fontSize??16;a=J`
2638
2638
  <c:title>
2639
- ${ZJ(e.data.title.text,t,n,e.data.title)}
2639
+ ${QJ(e.data.title.text,t,n,e.data.title)}
2640
2640
  <c:overlay val="0" />
2641
2641
  </c:title>
2642
- `}let o=J``;switch(e.data.type){case`bar`:o=rY(e.data);break;case`combo`:o=iY(e.data);break;case`pyramid`:o=aY(e.data);break;case`line`:o=sY(e.data);break;case`scatter`:o=cY(e.data);break;case`pie`:o=uY(e.data,t,n);break;case`radar`:o=lY(e.data)}let s=`none`;switch(e.data.legendPosition){case`bottom`:s=`b`;break;case`left`:s=`l`;break;case`right`:s=`r`;break;case`top`:s=`t`;break}let c=e.data.fontColor;return OO(J`
2642
+ `}let o=J``;switch(e.data.type){case`bar`:o=iY(e.data);break;case`combo`:o=aY(e.data);break;case`pyramid`:o=oY(e.data);break;case`line`:o=cY(e.data);break;case`scatter`:o=lY(e.data);break;case`pie`:o=dY(e.data,t,n);break;case`radar`:o=uY(e.data)}let s=`none`;switch(e.data.legendPosition){case`bottom`:s=`b`;break;case`left`:s=`l`;break;case`right`:s=`r`;break;case`top`:s=`t`;break}let c=e.data.fontColor;return OO(J`
2643
2643
  <c:chartSpace ${K(r)}>
2644
2644
  <c:roundedCorners val="0" />
2645
2645
  <!-- <manualLayout/> to manually position the chart in the figure container -->
@@ -2651,26 +2651,26 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2651
2651
  <!-- how the chart element is placed on the chart -->
2652
2652
  <c:layout />
2653
2653
  ${o}
2654
- ${JJ({backgroundColor:e.data.backgroundColor})}
2654
+ ${YJ({backgroundColor:e.data.backgroundColor})}
2655
2655
  </c:plotArea>
2656
- ${s===`none`?``:pY(s,c)}
2656
+ ${s===`none`?``:mY(s,c)}
2657
2657
  </c:chart>
2658
2658
  </c:chartSpace>
2659
- `)}function JJ(e){return J`
2659
+ `)}function YJ(e){return J`
2660
2660
  <c:spPr>
2661
- ${e.backgroundColor?YJ(e.backgroundColor):``}
2662
- ${e.line?XJ(e.line):``}
2661
+ ${e.backgroundColor?XJ(e.backgroundColor):``}
2662
+ ${e.line?ZJ(e.line):``}
2663
2663
  </c:spPr>
2664
- `}function YJ(e){return J`
2664
+ `}function XJ(e){return J`
2665
2665
  <a:solidFill>
2666
2666
  <a:srgbClr val="${e}"/>
2667
2667
  </a:solidFill>
2668
- `}function XJ(e){let t=[[`cmpd`,`sng`]];e.width&&t.push([`w`,iN(e.width)]);let n=e.style?J`<a:prstDash val="${e.style}"/>`:``;return J`
2668
+ `}function ZJ(e){let t=[[`cmpd`,`sng`]];e.width&&t.push([`w`,iN(e.width)]);let n=e.style?J`<a:prstDash val="${e.style}"/>`:``;return J`
2669
2669
  <a:ln ${K(t)}>
2670
- ${YJ(e.color)}
2670
+ ${XJ(e.color)}
2671
2671
  ${n}
2672
2672
  </a:ln>
2673
- `}function ZJ(e,t=`000000`,n=16,r={}){return J`
2673
+ `}function QJ(e,t=`000000`,n=16,r={}){return J`
2674
2674
  <c:tx>
2675
2675
  <c:rich>
2676
2676
  <a:bodyPr />
@@ -2678,7 +2678,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2678
2678
  <a:p>
2679
2679
  <a:pPr lvl="0">
2680
2680
  <a:defRPr b="${+!!r?.bold}" i="${+!!r?.italic}">
2681
- ${YJ(t)}
2681
+ ${XJ(t)}
2682
2682
  <a:latin typeface="+mn-lt"/>
2683
2683
  </a:defRPr>
2684
2684
  </a:pPr>
@@ -2689,29 +2689,29 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2689
2689
  </a:p>
2690
2690
  </c:rich>
2691
2691
  </c:tx>
2692
- `}function QJ(e=12,t=`000000`,n=!1,r=!1){return J`
2692
+ `}function $J(e=12,t=`000000`,n=!1,r=!1){return J`
2693
2693
  <c:txPr>
2694
2694
  <a:bodyPr/>
2695
2695
  <a:lstStyle/>
2696
2696
  <a:p>
2697
2697
  <a:pPr lvl="0">
2698
2698
  <a:defRPr ${K([[`b`,n?`1`:`0`],[`i`,r?`1`:`0`],[`sz`,e*100]])}>
2699
- ${YJ(t)}
2699
+ ${XJ(t)}
2700
2700
  <a:latin typeface="+mn-lt"/>
2701
2701
  </a:defRPr>
2702
2702
  </a:pPr>
2703
2703
  </a:p>
2704
2704
  </c:txPr>
2705
- `}function $J(e,t){if(!e)return J``;let{type:n,order:r,window:i}=e,a=[];switch(n){case`poly`:r&&r>1?(a.push(J`<c:trendlineType val="poly" />`),a.push(J`<c:order val="${r}" />`)):a.push(J`<c:trendlineType val="linear" />`);break;case`movingAvg`:a.push(J`<c:trendlineType val="movingAvg" />`),i&&a.push(J`<c:period val="${i}" />`);break;default:a.push(J`<c:trendlineType val="${n}" />`);break}return J`
2705
+ `}function eY(e,t){if(!e)return J``;let{type:n,order:r,window:i}=e,a=[];switch(n){case`poly`:r&&r>1?(a.push(J`<c:trendlineType val="poly" />`),a.push(J`<c:order val="${r}" />`)):a.push(J`<c:trendlineType val="linear" />`);break;case`movingAvg`:a.push(J`<c:trendlineType val="movingAvg" />`),i&&a.push(J`<c:period val="${i}" />`);break;default:a.push(J`<c:trendlineType val="${n}" />`);break}return J`
2706
2706
  <c:trendline>
2707
- ${eY(e,t)}
2707
+ ${tY(e,t)}
2708
2708
  ${q(a)}
2709
2709
  </c:trendline>
2710
- `}function eY(e,t){return e?J`
2710
+ `}function tY(e,t){return e?J`
2711
2711
  <c:spPr>
2712
2712
  <a:ln w="19050" cap="rnd">
2713
2713
  <a:solidFill>
2714
- <a:srgbClr ${K([[`val`,e.color?G(e.color).slice(-6):tY(t)]])}/>
2714
+ <a:srgbClr ${K([[`val`,e.color?G(e.color).slice(-6):nY(t)]])}/>
2715
2715
  </a:solidFill>
2716
2716
  <a:prstDash val="sysDot" />
2717
2717
  </a:ln>
@@ -2719,22 +2719,22 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2719
2719
  </c:spPr>
2720
2720
  <c:dispRSqr val="0" />
2721
2721
  <c:dispEq val="0" />
2722
- `:J``}function tY(e){return G(An(e,.5))}function nY(e){return e?`text`in e&&e.text?J`
2722
+ `:J``}function nY(e){return G(An(e,.5))}function rY(e){return e?`text`in e&&e.text?J`
2723
2723
  <c:tx><c:v>${e.text}</c:v></c:tx>
2724
2724
  `:`reference`in e&&e.reference?J`
2725
2725
  <c:tx>
2726
- ${hY(e.reference)}
2726
+ ${gY(e.reference)}
2727
2727
  </c:tx>
2728
- `:J``:J``}function rY(e){let t=e.horizontal?`bar`:`col`,n=e.dataSets.map(e=>e.backgroundColor??``),r=new Un(e.dataSets.length,n),i=[],a=[];for(let[t,n]of Object.entries(e.dataSets)){let o=G(r.next()),s=JJ({backgroundColor:o,line:{color:o}}),c=J`
2728
+ `:J``:J``}function iY(e){let t=e.horizontal?`bar`:`col`,n=e.dataSets.map(e=>e.backgroundColor??``),r=new Un(e.dataSets.length,n),i=[],a=[];for(let[t,n]of Object.entries(e.dataSets)){let o=G(r.next()),s=YJ({backgroundColor:o,line:{color:o}}),c=J`
2729
2729
  <c:ser>
2730
2730
  <c:idx val="${t}"/>
2731
2731
  <c:order val="${t}"/>
2732
- ${$J(n.trend,o)}
2733
- ${nY(n.label)}
2732
+ ${eY(n.trend,o)}
2733
+ ${rY(n.label)}
2734
2734
  ${s}
2735
- ${e.labelRange?J`<c:cat>${hY(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
2735
+ ${e.labelRange?J`<c:cat>${gY(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
2736
2736
  <c:val> <!-- x-coordinate values -->
2737
- ${gY(n.range)}
2737
+ ${_Y(n.range)}
2738
2738
  </c:val>
2739
2739
  </c:ser>
2740
2740
  `;n.rightYAxis?a.push(c):i.push(c)}let o=e.stacked?`stacked`:`clustered`,s=e.stacked?100:-20;return J`
@@ -2747,11 +2747,11 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2747
2747
  <!-- each data marker in the series does not have a different color -->
2748
2748
  <c:varyColors val="0"/>
2749
2749
  ${q(i)}
2750
- <c:axId val="${UJ}" />
2751
- <c:axId val="${GJ}" />
2750
+ <c:axId val="${WJ}" />
2751
+ <c:axId val="${KJ}" />
2752
2752
  </c:barChart>
2753
- ${t===`col`?fY(`b`,`c:catAx`,UJ,GJ,e.axesDesign?.x?.title,e.fontColor):fY(`b`,`c:catAx`,UJ,GJ,e.axesDesign?.y?.title,e.fontColor,void 0,`maxMin`)}
2754
- ${t===`col`?fY(`l`,`c:valAx`,GJ,UJ,e.axesDesign?.y?.title,e.fontColor):fY(`l`,`c:valAx`,GJ,UJ,e.axesDesign?.x?.title,e.fontColor,void 0,void 0,`max`)}
2753
+ ${t===`col`?pY(`b`,`c:catAx`,WJ,KJ,e.axesDesign?.x?.title,e.fontColor):pY(`b`,`c:catAx`,WJ,KJ,e.axesDesign?.y?.title,e.fontColor,void 0,`maxMin`)}
2754
+ ${t===`col`?pY(`l`,`c:valAx`,KJ,WJ,e.axesDesign?.y?.title,e.fontColor):pY(`l`,`c:valAx`,KJ,WJ,e.axesDesign?.x?.title,e.fontColor,void 0,void 0,`max`)}
2755
2755
  `:``}
2756
2756
  ${a.length?J`
2757
2757
  <c:barChart>
@@ -2762,25 +2762,25 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2762
2762
  <!-- each data marker in the series does not have a different color -->
2763
2763
  <c:varyColors val="0"/>
2764
2764
  ${q(a)}
2765
- <c:axId val="${UJ+1}" />
2766
- <c:axId val="${GJ+1}" />
2765
+ <c:axId val="${WJ+1}" />
2766
+ <c:axId val="${KJ+1}" />
2767
2767
  </c:barChart>
2768
- ${fY(`b`,`c:catAx`,UJ+1,GJ+1,e.axesDesign?.x?.title,e.fontColor,+!!i.length)}
2769
- ${fY(`r`,`c:valAx`,GJ+1,UJ+1,e.axesDesign?.y1?.title,e.fontColor)}
2770
- `:``}`}function iY(e){let t=e.dataSets,n=t.map(e=>e.backgroundColor??``),r=new Un(t.length,n),i=t[0],a=G(r.next()),o=i.rightYAxis??!1,s=J`
2768
+ ${pY(`b`,`c:catAx`,WJ+1,KJ+1,e.axesDesign?.x?.title,e.fontColor,+!!i.length)}
2769
+ ${pY(`r`,`c:valAx`,KJ+1,WJ+1,e.axesDesign?.y1?.title,e.fontColor)}
2770
+ `:``}`}function aY(e){let t=e.dataSets,n=t.map(e=>e.backgroundColor??``),r=new Un(t.length,n),i=t[0],a=G(r.next()),o=i.rightYAxis??!1,s=J`
2771
2771
  <c:ser>
2772
2772
  <c:idx val="0"/>
2773
2773
  <c:order val="0"/>
2774
- ${$J(i.trend,a)}
2775
- ${nY(i.label)}
2776
- ${JJ({backgroundColor:a,line:{color:a}})}
2777
- ${e.labelRange?J`<c:cat>${hY(e.labelRange)}</c:cat>`:``}
2774
+ ${eY(i.trend,a)}
2775
+ ${rY(i.label)}
2776
+ ${YJ({backgroundColor:a,line:{color:a}})}
2777
+ ${e.labelRange?J`<c:cat>${gY(e.labelRange)}</c:cat>`:``}
2778
2778
  <!-- x-coordinate values -->
2779
2779
  <c:val>
2780
- ${gY(i.range)}
2780
+ ${_Y(i.range)}
2781
2781
  </c:val>
2782
2782
  </c:ser>
2783
- `,c=[],l=[];for(let n=1;n<t.length;n++){i=t[n];let a=G(r.next()),o=JJ({backgroundColor:a,line:{color:a}}),s=J`
2783
+ `,c=[],l=[];for(let n=1;n<t.length;n++){i=t[n];let a=G(r.next()),o=YJ({backgroundColor:a,line:{color:a}}),s=J`
2784
2784
  <c:ser>
2785
2785
  <c:idx val="${n}"/>
2786
2786
  <c:order val="${n}"/>
@@ -2790,13 +2790,13 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2790
2790
  <c:size val="5"/>
2791
2791
  ${o}
2792
2792
  </c:marker>
2793
- ${$J(i.trend,a)}
2794
- ${nY(i.label)}
2793
+ ${eY(i.trend,a)}
2794
+ ${rY(i.label)}
2795
2795
  ${o}
2796
- ${e.labelRange?J`<c:cat>${hY(e.labelRange)}</c:cat>`:``}
2796
+ ${e.labelRange?J`<c:cat>${gY(e.labelRange)}</c:cat>`:``}
2797
2797
  <!-- x-coordinate values -->
2798
2798
  <c:val>
2799
- ${gY(i.range)}
2799
+ ${_Y(i.range)}
2800
2800
  </c:val>
2801
2801
  </c:ser>
2802
2802
  `;i.rightYAxis?l.push(s):c.push(s)}return J`
@@ -2808,8 +2808,8 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2808
2808
  <!-- each data marker in the series does not have a different color -->
2809
2809
  <c:varyColors val="0"/>
2810
2810
  ${s}
2811
- <c:axId val="${o?WJ:UJ}" />
2812
- <c:axId val="${o?KJ:GJ}" />
2811
+ <c:axId val="${o?GJ:WJ}" />
2812
+ <c:axId val="${o?qJ:KJ}" />
2813
2813
  </c:barChart>
2814
2814
  ${c.length?J`
2815
2815
  <c:lineChart>
@@ -2817,8 +2817,8 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2817
2817
  <!-- each data marker in the series does not have a different color -->
2818
2818
  <c:varyColors val="0"/>
2819
2819
  ${q(c)}
2820
- <c:axId val="${UJ}" />
2821
- <c:axId val="${GJ}" />
2820
+ <c:axId val="${WJ}" />
2821
+ <c:axId val="${KJ}" />
2822
2822
  </c:lineChart>
2823
2823
  `:``}
2824
2824
  ${l.length?J`
@@ -2827,19 +2827,19 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2827
2827
  <!-- each data marker in the series does not have a different color -->
2828
2828
  <c:varyColors val="0"/>
2829
2829
  ${q(l)}
2830
- <c:axId val="${WJ}" />
2831
- <c:axId val="${KJ}" />
2830
+ <c:axId val="${GJ}" />
2831
+ <c:axId val="${qJ}" />
2832
2832
  </c:lineChart>
2833
2833
  `:``}
2834
2834
  ${!o||c.length?J`
2835
- ${fY(`b`,`c:catAx`,UJ,GJ,e.axesDesign?.x?.title,e.fontColor,0)}
2836
- ${fY(`l`,`c:valAx`,GJ,UJ,e.axesDesign?.y?.title,e.fontColor)}
2835
+ ${pY(`b`,`c:catAx`,WJ,KJ,e.axesDesign?.x?.title,e.fontColor,0)}
2836
+ ${pY(`l`,`c:valAx`,KJ,WJ,e.axesDesign?.y?.title,e.fontColor)}
2837
2837
  `:``}
2838
2838
  ${o||l.length?J`
2839
- ${fY(`b`,`c:catAx`,WJ,KJ,e.axesDesign?.x?.title,e.fontColor,c.length||!o?1:0)}
2840
- ${fY(`r`,`c:valAx`,KJ,WJ,e.axesDesign?.y1?.title,e.fontColor)}
2839
+ ${pY(`b`,`c:catAx`,GJ,qJ,e.axesDesign?.x?.title,e.fontColor,c.length||!o?1:0)}
2840
+ ${pY(`r`,`c:valAx`,qJ,GJ,e.axesDesign?.y1?.title,e.fontColor)}
2841
2841
  `:``}
2842
- `}function aY(e){let t=e.dataSets,n=t.map(e=>e.backgroundColor??``),r=new Un(t.length,n),i=t[0],a=t[1],o=G(r.next()),s=G(r.next()),{maxValue:c,majorUnit:l}=oY(e.maxValue),u=e.labelRange?J`<c:cat>${hY(e.labelRange)}</c:cat>`:``;return J`
2842
+ `}function oY(e){let t=e.dataSets,n=t.map(e=>e.backgroundColor??``),r=new Un(t.length,n),i=t[0],a=t[1],o=G(r.next()),s=G(r.next()),{maxValue:c,majorUnit:l}=sY(e.maxValue),u=e.labelRange?J`<c:cat>${gY(e.labelRange)}</c:cat>`:``;return J`
2843
2843
  <c:barChart>
2844
2844
  <c:barDir val="bar"/>
2845
2845
  <c:grouping val="clustered"/>
@@ -2849,18 +2849,18 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2849
2849
  <c:idx val="0"/>
2850
2850
  <c:order val="0"/>
2851
2851
  <c:invertIfNegative val="0" />
2852
- ${nY(i.label)}
2853
- ${JJ({backgroundColor:o,line:{color:o}})}
2852
+ ${rY(i.label)}
2853
+ ${YJ({backgroundColor:o,line:{color:o}})}
2854
2854
  ${u}
2855
2855
  <!-- x-coordinate values -->
2856
2856
  <c:val>
2857
- ${gY(i.range)}
2857
+ ${_Y(i.range)}
2858
2858
  </c:val>
2859
2859
  </c:ser>
2860
2860
  `}
2861
2861
  <c:gapWidth val="50" />
2862
- <c:axId val="${UJ}" />
2863
- <c:axId val="${GJ}" />
2862
+ <c:axId val="${WJ}" />
2863
+ <c:axId val="${KJ}" />
2864
2864
  </c:barChart>
2865
2865
  <c:barChart>
2866
2866
  <c:barDir val="bar"/>
@@ -2871,24 +2871,24 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2871
2871
  <c:idx val="1"/>
2872
2872
  <c:order val="1"/>
2873
2873
  <c:invertIfNegative val="0" />
2874
- ${nY(a.label)}
2875
- ${JJ({backgroundColor:s,line:{color:s}})}
2876
- ${e.labelRange?J`<c:cat>${hY(e.labelRange)}</c:cat>`:``}
2874
+ ${rY(a.label)}
2875
+ ${YJ({backgroundColor:s,line:{color:s}})}
2876
+ ${e.labelRange?J`<c:cat>${gY(e.labelRange)}</c:cat>`:``}
2877
2877
  <!-- x-coordinate values -->
2878
2878
  <c:val>
2879
- ${gY(a.range)}
2879
+ ${_Y(a.range)}
2880
2880
  </c:val>
2881
2881
  </c:ser>
2882
2882
  `}
2883
2883
  <c:gapWidth val="50" />
2884
- <c:axId val="${WJ}" />
2885
- <c:axId val="${KJ}" />
2884
+ <c:axId val="${GJ}" />
2885
+ <c:axId val="${qJ}" />
2886
2886
  </c:barChart>
2887
- ${fY(`r`,`c:catAx`,UJ,GJ,e.axesDesign?.y?.title,e.fontColor,0,`maxMin`,`autoZero`,`high`)}
2888
- ${fY(`b`,`c:valAx`,GJ,UJ,e.axesDesign?.x?.title,e.fontColor,0,`maxMin`,`max`,`nextTo`,c,l,`#0;#0`)}
2889
- ${fY(`t`,`c:valAx`,KJ,WJ,void 0,e.fontColor,1)}
2890
- ${fY(`l`,`c:catAx`,WJ,KJ,void 0,e.fontColor,1,`maxMin`)}
2891
- `}function oY(e){let t=((e,t)=>{let n=Math.ceil(e);for(;n%t!==0;)n++;return n})(e,3);return{maxValue:t,majorUnit:t/3}}function sY(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new Un(e.dataSets.length,t),r=[],i=[];for(let[t,a]of Object.entries(e.dataSets)){let o=G(n.next()),s=JJ({line:{width:2.5,style:`solid`,color:o}}),c=J`
2887
+ ${pY(`r`,`c:catAx`,WJ,KJ,e.axesDesign?.y?.title,e.fontColor,0,`maxMin`,`autoZero`,`high`)}
2888
+ ${pY(`b`,`c:valAx`,KJ,WJ,e.axesDesign?.x?.title,e.fontColor,0,`maxMin`,`max`,`nextTo`,c,l,`#0;#0`)}
2889
+ ${pY(`t`,`c:valAx`,qJ,GJ,void 0,e.fontColor,1)}
2890
+ ${pY(`l`,`c:catAx`,GJ,qJ,void 0,e.fontColor,1,`maxMin`)}
2891
+ `}function sY(e){let t=((e,t)=>{let n=Math.ceil(e);for(;n%t!==0;)n++;return n})(e,3);return{maxValue:t,majorUnit:t/3}}function cY(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new Un(e.dataSets.length,t),r=[],i=[];for(let[t,a]of Object.entries(e.dataSets)){let o=G(n.next()),s=YJ({line:{width:2.5,style:`solid`,color:o}}),c=J`
2892
2892
  <c:ser>
2893
2893
  <c:idx val="${t}"/>
2894
2894
  <c:order val="${t}"/>
@@ -2896,14 +2896,14 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2896
2896
  <c:marker>
2897
2897
  <c:symbol val="circle" />
2898
2898
  <c:size val="5"/>
2899
- ${JJ({backgroundColor:o,line:{color:o}})}
2899
+ ${YJ({backgroundColor:o,line:{color:o}})}
2900
2900
  </c:marker>
2901
- ${$J(a.trend,o)}
2902
- ${nY(a.label)}
2901
+ ${eY(a.trend,o)}
2902
+ ${rY(a.label)}
2903
2903
  ${s}
2904
- ${e.labelRange?J`<c:cat>${hY(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
2904
+ ${e.labelRange?J`<c:cat>${gY(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
2905
2905
  <c:val> <!-- x-coordinate values -->
2906
- ${gY(a.range)}
2906
+ ${_Y(a.range)}
2907
2907
  </c:val>
2908
2908
  </c:ser>
2909
2909
  `;a.rightYAxis?i.push(c):r.push(c)}let a=e.stacked?`stacked`:`standard`;return J`
@@ -2913,11 +2913,11 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2913
2913
  <!-- each data marker in the series does not have a different color -->
2914
2914
  <c:varyColors val="0"/>
2915
2915
  ${q(r)}
2916
- <c:axId val="${UJ}" />
2917
- <c:axId val="${GJ}" />
2916
+ <c:axId val="${WJ}" />
2917
+ <c:axId val="${KJ}" />
2918
2918
  </c:lineChart>
2919
- ${fY(`b`,`c:catAx`,UJ,GJ,e.axesDesign?.x?.title,e.fontColor)}
2920
- ${fY(`l`,`c:valAx`,GJ,UJ,e.axesDesign?.y?.title,e.fontColor)}
2919
+ ${pY(`b`,`c:catAx`,WJ,KJ,e.axesDesign?.x?.title,e.fontColor)}
2920
+ ${pY(`l`,`c:valAx`,KJ,WJ,e.axesDesign?.y?.title,e.fontColor)}
2921
2921
  `:``}
2922
2922
  ${i.length?J`
2923
2923
  <c:lineChart>
@@ -2925,13 +2925,13 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2925
2925
  <!-- each data marker in the series does not have a different color -->
2926
2926
  <c:varyColors val="0"/>
2927
2927
  ${q(i)}
2928
- <c:axId val="${UJ+1}" />
2929
- <c:axId val="${GJ+1}" />
2928
+ <c:axId val="${WJ+1}" />
2929
+ <c:axId val="${KJ+1}" />
2930
2930
  </c:lineChart>
2931
- ${fY(`b`,`c:catAx`,UJ+1,GJ+1,e.axesDesign?.x?.title,e.fontColor,+!!r.length)}
2932
- ${fY(`r`,`c:valAx`,GJ+1,UJ+1,e.axesDesign?.y1?.title,e.fontColor)}
2931
+ ${pY(`b`,`c:catAx`,WJ+1,KJ+1,e.axesDesign?.x?.title,e.fontColor,+!!r.length)}
2932
+ ${pY(`r`,`c:valAx`,KJ+1,WJ+1,e.axesDesign?.y1?.title,e.fontColor)}
2933
2933
  `:``}
2934
- `}function cY(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new Un(e.dataSets.length,t),r=[],i=[];for(let[t,a]of Object.entries(e.dataSets)){let o=G(n.next()),s=J`
2934
+ `}function lY(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new Un(e.dataSets.length,t),r=[],i=[];for(let[t,a]of Object.entries(e.dataSets)){let o=G(n.next()),s=J`
2935
2935
  <c:ser>
2936
2936
  <c:idx val="${t}"/>
2937
2937
  <c:order val="${t}"/>
@@ -2946,15 +2946,15 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2946
2946
  <c:marker>
2947
2947
  <c:symbol val="circle" />
2948
2948
  <c:size val="5"/>
2949
- ${JJ({backgroundColor:o,line:{color:o}})}
2949
+ ${YJ({backgroundColor:o,line:{color:o}})}
2950
2950
  </c:marker>
2951
- ${$J(a.trend,o)}
2952
- ${nY(a.label)}
2951
+ ${eY(a.trend,o)}
2952
+ ${rY(a.label)}
2953
2953
  ${e.labelRange?J`<c:xVal> <!-- x-coordinate values -->
2954
- ${gY(e.labelRange)}
2954
+ ${_Y(e.labelRange)}
2955
2955
  </c:xVal>`:``}
2956
2956
  <c:yVal> <!-- y-coordinate values -->
2957
- ${gY(a.range)}
2957
+ ${_Y(a.range)}
2958
2958
  </c:yVal>
2959
2959
  </c:ser>
2960
2960
  `;a.rightYAxis?i.push(s):r.push(s)}return J`
@@ -2964,11 +2964,11 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2964
2964
  <c:varyColors val="0"/>
2965
2965
  <c:scatterStyle val="lineMarker"/>
2966
2966
  ${q(r)}
2967
- <c:axId val="${UJ}" />
2968
- <c:axId val="${GJ}" />
2967
+ <c:axId val="${WJ}" />
2968
+ <c:axId val="${KJ}" />
2969
2969
  </c:scatterChart>
2970
- ${fY(`b`,`c:valAx`,UJ,GJ,e.axesDesign?.x?.title,e.fontColor)}
2971
- ${fY(`l`,`c:valAx`,GJ,UJ,e.axesDesign?.y?.title,e.fontColor)}
2970
+ ${pY(`b`,`c:valAx`,WJ,KJ,e.axesDesign?.x?.title,e.fontColor)}
2971
+ ${pY(`l`,`c:valAx`,KJ,WJ,e.axesDesign?.y?.title,e.fontColor)}
2972
2972
  `:``}
2973
2973
  ${i.length?J`
2974
2974
  <c:scatterChart>
@@ -2976,12 +2976,12 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2976
2976
  <c:varyColors val="0"/>
2977
2977
  <c:scatterStyle val="lineMarker"/>
2978
2978
  ${q(i)}
2979
- <c:axId val="${UJ+1}" />
2980
- <c:axId val="${GJ+1}" />
2979
+ <c:axId val="${WJ+1}" />
2980
+ <c:axId val="${KJ+1}" />
2981
2981
  </c:scatterChart>
2982
- ${fY(`b`,`c:valAx`,UJ+1,GJ+1,e.axesDesign?.x?.title,e.fontColor,+!!r.length)}
2983
- ${fY(`r`,`c:valAx`,GJ+1,UJ+1,e.axesDesign?.y1?.title,e.fontColor)}
2984
- `:``}`}function lY(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new Un(e.dataSets.length,t),r=[];for(let[t,i]of Object.entries(e.dataSets)){let a=G(n.next()),o=JJ({line:{width:2.5,style:`solid`,color:a}}),s=J`
2982
+ ${pY(`b`,`c:valAx`,WJ+1,KJ+1,e.axesDesign?.x?.title,e.fontColor,+!!r.length)}
2983
+ ${pY(`r`,`c:valAx`,KJ+1,WJ+1,e.axesDesign?.y1?.title,e.fontColor)}
2984
+ `:``}`}function uY(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new Un(e.dataSets.length,t),r=[];for(let[t,i]of Object.entries(e.dataSets)){let a=G(n.next()),o=YJ({line:{width:2.5,style:`solid`,color:a}}),s=J`
2985
2985
  <c:ser>
2986
2986
  <c:idx val="${t}"/>
2987
2987
  <c:order val="${t}"/>
@@ -2989,13 +2989,13 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
2989
2989
  <c:marker>
2990
2990
  <c:symbol val="circle" />
2991
2991
  <c:size val="5"/>
2992
- ${JJ({backgroundColor:a,line:{color:a}})}
2992
+ ${YJ({backgroundColor:a,line:{color:a}})}
2993
2993
  </c:marker>
2994
- ${nY(i.label)}
2994
+ ${rY(i.label)}
2995
2995
  ${o}
2996
- ${e.labelRange?J`<c:cat>${hY(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
2996
+ ${e.labelRange?J`<c:cat>${gY(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
2997
2997
  <c:val> <!-- x-coordinate values -->
2998
- ${gY(i.range)}
2998
+ ${_Y(i.range)}
2999
2999
  </c:val>
3000
3000
  </c:ser>
3001
3001
  `;r.push(s)}return J`
@@ -3004,13 +3004,13 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3004
3004
  <c:radarStyle val="marker"/>
3005
3005
  <c:varyColors val="0"/>
3006
3006
  ${q(r)}
3007
- <c:axId val="${UJ}" />
3008
- <c:axId val="${GJ}" />
3007
+ <c:axId val="${WJ}" />
3008
+ <c:axId val="${KJ}" />
3009
3009
  </c:radarChart>
3010
- ${fY(`b`,`c:catAx`,UJ,GJ,e.axesDesign?.x?.title,e.fontColor)}
3011
- ${fY(`l`,`c:valAx`,GJ,UJ,e.axesDesign?.y?.title,e.fontColor)}
3010
+ ${pY(`b`,`c:catAx`,WJ,KJ,e.axesDesign?.x?.title,e.fontColor)}
3011
+ ${pY(`l`,`c:valAx`,KJ,WJ,e.axesDesign?.y?.title,e.fontColor)}
3012
3012
  `}
3013
- `}function uY(e,t,n){let r=$t(e.dataSets.map(e=>aN(e.range,t,n))),i=new Un(r),a=S(0,r).map(()=>G(i.next())),o=[];for(let[r,i]of Object.entries(e.dataSets).reverse()){let s=aN(i.range,t,n),c=[];for(let e of S(0,s)){let t=JJ({backgroundColor:a[e],line:{color:`FFFFFF`,width:1.5}});c.push(J`
3013
+ `}function dY(e,t,n){let r=$t(e.dataSets.map(e=>aN(e.range,t,n))),i=new Un(r),a=S(0,r).map(()=>G(i.next())),o=[];for(let[r,i]of Object.entries(e.dataSets).reverse()){let s=aN(i.range,t,n),c=[];for(let e of S(0,s)){let t=YJ({backgroundColor:a[e],line:{color:`FFFFFF`,width:1.5}});c.push(J`
3014
3014
  <c:dPt>
3015
3015
  <c:idx val="${e}"/>
3016
3016
  ${t}
@@ -3019,22 +3019,22 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3019
3019
  <c:ser>
3020
3020
  <c:idx val="${r}"/>
3021
3021
  <c:order val="${r}"/>
3022
- ${nY(i.label)}
3022
+ ${rY(i.label)}
3023
3023
  ${q(c)}
3024
- ${dY({showLeaderLines:!0})}
3025
- ${e.labelRange?J`<c:cat>${hY(e.labelRange)}</c:cat>`:``}
3024
+ ${fY({showLeaderLines:!0})}
3025
+ ${e.labelRange?J`<c:cat>${gY(e.labelRange)}</c:cat>`:``}
3026
3026
  <c:val>
3027
- ${gY(i.range)}
3027
+ ${_Y(i.range)}
3028
3028
  </c:val>
3029
3029
  </c:ser>
3030
3030
  `)}return J`
3031
3031
  <c:doughnutChart>
3032
3032
  <c:varyColors val="1" />
3033
3033
  <c:holeSize val="${e.pieHolePercentage??(e.isDoughnut?50:0)}" />
3034
- ${dY()}
3034
+ ${fY()}
3035
3035
  ${q(o)}
3036
3036
  </c:doughnutChart>
3037
- `}function dY({showLeaderLines:e}={showLeaderLines:!1}){return J`
3037
+ `}function fY({showLeaderLines:e}={showLeaderLines:!1}){return J`
3038
3038
  <dLbls>
3039
3039
  <c:showLegendKey val="0"/>
3040
3040
  <c:showVal val="0"/>
@@ -3044,7 +3044,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3044
3044
  <c:showBubbleSize val="0"/>
3045
3045
  <c:showLeaderLines val="${e?`1`:`0`}"/>
3046
3046
  </dLbls>
3047
- `}function fY(e,t,n,r,i,a,o=0,s=`minMax`,c,l=`nextTo`,u,d,f=`General`){let p=i?.color?G(i.color):a,m=i?.fontSize??12,h=t===`c:valAx`?J`<c:crossBetween val="between" />`:``,g=u?J`<c:max val="${u}" />`:``,_=u?J`<c:min val="${-u}" />`:``,v=d?J`<c:majorUnit val="${d}" />`:``;return J`
3047
+ `}function pY(e,t,n,r,i,a,o=0,s=`minMax`,c,l=`nextTo`,u,d,f=`General`){let p=i?.color?G(i.color):a,m=i?.fontSize??12,h=t===`c:valAx`?J`<c:crossBetween val="between" />`:``,g=u?J`<c:max val="${u}" />`:``,_=u?J`<c:min val="${-u}" />`:``,v=d?J`<c:majorUnit val="${d}" />`:``;return J`
3048
3048
  <${t}>
3049
3049
  <c:axId val="${n}"/>
3050
3050
  <c:crossAx val="${r}"/> <!-- reference to the other axe of the chart -->
@@ -3060,42 +3060,42 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3060
3060
  ${v}
3061
3061
  <c:axPos val="${e}" />
3062
3062
  <c:tickLblPos val="${l}" />
3063
- ${mY()}
3063
+ ${hY()}
3064
3064
  <c:majorTickMark val="out" />
3065
3065
  <c:minorTickMark val="none" />
3066
3066
  <c:numFmt formatCode="${f}" sourceLinked="${f===`General`?`1`:`0`}" />
3067
3067
  <c:title>
3068
- ${ZJ(i?.text??``,p,m,i)}
3068
+ ${QJ(i?.text??``,p,m,i)}
3069
3069
  </c:title>
3070
- ${QJ(10,a)}
3070
+ ${$J(10,a)}
3071
3071
  </${t}>
3072
3072
  <!-- <tickLblPos/> omitted -->
3073
- `}function pY(e,t){return J`
3073
+ `}function mY(e,t){return J`
3074
3074
  <c:legend>
3075
3075
  <c:legendPos val="${e}"/>
3076
3076
  <c:overlay val="0"/>
3077
- ${QJ(10,t)}
3077
+ ${$J(10,t)}
3078
3078
  </c:legend>
3079
- `}function mY(e=`B7B7B7`){return J`
3079
+ `}function hY(e=`B7B7B7`){return J`
3080
3080
  <c:majorGridlines>
3081
- ${JJ({line:{color:e}})}
3081
+ ${YJ({line:{color:e}})}
3082
3082
  </c:majorGridlines>
3083
- `}function hY(e){return J`
3083
+ `}function gY(e){return J`
3084
3084
  <c:strRef>
3085
3085
  <c:f>${e}</c:f>
3086
3086
  </c:strRef>
3087
- `}function gY(e){return J`
3087
+ `}function _Y(e){return J`
3088
3088
  <c:numRef>
3089
3089
  <c:f>${e}</c:f>
3090
3090
  <c:numCache />
3091
3091
  </c:numRef>
3092
- `}function _Y(e,t,n){if(!e)return{attrs:[],node:J``};let r=WM(t);return r===void 0?{attrs:[],node:J``}:{attrs:[[`cm`,`1`],[`t`,r]],node:J`<f t="array" ref="${n}">${yY(e)}</f><v>${bY(t)}</v>`}}function vY(e,t,n=!1){let r=e,i=[],a=r.trim().toUpperCase();return!n&&[`TRUE`,`FALSE`].includes(a)?(r=a===`TRUE`?`1`:`0`,i.push([`t`,`b`])):(n||!Hi(r,D))&&(r=eN(e,t),i.push([`t`,`s`])),{attrs:i,node:J`<v>${r}</v>`}}function yY(e){e[0]===`=`&&(e=e.slice(1));let t;try{t=Zy(e)}catch{return e}return t=$y(t,`STRING`,CY),t=$y(t,`FUNCALL`,e=>(e={...e,value:e.value.toUpperCase()},e=SY(e),e=xY(e),e)),t=$y(t,`REFERENCE`,e=>e.value===k.InvalidReference?{...e,value:`#REF!`}:e),t?PB(t):e}function bY(e){return e===k.InvalidReference?`#REF!`:e}function xY(e){let t=e.value.toUpperCase(),n=e.args,r=$f[t];if(r){let i=zS.content[t].args.filter(e=>!e.optional),a=i.length-e.args.length;if(a)for(let t=e.args.length;t<i.length;t++){let e=r[t-a];n.push({type:e.type,value:e.value,tokenEndIndex:0,tokenStartIndex:0})}}return{...e,args:n}}function SY(e){let t=e.value.toUpperCase();return{...e,value:ep.includes(t)?`_xlfn.${t}`:t}}function CY(e){let t=e.value.replace(RegExp(`"`,`g`),``),n=fi(t,D);if(n){let r=[];return(ri.test(t)||ii.test(t))&&r.push(`yyyy-mm-dd`),ci.test(t)&&r.push(`hh:mm:ss`),{...e,value:L(n.value,{format:r.join(` `),locale:D})}}else return{...e,value:e.value.replace(/\\"/g,`""`)}}function wY(e,t){let n=[];for(let r of t)switch(r.rule.type){case`CellIsRule`:n.push(TY(r,r.rule,e));break;case`ColorScaleRule`:n.push(kY(r,r.rule));break;case`IconSetRule`:n.push(AY(r,r.rule));break;case`DataBarRule`:n.push(OY(r,r.rule));break;default:console.warn(`Conditional formatting ${r.rule.type} not implemented`);break}return n}function TY(e,t,n){let r=jY(e),i=UM(t.operator);r.push(...DY(t)),i.length&&r.push([`operator`,i]);let a=EY(e.ranges,t).map(e=>J`<formula>${e}</formula>`),o={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&&(o.fill={fgColor:{rgb:t.style.fillColor}}),r.push([`dxfId`,eN(o,n)]),J`
3092
+ `}function vY(e,t,n){if(!e)return{attrs:[],node:J``};let r=WM(t);return r===void 0?{attrs:[],node:J``}:{attrs:[[`cm`,`1`],[`t`,r]],node:J`<f t="array" ref="${n}">${bY(e)}</f><v>${xY(t)}</v>`}}function yY(e,t,n=!1){let r=e,i=[],a=r.trim().toUpperCase();return!n&&[`TRUE`,`FALSE`].includes(a)?(r=a===`TRUE`?`1`:`0`,i.push([`t`,`b`])):(n||!Hi(r,D))&&(r=eN(e,t),i.push([`t`,`s`])),{attrs:i,node:J`<v>${r}</v>`}}function bY(e){e[0]===`=`&&(e=e.slice(1));let t;try{t=Zy(e)}catch{return e}return t=$y(t,`STRING`,wY),t=$y(t,`FUNCALL`,e=>(e={...e,value:e.value.toUpperCase()},e=CY(e),e=SY(e),e)),t=$y(t,`REFERENCE`,e=>e.value===k.InvalidReference?{...e,value:`#REF!`}:e),t?PB(t):e}function xY(e){return e===k.InvalidReference?`#REF!`:e}function SY(e){let t=e.value.toUpperCase(),n=e.args,r=$f[t];if(r){let i=zS.content[t].args.filter(e=>!e.optional),a=i.length-e.args.length;if(a)for(let t=e.args.length;t<i.length;t++){let e=r[t-a];n.push({type:e.type,value:e.value,tokenEndIndex:0,tokenStartIndex:0})}}return{...e,args:n}}function CY(e){let t=e.value.toUpperCase();return{...e,value:ep.includes(t)?`_xlfn.${t}`:t}}function wY(e){let t=e.value.replace(RegExp(`"`,`g`),``),n=fi(t,D);if(n){let r=[];return(ri.test(t)||ii.test(t))&&r.push(`yyyy-mm-dd`),ci.test(t)&&r.push(`hh:mm:ss`),{...e,value:L(n.value,{format:r.join(` `),locale:D})}}else return{...e,value:e.value.replace(/\\"/g,`""`)}}function TY(e,t){let n=[];for(let r of t)switch(r.rule.type){case`CellIsRule`:n.push(EY(r,r.rule,e));break;case`ColorScaleRule`:n.push(AY(r,r.rule));break;case`IconSetRule`:n.push(jY(r,r.rule));break;case`DataBarRule`:n.push(kY(r,r.rule));break;default:console.warn(`Conditional formatting ${r.rule.type} not implemented`);break}return n}function EY(e,t,n){let r=MY(e),i=UM(t.operator);r.push(...OY(t)),i.length&&r.push([`operator`,i]);let a=DY(e.ranges,t).map(e=>J`<formula>${e}</formula>`),o={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&&(o.fill={fgColor:{rgb:t.style.fillColor}}),r.push([`dxfId`,eN(o,n)]),J`
3093
3093
  <conditionalFormatting sqref="${e.ranges.join(` `)}">
3094
3094
  <cfRule ${K(r)}>
3095
3095
  ${q(a)}
3096
3096
  </cfRule>
3097
3097
  </conditionalFormatting>
3098
- `}function EY(e,t){let n=e[0].split(`:`)[0],r=t.values;switch(t.operator){case`containsText`:return[`NOT(ISERROR(SEARCH("${r[0]}",${n})))`];case`notContainsText`:return[`ISERROR(SEARCH("${r[0]}",${n}))`];case`beginsWithText`:return[`LEFT(${n},LEN("${r[0]}"))="${r[0]}"`];case`endsWithText`:return[`RIGHT(${n},LEN("${r[0]}"))="${r[0]}"`];case`isEmpty`:return[`LEN(TRIM(${n}))=0`];case`isNotEmpty`:return[`LEN(TRIM(${n}))>0`];case`isEqual`:case`isNotEqual`:case`isGreaterThan`:case`isGreaterOrEqualTo`:case`isLessThan`:case`isLessOrEqualTo`:return[r[0]];case`customFormula`:return r[0].startsWith(`=`)?[r[0].slice(1)]:[r[0]];case`isBetween`:case`isNotBetween`:return[r[0],r[1]]}}function DY(e){let t=UM(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`]]}}function OY(e,t){let n=jY(e);return n.push([`type`,`dataBar`]),J`
3098
+ `}function DY(e,t){let n=e[0].split(`:`)[0],r=t.values;switch(t.operator){case`containsText`:return[`NOT(ISERROR(SEARCH("${r[0]}",${n})))`];case`notContainsText`:return[`ISERROR(SEARCH("${r[0]}",${n}))`];case`beginsWithText`:return[`LEFT(${n},LEN("${r[0]}"))="${r[0]}"`];case`endsWithText`:return[`RIGHT(${n},LEN("${r[0]}"))="${r[0]}"`];case`isEmpty`:return[`LEN(TRIM(${n}))=0`];case`isNotEmpty`:return[`LEN(TRIM(${n}))>0`];case`isEqual`:case`isNotEqual`:case`isGreaterThan`:case`isGreaterOrEqualTo`:case`isLessThan`:case`isLessOrEqualTo`:return[r[0]];case`customFormula`:return r[0].startsWith(`=`)?[r[0].slice(1)]:[r[0]];case`isBetween`:case`isNotBetween`:return[r[0],r[1]]}}function OY(e){let t=UM(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`]]}}function kY(e,t){let n=MY(e);return n.push([`type`,`dataBar`]),J`
3099
3099
  <conditionalFormatting sqref="${e.ranges.join(` `)}">
3100
3100
  <cfRule ${K(n)}>
3101
3101
  <dataBar>
@@ -3105,7 +3105,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3105
3105
  </dataBar>
3106
3106
  </cfRule>
3107
3107
  </conditionalFormatting>
3108
- `}function kY(e,t){let n=jY(e);n.push([`type`,`colorScale`]);let r=[];for(let i of e.ranges){let e=[],a=[],o=!0;for(let n of[`minimum`,`midpoint`,`maximum`]){let r=t[n];if(r){if(r.type===`formula`){o=!1;continue}e.push(FY(r,n)),a.push([[`rgb`,G(dn(r.color))]])}}if(!o){console.warn(`Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.`);continue}let s=e.map(e=>J`<cfvo ${K(e)}/>`),c=a.map(e=>J`<color ${K(e)}/>`);r.push(J`
3108
+ `}function AY(e,t){let n=MY(e);n.push([`type`,`colorScale`]);let r=[];for(let i of e.ranges){let e=[],a=[],o=!0;for(let n of[`minimum`,`midpoint`,`maximum`]){let r=t[n];if(r){if(r.type===`formula`){o=!1;continue}e.push(IY(r,n)),a.push([[`rgb`,G(dn(r.color))]])}}if(!o){console.warn(`Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.`);continue}let s=e.map(e=>J`<cfvo ${K(e)}/>`),c=a.map(e=>J`<color ${K(e)}/>`);r.push(J`
3109
3109
  <conditionalFormatting sqref="${i}">
3110
3110
  <cfRule ${K(n)}>
3111
3111
  <colorScale>
@@ -3114,7 +3114,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3114
3114
  </colorScale>
3115
3115
  </cfRule>
3116
3116
  </conditionalFormatting>
3117
- `)}return q(r)}function AY(e,t){let n=jY(e);n.push([`type`,`iconSet`]);let r=[];for(let i of e.ranges){let e=[[[`type`,`percent`],[`val`,0]]],a=!0;for(let n of[`lowerInflectionPoint`,`upperInflectionPoint`]){if(t[n].type===`formula`){a=!1;continue}let r=t[n];e.push([...FY(r,n),[`gte`,r.operator===`ge`?`1`:`0`]])}if(!a){console.warn(`Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.`);continue}let o=e.map(e=>J`<cfvo ${K(e)} />`),s=[[`iconSet`,NY(t.icons)]];MY(t.icons)&&s.push([`reverse`,`1`]),r.push(J`
3117
+ `)}return q(r)}function jY(e,t){let n=MY(e);n.push([`type`,`iconSet`]);let r=[];for(let i of e.ranges){let e=[[[`type`,`percent`],[`val`,0]]],a=!0;for(let n of[`lowerInflectionPoint`,`upperInflectionPoint`]){if(t[n].type===`formula`){a=!1;continue}let r=t[n];e.push([...IY(r,n),[`gte`,r.operator===`ge`?`1`:`0`]])}if(!a){console.warn(`Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.`);continue}let o=e.map(e=>J`<cfvo ${K(e)} />`),s=[[`iconSet`,PY(t.icons)]];NY(t.icons)&&s.push([`reverse`,`1`]),r.push(J`
3118
3118
  <conditionalFormatting sqref="${i}">
3119
3119
  <cfRule ${K(n)}>
3120
3120
  <iconSet ${K(s)}>
@@ -3122,7 +3122,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3122
3122
  </iconSet>
3123
3123
  </cfRule>
3124
3124
  </conditionalFormatting>
3125
- `)}return q(r)}function jY(e){return[[`priority`,1],[`stopIfTrue`,+!!e.stopIfTrue]]}function MY(e){let t=Lj[PY(e)];return e.upper===t.bad&&e.lower===t.good}function NY(e){return Hf[PY(e)]}function PY(e){return Object.keys(Lj).find(t=>Object.values(Lj[t]).includes(e.upper))||`dots`}function FY(e,t){let n=IY(e.type,t),r=[[`type`,n]];if(n!==`min`&&n!==`max`){let t=e.value;if(n===`formula`)try{t=yY(e.value)}catch{t=e.value}r.push([`val`,t])}return r}function IY(e,t){switch(e){case`value`:return t===`minimum`?`min`:`max`;case`number`:return`num`;case`percentage`:return`percent`;default:return e}}function LY(e){let t=e.length;if(t===0)return[];let n=[new wO(`<dataValidations count="${t}">`)];for(let t of e)switch(t.criterion.type){case`dateIs`:case`dateIsBefore`:case`dateIsOnOrBefore`:case`dateIsAfter`:case`dateIsOnOrAfter`:case`dateIsBetween`:case`dateIsNotBetween`:n.push(RY(t));break;case`isEqual`:case`isNotEqual`:case`isGreaterThan`:case`isGreaterOrEqualTo`:case`isLessThan`:case`isLessOrEqualTo`:case`isBetween`:case`isNotBetween`:n.push(zY(t));break;case`isValueInRange`:case`isValueInList`:n.push(BY(t));break;case`customFormula`:n.push(VY(t));break;default:console.warn(`Data validation ${t.criterion.type} is not supported in xlsx.`);break}return n.push(new wO(`</dataValidations>`)),n}function RY(e){let t=e.criterion,n=yY(t.values[0]),r=t.values[1]?yY(t.values[1]):void 0,i=uN(e.criterion.type),a=HY(e);return a.push([`type`,`date`],[`operator`,i]),r?J`
3125
+ `)}return q(r)}function MY(e){return[[`priority`,1],[`stopIfTrue`,+!!e.stopIfTrue]]}function NY(e){let t=Lj[FY(e)];return e.upper===t.bad&&e.lower===t.good}function PY(e){return Hf[FY(e)]}function FY(e){return Object.keys(Lj).find(t=>Object.values(Lj[t]).includes(e.upper))||`dots`}function IY(e,t){let n=LY(e.type,t),r=[[`type`,n]];if(n!==`min`&&n!==`max`){let t=e.value;if(n===`formula`)try{t=bY(e.value)}catch{t=e.value}r.push([`val`,t])}return r}function LY(e,t){switch(e){case`value`:return t===`minimum`?`min`:`max`;case`number`:return`num`;case`percentage`:return`percent`;default:return e}}function RY(e){let t=e.length;if(t===0)return[];let n=[new wO(`<dataValidations count="${t}">`)];for(let t of e)switch(t.criterion.type){case`dateIs`:case`dateIsBefore`:case`dateIsOnOrBefore`:case`dateIsAfter`:case`dateIsOnOrAfter`:case`dateIsBetween`:case`dateIsNotBetween`:n.push(zY(t));break;case`isEqual`:case`isNotEqual`:case`isGreaterThan`:case`isGreaterOrEqualTo`:case`isLessThan`:case`isLessOrEqualTo`:case`isBetween`:case`isNotBetween`:n.push(BY(t));break;case`isValueInRange`:case`isValueInList`:n.push(VY(t));break;case`customFormula`:n.push(HY(t));break;default:console.warn(`Data validation ${t.criterion.type} is not supported in xlsx.`);break}return n.push(new wO(`</dataValidations>`)),n}function zY(e){let t=e.criterion,n=bY(t.values[0]),r=t.values[1]?bY(t.values[1]):void 0,i=uN(e.criterion.type),a=UY(e);return a.push([`type`,`date`],[`operator`,i]),r?J`
3126
3126
  <dataValidation ${K(a)}>
3127
3127
  <formula1>${M(n,D)}</formula1>
3128
3128
  <formula2>${M(r,D)}</formula2>
@@ -3131,7 +3131,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3131
3131
  <dataValidation ${K(a)}>
3132
3132
  <formula1>${M(n,D)}</formula1>
3133
3133
  </dataValidation>
3134
- `}function zY(e){let t=e.criterion,n=yY(t.values[0]),r=t.values[1]?yY(t.values[1]):void 0,i=lN(e.criterion.type),a=HY(e);return a.push([`type`,`decimal`],[`operator`,i]),r?J`
3134
+ `}function BY(e){let t=e.criterion,n=bY(t.values[0]),r=t.values[1]?bY(t.values[1]):void 0,i=lN(e.criterion.type),a=UY(e);return a.push([`type`,`decimal`],[`operator`,i]),r?J`
3135
3135
  <dataValidation ${K(a)}>
3136
3136
  <formula1>${n}</formula1>
3137
3137
  <formula2>${r}</formula2>
@@ -3140,19 +3140,19 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3140
3140
  <dataValidation ${K(a)}>
3141
3141
  <formula1>${n}</formula1>
3142
3142
  </dataValidation>
3143
- `}function BY(e){let t=e.criterion,n=e.criterion.type===`isValueInRange`?yY(t.values[0]):`"${t.values.join(`,`)}"`,r=HY(e);return r.push([`type`,`list`]),J`
3143
+ `}function VY(e){let t=e.criterion,n=e.criterion.type===`isValueInRange`?bY(t.values[0]):`"${t.values.join(`,`)}"`,r=UY(e);return r.push([`type`,`list`]),J`
3144
3144
  <dataValidation ${K(r)}>
3145
3145
  <formula1>${n}</formula1>
3146
3146
  </dataValidation>
3147
- `}function VY(e){let t=e.criterion,n=yY(t.values[0]),r=HY(e);return r.push([`type`,`custom`]),J`
3147
+ `}function HY(e){let t=e.criterion,n=bY(t.values[0]),r=UY(e);return r.push([`type`,`custom`]),J`
3148
3148
  <dataValidation ${K(r)}>
3149
3149
  <formula1>${n}</formula1>
3150
3150
  </dataValidation>
3151
- `}function HY(e){return[[`allowBlank`,`1`],[`showInputMessage`,`1`],[`showErrorMessage`,`1`],[`errorStyle`,e.isBlocking?``:`warning`],[`sqref`,e.ranges.join(` `)]]}function UY(e,t,n,r){let i=[[`xmlns:xdr`,Uf.drawing],[`xmlns:r`,Jf],[`xmlns:a`,Wf],[`xmlns:c`,Gf]],a=[];for(let[i,o]of Object.entries(n))switch(o?.tag){case`chart`:a.push(KY(o,t,e[i],r));break;case`image`:a.push(qY(o,t,e[i]));break}return OO(J`
3151
+ `}function UY(e){return[[`allowBlank`,`1`],[`showInputMessage`,`1`],[`showErrorMessage`,`1`],[`errorStyle`,e.isBlocking?``:`warning`],[`sqref`,e.ranges.join(` `)]]}function WY(e,t,n,r){let i=[[`xmlns:xdr`,Uf.drawing],[`xmlns:r`,Jf],[`xmlns:a`,Wf],[`xmlns:c`,Gf]],a=[];for(let[i,o]of Object.entries(n))switch(o?.tag){case`chart`:a.push(qY(o,t,e[i],r));break;case`image`:a.push(JY(o,t,e[i]));break}return OO(J`
3152
3152
  <xdr:wsDr ${K(i)}>
3153
3153
  ${q(a)}
3154
3154
  </xdr:wsDr>
3155
- `)}function WY(e,t){let{col:n,row:r,offset:i,width:a,height:o}=e,{x:s,y:c}=i,l=Object.values(t.rows),{index:u,offset:d}=GY(l,r,c),{index:f,offset:p}=GY(l,r,c+o),m=Object.values(t.cols),{index:h,offset:g}=GY(m,n,s),{index:_,offset:v}=GY(m,n,s+a);return{from:{col:h,colOff:g,row:u,rowOff:d},to:{col:_,colOff:v,row:f,rowOff:p}}}function GY(e,t,n){let r=0;for(let[i,a]of e.slice(t).entries())if(r<=n&&n<r+a.size)return{index:t+i,offset:iN(n-r+1)};else i<e.length-1&&(r+=a.size);return{index:e.length-1,offset:iN(n-r+1)}}function KY(e,t,n,r){let{from:i,to:a}=WY(e,t),o=tN(e.id,r),s=[[`id`,o],[`name`,`Chart ${o}`],[`title`,`Chart`]];return J`
3155
+ `)}function GY(e,t){let{col:n,row:r,offset:i,width:a,height:o}=e,{x:s,y:c}=i,l=Object.values(t.rows),{index:u,offset:d}=KY(l,r,c),{index:f,offset:p}=KY(l,r,c+o),m=Object.values(t.cols),{index:h,offset:g}=KY(m,n,s),{index:_,offset:v}=KY(m,n,s+a);return{from:{col:h,colOff:g,row:u,rowOff:d},to:{col:_,colOff:v,row:f,rowOff:p}}}function KY(e,t,n){let r=0;for(let[i,a]of e.slice(t).entries())if(r<=n&&n<r+a.size)return{index:t+i,offset:iN(n-r+1)};else i<e.length-1&&(r+=a.size);return{index:e.length-1,offset:iN(n-r+1)}}function qY(e,t,n,r){let{from:i,to:a}=GY(e,t),o=tN(e.id,r),s=[[`id`,o],[`name`,`Chart ${o}`],[`title`,`Chart`]];return J`
3156
3156
  <xdr:twoCellAnchor>
3157
3157
  <xdr:from>
3158
3158
  <xdr:col>${i.col}</xdr:col>
@@ -3183,7 +3183,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3183
3183
  </xdr:graphicFrame>
3184
3184
  <xdr:clientData fLocksWithSheet="0"/>
3185
3185
  </xdr:twoCellAnchor>
3186
- `}function qY(e,t,n){let{from:r,to:i}=WY(e,t),a=rN(e.id),o=[[`id`,a],[`name`,`Image ${a}`],[`title`,`Image`]],s=iN(e.width),c=iN(e.height);return J`
3186
+ `}function JY(e,t,n){let{from:r,to:i}=GY(e,t),a=rN(e.id),o=[[`id`,a],[`name`,`Image ${a}`],[`title`,`Image`]],s=iN(e.width),c=iN(e.height);return J`
3187
3187
  <xdr:twoCellAnchor editAs="oneCell">
3188
3188
  <xdr:from>
3189
3189
  <xdr:col>${r.col}</xdr:col>
@@ -3220,13 +3220,13 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3220
3220
  </xdr:pic>
3221
3221
  <xdr:clientData fLocksWithSheet="0"/>
3222
3222
  </xdr:twoCellAnchor>
3223
- `}function JY(e){let t=[];for(let[n,r]of Object.entries(e)){let e=[[`numFmtId`,parseInt(n)+164],[`formatCode`,r.format]];t.push(J`
3223
+ `}function YY(e){let t=[];for(let[n,r]of Object.entries(e)){let e=[[`numFmtId`,parseInt(n)+164],[`formatCode`,r.format]];t.push(J`
3224
3224
  <numFmt ${K(e)}/>
3225
3225
  `)}return J`
3226
3226
  <numFmts count="${e.length}">
3227
3227
  ${q(t)}
3228
3228
  </numFmts>
3229
- `}function YY(e){return kt(e)?J``:J`
3229
+ `}function XY(e){return kt(e)?J``:J`
3230
3230
  <font>
3231
3231
  ${e.bold?J`<b />`:``}
3232
3232
  ${e.italic?J`<i />`:``}
@@ -3236,11 +3236,11 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3236
3236
  ${e.color&&e.color.rgb?J`<color rgb="${G(e.color.rgb)}" />`:``}
3237
3237
  ${e.name?J`<name val="${e.name}" />`:``}
3238
3238
  </font>
3239
- `}function XY(e){return J`
3239
+ `}function ZY(e){return J`
3240
3240
  <fonts count="${e.length}">
3241
- ${q(Object.values(e).map(YY))}
3241
+ ${q(Object.values(e).map(XY))}
3242
3242
  </fonts>
3243
- `}function ZY(e){let t=[];for(let n of Object.values(e))n.reservedAttribute===void 0?t.push(J`
3243
+ `}function QY(e){let t=[];for(let n of Object.values(e))n.reservedAttribute===void 0?t.push(J`
3244
3244
  <fill>
3245
3245
  <patternFill patternType="solid">
3246
3246
  <fgColor rgb="${G(n.fgColor.rgb)}" />
@@ -3255,35 +3255,35 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3255
3255
  <fills count="${e.length}">
3256
3256
  ${q(t)}
3257
3257
  </fills>
3258
- `}function QY(e){let t=[];for(let n of Object.values(e))t.push(J`
3258
+ `}function $Y(e){let t=[];for(let n of Object.values(e))t.push(J`
3259
3259
  <border>
3260
- <left ${$Y(n.left)}>
3261
- ${eX(n.left)}
3260
+ <left ${eX(n.left)}>
3261
+ ${tX(n.left)}
3262
3262
  </left>
3263
- <right ${$Y(n.right)}>
3264
- ${eX(n.right)}
3263
+ <right ${eX(n.right)}>
3264
+ ${tX(n.right)}
3265
3265
  </right>
3266
- <top ${$Y(n.top)}>
3267
- ${eX(n.top)}
3266
+ <top ${eX(n.top)}>
3267
+ ${tX(n.top)}
3268
3268
  </top>
3269
- <bottom ${$Y(n.bottom)}>
3270
- ${eX(n.bottom)}
3269
+ <bottom ${eX(n.bottom)}>
3270
+ ${tX(n.bottom)}
3271
3271
  </bottom>
3272
- <diagonal ${$Y(n.diagonal)}>
3273
- ${eX(n.diagonal)}
3272
+ <diagonal ${eX(n.diagonal)}>
3273
+ ${tX(n.diagonal)}
3274
3274
  </diagonal>
3275
3275
  </border>
3276
3276
  `);return J`
3277
3277
  <borders count="${e.length}">
3278
3278
  ${q(t)}
3279
3279
  </borders>
3280
- `}function $Y(e){return e?K([[`style`,e.style]]):J``}function eX(e){return e?J`
3280
+ `}function eX(e){return e?K([[`style`,e.style]]):J``}function tX(e){return e?J`
3281
3281
  <color ${K([[`rgb`,G(e.color.rgb)]])}/>
3282
- `:J``}function tX(e){let t=[];for(let n of e){let e=[[`numFmtId`,n.numFmtId],[`fillId`,n.fillId],[`fontId`,n.fontId],[`borderId`,n.borderId]],r=[];n.alignment&&n.alignment.vertical&&r.push([`vertical`,n.alignment.vertical]),n.alignment&&n.alignment.horizontal&&r.push([`horizontal`,n.alignment.horizontal]),n.alignment&&n.alignment.wrapText&&r.push([`wrapText`,`1`]),n.alignment&&n.alignment.shrinkToFit&&r.push([`shrinkToFit`,`1`]),r.length>0?(e.push([`applyAlignment`,`1`]),t.push(J`<xf ${K(e)}><alignment ${K(r)} /></xf> `)):t.push(J`<xf ${K(e)} />`)}return J`
3282
+ `:J``}function nX(e){let t=[];for(let n of e){let e=[[`numFmtId`,n.numFmtId],[`fillId`,n.fillId],[`fontId`,n.fontId],[`borderId`,n.borderId]],r=[];n.alignment&&n.alignment.vertical&&r.push([`vertical`,n.alignment.vertical]),n.alignment&&n.alignment.horizontal&&r.push([`horizontal`,n.alignment.horizontal]),n.alignment&&n.alignment.wrapText&&r.push([`wrapText`,`1`]),n.alignment&&n.alignment.shrinkToFit&&r.push([`shrinkToFit`,`1`]),r.length>0?(e.push([`applyAlignment`,`1`]),t.push(J`<xf ${K(e)}><alignment ${K(r)} /></xf> `)):t.push(J`<xf ${K(e)} />`)}return J`
3283
3283
  <cellXfs count="${e.length}">
3284
3284
  ${q(t)}
3285
3285
  </cellXfs>
3286
- `}function nX(e){let t=[];for(let n of e){let e=J``;n.font&&(e=YY(n.font));let r=J``;n.fill&&(r=J`
3286
+ `}function rX(e){let t=[];for(let n of e){let e=J``;n.font&&(e=XY(n.font));let r=J``;n.fill&&(r=J`
3287
3287
  <fill>
3288
3288
  <patternFill>
3289
3289
  <bgColor rgb="${G(n.fill.fgColor.rgb)}" />
@@ -3298,35 +3298,35 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3298
3298
  <dxfs count="${e.length}">
3299
3299
  ${q(t)}
3300
3300
  </dxfs>
3301
- `}function rX(e,t,n){return OO(J`
3301
+ `}function iX(e,t,n){return OO(J`
3302
3302
  <table ${K([[`id`,t],[`name`,`Table${t}`],[`displayName`,`Table${t}`],[`ref`,e.range],[`headerRowCount`,e.config.numberOfHeaders],[`totalsRowCount`,+!!e.config.totalRow],[`xmlns`,Uf.table],[`xmlns:xr`,Uf.revision],[`xmlns:xr3`,Uf.revision3],[`xmlns:mc`,Uf.markupCompatibility]])}>
3303
- ${e.config.hasFilters?iX(e):``}
3304
- ${sX(e,n)}
3305
- ${cX(e)}
3303
+ ${e.config.hasFilters?aX(e):``}
3304
+ ${cX(e,n)}
3305
+ ${lX(e)}
3306
3306
  </table>
3307
- `)}function iX(e){return J`
3307
+ `)}function aX(e){return J`
3308
3308
  <autoFilter ${K([[`ref`,e.range]])}>
3309
- ${q(aX(e))}
3309
+ ${q(oX(e))}
3310
3310
  </autoFilter>
3311
- `}function aX(e){let t=[];for(let n of e.filters){let e=J`
3311
+ `}function oX(e){let t=[];for(let n of e.filters){let e=J`
3312
3312
  <filterColumn ${K([[`colId`,n.colId]])}>
3313
- ${oX(n)}
3313
+ ${sX(n)}
3314
3314
  </filterColumn>
3315
- `;t.push(e)}return t}function oX(e){let t=e.displayedValues.map(e=>J`<filter ${K([[`val`,e]])}/>`);return J`
3315
+ `;t.push(e)}return t}function sX(e){let t=e.displayedValues.map(e=>J`<filter ${K([[`val`,e]])}/>`);return J`
3316
3316
  <filters ${K(e.displayBlanks?[[`blank`,1]]:[])}>
3317
3317
  ${q(t)}
3318
3318
  </filters>
3319
- `}function sX(e,t){let n=Ts(e.range),r=[];for(let i of S(0,Us(n).numberOfCols)){let a=T(n.left+i,n.top),o=t.cells[a]||`col${i}`,s=[[`id`,i+1],[`name`,o]];if(e.config.totalRow){let e=T(n.left+i,n.bottom);t.cells[e]?.startsWith(`=`)&&s.push([`totalsRowFunction`,`custom`])}r.push(J`<tableColumn ${K(s)}/>`)}return J`
3319
+ `}function cX(e,t){let n=Ts(e.range),r=[];for(let i of S(0,Us(n).numberOfCols)){let a=T(n.left+i,n.top),o=t.cells[a]||`col${i}`,s=[[`id`,i+1],[`name`,o]];if(e.config.totalRow){let e=T(n.left+i,n.bottom);t.cells[e]?.startsWith(`=`)&&s.push([`totalsRowFunction`,`custom`])}r.push(J`<tableColumn ${K(s)}/>`)}return J`
3320
3320
  <tableColumns ${K([[`count`,r.length]])}>
3321
3321
  ${q(r)}
3322
3322
  </tableColumns>
3323
- `}function cX(e){return J`<tableStyleInfo ${K([[`name`,e.config.styleId],[`showFirstColumn`,+!!e.config.firstColumn],[`showLastColumn`,+!!e.config.lastColumn],[`showRowStripes`,+!!e.config.bandedRows],[`showColumnStripes`,+!!e.config.bandedColumns]])}/>`}function lX(e){if(!Object.values(e).length)return J``;let t=[];for(let[n,r]of Object.entries(e)){let e=[[`min`,parseInt(n)+1],[`max`,parseInt(n)+1],[`width`,KM(r.size||96)],[`customWidth`,1],[`hidden`,+!!r.isHidden]];r.outlineLevel&&e.push([`outlineLevel`,r.outlineLevel]),r.collapsed&&e.push([`collapsed`,1]),t.push(J`
3323
+ `}function lX(e){return J`<tableStyleInfo ${K([[`name`,e.config.styleId],[`showFirstColumn`,+!!e.config.firstColumn],[`showLastColumn`,+!!e.config.lastColumn],[`showRowStripes`,+!!e.config.bandedRows],[`showColumnStripes`,+!!e.config.bandedColumns]])}/>`}function uX(e){if(!Object.values(e).length)return J``;let t=[];for(let[n,r]of Object.entries(e)){let e=[[`min`,parseInt(n)+1],[`max`,parseInt(n)+1],[`width`,KM(r.size||96)],[`customWidth`,1],[`hidden`,+!!r.isHidden]];r.outlineLevel&&e.push([`outlineLevel`,r.outlineLevel]),r.collapsed&&e.push([`collapsed`,1]),t.push(J`
3324
3324
  <col ${K(e)}/>
3325
3325
  `)}return J`
3326
3326
  <cols>
3327
3327
  ${q(t)}
3328
3328
  </cols>
3329
- `}function uX(e,t,n){let r=[],i=new LF(gc(n.id,n.styles)),a=new LF(gc(n.id,n.borders)),o=new LF(gc(n.id,n.formats));for(let s=0;s<n.rowNumber;s++){let c=[[`r`,s+1]],l=n.rows[s]||{};l.size&&l.size!==23&&c.push([`ht`,GM(l.size)],[`customHeight`,1]),l.isHidden&&c.push([`hidden`,1]),l.outlineLevel&&c.push([`outlineLevel`,l.outlineLevel]),l.collapsed&&c.push([`collapsed`,1]);let u=[];for(let r=0;r<n.colNumber;r++){let c=T(r,s),l=n.cells[c],d=n.cellValues[c],f={sheetId:n.id,col:r,row:s},p=i.get(f),m=o.get(f),h=a.get(f);if(l||p||m||h||d!==void 0){let i=[[`r`,c]],a=XM(e,YM(t,l,p,m,h));a&&i.push([`s`,a]);let o=[],f=J``;if(l?.startsWith(`=`)&&d!==void 0){let e=_Y(l,d,n.formulaSpillRanges[c]??c);if(!e)continue;({attrs:o,node:f}=e)}else if(l&&xt(l)){let{label:t}=wt(l);({attrs:o,node:f}=vY(t,e.sharedStrings))}else if(l&&l!==``){let i=dX(r,s,n),a=fX(r,s,n),c=!!(m&&$o(t.formats[m]));({attrs:o,node:f}=vY(l,e.sharedStrings,i||a||c))}i.push(...o),u.push(J`<c ${K(i)}>
3329
+ `}function dX(e,t,n){let r=[],i=new LF(gc(n.id,n.styles)),a=new LF(gc(n.id,n.borders)),o=new LF(gc(n.id,n.formats));for(let s=0;s<n.rowNumber;s++){let c=[[`r`,s+1]],l=n.rows[s]||{};l.size&&l.size!==23&&c.push([`ht`,GM(l.size)],[`customHeight`,1]),l.isHidden&&c.push([`hidden`,1]),l.outlineLevel&&c.push([`outlineLevel`,l.outlineLevel]),l.collapsed&&c.push([`collapsed`,1]);let u=[];for(let r=0;r<n.colNumber;r++){let c=T(r,s),l=n.cells[c],d=n.cellValues[c],f={sheetId:n.id,col:r,row:s},p=i.get(f),m=o.get(f),h=a.get(f);if(l||p||m||h||d!==void 0){let i=[[`r`,c]],a=XM(e,YM(t,l,p,m,h));a&&i.push([`s`,a]);let o=[],f=J``;if(l?.startsWith(`=`)&&d!==void 0){let e=vY(l,d,n.formulaSpillRanges[c]??c);if(!e)continue;({attrs:o,node:f}=e)}else if(l&&xt(l)){let{label:t}=wt(l);({attrs:o,node:f}=yY(t,e.sharedStrings))}else if(l&&l!==``){let i=fX(r,s,n),a=pX(r,s,n),c=!!(m&&$o(t.formats[m]));({attrs:o,node:f}=yY(l,e.sharedStrings,i||a||c))}i.push(...o),u.push(J`<c ${K(i)}>
3330
3330
  ${f}
3331
3331
  </c>`)}}(u.length||l.size!==23||l.isHidden||l.outlineLevel||l.collapsed)&&r.push(J`
3332
3332
  <row ${K(c)}>
@@ -3336,7 +3336,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3336
3336
  <sheetData>
3337
3337
  ${q(r)}
3338
3338
  </sheetData>
3339
- `}function dX(e,t,n){return n.tables.some(n=>{let r=Ts(n.range);return Vs(e,t,{...r,bottom:r.top})})}function fX(e,t,n){return n.tables.some(n=>{if(!n.config.totalRow)return!1;let r=Ts(n.range);return Vs(e,t,{...r,top:r.bottom})})}function pX(e,t,n){let r=t.sheets[n].cells,i=[];for(let a in r){let o=r[a];if(o&&xt(o)){let{label:r,url:s}=wt(o);if(Et(s)){let e=Ot(s),n=t.sheets.find(t=>t.id===e),o=n?`${n.name}!A1`:k.InvalidReference,c=[[`display`,r],[`location`,o],[`ref`,a]];i.push(J`
3339
+ `}function fX(e,t,n){return n.tables.some(n=>{let r=Ts(n.range);return Vs(e,t,{...r,bottom:r.top})})}function pX(e,t,n){return n.tables.some(n=>{if(!n.config.totalRow)return!1;let r=Ts(n.range);return Vs(e,t,{...r,top:r.bottom})})}function mX(e,t,n){let r=t.sheets[n].cells,i=[];for(let a in r){let o=r[a];if(o&&xt(o)){let{label:r,url:s}=wt(o);if(Et(s)){let e=Ot(s),n=t.sheets.find(t=>t.id===e),o=n?`${n.name}!A1`:k.InvalidReference,c=[[`display`,r],[`location`,o],[`ref`,a]];i.push(J`
3340
3340
  <hyperlink ${K(c)}/>
3341
3341
  `)}else{let t=[[`r:id`,QM(e.relsFiles,`xl/worksheets/_rels/sheet${n}.xml.rels`,{target:Ur(s),type:qf.hyperlink,targetMode:`External`})],[`ref`,a]];i.push(J`
3342
3342
  <hyperlink ${K(t)}/>
@@ -3344,11 +3344,11 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3344
3344
  <hyperlinks>
3345
3345
  ${q(i)}
3346
3346
  </hyperlinks>
3347
- `:J``}function mX(e){if(e.length){let t=e.map(e=>J`<mergeCell ref="${e}" />`);return J`
3347
+ `:J``}function hX(e){if(e.length){let t=e.map(e=>J`<mergeCell ref="${e}" />`);return J`
3348
3348
  <mergeCells count="${e.length}">
3349
3349
  ${q(t)}
3350
3350
  </mergeCells>
3351
- `}else return J``}function hX(e){let t=e.panes,n=J``;if(t&&(t.xSplit||t.ySplit)){let e=T(t.xSplit,t.ySplit),r=t.xSplit?J`xSplit="${t.xSplit}"`:``,i=t.ySplit?J`ySplit="${t.ySplit}"`:``,a=t.xSplit?J`<selection pane="topRight"/>`:``,o=t.ySplit?J`<selection pane="bottomLeft"/>`:``,s=t.xSplit&&t.ySplit?J`<selection pane="bottomRight"/>`:``;n=J`
3351
+ `}else return J``}function gX(e){let t=e.panes,n=J``;if(t&&(t.xSplit||t.ySplit)){let e=T(t.xSplit,t.ySplit),r=t.xSplit?J`xSplit="${t.xSplit}"`:``,i=t.ySplit?J`ySplit="${t.ySplit}"`:``,a=t.xSplit?J`<selection pane="topRight"/>`:``,o=t.ySplit?J`<selection pane="bottomLeft"/>`:``,s=t.xSplit&&t.ySplit?J`<selection pane="bottomRight"/>`:``;n=J`
3352
3352
  <pane
3353
3353
  ${r}
3354
3354
  ${i}
@@ -3364,11 +3364,11 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3364
3364
  ${n}
3365
3365
  </sheetView>
3366
3366
  </sheetViews>
3367
- `}function gX(e){return e.color?J`
3367
+ `}function _X(e){return e.color?J`
3368
3368
  <sheetPr>
3369
3369
  <tabColor ${K([[`rgb`,G(e.color)]])} />
3370
3370
  </sheetPr>
3371
- `:``}function _X(e){e=EX(e),e=DX(e);let t=[],n=AO(e);return t.push(vX(e,n)),t.push(...yX(e,n)),t.push(xX(n)),t.push(SX(n.sharedStrings)),t.push(...CX(n.relsFiles)),t.push(wX(t)),t.push(TX()),{name:`my_spreadsheet.xlsx`,files:t}}function vX(e,t){let n=[[`xmlns`,Uf.workbook],[`xmlns:r`,Jf]],r=[];for(let[n,i]of Object.entries(e.sheets)){let e=[[`state`,i.isVisible?`visible`:`hidden`],[`name`,i.name],[`sheetId`,parseInt(n)+1],[`r:id`,`rId${parseInt(n)+1}`]];r.push(J`
3371
+ `:``}function vX(e){e=DX(e),e=OX(e);let t=[],n=AO(e);return t.push(yX(e,n)),t.push(...bX(e,n)),t.push(SX(n)),t.push(CX(n.sharedStrings)),t.push(...wX(n.relsFiles)),t.push(TX(t)),t.push(EX()),{name:`my_spreadsheet.xlsx`,files:t}}function yX(e,t){let n=[[`xmlns`,Uf.workbook],[`xmlns:r`,Jf]],r=[];for(let[n,i]of Object.entries(e.sheets)){let e=[[`state`,i.isVisible?`visible`:`hidden`],[`name`,i.name],[`sheetId`,parseInt(n)+1],[`r:id`,`rId${parseInt(n)+1}`]];r.push(J`
3372
3372
  <sheet ${K(e)} />
3373
3373
  `),QM(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:qf.sheet,target:`worksheets/sheet${n}.xml`})}return EO(OO(J`
3374
3374
  <workbook ${K(n)}>
@@ -3376,17 +3376,17 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3376
3376
  ${q(r)}
3377
3377
  </sheets>
3378
3378
  </workbook>
3379
- `),`xl/workbook.xml`,`workbook`)}function yX(e,t){let n=[],r=1;for(let[i,a]of Object.entries(e.sheets)){let o=[[`xmlns`,Uf.worksheet],[`xmlns:r`,Jf]],s=[[`defaultRowHeight`,GM(23)],[`defaultColWidth`,KM(96)]],c=bX(a,i,r,t,n);r+=a.tables.length;let l=J``,u=[];for(let r of a.charts){let a=tN(r.id,t),o=QM(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../charts/chart${a}.xml`,type:qf.chart});u.push(o),n.push(EO(qJ(r,i,e),`xl/charts/chart${a}.xml`,`chart`))}for(let e of a.images){let r=e.data.mimetype;if(r===void 0)continue;let a=mM[r];if(a===void 0)continue;let o=`image${rN(e.id)}.${a}`,s=QM(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../media/${o}`,type:qf.image});u.push(s),n.push({path:`xl/media/${o}`,imageSrc:e.data.path})}let d=[...a.charts,...a.images];if(d.length){let e=QM(t.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:`../drawings/drawing${i}.xml`,type:qf.drawing});n.push(EO(UY(u,a,d,t),`xl/drawings/drawing${i}.xml`,`drawing`)),l=J`<drawing r:id="${e}" />`}let f=J`
3379
+ `),`xl/workbook.xml`,`workbook`)}function bX(e,t){let n=[],r=1;for(let[i,a]of Object.entries(e.sheets)){let o=[[`xmlns`,Uf.worksheet],[`xmlns:r`,Jf]],s=[[`defaultRowHeight`,GM(23)],[`defaultColWidth`,KM(96)]],c=xX(a,i,r,t,n);r+=a.tables.length;let l=J``,u=[];for(let r of a.charts){let a=tN(r.id,t),o=QM(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../charts/chart${a}.xml`,type:qf.chart});u.push(o),n.push(EO(JJ(r,i,e),`xl/charts/chart${a}.xml`,`chart`))}for(let e of a.images){let r=e.data.mimetype;if(r===void 0)continue;let a=mM[r];if(a===void 0)continue;let o=`image${rN(e.id)}.${a}`,s=QM(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../media/${o}`,type:qf.image});u.push(s),n.push({path:`xl/media/${o}`,imageSrc:e.data.path})}let d=[...a.charts,...a.images];if(d.length){let e=QM(t.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:`../drawings/drawing${i}.xml`,type:qf.drawing});n.push(EO(WY(u,a,d,t),`xl/drawings/drawing${i}.xml`,`drawing`)),l=J`<drawing r:id="${e}" />`}let f=J`
3380
3380
  <worksheet ${K(o)}>
3381
+ ${_X(a)}
3381
3382
  ${gX(a)}
3382
- ${hX(a)}
3383
3383
  <sheetFormatPr ${K(s)} />
3384
- ${lX(a.cols)}
3385
- ${uX(t,e,a)}
3386
- ${mX(a.merges)}
3387
- ${q(wY(t.dxfs,a.conditionalFormats))}
3388
- ${q(LY(a.dataValidationRules))}
3389
- ${pX(t,e,i)}
3384
+ ${uX(a.cols)}
3385
+ ${dX(t,e,a)}
3386
+ ${hX(a.merges)}
3387
+ ${q(TY(t.dxfs,a.conditionalFormats))}
3388
+ ${q(RY(a.dataValidationRules))}
3389
+ ${mX(t,e,i)}
3390
3390
  ${l}
3391
3391
  ${c}
3392
3392
  </worksheet>
@@ -3412,38 +3412,38 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
3412
3412
  </bk>
3413
3413
  </cellMetadata>
3414
3414
  </metadata>
3415
- `;return n.push(EO(OO(i),`xl/metadata.xml`,`metadata`)),QM(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:qf.sharedStrings,target:`sharedStrings.xml`}),QM(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:qf.styles,target:`styles.xml`}),QM(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:qf.metadata,target:`metadata.xml`}),n}function bX(e,t,n,r,i){let a=n;if(!e.tables.length)return new wO(``);let o=`xl/worksheets/_rels/sheet${t}.xml.rels`,s=[];for(let t of e.tables){let n=QM(r.relsFiles,o,{target:`../tables/table${a}.xml`,type:qf.table});i.push(EO(rX(t,a,e),`xl/tables/table${a}.xml`,`table`)),s.push(J`<tablePart r:id="${n}" />`),a++}return J`
3415
+ `;return n.push(EO(OO(i),`xl/metadata.xml`,`metadata`)),QM(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:qf.sharedStrings,target:`sharedStrings.xml`}),QM(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:qf.styles,target:`styles.xml`}),QM(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:qf.metadata,target:`metadata.xml`}),n}function xX(e,t,n,r,i){let a=n;if(!e.tables.length)return new wO(``);let o=`xl/worksheets/_rels/sheet${t}.xml.rels`,s=[];for(let t of e.tables){let n=QM(r.relsFiles,o,{target:`../tables/table${a}.xml`,type:qf.table});i.push(EO(iX(t,a,e),`xl/tables/table${a}.xml`,`table`)),s.push(J`<tablePart r:id="${n}" />`),a++}return J`
3416
3416
  <tableParts count="${e.tables.length}">
3417
3417
  ${q(s)}
3418
3418
  </tableParts>
3419
- `}function xX(e){return EO(OO(J`
3419
+ `}function SX(e){return EO(OO(J`
3420
3420
  <styleSheet ${K([[`xmlns`,Uf.styleSheet],[`xmlns:r`,Jf]])}>
3421
- ${JY(e.numFmts)}
3422
- ${XY(e.fonts)}
3423
- ${ZY(e.fills)}
3424
- ${QY(e.borders)}
3425
- ${tX(e.styles)}
3426
- ${nX(e.dxfs)}
3421
+ ${YY(e.numFmts)}
3422
+ ${ZY(e.fonts)}
3423
+ ${QY(e.fills)}
3424
+ ${$Y(e.borders)}
3425
+ ${nX(e.styles)}
3426
+ ${rX(e.dxfs)}
3427
3427
  </styleSheet>
3428
- `),`xl/styles.xml`,`styles`)}function SX(e){let t=[[`xmlns`,Uf.sst],[`count`,e.length],[`uniqueCount`,e.length]],n=e.map(e=>e.trim()===e?J`<si><t>${e}</t></si>`:J`<si><t xml:space="preserve">${e}</t></si>`);return EO(OO(J`
3428
+ `),`xl/styles.xml`,`styles`)}function CX(e){let t=[[`xmlns`,Uf.sst],[`count`,e.length],[`uniqueCount`,e.length]],n=e.map(e=>e.trim()===e?J`<si><t>${e}</t></si>`:J`<si><t xml:space="preserve">${e}</t></si>`);return EO(OO(J`
3429
3429
  <sst ${K(t)}>
3430
3430
  ${q(n)}
3431
3431
  </sst>
3432
- `),`xl/sharedStrings.xml`,`sharedStrings`)}function CX(e){let t=[];for(let n of e){let e=[];for(let t of n.rels){let n=[[`Id`,t.id],[`Target`,t.target],[`Type`,t.type]];t.targetMode&&n.push([`TargetMode`,t.targetMode]),e.push(J`
3432
+ `),`xl/sharedStrings.xml`,`sharedStrings`)}function wX(e){let t=[];for(let n of e){let e=[];for(let t of n.rels){let n=[[`Id`,t.id],[`Target`,t.target],[`Type`,t.type]];t.targetMode&&n.push([`TargetMode`,t.targetMode]),e.push(J`
3433
3433
  <Relationship ${K(n)} />
3434
3434
  `)}let r=J`
3435
3435
  <Relationships xmlns="${Uf.Relationships}">
3436
3436
  ${q(e)}
3437
3437
  </Relationships>
3438
- `;t.push(EO(OO(r),n.path))}return t}function wX(e){let t=[],n=Object.entries(mM).map(([e,t])=>MO(t,e));for(let n of e)`contentType`in n&&n.contentType&&t.push(jO(`/`+n.path,Kf[n.contentType]));return EO(OO(J`
3438
+ `;t.push(EO(OO(r),n.path))}return t}function TX(e){let t=[],n=Object.entries(mM).map(([e,t])=>MO(t,e));for(let n of e)`contentType`in n&&n.contentType&&t.push(jO(`/`+n.path,Kf[n.contentType]));return EO(OO(J`
3439
3439
  <Types xmlns="${Uf.Types}">
3440
3440
  ${q(Object.values(n))}
3441
3441
  <Default ${K([[`Extension`,`rels`],[`ContentType`,`application/vnd.openxmlformats-package.relationships+xml`]])} />
3442
3442
  <Default ${K([[`Extension`,`xml`],[`ContentType`,`application/xml`]])} />
3443
3443
  ${q(t)}
3444
3444
  </Types>
3445
- `),`[Content_Types].xml`)}function TX(){let e=[[`Id`,`rId1`],[`Type`,qf.document],[`Target`,`xl/workbook.xml`]];return EO(OO(J`
3445
+ `),`[Content_Types].xml`)}function EX(){let e=[[`Id`,`rId1`],[`Type`,qf.document],[`Target`,`xl/workbook.xml`]];return EO(OO(J`
3446
3446
  <Relationships xmlns="${Uf.Relationships}">
3447
3447
  <Relationship ${K(e)} />
3448
3448
  </Relationships>
3449
- `),`_rels/.rels`)}function EX(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=an(e,n,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),n.push(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${ut(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function DX(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>Us(Ts(e.range)).numberOfRows>1);return e}var OX=class extends cf{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},n={},r=[],i=new jl,a=!1){let o=performance.now();console.debug(`##### Model creation #####`),super(),dr(),r=jP(e,r);let s=CP(e,a);this.state=new HJ,this.uuidGenerator=i,this.config=this.setupConfig(n),this.session=this.setupSession(s.revisionId),this.coreGetters={},this.range=new dW(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.selection=new BJ(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of cq.getAll())this.setupCorePlugin(e,s);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(r);for(let e of dq.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of uq.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of lq.getAll()){let 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(),n.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly()){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),this.garbageCollectExternalResources(),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}(0,t.markRaw)(this),console.debug(`Model created in`,performance.now()-o,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:Nt(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCoreViewPlugin(e){let t=new e(this.coreViewPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new oK(IJ({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowed(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e)}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:E(`Anonymous`).toString()},n=e.transportService||new Hq,r=e.mode===`readonly`||e.mode===`dashboard`;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:r?new OJ(n):n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(Pr));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){let t=Dr(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>e!==`Success`)?new kr(t.flat()):kr.Success}checkDispatchAllowedCoreCommand(e){let 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(let e of this.handlers)e.finalize();this.status=0,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed(kX(e,t));dispatch=(e,t)=>{let n=kX(e,t),r=this.status;if(this.getters.isReadonly()&&!Or(n))return new kr(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new kr(`WaitingSessionConfirmation`);switch(r){case 0:let t=this.checkDispatchAllowed(n);if(!t.isSuccessful)return this.trigger(`update`),t;this.status=1;let{changes:r,commands:i}=this.state.recordChanges(()=>{let t=performance.now();Dr(n)&&this.state.addCommand(n),this.dispatchToHandlers(this.handlers,n),this.finalize();let r=performance.now()-t;r>5&&console.debug(e,r,`ms`)});this.session.save(n,i,r),this.status=0,this.trigger(`update`);break;case 1:if(Dr(n)){let e=this.checkDispatchAllowed(n);if(!e.isSuccessful)return e;this.state.addCommand(n)}this.dispatchToHandlers(this.handlers,n);break;case 3:throw Error(`Cannot dispatch commands in the finalize state`);case 2:if(Dr(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return kr.Success};dispatchFromCorePlugin=(e,t)=>{let n=kX(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,kr.Success};dispatchToHandlers(e,t){let n=Dr(t);for(let r of e)!n&&r instanceof YU||r.beforeHandle(t);for(let r of e)!n&&r instanceof YU||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let e=RP();for(let t of this.handlers)t instanceof YU&&t.export(e);return e.revisionId=this.session.getRevisionId()||`START_REVISION`,e=b(e),e}updateMode(e){this.config.mode=e,this.trigger(`update`)}exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=BP();for(let t of this.handlers)t instanceof Lp&&t.exportForExcel(e);return e=b(e),_X(e)}garbageCollectExternalResources(){for(let e of this.corePlugins)e.garbageCollectExternalResources()}};function kX(e,t={}){let n=b(t);return n.type=e,n}let AX={},jX={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},MX={autoCompleteProviders:up,autofillModifiersRegistry:lG,autofillRulesRegistry:uG,cellMenuRegistry:zR,colMenuRegistry:rB,errorTypes:Ki,linkMenuRegistry:LA,functionRegistry:zS,featurePluginRegistry:lq,iconsOnCellRegistry:$W,statefulUIPluginRegistry:uq,coreViewsPluginRegistry:dq,corePluginRegistry:cq,rowMenuRegistry:uB,sidePanelRegistry:RU,figureRegistry:pk,chartSidePanelComponentRegistry:EH,chartComponentRegistry:pO,chartRegistry:fO,chartSubtypeRegistry:hO,topbarMenuRegistry:Bq,topbarComponentRegistry:Vq,clickableCellRegistry:gq,otRegistry:wG,inverseCommandRegistry:yq,urlRegistry:Wr,cellPopoverRegistry:gk,numberFormatMenuRegistry:Fq,repeatLocalCommandTransformRegistry:HK,repeatCommandTransformRegistry:VK,clipboardHandlersRegistries:af,pivotRegistry:vR,pivotTimeAdapterRegistry:od,pivotSidePanelRegistry:yU,pivotNormalizationValueRegistry:Ld,supportedPivotPositionalFormulaRegistry:GU,pivotToFunctionValueRegistry:Rd,migrationStepRegistry:vP,chartJsExtensionRegistry:Mf},NX={arg:H,isEvaluationError:j,toBoolean:P,toJsDate:F,toNumber:M,toString:N,toNormalizedPivotValue:Nd,toFunctionPivotValue:Fd,toXC:T,toZone:Ts,toUnboundedZone:ws,toCartesian:ir,numberToLetters:Yn,lettersToNumber:Xn,UuidGenerator:jl,formatValue:L,createCurrencyFormat:Ro,ColorGenerator:Un,computeTextWidth:ml,createEmptyWorkbookData:RP,createEmptySheet:LP,createEmptyExcelSheet:zP,rgbaToHex:bn,colorToRGBA:xn,positionToZone:R,isDefined:C,isMatrix:Ir,lazy:Nt,genericRepeat:UK,createAction:m,createActions:f,transformRangeData:sf,deepEquals:w,overlap:zs,union:Fs,isInside:Vs,deepCopy:b,expandZoneOnInsertion:js,reduceZoneOnDeletion:Ps,unquote:pt,getMaxObjectId:Td,getFunctionsFromTokens:fC,getFirstPivotFunction:hU,getNumberOfPivotFunctions:gU,parseDimension:Od,isDateOrDatetimeField:kd,makeFieldProposal:uU,insertTokenAfterArgSeparator:fU,insertTokenAfterLeftParenthesis:pU,mergeContiguousZones:dc,getPivotHighlights:YH,pivotTimeAdapter:sd,UNDO_REDO_PIVOT_COMMANDS:oG,createPivotFormula:Md,areDomainArgsFieldsValid:jd,splitReference:jc,sanitizeSheetName:ht,getUniqueText:an,isNumber:Hi,isDateTime:ui,createCustomFields:Wd},PX={isMarkdownLink:xt,parseMarkdownLink:wt,markdownLink:Ct,openLink:Yr,urlRepresentation:Jr},FX={Checkbox:bA,Section:X,RoundColorPicker:aA,ChartDataSeries:IV,ChartErrorSection:LV,ChartLabelRange:RV,ChartTitle:HV,ChartPanel:kH,ChartFigure:dk,ChartJsComponent:Ew,ClickableCellSortIcon:KU,ZoomableChartJsComponent:TD,Grid:WU,GridOverlay:oV,ScorecardChart:Uw,GaugeChartComponent:jD,LineConfigPanel:dH,BarConfigPanel:BV,PieChartDesignPanel:mH,GenericChartConfigPanel:zV,ChartWithAxisDesignPanel:ZV,GenericZoomableChartDesignPanel:QV,LineChartDesignPanel:fH,GaugeChartConfigPanel:iH,GaugeChartDesignPanel:aH,ScorecardChartConfigPanel:_H,ScorecardChartDesignPanel:vH,GeoChartDesignPanel:lH,RadarChartDesignPanel:hH,WaterfallChartDesignPanel:TH,ComboChartDesignPanel:tH,FunnelChartDesignPanel:rH,SunburstChartDesignPanel:yH,TreeMapChartDesignPanel:wH,ChartTypePicker:DH,FigureComponent:mk,MenuPopover:ck,Popover:ik,SelectionInput:mA,ValidationMessages:ZB,AddDimensionButton:eU,PivotDimensionGranularity:nU,PivotDimensionOrder:rU,PivotDimension:tU,PivotLayoutConfigurator:sU,PivotHTMLRenderer:JU,PivotDeferUpdate:ZH,PivotTitleSection:cU,CogWheelMenu:PV,TextInput:kV,SidePanelCollapsible:bk,RadioSelection:WV,GeoChartRegionSelectSection:oH,ChartDashboardMenu:lk,FullScreenFigure:qU},IX={useDragAndDropListItems:sA,useHighlights:MH,useHighlightsOnHover:jH},LX={useStoreProvider:pf,DependencyContainer:lf,CellPopoverStore:TA,ComposerFocusStore:Sf,CellComposerStore:RB,FindAndReplaceStore:UH,HighlightStore:Kk,DelayedHoveredCellStore:hk,HoveredTableStore:rV,ModelStore:vf,NotificationStore:qk,RendererStore:yf,SelectionInputStore:pA,SpreadsheetStore:bf,useStore:z,useLocalStore:mf,SidePanelStore:BU,PivotSidePanelStore:_U,PivotMeasureDisplayPanelStore:qH,ClientFocusStore:fB,GridRenderer:mV};function RX(e,t){return zS.add(e,t),{addFunction:(e,t)=>RX(e,t)}}let zX={DEFAULT_LOCALE:D,HIGHLIGHT_COLOR:v,PIVOT_TABLE_CONFIG:tt,ChartTerms:Ub,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2},BX={...xO,...vD};e.AbstractCellClipboardHandler=Hl,e.AbstractChart=Dw,e.AbstractFigureClipboardHandler=Wl,e.CellErrorType=k,e.ClientDisconnectedError=aK,e.CommandResult=jr,e.CorePlugin=YU,e.CoreViewPlugin=bW,e.DispatchResult=kr,e.EvaluationError=A,e.LocalTransportService=Hq,e.Model=OX,e.PivotRuntimeDefinition=eR,e.Registry=g,e.Revision=iK,e.SPREADSHEET_DIMENSIONS=jX,e.Spreadsheet=DJ,e.SpreadsheetPivotTable=nR,e.UIPlugin=Rp,e.__info__=AX,e.addFunction=RX,e.addRenderingLayer=zr,e.astToFormula=PB,e.chartHelpers=BX,e.compile=rC,e.compileTokens=iC,e.components=FX,e.constants=zX,e.convertAstNodes=$y,e.coreTypes=Er,e.findCellInNewZone=Qs,e.functionCache=nC,e.getCaretDownSvg=Tj,e.getCaretUpSvg=Ej,e.helpers=NX,e.hooks=IX,e.invalidateCFEvaluationCommands=Sr,e.invalidateChartEvaluationCommands=br,e.invalidateDependenciesCommands=xr,e.invalidateEvaluationCommands=yr,e.iterateAstNodes=eb,e.links=PX,e.load=CP,e.parse=Zy,e.parseTokens=Qy,e.readonlyAllowedCommands=Tr,e.registries=MX,e.setDefaultSheetViewSize=$e,e.setTranslationMethod=ur,e.stores=LX,e.tokenColors=ot,e.tokenize=Jl,AX.version=`19.0.35`,AX.date=`2026-05-15T07:06:09.392Z`,AX.hash=`5de341b`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
3449
+ `),`_rels/.rels`)}function DX(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=an(e,n,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),n.push(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${ut(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function OX(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>Us(Ts(e.range)).numberOfRows>1);return e}var kX=class extends cf{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},n={},r=[],i=new jl,a=!1){let o=performance.now();console.debug(`##### Model creation #####`),super(),dr(),r=jP(e,r);let s=CP(e,a);this.state=new UJ,this.uuidGenerator=i,this.config=this.setupConfig(n),this.session=this.setupSession(s.revisionId),this.coreGetters={},this.range=new fW(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.selection=new VJ(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of lq.getAll())this.setupCorePlugin(e,s);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(r);for(let e of fq.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of dq.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of uq.getAll()){let 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(),n.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly()){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),this.garbageCollectExternalResources(),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}(0,t.markRaw)(this),console.debug(`Model created in`,performance.now()-o,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:Nt(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCoreViewPlugin(e){let t=new e(this.coreViewPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new sK(LJ({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowed(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e)}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:E(`Anonymous`).toString()},n=e.transportService||new Uq,r=e.mode===`readonly`||e.mode===`dashboard`;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:r?new kJ(n):n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(Pr));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){let t=Dr(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>e!==`Success`)?new kr(t.flat()):kr.Success}checkDispatchAllowedCoreCommand(e){let 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(let e of this.handlers)e.finalize();this.status=0,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed(AX(e,t));dispatch=(e,t)=>{let n=AX(e,t),r=this.status;if(this.getters.isReadonly()&&!Or(n))return new kr(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new kr(`WaitingSessionConfirmation`);switch(r){case 0:let t=this.checkDispatchAllowed(n);if(!t.isSuccessful)return this.trigger(`update`),t;this.status=1;let{changes:r,commands:i}=this.state.recordChanges(()=>{let t=performance.now();Dr(n)&&this.state.addCommand(n),this.dispatchToHandlers(this.handlers,n),this.finalize();let r=performance.now()-t;r>5&&console.debug(e,r,`ms`)});this.session.save(n,i,r),this.status=0,this.trigger(`update`);break;case 1:if(Dr(n)){let e=this.checkDispatchAllowed(n);if(!e.isSuccessful)return e;this.state.addCommand(n)}this.dispatchToHandlers(this.handlers,n);break;case 3:throw Error(`Cannot dispatch commands in the finalize state`);case 2:if(Dr(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return kr.Success};dispatchFromCorePlugin=(e,t)=>{let n=AX(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,kr.Success};dispatchToHandlers(e,t){let n=Dr(t);for(let r of e)!n&&r instanceof XU||r.beforeHandle(t);for(let r of e)!n&&r instanceof XU||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let e=RP();for(let t of this.handlers)t instanceof XU&&t.export(e);return e.revisionId=this.session.getRevisionId()||`START_REVISION`,e=b(e),e}updateMode(e){this.config.mode=e,this.trigger(`update`)}exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=BP();for(let t of this.handlers)t instanceof Lp&&t.exportForExcel(e);return e=b(e),vX(e)}garbageCollectExternalResources(){for(let e of this.corePlugins)e.garbageCollectExternalResources()}};function AX(e,t={}){let n=b(t);return n.type=e,n}let jX={},MX={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},NX={autoCompleteProviders:up,autofillModifiersRegistry:uG,autofillRulesRegistry:dG,cellMenuRegistry:zR,colMenuRegistry:rB,errorTypes:Ki,linkMenuRegistry:LA,functionRegistry:zS,featurePluginRegistry:uq,iconsOnCellRegistry:eG,statefulUIPluginRegistry:dq,coreViewsPluginRegistry:fq,corePluginRegistry:lq,rowMenuRegistry:uB,sidePanelRegistry:zU,figureRegistry:pk,chartSidePanelComponentRegistry:EH,chartComponentRegistry:pO,chartRegistry:fO,chartSubtypeRegistry:hO,topbarMenuRegistry:Vq,topbarComponentRegistry:Hq,clickableCellRegistry:_q,otRegistry:TG,inverseCommandRegistry:bq,urlRegistry:Wr,cellPopoverRegistry:gk,numberFormatMenuRegistry:Iq,repeatLocalCommandTransformRegistry:UK,repeatCommandTransformRegistry:HK,clipboardHandlersRegistries:af,pivotRegistry:vR,pivotTimeAdapterRegistry:od,pivotSidePanelRegistry:bU,pivotNormalizationValueRegistry:Ld,supportedPivotPositionalFormulaRegistry:KU,pivotToFunctionValueRegistry:Rd,migrationStepRegistry:vP,chartJsExtensionRegistry:Mf},PX={arg:H,isEvaluationError:j,toBoolean:P,toJsDate:F,toNumber:M,toString:N,toNormalizedPivotValue:Nd,toFunctionPivotValue:Fd,toXC:T,toZone:Ts,toUnboundedZone:ws,toCartesian:ir,numberToLetters:Yn,lettersToNumber:Xn,UuidGenerator:jl,formatValue:L,createCurrencyFormat:Ro,ColorGenerator:Un,computeTextWidth:ml,createEmptyWorkbookData:RP,createEmptySheet:LP,createEmptyExcelSheet:zP,rgbaToHex:bn,colorToRGBA:xn,positionToZone:R,isDefined:C,isMatrix:Ir,lazy:Nt,genericRepeat:WK,createAction:m,createActions:f,transformRangeData:sf,deepEquals:w,overlap:zs,union:Fs,isInside:Vs,deepCopy:b,expandZoneOnInsertion:js,reduceZoneOnDeletion:Ps,unquote:pt,getMaxObjectId:Td,getFunctionsFromTokens:fC,getFirstPivotFunction:hU,getNumberOfPivotFunctions:_U,parseDimension:Od,isDateOrDatetimeField:kd,makeFieldProposal:uU,insertTokenAfterArgSeparator:fU,insertTokenAfterLeftParenthesis:pU,mergeContiguousZones:dc,getPivotHighlights:YH,pivotTimeAdapter:sd,UNDO_REDO_PIVOT_COMMANDS:sG,createPivotFormula:Md,areDomainArgsFieldsValid:jd,splitReference:jc,sanitizeSheetName:ht,getUniqueText:an,isNumber:Hi,isDateTime:ui,createCustomFields:Wd},FX={isMarkdownLink:xt,parseMarkdownLink:wt,markdownLink:Ct,openLink:Yr,urlRepresentation:Jr},IX={Checkbox:bA,Section:X,RoundColorPicker:aA,ChartDataSeries:IV,ChartErrorSection:LV,ChartLabelRange:RV,ChartTitle:HV,ChartPanel:kH,ChartFigure:dk,ChartJsComponent:Ew,ClickableCellSortIcon:qU,ZoomableChartJsComponent:TD,Grid:GU,GridOverlay:oV,ScorecardChart:Uw,GaugeChartComponent:jD,LineConfigPanel:dH,BarConfigPanel:BV,PieChartDesignPanel:mH,GenericChartConfigPanel:zV,ChartWithAxisDesignPanel:ZV,GenericZoomableChartDesignPanel:QV,LineChartDesignPanel:fH,GaugeChartConfigPanel:iH,GaugeChartDesignPanel:aH,ScorecardChartConfigPanel:_H,ScorecardChartDesignPanel:vH,GeoChartDesignPanel:lH,RadarChartDesignPanel:hH,WaterfallChartDesignPanel:TH,ComboChartDesignPanel:tH,FunnelChartDesignPanel:rH,SunburstChartDesignPanel:yH,TreeMapChartDesignPanel:wH,ChartTypePicker:DH,FigureComponent:mk,MenuPopover:ck,Popover:ik,SelectionInput:mA,ValidationMessages:ZB,AddDimensionButton:eU,PivotDimensionGranularity:nU,PivotDimensionOrder:rU,PivotDimension:tU,PivotLayoutConfigurator:sU,PivotHTMLRenderer:YU,PivotDeferUpdate:ZH,PivotTitleSection:cU,CogWheelMenu:PV,TextInput:kV,SidePanelCollapsible:bk,RadioSelection:WV,GeoChartRegionSelectSection:oH,ChartDashboardMenu:lk,FullScreenFigure:JU},LX={useDragAndDropListItems:sA,useHighlights:MH,useHighlightsOnHover:jH},RX={useStoreProvider:pf,DependencyContainer:lf,CellPopoverStore:TA,ComposerFocusStore:Sf,CellComposerStore:RB,FindAndReplaceStore:UH,HighlightStore:Kk,DelayedHoveredCellStore:hk,HoveredTableStore:rV,ModelStore:vf,NotificationStore:qk,RendererStore:yf,SelectionInputStore:pA,SpreadsheetStore:bf,useStore:z,useLocalStore:mf,SidePanelStore:VU,PivotSidePanelStore:vU,PivotMeasureDisplayPanelStore:qH,ClientFocusStore:fB,GridRenderer:mV};function zX(e,t){return zS.add(e,t),{addFunction:(e,t)=>zX(e,t)}}let BX={DEFAULT_LOCALE:D,HIGHLIGHT_COLOR:v,PIVOT_TABLE_CONFIG:tt,ChartTerms:Ub,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2},VX={...xO,...vD};e.AbstractCellClipboardHandler=Hl,e.AbstractChart=Dw,e.AbstractFigureClipboardHandler=Wl,e.CellErrorType=k,e.ClientDisconnectedError=oK,e.CommandResult=jr,e.CorePlugin=XU,e.CoreViewPlugin=xW,e.DispatchResult=kr,e.EvaluationError=A,e.LocalTransportService=Uq,e.Model=kX,e.PivotRuntimeDefinition=eR,e.Registry=g,e.Revision=aK,e.SPREADSHEET_DIMENSIONS=MX,e.Spreadsheet=OJ,e.SpreadsheetPivotTable=nR,e.UIPlugin=Rp,e.__info__=jX,e.addFunction=zX,e.addRenderingLayer=zr,e.astToFormula=PB,e.chartHelpers=VX,e.compile=rC,e.compileTokens=iC,e.components=IX,e.constants=BX,e.convertAstNodes=$y,e.coreTypes=Er,e.findCellInNewZone=Qs,e.functionCache=nC,e.getCaretDownSvg=Tj,e.getCaretUpSvg=Ej,e.helpers=PX,e.hooks=LX,e.invalidateCFEvaluationCommands=Sr,e.invalidateChartEvaluationCommands=br,e.invalidateDependenciesCommands=xr,e.invalidateEvaluationCommands=yr,e.iterateAstNodes=eb,e.links=FX,e.load=CP,e.parse=Zy,e.parseTokens=Qy,e.readonlyAllowedCommands=Tr,e.registries=NX,e.setDefaultSheetViewSize=$e,e.setTranslationMethod=ur,e.stores=RX,e.tokenColors=ot,e.tokenize=Jl,jX.version=`19.0.36`,jX.date=`2026-05-27T05:57:35.932Z`,jX.hash=`3f73c94`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);