@odoo/o-spreadsheet 15.2.12 → 15.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- !function(e,t){"use strict";function s(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if("default"!==s){var o=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,o.get?o:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var o=s(t);let i=e=>e;function n(e,...t){if(1===t.length&&"object"==typeof t[0]){const s=t[0];e=e.replace(/\%\(?([^\)]+)\)s/g,((e,t)=>s[t]))}else t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));return e}const r=function(e,...t){return n(i(e),...t)},a=function(e,...t){return{toString:function(){return n(i(e),...t)}}},l="#f5f5f5",c="#F8F9FA",h="#E8EAED",d="#595959",u="#666666",p="#3266ca",g="#FFFFFF",f=11982760,m=26,v=48,E=63,b=96,S=23,C=15,y=14,w=4,I=200,x=1,T="400",R=10,L="'Roboto', arial",M=["thin","#000"],A="#00f",_=/[ymd:]/,O="#REF",N="START_REVISION",k=a("Invalid expression"),F=["'","*","?","/","\\","[","]"],$=/'|\*|\?|\/|\\|\[|\]/,D=void 0,P="|",U=2e3,V=(new Date).getFullYear(),B=new Date(1899,11,30),H=new Date(0)-B,z=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,Z=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,G=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function W(e){let t;const s=(e=e.trim()).match(G);if(s){if(t=function(e){if(e=e.trim(),G.test(e)){const t=/AM/i.test(e),s=/PM/i.test(e),o=(t||s?e.substring(0,e.length-2).trim():e).split(/:/),i=o.length>=2,n=3===o.length;let r=Number(o[0]),a=i?Number(o[1]):0,l=n?Number(o[2]):0,c=n?"hh:mm:ss":"hh:mm";if(t||s)c+=" a";else if(!i)return null;r>=12&&t?r-=12:r<12&&s&&(r+=12),a+=Math.floor(l/60),l%=60,r+=Math.floor(a/60),a%=60,r>=24&&(c="hhhh:mm:ss");return{value:r/24+a/1440+l/86400,format:c,jsDate:new Date(1899,11,30,r,a,l)}}return null}(s[0]),null===t)return null;e=e.replace(s[0],"").trim()}let o;const i=e.match(z),n=e.match(Z);if(i||n){let t;if(i?(t=i[0],o=q(t,"mdy")):(t=n[0],o=q(t,"ymd")),null===o)return null;e=e.replace(t,"").trim()}return""!==e||!o&&!t?null:o&&t?{value:o.value+t.value,format:o.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new Date(o.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,o.jsDate.getMonth()+t.jsDate.getMonth()-11,o.jsDate.getDate()+t.jsDate.getDate()-30,o.jsDate.getHours()+t.jsDate.getHours(),o.jsDate.getMinutes()+t.jsDate.getMinutes(),o.jsDate.getSeconds()+t.jsDate.getSeconds())}:o||t}function q(e,t){const s="mdy"===t;if(s||"ymd"===t){const t=e.split(/\/|-|\s/),o=s?0:1,i=s?1:2,n=s?2:0,r=Number(t[o]),a=Number(t[i]),l=2===t[o].length&&r<10||2===t[i].length&&a<10,c=t[n]?function(e){const t=Number(e);switch(e.length){case 1:return U+t;case 2:return U+(U+t>V+10?-100:0)+t;case 3:case 4:return t}return 0}(t[n]):V,h=new Date(c,r-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==r-1||h.getDate()!==a)return null;const u=h-B;let p=l?`mm${d}dd`:`m${d}d`;return t[n]&&(p=s?p+d+"yyyy":"yyyy"+d+p),{value:Math.round(u/864e5),format:p,jsDate:h}}return null}function j(e){const t=Math.trunc(e);let s=new Date(86400*t*1e3-H),o=e-t;o=o<0?1+o:o;const i=Math.round(24*o),n=Math.round(24*(o-i/24)*60),r=Math.round(24*(o-i/24-n/24/60)*60*60);return s.setHours(i),s.setMinutes(n),s.setSeconds(r),s}function X(e){const t=e.format,s=e.jsDate||j(e.value),o=t.indexOf("h");let i="",n="";return o>0?(i=Y(s,t.substring(0,o-1)),n=K(s,t.substring(o))):0===o?n=K(s,t):o<0&&(i=Y(s,t)),i+(i&&n?" ":"")+n}function Y(e,t){const s=t.match(/\/|-|\s/)[0];return t.split(s).map((s=>{switch(s){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"yyyy":return e.getFullYear();default:throw new Error(`invalid format: ${t}`)}})).join(s)}function K(e,t){let s=t.split(/:|\s/);const o=e.getHours(),i="a"===s[s.length-1];let n=o,r="";return i&&(n=0===n?12:n>12?n-12:n,r=o>=12?" PM":" AM",s.pop()),s.map((s=>{switch(s){case"hhhh":return Math.floor((e.getTime()-B)/36e5).toString();case"hh":return n.toString().padStart(2,"0");case"mm":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");default:throw new Error(`invalid format: ${t}`)}})).join(":")+r}const Q=/(^-?\d+(\.?\d*(e\d+)?)?(\s*%)?|^-?\.\d+(\s*%)?)(?!\w|!)/,J=/^-?\d+(,\d+)*(\.?\d*(e\d+)?)?(\s*%)?$|^-?\.\d+(\s*%)?$/;function ee(e){return J.test(e.trim())}const te=/,/g;function se(e){let t=Number(e.replace(te,""));return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}const oe=new Intl.NumberFormat("en-US",{useGrouping:!1,maximumFractionDigits:10});function ie(e){return Number.isInteger(e)?e.toString():oe.format(e)}let ne=[];const re=20;function ae(e,t,s=""){if(e<0)return"-"+ae(-e,t);const o=t>=re?re:t;let i=ne[o];i||(i=new Intl.NumberFormat("en-US",{minimumFractionDigits:o,maximumFractionDigits:o,useGrouping:!1}),ne[o]=i);let n=i.format(e);if(s){let e=n.indexOf(".");n=n.replace(/\d(?=(?:\d{3})+(?:\.|$))/g,((t,o)=>e<0||o<e?`${t}${s}`:t))}return n}function le(e,t){const s=t.split("."),o=1===s.length?0:s[1].match(/0/g).length,i=s[0].includes(",")?",":"",n=t.includes("%");n&&(e*=100);const r=ae(e,o,i);return n?r+"%":r}function ce(e,t){if(!e())throw new Error(t)}const he=e=>a("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function de(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(ee(e)||""===e)return se(e);const t=W(e);if(t)return t.value;throw new Error(he(e));default:return 0}}function ue(e){if(""===e)throw new Error(he(e));return de(e)}function pe(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}const ge=e=>a("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function fe(e){switch(typeof e){case"boolean":return e;case"string":if(e){let t=e.toUpperCase();if("TRUE"===t)return!0;if("FALSE"===t)return!1;throw new Error(ge(e))}return!1;case"number":return!!e;default:return!1}}function me(e){return j(de(e))}function ve(e,t,s){for(let o of e)if(Array.isArray(o)){const e=o.length,s=o[0].length;for(let i=0;i<s;i++)for(let s=0;s<e;s++)t(o[s][i])}else s(o)}function Ee(e,t){ve(e,t,t)}function be(e,t){ve(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(ue(e))}))}function Se(e,t,s,o){let i=o;for(let o of e)if(Array.isArray(o)){const e=o.length,s=o[0].length;for(let n=0;n<s;n++)for(let s=0;s<e;s++)i=t(i,o[s][n])}else i=s(i,o);return i}function Ce(e,t,s){return Se(e,t,t,s)}function ye(e,t,s){return Se(e,((e,s)=>"number"==typeof s?t(e,s):e),((e,s)=>t(e,ue(s))),s)}function we(e,t,s){return Se(e,((e,s)=>null!=s?t(e,"number"==typeof s?s:"boolean"==typeof s?de(s):0):e),((e,s)=>t(e,de(s))),s)}function Ie(e,t){return function(e,t,s){for(let o of e)if(Array.isArray(o)){const e=o.length,s=o[0].length;for(let i=0;i<s;i++)for(let s=0;s<e;s++)if(!t(o[s][i]))return}else if(!s(o))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(ge(e));return fe(e)}(e))))}function xe(e,t){let s,o,i=e.substring(0,2);"<="===i||">="===i||"<>"===i?(s=i,o=e.substring(2)):(i=e.substring(0,1),"<"===i||">"===i||"="===i?(s=i,o=e.substring(1)):(s="=",o=e)),ee(o)?o=de(o):"TRUE"!==o&&"FALSE"!==o||(o=fe(o));const n={operator:s,operand:o};return"string"==typeof o&&(t&&(o+="*"),n.regexp=function(e){let t="",s="";for(let o of e)"?"===o&&"~"!==s?t+=".":"*"===o&&"~"!==s?t+=".*":("*"!==o&&"?"!==o||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(o)&&(t+="\\"),t+=o),s=o;return new RegExp("^"+t+"$","i")}(o)),n}function Te(e,t){const{operator:s,operand:o}=t;if(void 0===e||void 0===o)return!1;if("number"==typeof o&&"="===s)return pe(e)===pe(o);if("<>"===s||"="===s){let i;return i=typeof e==typeof o&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===o),"="===s?i:!i}if(typeof e==typeof o)switch(s){case"<":return e<o;case">":return e>o;case"<=":return e<=o;case">=":return e>=o}return!1}function Re(e,t,s=!1){const o=e.length;if(o%2==1)throw new Error(a("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const i=e[0].length,n=e[0][0].length;let r=[];for(let t=0;t<o-1;t+=2){const o=e[t];if(!Array.isArray(o)||o.length!==i||o[0].length!==n)throw new Error(a("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=pe(e[t+1]);r.push(xe(l,s))}for(let s=0;s<i;s++)for(let i=0;i<n;i++){let n=!0;for(let t=0;t<o-1;t+=2){if(n=Te(e[t][s][i],r[t/2]),!n)break}n&&t(s,i)}}function Le(e,t){if(void 0===t)return-1;const s=typeof t;let o,i,n,r,a,l,c=0,h=e.length-1;if(typeof e[c]===s&&t<e[c])return-1;if(typeof e[h]===s&&e[h]<=t)return h;for(;h-c>=0;){for(n=Math.ceil((c+h)/2),r=n,a=e[r],l=typeof a;c<=r&&s!==l;)r--,a=e[r],l=typeof a;l===s&&a<=t&&(void 0===o||o<a||o===a&&i<r)&&(o=a,i=r),l===s&&a>t?h=r-1:c=n+1}return void 0!==i?i:-1}class Me{constructor(){this.content={}}add(e,t){return this.content[e]=t,this}get(e){const t=this.content[e];if(!t&&!(e in this.content))throw new Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}remove(e){delete this.content[e]}}const Ae=/(.*?)\((.*?)\)(.*)/,_e=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function Oe(e){let t=e.split("\n");const s=[];for(let e of t)e=e.trim(),e&&s.push(Ne(e));return s}function Ne(e){let t,s=e.match(Ae),o=s[1].trim(),i=[],n=!1,r=!1,a=!1;for(let e of s[2].split(",")){const s=e.trim().toUpperCase();let o=_e.find((e=>s===e));o?i.push(o):"RANGE<ANY>"===s?i.push("RANGE"):"OPTIONAL"===s?n=!0:"REPEATING"===s?r=!0:"LAZY"===s?a=!0:s.startsWith("DEFAULT=")&&(t=e.trim().slice(8))}const l={name:o,description:s[3].trim(),type:i};return n&&(l.optional=!0),r&&(l.repeating=!0),a&&(l.lazy=!0),void 0!==t&&(l.default=!0,l.defaultValue=t),l}function ke(e){let t=0,s=0,o=0;for(let i of e.args)t++,i.optional||i.repeating||i.default||s++,i.repeating&&o++;const i=e;return i.minArgRequired=s,i.maxArgPossible=o?1/0:t,i.nbrArgRepeating=o,i.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const s=e-t;return e=>{if(e<=s)return e;return s+((e-s)%t||t)}}(t,o),i}var Fe;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(Fe||(Fe={}));const $e=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),De=new Set(["START","ACTIVATE_SHEET","COPY","START_SELECTION","SET_SELECTION","ALTER_SELECTION","START_SELECTION_EXPANSION","PREPARE_SELECTION_EXPANSION","STOP_SELECTION","RESIZE_VIEWPORT","SET_VIEWPORT_OFFSET","SELECT_ALL","SELECT_CELL","SELECT_COLUMN","SELECT_ROW","MOVE_POSITION","SELECT_SEARCH_NEXT_MATCH","SELECT_SEARCH_PREVIOUS_MATCH","REFRESH_SEARCH","UPDATE_SEARCH","CLEAR_SEARCH","EVALUATE_CELLS","SET_CURRENT_CONTENT","SET_FORMULA_VISIBILITY"]),Pe=new Set(["UPDATE_CELL","UPDATE_CELL_POSITION","CLEAR_CELL","DELETE_CONTENT","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","RESIZE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","UNHIDE_COLUMNS_ROWS","SET_GRID_LINES_VISIBILITY","ADD_MERGE","REMOVE_MERGE","CREATE_SHEET","DELETE_SHEET","DUPLICATE_SHEET","MOVE_SHEET","RENAME_SHEET","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","CREATE_CHART","UPDATE_CHART"]);function Ue(e){return Pe.has(e.type)}class Ve{constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new Ve}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var Be,He,ze,Ze;e.CommandResult=void 0,(Be=e.CommandResult||(e.CommandResult={}))[Be.Success=0]="Success",Be[Be.CancelledForUnknownReason=1]="CancelledForUnknownReason",Be[Be.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",Be[Be.MergeIsDestructive=3]="MergeIsDestructive",Be[Be.CellIsMerged=4]="CellIsMerged",Be[Be.InvalidTarget=5]="InvalidTarget",Be[Be.EmptyUndoStack=6]="EmptyUndoStack",Be[Be.EmptyRedoStack=7]="EmptyRedoStack",Be[Be.NotEnoughElements=8]="NotEnoughElements",Be[Be.NotEnoughSheets=9]="NotEnoughSheets",Be[Be.MissingSheetName=10]="MissingSheetName",Be[Be.DuplicatedSheetName=11]="DuplicatedSheetName",Be[Be.DuplicatedSheetId=12]="DuplicatedSheetId",Be[Be.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",Be[Be.WrongSheetMove=14]="WrongSheetMove",Be[Be.WrongSheetPosition=15]="WrongSheetPosition",Be[Be.InvalidAnchorZone=16]="InvalidAnchorZone",Be[Be.SelectionOutOfBound=17]="SelectionOutOfBound",Be[Be.TargetOutOfSheet=18]="TargetOutOfSheet",Be[Be.WrongPasteSelection=19]="WrongPasteSelection",Be[Be.EmptyClipboard=20]="EmptyClipboard",Be[Be.EmptyRange=21]="EmptyRange",Be[Be.InvalidRange=22]="InvalidRange",Be[Be.InvalidSheetId=23]="InvalidSheetId",Be[Be.InputAlreadyFocused=24]="InputAlreadyFocused",Be[Be.MaximumRangesReached=25]="MaximumRangesReached",Be[Be.InvalidChartDefinition=26]="InvalidChartDefinition",Be[Be.EmptyDataSet=27]="EmptyDataSet",Be[Be.InvalidDataSet=28]="InvalidDataSet",Be[Be.InvalidLabelRange=29]="InvalidLabelRange",Be[Be.InvalidAutofillSelection=30]="InvalidAutofillSelection",Be[Be.WrongComposerSelection=31]="WrongComposerSelection",Be[Be.MinBiggerThanMax=32]="MinBiggerThanMax",Be[Be.LowerBiggerThanUpper=33]="LowerBiggerThanUpper",Be[Be.MidBiggerThanMax=34]="MidBiggerThanMax",Be[Be.MinBiggerThanMid=35]="MinBiggerThanMid",Be[Be.FirstArgMissing=36]="FirstArgMissing",Be[Be.SecondArgMissing=37]="SecondArgMissing",Be[Be.MinNaN=38]="MinNaN",Be[Be.MidNaN=39]="MidNaN",Be[Be.MaxNaN=40]="MaxNaN",Be[Be.ValueUpperInflectionNaN=41]="ValueUpperInflectionNaN",Be[Be.ValueLowerInflectionNaN=42]="ValueLowerInflectionNaN",Be[Be.MinInvalidFormula=43]="MinInvalidFormula",Be[Be.MidInvalidFormula=44]="MidInvalidFormula",Be[Be.MaxInvalidFormula=45]="MaxInvalidFormula",Be[Be.ValueUpperInvalidFormula=46]="ValueUpperInvalidFormula",Be[Be.ValueLowerInvalidFormula=47]="ValueLowerInvalidFormula",Be[Be.InvalidSortZone=48]="InvalidSortZone",Be[Be.WaitingSessionConfirmation=49]="WaitingSessionConfirmation",Be[Be.MergeOverlap=50]="MergeOverlap",Be[Be.TooManyHiddenElements=51]="TooManyHiddenElements",Be[Be.Readonly=52]="Readonly",Be[Be.InvalidOffset=53]="InvalidOffset",Be[Be.InvalidViewportSize=54]="InvalidViewportSize",Be[Be.FigureDoesNotExist=55]="FigureDoesNotExist",Be[Be.DuplicatedFigureId=56]="DuplicatedFigureId",Be[Be.DuplicatedChartId=57]="DuplicatedChartId",Be[Be.ChartDoesNotExist=58]="ChartDoesNotExist",function(e){e.FormatFromArgument="FormatFromArgument"}(He||(He={})),function(e){e[e.UP=0]="UP",e[e.DOWN=1]="DOWN",e[e.LEFT=2]="LEFT",e[e.RIGHT=3]="RIGHT"}(ze||(ze={})),function(e){e[e.Background=0]="Background",e[e.Highlights=1]="Highlights",e[e.Clipboard=2]="Clipboard",e[e.Search=3]="Search",e[e.Chart=4]="Chart",e[e.Selection=5]="Selection",e[e.Autofill=6]="Autofill",e[e.Headers=7]="Headers"}(Ze||(Ze={}));const Ge={description:a("Absolute value of a number."),args:Oe(`\n value (number) ${a("The number of which to return the absolute value.")}\n `),returns:["NUMBER"],compute:function(e){return Math.abs(de(e))},isExported:!0},We={description:a("Inverse cosine of a value, in radians."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>Math.abs(t)<=1),a("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},qe={description:a("Inverse hyperbolic cosine of a number."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>t>=1),a("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},je={description:a("Inverse cotangent of a value."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse cotangent.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Xe={description:a("Inverse hyperbolic cotangent of a value."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>Math.abs(t)>1),a("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},Ye={description:a("Inverse sine of a value, in radians."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>Math.abs(t)<=1),a("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},Ke={description:a("Inverse hyperbolic sine of a number."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic sine.")}\n `),returns:["NUMBER"],compute:function(e){return Math.asinh(de(e))},isExported:!0},Qe={description:a("Inverse tangent of a value, in radians."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse tangent.")}\n `),returns:["NUMBER"],compute:function(e){return Math.atan(de(e))},isExported:!0},Je={description:a("Angle from the X axis to a point (x,y), in radians."),args:Oe(`\n x (number) ${a("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")}\n y (number) ${a("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")}\n `),returns:["NUMBER"],compute:function(e,t){const s=de(e),o=de(t);return ce((()=>0!==s||0!==o),a("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(o,s)},isExported:!0},et={description:a("Inverse hyperbolic tangent of a number."),args:Oe(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>Math.abs(t)<1),a("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},tt={description:a("Rounds number up to nearest multiple of factor."),args:Oe(`\n value (number) ${a("The value to round up to the nearest integer multiple of factor.")}\n factor (number, default=1) ${a("The number to whose multiples value will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1){const s=de(e),o=de(t);return ce((()=>o>=0||s<=0),a("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),s.toString())),o?Math.ceil(s/o)*o:0},isExported:!0},st={description:a("Rounds number up to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${a("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1,s=0){let o=de(t);if(0===o)return 0;const i=de(e);if(o=Math.abs(o),i>=0)return Math.ceil(i/o)*o;return 0===de(s)?-Math.floor(Math.abs(i)/o)*o:-Math.ceil(Math.abs(i)/o)*o},isExported:!0},ot={description:a("Rounds number up to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return st.compute(e,t,0)},isExported:!0},it={description:a("Cosine of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the cosine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cos(de(e))},isExported:!0},nt={description:a("Hyperbolic cosine of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic cosine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cosh(de(e))},isExported:!0},rt={description:a("Cotangent of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the cotangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},at={description:a("Hyperbolic cotangent of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic cotangent of.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},lt={description:a("Number of empty values."),args:Oe(`\n value1 (any, range) ${a("The first value or range in which to count the number of blanks.")}\n value2 (any, range, repeating) ${a("Additional values or ranges in which to count the number of blanks.")}\n `),returns:["NUMBER"],compute:function(...e){return Ce(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},ct={description:a("A conditional count across a range."),args:Oe(`\n range (range) ${a("The range that is tested against criterion.")}\n criterion (string) ${a("The pattern or test to apply to range.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return Re(e,((e,s)=>{t+=1})),t},isExported:!0},ht={description:a("Count values depending on multiple criteria."),args:Oe(`\n criteria_range1 (range) ${a("The range to check against criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${a("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.")}\n criterion2 (string, repeating) ${a("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return Re(e,((e,s)=>{t+=1})),t},isExported:!0};function dt(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const ut={description:a("Counts number of unique values in a range."),args:Oe(`\n value1 (any, range) ${a("The first value or range to consider for uniqueness.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider for uniqueness.")}\n `),returns:["NUMBER"],compute:function(...e){return Ce(e,((e,t)=>dt(t)?e.add(t):e),new Set).size}},pt={description:a("Counts number of unique values in a range, filtered by a set of criteria."),args:Oe(`\n range (range) ${a("The range of cells from which the number of unique values will be counted.")}\n criteria_range1 (range) ${a("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${a("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.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=new Set;return Re(t,((t,o)=>{const i=e[t][o];dt(i)&&s.add(i)})),s.size}},gt={description:a("Cosecant of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the cosecant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},ft={description:a("Hyperbolic cosecant of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic cosecant of.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},mt={description:a("Converts from another base to decimal."),args:Oe(`\n value (string) ${a("The number to convert.")},\n base (number) ${a("The base to convert the value from.")},\n `),returns:["NUMBER"],compute:function(e,t){let s=de(t);s=Math.floor(s),ce((()=>2<=s&&s<=36),a("The base (%s) must be between 2 and 36 inclusive.",s.toString()));const o=pe(e);if(""===o)return 0;ce((()=>!!o.match(/^-?[a-z0-9]+$/i)),a("The value (%s) must be a valid base %s representation.",o,s.toString()));const i=parseInt(o,s);return ce((()=>!isNaN(i)),a("The value (%s) must be a valid base %s representation.",o,s.toString())),i},isExported:!0},vt={description:a("Converts an angle value in radians to degrees."),args:Oe(`\n angle (number) ${a("The angle to convert from radians to degrees.")}\n `),returns:["NUMBER"],compute:function(e){return 180*de(e)/Math.PI},isExported:!0},Et={description:a("Euler's number, e (~2.718) raised to a power."),args:Oe(`\n value (number) ${a("The exponent to raise e.")}\n `),returns:["NUMBER"],compute:function(e){return Math.exp(de(e))},isExported:!0},bt={description:a("Rounds number down to nearest multiple of factor."),args:Oe(`\n value (number) ${a("The value to round down to the nearest integer multiple of factor.")}\n factor (number, default=1) ${a("The number to whose multiples value will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1){const s=de(e),o=de(t);return ce((()=>o>=0||s<=0),a("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),s.toString())),o?Math.floor(s/o)*o:0},isExported:!0},St={description:a("Rounds number down to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${a("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1,s=0){let o=de(t);if(0===o)return 0;const i=de(e);if(o=Math.abs(o),i>=0)return Math.floor(i/o)*o;return 0===de(s)?-Math.ceil(Math.abs(i)/o)*o:-Math.floor(Math.abs(i)/o)*o},isExported:!0},Ct={description:a("Rounds number down to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1){return St.compute(e,t,0)},isExported:!0},yt={description:a("Whether the provided value is even."),args:Oe(`\n value (number) ${a("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=ue(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},wt={description:a("Rounds number up to nearest multiple of factor."),args:Oe(`\n number (number) ${a("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=1){return st.compute(e,t,0)},isExported:!0},It={description:a("Whether the provided value is even."),args:Oe(`\n value (number) ${a("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=ue(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},xt={description:a("The logarithm of a number, base e (euler's number)."),args:Oe(`\n value (number) ${a("The value for which to calculate the logarithm, base e.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e);return ce((()=>t>0),a("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},Tt={description:a("Modulo (remainder) operator."),args:Oe(`\n dividend (number) ${a("The number to be divided to find the remainder.")}\n divisor (number) ${a("The number to divide by.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=de(t);ce((()=>0!==s),a("The divisor must be different from 0."));const o=de(e)%s;return o>0&&s<0||o<0&&s>0?o+s:o},isExported:!0},Rt={description:a("Rounds a number up to the nearest odd integer."),args:Oe(`\n value (number) ${a("The value to round to the next greatest odd number.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e){const t=de(e);let s=Math.ceil(Math.abs(t));return s=1&s?s:s+1,t<0?-s:s},isExported:!0},Lt={description:a("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},Mt={description:a("A number raised to a power."),args:Oe(`\n base (number) ${a("The number to raise to the exponent power.")}\n exponent (number) ${a("The exponent to raise base to.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=de(e),o=de(t);return ce((()=>s>=0||Number.isInteger(o)),a("The exponent (%s) must be an integer when the base is negative.",o.toString())),Math.pow(s,o)},isExported:!0},At={description:a("Result of multiplying a series of numbers together."),args:Oe(`\n factor1 (number, range<number>) ${a("The first number or range to calculate for the product.")}\n factor2 (number, range<number>, repeating) ${a("More numbers or ranges to calculate for the product.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t=0,s=1;for(let o of e)if(Array.isArray(o))for(let e of o)for(let o of e)"number"==typeof o&&(s*=o,t+=1);else null!=o&&(s*=ue(o),t+=1);return 0===t?0:s},isExported:!0},_t={description:a("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},Ot={description:a("Random integer between two values, inclusive."),args:Oe(`\n low (number) ${a("The low end of the random range.")}\n high (number) ${a("The high end of the random range.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){let s=de(e);Number.isInteger(s)||(s=Math.ceil(s));let o=de(t);return Number.isInteger(o)||(o=Math.floor(o)),ce((()=>s<=o),a("The high (%s) must be greater than or equal to the low (%s).",o.toString(),s.toString())),s+Math.ceil((o-s+1)*Math.random())-1},isExported:!0},Nt={description:a("Rounds a number according to standard rules."),args:Oe(`\n value (number) ${a("The value to round to places number of places.")}\n places (number, default=0) ${a("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=0){const s=de(e);let o=de(t);const i=Math.abs(s);let n;return 0===o?n=Math.round(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.round(i*Math.pow(10,o))/Math.pow(10,o)),s>=0?n:-n},isExported:!0},kt={description:a("Rounds down a number."),args:Oe(`\n value (number) ${a("The value to round to places number of places, always rounding down.")}\n places (number, default=0) ${a("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=0){const s=de(e);let o=de(t);const i=Math.abs(s);let n;return 0===o?n=Math.floor(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.floor(i*Math.pow(10,o))/Math.pow(10,o)),s>=0?n:-n},isExported:!0},Ft={description:a("Rounds up a number."),args:Oe(`\n value (number) ${a("The value to round to places number of places, always rounding up.")}\n places (number, default=0) ${a("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=0){const s=de(e);let o=de(t);const i=Math.abs(s);let n;return 0===o?n=Math.ceil(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.ceil(i*Math.pow(10,o))/Math.pow(10,o)),s>=0?n:-n},isExported:!0},$t={description:a("Secant of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the secant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cos(de(e))},isExported:!0},Dt={description:a("Hyperbolic secant of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic secant of.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cosh(de(e))},isExported:!0},Pt={description:a("Sine of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the sine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sin(de(e))},isExported:!0},Ut={description:a("Hyperbolic sine of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic sine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sinh(de(e))},isExported:!0},Vt={description:a("Positive square root of a positive number."),args:Oe(`\n value (number) ${a("The number for which to calculate the positive square root.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e){const t=de(e);return ce((()=>t>=0),a("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},Bt={description:a("Sum of a series of numbers and/or cells."),args:Oe(`\n value1 (number, range<number>) ${a("The first number or range to add together.")}\n value2 (number, range<number>, repeating) ${a("Additional numbers or ranges to add to value1.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){return ye(e,((e,t)=>e+t),0)},isExported:!0},Ht={description:a("A conditional sum across a range."),args:Oe(`\n criteria_range (range) ${a("The range which is tested against criterion.")}\n criterion (string) ${a("The pattern or test to apply to range.")}\n sum_range (range, default=criteria_range) ${a("The range to be summed, if different from range.")}\n `),returns:["NUMBER"],compute:function(e,t,s){void 0===s&&(s=e);let o=0;return Re([e,t],((e,t)=>{const i=s[e][t];"number"==typeof i&&(o+=i)})),o},isExported:!0},zt={description:a("Sums a range depending on multiple criteria."),args:Oe(`\n sum_range (range) ${a("The range to sum.")}\n criteria_range1 (range) ${a("The range to check against criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${a("Additional ranges to check.")}\n criterion2 (string, repeating) ${a("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=0;return Re(t,((t,o)=>{const i=e[t][o];"number"==typeof i&&(s+=i)})),s},isExported:!0},Zt={description:a("Tangent of an angle provided in radians."),args:Oe(`\n angle (number) ${a("The angle to find the tangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tan(de(e))},isExported:!0},Gt={description:a("Hyperbolic tangent of any real number."),args:Oe(`\n value (number) ${a("Any real value to calculate the hyperbolic tangent of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tanh(de(e))},isExported:!0},Wt={description:a("Truncates a number."),args:Oe(`\n value (number) ${a("The value to be truncated.")}\n places (number, default=0) ${a("The number of significant digits to the right of the decimal point to retain.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t=0){const s=de(e);let o=de(t);return 0===o?Math.trunc(s):(Number.isInteger(o)||(o=Math.trunc(o)),Math.trunc(s*Math.pow(10,o))/Math.pow(10,o))},isExported:!0};var qt=Object.freeze({__proto__:null,ABS:Ge,ACOS:We,ACOSH:qe,ACOT:je,ACOTH:Xe,ASIN:Ye,ASINH:Ke,ATAN:Qe,ATAN2:Je,ATANH:et,CEILING:tt,CEILING_MATH:st,CEILING_PRECISE:ot,COS:it,COSH:nt,COT:rt,COTH:at,COUNTBLANK:lt,COUNTIF:ct,COUNTIFS:ht,COUNTUNIQUE:ut,COUNTUNIQUEIFS:pt,CSC:gt,CSCH:ft,DECIMAL:mt,DEGREES:vt,EXP:Et,FLOOR:bt,FLOOR_MATH:St,FLOOR_PRECISE:Ct,ISEVEN:yt,ISO_CEILING:wt,ISODD:It,LN:xt,MOD:Tt,ODD:Rt,PI:Lt,POWER:Mt,PRODUCT:At,RAND:_t,RANDBETWEEN:Ot,ROUND:Nt,ROUNDDOWN:kt,ROUNDUP:Ft,SEC:$t,SECH:Dt,SIN:Pt,SINH:Ut,SQRT:Vt,SUM:Bt,SUMIF:Ht,SUMIFS:zt,TAN:Zt,TANH:Gt,TRUNC:Wt});const jt=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function Xt(e){return e.toString(16).padStart(6,"0")}let Yt=0;function Kt(){return Yt=++Yt%jt.length,jt[Yt]}function Qt(e){return e.includes("rgb")?function(e){return e.slice(4,-1).split(",").map((e=>parseInt(e,10).toString(16).padStart(2,"0"))).join("").toUpperCase()}(e):(3===(e=e.replace("#","").toUpperCase()).length&&(e=e.split("").reduce(((e,t)=>e+t+t),"")),e)}const Jt=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),es=new RegExp(/^\s*('.+'!|[^']+!)?\$?[A-Z]{1,3}\$?[0-9]{1,7}(\s*:\s*\$?[A-Z]{1,3}\$?[0-9]{1,7})?$/,"i");function ts(e){const t=e.split("!"),s=t.pop();return{sheetName:t.join("!")||void 0,xc:s}}function ss(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):ss(Math.floor(e/26)-1)+ss(e%26)}function os(e){const t=(e=e.toUpperCase().trim()).match(Jt);if(null!==t){const[s,o,i]=t;if(s===e){const e=function(e){let t=0;const s=e.length;for(let o=0;o<s;o++)t+=(e.charCodeAt(o)-65+(o<s-1?1:0))*26**(s-o-1);return t}(o);return[e,parseInt(i,10)-1]}}throw new Error(`Invalid cell description: ${e}`)}function is(e,t,s={colFixed:!1,rowFixed:!1}){return(s.colFixed?"$":"")+ss(e)+(s.rowFixed?"$":"")+String(t+1)}const ns=140,rs=20,as=.035;function ls(e){return rs+(ns-rs)*Math.exp(-as*(e-1))}const cs=[{pt:7.5,px:10},{pt:8,px:11},{pt:9,px:12},{pt:10,px:13},{pt:10.5,px:14},{pt:11,px:15},{pt:12,px:16},{pt:14,px:18.7},{pt:15,px:20},{pt:16,px:21.3},{pt:18,px:24},{pt:22,px:29.3},{pt:24,px:32},{pt:26,px:34.7},{pt:36,px:48}],hs={};for(let e of cs)hs[e.pt]=e.px;function ds(e){return JSON.stringify(e,Object.keys(e).sort())}function us(e){return'"'===e[0]&&'"'===e[e.length-1]?e.slice(1).slice(0,e.length-2):e}function ps(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gs(e){const t=Array.isArray(e)?[]:{};switch(typeof e){case"object":if(null===e)return e;if(!(function(e){return"object"==typeof e&&(null==e?void 0:e.constructor)===Object}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");for(const s in e)t[s]=gs(e[s]);return t;case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function fs(e){var t;return(null===(t=e.match(/\w/g))||void 0===t?void 0:t.length)!==e.length&&(e=`'${e}'`),e}function ms(e,t,s){return e<t?t:e>s?s:e}function vs(e,t,s){const o=s.italic?"italic ":"",i=s.bold?"bold":T,n=s.fontSize||R,r=hs[n];return e.font=`${o}${i} ${r}px ${L}`,e.measureText(t).width}function Es(e,t,s=1){if(t<=e&&s>0)return[];if(0===s)throw new Error("range() step must not be zero");const o=Math.ceil(Math.abs((t-e)/s)),i=Array(o);for(let t=0;t<o;t++)i[t]=e+t*s;return i}function bs(e){return e.reduce(((e,t,s,o)=>{if(1===Math.abs(t-o[s-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*Ss(e,t){t.next();for(const s of e){const e=t.next();yield{...s,next:e.done?void 0:e.value}}}function Cs(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}function ys(e){return null!==W(e)}const ws=/^\[([^\[]+)\]\((.+)\)$/,Is=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function xs(e){return ws.test(e)}function Ts(e,t){return`[${e}](${t})`}function Rs(e){const t=e.match(ws)||[],s=t[1],o=t[2];if(!s||!o)throw new Error(`Could not parse markdown link ${e}.`);return{label:s,url:o}}const Ls="o-spreadsheet://";function Ms(e){if(!xs(e))return!1;const{url:t}=Rs(e);return t.startsWith(Ls)}function As(e){if(e.startsWith(Ls))return e.substr(Ls.length);throw new Error(`${e} is not a valid sheet link`)}function _s(e){return void 0!==e}const Os={};function Ns(e,t){for(let[s,o]of Object.entries(t))if(ds(o)===ds(e))return parseInt(s,10);const s=Object.keys(t),o=0===s.length?0:Math.max(...s.map((e=>parseInt(e,10))));return t[o+1]=e,o+1}function ks(e){let t,s=!1;const o=()=>(s||(t=e(),s=!0),t);return o.map=e=>ks((()=>e(o()))),o}function Fs(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;if(typeof e!=typeof t)return!1;if("object"!=typeof e)return e===t;const s=new Set;Object.keys(e).forEach((e=>s.add(e))),Object.keys(t).forEach((e=>s.add(e)));for(let o of s){if(typeof e[o]!=typeof e[o])return!1;if("object"==typeof e[o]){if(!Fs(e[o],t[o]))return!1}else if(e[o]!==t[o])return!1}return!0}function $s(e){const t=[];let s=0;for(let o=0;o<e;o++){const e={start:s,end:s+b,size:b,name:ss(o)};t.push(e),s=e.end}return t}function Ds(e){const t=[];let s=0;for(let o=0;o<e;o++){const e={start:s,end:s+S,size:S,name:String(o+1),cells:{}};t.push(e),s=e.end}return t}function Ps(e,t){var s;const o=[];let i=0;for(let n=0;n<t;n++){const t=e[n]&&e[n].size||b,r=(null===(s=e[n])||void 0===s?void 0:s.isHidden)||!1,a={start:i,end:r?i:i+t,size:t,name:ss(n)};r&&(a.isHidden=r),o.push(a),i=a.end}return o}function Us(e,t){var s;const o=[];let i=0;for(let n=0;n<t;n++){const t=e[n]&&e[n].size||S,r=(null===(s=e[n])||void 0===s?void 0:s.isHidden)||!1,a={start:i,end:r?i:i+t,size:t,name:String(n+1),cells:{}};r&&(a.isHidden=r),o.push(a),i=a.end}return o}function Vs(e,t=!1){const s={};for(let o in e){const i=e[o];(i.size!==b||t)&&(s[o]={size:i.size}),i.isHidden&&(s[o]=s[o]||{},s[o].isHidden=i.isHidden)}return s}function Bs(e,t=!1){const s={};for(let o in e){const i=e[o];(i.size!==S||t)&&(s[o]={size:i.size}),i.isHidden&&(s[o]=s[o]||{},s[o].isHidden=i.isHidden)}return s}class Hs{constructor(){this.isFastIdStrategy=!1,this.fastIdStart=0}setIsFastStrategy(e){this.isFastIdStrategy=e}uuidv4(){return this.isFastIdStrategy?(this.fastIdStart++,String(this.fastIdStart)):window.crypto&&window.crypto.getRandomValues?([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16))):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}}function zs(e,t,s){return[Zs(e,"cols",Es(t,e.cols.length)),Zs(e,"rows",Es(s,e.rows.length))]}function Zs(e,t,s){const o=e[t];return s.find((e=>!o[e].isHidden))}function Gs(e,t){let s=e[t].length-1;for(;s>=0&&!0===e[t][s].isHidden;)s--;return e[t][s]}function Ws(e){const t=(e=e.split("!").pop()).replace(/\$/g,"").split(":");let s,o,i,n,r=os(t[0].trim());if(i=n=r[0],s=o=r[1],2===t.length){let e=os(t[1].trim());n=e[0],o=e[1]}return{top:s,bottom:o,left:i,right:n}}function qs(e){let{top:t,bottom:s,left:o,right:i}=Ws(e);return i<o&&([i,o]=[o,i]),s<t&&([s,t]=[t,s]),{top:t,bottom:s,left:o,right:i}}function js(e){return!(isNaN(e.bottom)||isNaN(e.top)||isNaN(e.left)||isNaN(e.right))&&(!(e.top<0||e.left<0||e.right<0||e.bottom<0)&&(e.bottom>=e.top&&e.right>=e.left))}function Xs(e){const{top:t,bottom:s,left:o,right:i}=e;return t===s&&o===i?is(o,t):`${is(o,t)}:${is(i,s)}`}function Ys(e,t,s,o,i){const n="left"===t?"columns":"rows",r="before"===o?s-1:s,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?ao(e,n,"RESIZE",i):r<e[t]?ao(e,n,"MOVE",i):{...e}}function Ks(e,t,s){const o="left"===t?"right":"bottom";let i=e[t],n=e[o];for(let r of s.sort(((e,t)=>t-e)))e[t]>r&&(i--,n--),e[t]<r&&e[o]>=r&&n--;return{...e,[t]:i,[o]:n}}function Qs(e,t){return{top:Math.min(e.top,t.top),left:Math.min(e.left,t.left),bottom:Math.max(e.bottom,t.bottom),right:Math.max(e.right,t.right)}}function Js(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function eo(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function to(e,t,s){const{left:o,right:i,top:n,bottom:r}=s;return e>=o&&e<=i&&t>=n&&t<=r}function so(e,t){const s={};for(let t of e)if(t){const e=qs(t);for(let t=e.left;t<=e.right;t++)void 0===s[t]&&(s[t]=[]),s[t].push({top:e.top,bottom:e.bottom,remove:!1})}for(let e of t){const t=qs(e);for(let e=t.left;e<=t.right;e++)void 0===s[e]&&(s[e]=[]),s[e].push({top:t.top,bottom:t.bottom,remove:!0})}const o=[];for(let[e,t]of Object.entries(s))o.push({col:parseInt(e),ranges:oo(t)});return function(e){const t=e.sort(((e,t)=>e.col-t.col)),s=[];let o=[],i=0;for(let e=0;e<=t.length-1;e++){let n=[];if(i+1===t[e].col)for(let s of t[e].ranges){let i=!1;for(let e of o)s.top==e.top&&s.bottom==e.bottom&&(n.push(e),i=!0);i||n.push({top:s.top,bottom:s.bottom,startCol:t[e].col})}else n=t[e].ranges.map((s=>({top:s.top,bottom:s.bottom,startCol:t[e].col})));const r=o.filter((e=>!n.includes(e)));for(let e of r)s.push({top:e.top,bottom:e.bottom,left:e.startCol,right:i});i=t[e].col,o=n}for(let e of o)s.push({top:e.top,bottom:e.bottom,left:e.startCol,right:i});return s}(o).map(Xs)}function oo(e){const t=new Set,s=new Set;for(let o of e)for(let e=o.top;e<=o.bottom;e++)o.remove?s.add(e):t.add(e);const o=[...t].filter((e=>!s.has(e))).sort(((e,t)=>e-t)),i=[];let n;for(let e of o)n?e===n.bottom+1?n.bottom=e:(i.push({top:n.top,bottom:n.bottom}),n={top:e,bottom:e}):n={top:e,bottom:e};return n&&i.push({top:n.top,bottom:n.bottom}),i}function io(e){return{height:e.bottom-e.top+1,width:e.right-e.left+1}}function no(e){const{width:t,height:s}=io(e);return 1===t||1===s}function ro(e){const t=[],[s,o]=[e.right,e.left].sort(((e,t)=>e-t)),[i,n]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of Es(s,o+1))for(const s of Es(i,n+1))t.push([e,s]);return t}function ao(e,t,s,o){const i="columns"===t?"right":"bottom",n={...e};return"MOVE"===s&&(n["columns"===t?"left":"top"]+=o),n[i]+=o,n}function lo(e){return e.reverse().filter(((e,t,s)=>t===s.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}function co(e){return{top:Math.min(e.top,e.bottom),bottom:Math.max(e.top,e.bottom),left:Math.min(e.left,e.right),right:Math.max(e.left,e.right)}}function ho(e,t,s){let o=[],i=[],n=0,r=0;Ee([e],(e=>{o.push(e),n+=1})),Ee([t],(e=>{i.push(e),r+=1})),ce((()=>n===r),a("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",n.toString(),r.toString()));let l=0,c=0,h=0;for(let e=0;e<n;e++){const t=o[e],s=i[e];"number"==typeof t&&"number"==typeof s&&(l+=1,c+=t,h+=s)}ce((()=>0!==l&&(!s||1!==l)),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const d=c/l,u=h/l;let p=0;for(let e=0;e<n;e++){const t=o[e],s=i[e];"number"==typeof t&&"number"==typeof s&&(p+=(t-d)*(s-u))}return p/(l-(s?1:0))}function uo(e,t,s){let o=0,i=0;const n=s?we:ye;i=n(e,((e,t)=>(o+=1,e+t)),0),ce((()=>0!==o&&(!t||1!==o)),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const r=i/o;return n(e,((e,t)=>e+Math.pow(t-r,2)),0)/(o-(t?1:0))}function po(e,t,s){const o=de(t);ce((()=>s?0<=o&&o<=1:0<o&&o<1),a("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let i,n=[],r=0;Ee(e,(e=>{"number"==typeof e&&(i=Le(n,e),n.splice(i+1,0,e),r++)})),ce((()=>0!==r),a("[[FUNCTION_NAME]] has no valid input data."));let l=(r+(s?-1:1))*o;if(s||(ce((()=>1<=l&&l<=r),a("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),l--),Number.isInteger(l))return n[l];const c=Math.ceil(l),h=Math.floor(l);return n[c]*(l-h)+n[h]*(c-l)}const go={description:a("Average magnitude of deviations from mean."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;const s=ye(e,((e,s)=>(t+=1,e+s)),0);ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const o=s/t;return ye(e,((e,t)=>e+Math.abs(o-t)),0)/t},isExported:!0},fo={description:a("Numerical average value in a dataset, ignoring text."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the average value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t=0;const s=ye(e,((e,s)=>(t+=1,e+s)),0);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/t},isExported:!0},mo=a("[[FUNCTION_NAME]] has mismatched range sizes."),vo=a("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),Eo={description:a("Weighted average."),args:Oe(`\n values (number, range<number>) ${a("Values to average.")}\n weights (number, range<number>) ${a("Weights for each corresponding value.")}\n additional_values (number, range<number>, repeating) ${a("Additional values to average.")}\n additional_weights (number, range<number>, repeating) ${a("Additional weights.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t,s,o=0,i=0;ce((()=>e.length%2==0),a("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let n=0;n<e.length-1;n+=2)if(t=e[n],s=e[n+1],Array.isArray(t)){ce((()=>Array.isArray(s)),mo);let e=t.length,n=t[0].length;ce((()=>e===s.length&&n===s[0].length),mo);for(let r=0;r<e;r++)for(let e=0;e<n;e++){let n=t[r][e],l=s[r][e],c="number"==typeof n,h="number"==typeof l;ce((()=>c===h),a("[[FUNCTION_NAME]] expects number values.")),h&&(ce((()=>l>=0),vo),o+=n*l,i+=l)}}else s=de(s),t=de(t),ce((()=>s>=0),vo),o+=t*s,i+=s;return ce((()=>0!==i),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/i}},bo={description:a("Numerical average value in a dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the average value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t=0;const s=we(e,((e,s)=>(t+=1,e+s)),0);return ce((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/t},isExported:!0},So={description:a("Average of values depending on criteria."),args:Oe(`\n criteria_range (range) ${a("The range to check against criterion.")}\n criterion (string) ${a("The pattern or test to apply to criteria_range.")}\n average_range (range, default=criteria_range) ${a("The range to average. If not included, criteria_range is used for the average instead.")}\n `),returns:["NUMBER"],compute:function(e,t,s){null==s&&(s=e);let o=0,i=0;return Re([e,t],((t,n)=>{const r=(s||e)[t][n];"number"==typeof r&&(o+=1,i+=r)})),ce((()=>0!==o),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/o},isExported:!0},Co={description:a("Average of values depending on multiple criteria."),args:Oe(`\n average_range (range) ${a("The range to average.")}\n criteria_range1 (range) ${a("The range to check against criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${a("Additional criteria_range and criterion to check.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=0,o=0;return Re(t,((t,i)=>{const n=e[t][i];"number"==typeof n&&(s+=1,o+=n)})),ce((()=>0!==s),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/s},isExported:!0},yo={description:a("The number of numeric values in dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when counting.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;for(let s of e)if(Array.isArray(s))for(let e of s)for(let s of e)"number"==typeof s&&(t+=1);else("string"!=typeof s||ee(s)||W(s))&&(t+=1);return t},isExported:!0},wo={description:a("The number of values in a dataset."),args:Oe(`\n value1 (any, range) ${a("The first value or range to consider when counting.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){return Ce(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},Io={description:a("The covariance of a dataset."),args:Oe(`\n data_y (any, range) ${a("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${a("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return ho(e,t,!1)},isExported:!0},xo={description:a("The covariance of a dataset."),args:Oe(`\n data_y (any, range) ${a("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${a("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return ho(e,t,!1)},isExported:!0},To={description:a("The sample covariance of a dataset."),args:Oe(`\n data_y (any, range) ${a("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${a("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return ho(e,t,!0)},isExported:!0},Ro={description:a("Nth largest element from a data set."),args:Oe(`\n data (any, range) ${a("Array or range containing the dataset to consider.")}\n n (number) ${a("The rank from largest to smallest of the element to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=Math.trunc(de(t));let o,i=[],n=0;Ee([e],(e=>{"number"==typeof e&&(o=Le(i,e),i.splice(o+1,0,e),n++,n>s&&(i.shift(),n--))}));const r=i.shift();return ce((()=>void 0!==r),a("[[FUNCTION_NAME]] has no valid input data.")),ce((()=>n>=s),a("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s.toString())),r},isExported:!0},Lo={description:a("Maximum value in a numeric dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the maximum value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the maximum value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){const t=ye(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},Mo={description:a("Maximum numeric value in a dataset."),args:Oe(`\n value1 (any, range) ${a("The first value or range to consider when calculating the maximum value.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider when calculating the maximum value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){const t=we(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},Ao={description:a("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:Oe(`\n range (range) ${a("The range of cells from which the maximum will be determined.")}\n criteria_range1 (range) ${a("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${a("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.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=-1/0;return Re(t,((t,o)=>{const i=e[t][o];"number"==typeof i&&(s=s<i?i:s)})),s===-1/0?0:s},isExported:!0},_o={description:a("Median value in a numeric dataset."),args:Oe(`\n value1 (any, range) ${a("The first value or range to consider when calculating the median value.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider when calculating the median value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){let t=[];return be(e,(e=>{t.push(e)})),po(t,.5,!0)},isExported:!0},Oo={description:a("Minimum value in a numeric dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the minimum value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){const t=ye(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},No={description:a("Minimum numeric value in a dataset."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the minimum value.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(...e){const t=we(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},ko={description:a("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:Oe(`\n range (range) ${a("The range of cells from which the minimum will be determined.")}\n criteria_range1 (range) ${a("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${a("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.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=1/0;return Re(t,((t,o)=>{const i=e[t][o];"number"==typeof i&&(s=s>i?i:s)})),s===1/0?0:s},isExported:!0},Fo={description:a("Value at a given percentile of a dataset."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n percentile (number) ${a("The percentile whose value within data will be calculated and returned.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return Do.compute(e,t)},isExported:!0},$o={description:a("Value at a given percentile of a dataset exclusive of 0 and 1."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n percentile (number) ${a("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return po([e],t,!1)},isExported:!0},Do={description:a("Value at a given percentile of a dataset."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n percentile (number) ${a("The percentile whose value within data will be calculated and returned.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return po([e],t,!0)},isExported:!0},Po={description:a("Value nearest to a specific quartile of a dataset."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n quartile_number (number) ${a("Which quartile value to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return Vo.compute(e,t)},isExported:!0},Uo={description:a("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n quartile_number (number) ${a("Which quartile value, exclusive of 0 and 4, to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return po([e],.25*Math.trunc(de(t)),!1)},isExported:!0},Vo={description:a("Value nearest to a specific quartile of a dataset."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n quartile_number (number) ${a("Which quartile value to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return po([e],.25*Math.trunc(de(t)),!0)},isExported:!0},Bo={description:a("Nth smallest element in a data set."),args:Oe(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n n (number) ${a("The rank from smallest to largest of the element to return.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=Math.trunc(de(t));let o,i=[],n=0;Ee([e],(e=>{"number"==typeof e&&(o=Le(i,e),i.splice(o+1,0,e),n++,n>s&&(i.pop(),n--))}));const r=i.pop();return ce((()=>void 0!==r),a("[[FUNCTION_NAME]] has no valid input data.")),ce((()=>n>=s),a("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s.toString())),r},isExported:!0},Ho={description:a("Standard deviation."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(jo.compute(...e))},isExported:!0},zo={description:a("Standard deviation of entire population."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Xo.compute(...e))},isExported:!0},Zo={description:a("Standard deviation."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Yo.compute(...e))},isExported:!0},Go={description:a("Standard deviation of sample (text as 0)."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Ko.compute(...e))},isExported:!0},Wo={description:a("Standard deviation of entire population."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Qo.compute(...e))},isExported:!0},qo={description:a("Standard deviation of entire population (text as 0)."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Jo.compute(...e))},isExported:!0},jo={description:a("Variance."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return uo(e,!0,!1)},isExported:!0},Xo={description:a("Variance of entire population."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return uo(e,!1,!1)},isExported:!0},Yo={description:a("Variance."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return uo(e,!0,!1)},isExported:!0},Ko={description:a("Variance of sample (text as 0)."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return uo(e,!0,!0)},isExported:!0},Qo={description:a("Variance of entire population."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return uo(e,!1,!1)},isExported:!0},Jo={description:a("Variance of entire population (text as 0)."),args:Oe(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return uo(e,!1,!0)},isExported:!0};var ei=Object.freeze({__proto__:null,AVEDEV:go,AVERAGE:fo,AVERAGE_WEIGHTED:Eo,AVERAGEA:bo,AVERAGEIF:So,AVERAGEIFS:Co,COUNT:yo,COUNTA:wo,COVAR:Io,COVARIANCE_P:xo,COVARIANCE_S:To,LARGE:Ro,MAX:Lo,MAXA:Mo,MAXIFS:Ao,MEDIAN:_o,MIN:Oo,MINA:No,MINIFS:ko,PERCENTILE:Fo,PERCENTILE_EXC:$o,PERCENTILE_INC:Do,QUARTILE:Po,QUARTILE_EXC:Uo,QUARTILE_INC:Vo,SMALL:Bo,STDEV:Ho,STDEV_P:zo,STDEV_S:Zo,STDEVA:Go,STDEVP:Wo,STDEVPA:qo,VAR:jo,VAR_P:Xo,VAR_S:Yo,VARA:Ko,VARP:Qo,VARPA:Jo});function ti(e,t,s){var o;const i=new Map,n=e.length;for(let t=n-1;t>=0;t--)i.set(pe(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(a("The field must be a number or a string"));let r;if("number"==typeof t){if(r=Math.trunc(t)-1,r<0||n-1<r)throw new Error(a("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),n.toString()))}else{const e=pe(t).toUpperCase();if(r=null!==(o=i.get(e))&&void 0!==o?o:-1,-1===r)throw new Error(a("The field (%s) must be one of %s.",pe(t),[...i.keys()].toString()))}const l=s[0].length;if(l<2)throw new Error(a("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const h=e[0].length;for(let t=1;t<l;t++){let o=[],n=!0;for(let r=0;r<s.length;r++){const a=pe(s[r][0]).toUpperCase(),l=i.get(a),c=s[r][t];if(void 0!==c){if(void 0===l){n=!1;break}o.push([e[l].slice(1,h)]),o.push(c)}}if(n){if(!(o.length>0)){c=new Set(Array(h-1).keys());break}Re(o,((e,t)=>{c.add(t)}),!0)}}const d=e[r];return[...c].map((e=>d[e+1]))}const si=Oe(`\n database (range) ${a("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.")}\n field (any) ${a("Indicates which column in database contains the values to be extracted and operated on.")}\n criteria (range) ${a("An array or range containing zero or more criteria to filter the database values by before operating.")}\n`),oi={description:a("Average of a set of values from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return fo.compute([o])},isExported:!0},ii={description:a("Counts values from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return yo.compute([o])},isExported:!0},ni={description:a("Counts values and text from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return wo.compute([o])},isExported:!0},ri={description:a("Single value from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return ce((()=>1===o.length),a("More than one match found in DGET evaluation.")),o[0]},isExported:!0},ai={description:a("Maximum of values from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return Lo.compute([o])},isExported:!0},li={description:a("Minimum of values from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return Oo.compute([o])},isExported:!0},ci={description:a("Product of values from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return At.compute([o])},isExported:!0},hi={description:a("Standard deviation of population sample from table."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return Ho.compute([o])},isExported:!0},di={description:a("Standard deviation of entire population from table."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return Wo.compute([o])},isExported:!0},ui={description:a("Sum of values from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return Bt.compute([o])},isExported:!0},pi={description:a("Variance of population sample from table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return jo.compute([o])},isExported:!0},gi={description:a("Variance of a population from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return Qo.compute([o])},isExported:!0};var fi=Object.freeze({__proto__:null,DAVERAGE:oi,DCOUNT:ii,DCOUNTA:ni,DGET:ri,DMAX:ai,DMIN:li,DPRODUCT:ci,DSTDEV:hi,DSTDEVP:di,DSUM:ui,DVAR:pi,DVARP:gi});const mi=new Date(1899,11,30);function vi(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}const Ei={description:a("Converts year/month/day into a date."),args:Oe(`\n year (number) ${a("The year component of the date.")}\n month (number) ${a("The month component of the date.")}\n day (number) ${a("The day component of the date.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t,s){let o=Math.trunc(de(e));const i=Math.trunc(de(t)),n=Math.trunc(de(s));ce((()=>0<=o&&o<=9999),a("The year (%s) must be between 0 and 9999 inclusive.",o.toString())),o<1900&&(o+=1900);const r=new Date(o,i-1,n).getTime()-mi.getTime();return ce((()=>r>=0),a("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),Math.round(r/864e5)},isExported:!0},bi={description:a("Converts a date string to a date value."),args:Oe(`\n date_string (string) ${a("The string representing the date.")}\n `),returns:["NUMBER"],compute:function(e){const t=pe(e),s=W(t);return ce((()=>null!==s),a("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(s.value)},isExported:!0},Si={description:a("Day of the month that a specific date falls on."),args:Oe(`\n date (string) ${a("The date from which to extract the day.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getDate()},isExported:!0},Ci={description:a("Number of days between two dates."),args:Oe(`\n end_date (date) ${a("The end of the date range.")}\n start_date (date) ${a("The start of the date range.")}\n `),returns:["NUMBER"],compute:function(e,t){const s=me(e),o=me(t),i=s.getTime()-o.getTime();return Math.round(i/864e5)},isExported:!0},yi={description:a("Date a number of months before/after another date."),args:Oe(`\n start_date (date) ${a("The date from which to calculate the result.")}\n months (number) ${a("The number of months before (negative) or after (positive) 'start_date' to calculate.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t){const s=me(e),o=Math.trunc(de(t)),i=s.getFullYear(),n=s.getMonth(),r=s.getDate(),a=new Date(i,n+o,r).getTime()-mi.getTime();return Math.round(a/864e5)},isExported:!0},wi={description:a("Last day of a month before or after a date."),args:Oe(`\n start_date (date) ${a("The date from which to calculate the result.")}\n months (number) ${a("The number of months before (negative) or after (positive) 'start_date' to consider.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t){const s=me(e),o=Math.trunc(de(t)),i=s.getFullYear(),n=s.getMonth(),r=new Date(i,n+o+1,0).getTime()-mi.getTime();return Math.round(r/864e5)},isExported:!0},Ii={description:a("Hour component of a specific time."),args:Oe(`\n time (date) ${a("The time from which to calculate the hour component.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getHours()},isExported:!0},xi={description:a("ISO week number of the year."),args:Oe(`\n date (date) ${a("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.")}\n `),returns:["NUMBER"],compute:function(e){const t=me(e),s=t.getFullYear();let o=1;for(;4!==new Date(s,0,o).getDay();)o+=1;const i=new Date(s,0,o-3);let n=31;for(;4!==new Date(s,11,n).getDay();)n-=1;const r=new Date(s,11,n+3);let a,l;switch(a=i.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=i;break;case 1:l=new Date(s,11,n+3+1);break;case-1:let e=1;for(;4!==new Date(s-1,0,e).getDay();)e+=1;l=new Date(s-1,0,e-3)}const c=(t.getTime()-l.getTime())/864e5;return Math.floor(c/7)+1},isExported:!0},Ti={description:a("Minute component of a specific time."),args:Oe(`\n time (date) ${a("The time from which to calculate the minute component.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getMinutes()},isExported:!0},Ri={description:a("Month of the year a specific date falls in"),args:Oe(`\n date (date) ${a("The date from which to extract the month.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getMonth()+1},isExported:!0},Li={description:a("Net working days between two provided days."),args:Oe(`\n start_date (date) ${a("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${a("The end date of the period from which to calculate the number of net working days.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the date serial numbers to consider holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,s){return Ai.compute(e,t,1,s)},isExported:!0};function Mi(e){if("string"==typeof e){ce((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),a('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let s=0;s<7;s++)"1"===e[s]&&t.push((s+1)%7);return t}if("number"==typeof e)return ce((()=>1<=e&&e<=7||11<=e&&e<=17),a("The weekend (%s) must be a string or a number in the range 1-7 or 11-17.",e.toString())),e<=7?[e-2==-1?6:e-2,e-1]:[e-11];throw Error(a("The weekend (%s) must be a number or a string.",e.toString()))}const Ai={description:a("Net working days between two dates (specifying weekends)."),args:Oe(`\n start_date (date) ${a("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${a("The end date of the period from which to calculate the number of net working days.")}\n weekend (any, default=1) ${a("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the dates to consider as holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1,o){const i=me(e),n=me(t),r=Mi(s);let a=new Set;void 0!==o&&Ee([o],(e=>{const t=me(e);a.add(t.getTime())}));const l=i.getTime()>n.getTime(),c=new Date((l?i:n).getTime());let h=new Date((l?n:i).getTime());const d=c.getTime();let u=h.getTime(),p=0;for(;u<=d;)r.includes(h.getDay())||a.has(u)||(p+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-p:p},isExported:!0},_i={description:a("Current date and time as a date value."),args:[],returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy hh:mm:ss"},compute:function(){let e=new Date;e.setMilliseconds(0);const t=e.getTime()-mi.getTime(),s=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/864e5)+s},isExported:!0},Oi={description:a("Minute component of a specific time."),args:Oe(`\n time (date) ${a("The time from which to calculate the second component.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getSeconds()},isExported:!0},Ni={description:a("Converts hour/minute/second into a time."),args:Oe(`\n hour (number) ${a("The hour component of the time.")}\n minute (number) ${a("The minute component of the time.")}\n second (number) ${a("The second component of the time.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"hh:mm:ss a"},compute:function(e,t,s){let o=Math.trunc(de(e)),i=Math.trunc(de(t)),n=Math.trunc(de(s));return i+=Math.floor(n/60),n=n%60+(n<0?60:0),o+=Math.floor(i/60),i=i%60+(i<0?60:0),o%=24,ce((()=>o>=0),a("The function [[FUNCTION_NAME]] result cannot be negative")),o/24+i/1440+n/86400},isExported:!0},ki={description:a("Converts a time string into its serial number representation."),args:Oe(`\n time_string (string) ${a("The string that holds the time representation.")}\n `),returns:["NUMBER"],compute:function(e){const t=pe(e),s=W(t);ce((()=>null!==s),a("The time_string (%s) cannot be parsed to date/time.",t));const o=s.value-Math.trunc(s.value);return o<0?1+o:o},isExported:!0},Fi={description:a("Current date as a date value."),args:[],returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(){const e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()-mi.getTime();return Math.round(t/864e5)},isExported:!0},$i={description:a("Day of the week of the date provided (as number)."),args:Oe(`\n date (date) ${a("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.")}\n type (number, default=1) ${a("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.")}\n `),returns:["NUMBER"],compute:function(e,t=1){const s=me(e),o=Math.round(de(t)),i=s.getDay();return ce((()=>[1,2,3].includes(o)),a("The type (%s) must be 1, 2 or 3.",o.toString())),1===o?i+1:2===o?0===i?7:i:0===i?6:i-1},isExported:!0},Di={description:a("Week number of the year."),args:Oe(`\n date (date) ${a("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.")}\n type (number, default=1) ${a("A number representing the day that a week starts on. Sunday = 1.")}\n `),returns:["NUMBER"],compute:function(e,t=1){const s=me(e),o=Math.round(de(t));if(ce((()=>1===o||2===o||11<=o&&o<=17||21===o),a("The type (%s) is out of range.",o.toString())),21===o)return xi.compute(e);let i;i=1===o||2===o?o-1:o-10==7?0:o-10;const n=s.getFullYear();let r=1,l=new Date(n,0,r);for(;l.getDay()!==i;)r+=1,l=new Date(n,0,r);const c=(s.getTime()-l.getTime())/864e5;return c<0?1:Math.floor(c/7)+(1===r?1:2)},isExported:!0},Pi={description:a("Number of working days from start date."),args:Oe(`\n start_date (date) ${a("The date from which to begin counting.")}\n num_days (number) ${a("The number of working days to advance from start_date. If negative, counts backwards.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the dates to consider holidays.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t,s){return Ui.compute(e,t,1,s)},isExported:!0},Ui={description:a("Net working days between two dates (specifying weekends)."),args:Oe(`\n start_date (date) ${a("The date from which to begin counting.")}\n num_days (number) ${a("The number of working days to advance from start_date. If negative, counts backwards.")}\n weekend (any, default=1) ${a("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the dates to consider holidays.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t,s=1,o){let i=me(e),n=Math.trunc(de(t));"string"==typeof s&&ce((()=>"1111111"!==s),a("The weekend (%s) must be different from '1111111'.",s));const r=Mi(s);let l=new Set;void 0!==o&&Ee([o],(e=>{const t=me(e);l.add(t.getTime())}));let c=new Date(i.getTime()),h=c.getTime();const d=Math.sign(n);let u=Math.abs(n);for(;u>0;)c.setDate(c.getDate()+d),h=c.getTime(),r.includes(c.getDay())||l.has(h)||(u-=1);const p=h-mi.getTime();return Math.round(p/864e5)},isExported:!0},Vi={description:a("Year specified by a given date."),args:Oe(`\n date (date) ${a("The date from which to extract the year.")}\n `),returns:["NUMBER"],compute:function(e){return me(e).getFullYear()},isExported:!0},Bi={description:a("Exact number of years between two dates."),args:Oe(`\n start_date (date) ${a("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.")}\n end_date (date) ${a("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.")}\n day_count_convention (number, default=0) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s=0){let o=Math.trunc(de(e)),i=Math.trunc(de(t));const n=Math.trunc(de(s));if(ce((()=>o>=0),a("The start_date (%s) must be positive or null.",o.toString())),ce((()=>i>=0),a("The end_date (%s) must be positive or null.",i.toString())),ce((()=>0<=n&&n<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",n.toString())),o===i)return 0;if(o>i){const e=i;i=o,o=e}const r=me(o),l=me(i);let c=r.getDate(),h=l.getDate();const d=r.getMonth(),u=l.getMonth(),p=r.getFullYear(),g=l.getFullYear();let f=0,m=0;switch(n){case 0:31===c&&(c=30),30===c&&31===h&&(h=30),1===d&&c===(vi(p)?29:28)&&(c=30,1===u&&h===(vi(g)?29:28)&&(h=30)),f=p+(30*d+c)/360,m=g+(30*u+h)/360;break;case 1:let e=365;const t=p===g;if(!t&&!(p+1===g)||!t&&d<u||!t&&d===u&&c<h){let t=0,s=0;for(let e=p;e<=g;e++)t++,s+=vi(e)?366:365;e=s/t}else t?vi(p)&&(e=366):(vi(p)&&d<2&&(e=366),vi(g)&&(u>1||1===u&&29===h)&&(e=366));f=o/e,m=i/e;break;case 2:f=o/360,m=i/360;break;case 3:f=o/365,m=i/365;break;case 4:31===c&&(c=30),31===h&&(h=30),f=p+(30*d+c)/360,m=g+(30*u+h)/360}return m-f}};var Hi=Object.freeze({__proto__:null,DATE:Ei,DATEVALUE:bi,DAY:Si,DAYS:Ci,EDATE:yi,EOMONTH:wi,HOUR:Ii,ISOWEEKNUM:xi,MINUTE:Ti,MONTH:Ri,NETWORKDAYS:Li,NETWORKDAYS_INTL:Ai,NOW:_i,SECOND:Oi,TIME:Ni,TIMEVALUE:ki,TODAY:Fi,WEEKDAY:$i,WEEKNUM:Di,WORKDAY:Pi,WORKDAY_INTL:Ui,YEAR:Vi,YEARFRAC:Bi});const zi={description:a("Compare two numeric values, returning 1 if they're equal."),args:Oe(`\n number1 (number) ${a("The first number to compare.")}\n number2 (number, default=0) ${a("The second number to compare.")}\n `),returns:["NUMBER"],compute:function(e,t=0){return de(e)===de(t)?1:0},isExported:!0};var Zi=Object.freeze({__proto__:null,DELTA:zi});function Gi(e,t,s,o,i=1e-10){let n,r,l,c=s,h=!1,d=0;do{l=e(c),n=c-l/t(c),r=Math.abs(n-c),c=n,h=r<i||Math.abs(l)<i,ce((()=>d<o),a("Function [[FUNCTION_NAME]] didn't find any result")),d++}while(!h);return c}const Wi={description:a("Depreciation via declining balance method."),args:Oe(`\n cost (number) ${a("The initial cost of the asset.")}\n salvage (number) ${a("The value of the asset at the end of depreciation.")}\n life (number) ${a("The number of periods over which the asset is depreciated.")}\n period (number) ${a("The single period within life for which to calculate depreciation.")}\n month (number, optional) ${a("The number of months in the first year of depreciation.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,t,s,o,...i){const n=de(e),r=de(t),l=de(s),c=Math.trunc(de(o)),h=i.length?Math.trunc(de(i[0])):12,d=l+(12===h?0:1);ce((()=>n>0),a("The cost (%s) must be strictly positive.",n.toString())),ce((()=>r>=0),a("The salvage (%s) must be positive or null.",r.toString())),ce((()=>l>0),a("The life (%s) must be strictly positive.",l.toString())),ce((()=>c>0),a("The period (%s) must be strictly positive.",c.toString())),ce((()=>1<=h&&h<=12),a("The month (%s) must be between 1 and 12 inclusive.",h.toString())),ce((()=>c<=d),a("The period (%s) must be less than or equal to %s.",c.toString(),d.toString()));const u=h/12;let p=1-Math.pow(r/n,1/l);p=Math.round(1e3*p)/1e3;let g=n,f=n*(1-p*u);for(let e=1;e<c;e++)g=f,f=g*(1-p),e===l&&(f=g*(1-p*(1-u)));return g-f}},qi={description:a("Number of periods for an investment to reach a value."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n yield (number) ${a("The expected annual yield of the security.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n=0){n=n||0;const r=Math.trunc(de(e)),l=Math.trunc(de(t)),c=de(s),h=de(o),d=Math.trunc(de(i)),u=Math.trunc(de(n));ce((()=>r<l),a("The maturity (%s) must be strictly greater than the settlement (%s).",l.toString(),r.toString())),ce((()=>c>=0),a("The rate (%s) must be positive or null.",c.toString())),ce((()=>h>=0),a("The yield (%s) must be positive or null.",h.toString())),ce((()=>[1,2,4].includes(d)),a("The frequency (%s) must be one of %s",d.toString(),[1,2,4].toString())),ce((()=>0<=u&&u<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",u.toString()));const p=Bi.compute(r,l,u),g=p-Math.trunc(p)||1/d,f=Math.ceil(p*d),m=c/d,v=h/d;let E=0,b=0;for(let e=1;e<=f;e++){const t=(m+(e===f?1:0))/(1+v)**e;b+=(g+(e-1)/d)*t,E+=t}return 0===E?0:b/E}},ji={description:a("Future value of an annuity investment."),args:Oe(`\n rate (number) ${a("The interest rate.")}\n number_of_periods (number) ${a("The number of payments to be made.")}\n payment_amount (number) ${a("The amount per period to be paid.")}\n present_value (number, default=0) ${a("The current value of the annuity.")}\n end_or_beginning (number, default=0) ${a("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,t,s,o=0,i=0){o=o||0,i=i||0;const n=de(e),r=de(t),a=de(s),l=de(o),c=fe(i)?1:0;return n?-l*(1+n)**r-a*(1+n*c)*((1+n)**r-1)/n:-(l+a*r)}},Xi={description:a("Internal rate of return given periodic cashflows."),args:Oe(`\n cashflow_amounts (number, range<number>) ${a("An array or range containing the income or payments associated with the investment.")}\n rate_guess (number, default=0.1) ${a("An estimate for what the internal rate of return will be.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"0%"},compute:function(e,t=.1){const s=de(t);ce((()=>s>-1),a("The rate_guess (%s) must be strictly greater than -1.",s.toString()));let o=!1,i=!1,n=[];be([e],(e=>{e>0&&(o=!0),e<0&&(i=!0),n.push(e)})),ce((()=>o&&i),a("The cashflow_amounts must include negative and positive values."));const r=n.shift();return Gi((function(e){return function(e,t,s){const o=s.length;let i=0;return s.reduce(((t,s)=>(i++,t+s*e**(o-i))),t*e**o)}(e,r,n)}),(function(e){return function(e,t,s){const o=s.length;let i=0;return s.reduce(((t,s)=>(i++,t+s*(o-i)*e**(o-i-1))),t*o*e**(o-1))}(e,r,n)}),s+1,20,1e-5)-1}},Yi={description:a("Modified Macaulay duration."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n yield (number) ${a("The expected annual yield of the security.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n=0){return qi.compute(e,t,s,o,i,n)/(1+de(o)/Math.trunc(de(i)))}};const Ki={description:a("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:Oe(`\n discount (number) ${a("The discount rate of the investment over one period.")}\n cashflow1 (number, range<number>) ${a("The first future cash flow.")}\n cashflow2 (number, range<number>, repeating) ${a("Additional future cash flows.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,...t){const s=de(e);return ce((()=>-1!==s),a("The discount (%s) must be different from -1.",s.toString())),function(e,t,s){let o=0;return ye(s,((t,s)=>(o++,t+s/(1+e)**o)),t)}(s,0,t)}},Qi={description:a("Computes the number of periods needed for an investment to reach a value."),args:Oe(`\n rate (number) ${a("The rate at which the investment grows each period.")}\n present_value (number) ${a("The investment's current value.")}\n future_value (number) ${a("The investment's desired future value.")}\n `),returns:["NUMBER"],compute:function(e,t,s){const o=de(e),i=de(t),n=de(s);return ce((()=>o>0),a("The rate (%s) must be strictly positive.",o.toString())),ce((()=>i>0),a("The present_value (%s) must be strictly positive.",i.toString())),ce((()=>n>0),a("The future_value (%s) must be strictly positive.",n.toString())),(Math.log(n)-Math.log(i))/Math.log(1+o)}},Ji={description:a("Present value of an annuity investment."),args:Oe(`\n rate (number) ${a("The interest rate.")}\n number_of_periods (number) ${a("The number of payments to be made.")}\n payment_amount (number) ${a("The amount per period to be paid.")}\n future_value (number, default=0) ${a("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${a("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,t,s,o=0,i=0){o=o||0,i=i||0;const n=de(e),r=de(t),a=de(s),l=de(o),c=fe(i)?1:0;return n?-(a*(1+n*c)*((1+n)**r-1)/n+l)/(1+n)**r:-(l+a*r)}},en={description:a("Price of a security paying periodic interest."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n yield (number) ${a("The expected annual yield of the security.")}\n redemption (number) ${a("The redemption amount per 100 face value, or par.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n,r=0){r=r||0;const l=Math.trunc(de(e)),c=Math.trunc(de(t)),h=de(s),d=de(o),u=de(i),p=Math.trunc(de(n)),g=Math.trunc(de(r));ce((()=>c>l),a("The maturity (%s) must be strictly greater than the settlement (%s).",c.toString(),l.toString())),ce((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ce((()=>d>=0),a("The yield (%s) must be positive or null.",d.toString())),ce((()=>u>0),a("The redemption (%s) must be strictly positive.",u.toString())),ce((()=>[1,2,4].includes(p)),a("The frequency (%s) must be one of %s.",p.toString(),[1,2,4].toString())),ce((()=>0<=g&&g<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",g.toString()));const f=Bi.compute(l,c,g)*p,m=Math.ceil(f),v=f-Math.floor(f)||1,E=1+d/p,b=100*h/p;if(1===m)return(b+u)/(v*d/p+1)-b*(1-v);let S=0;for(let e=1;e<=m;e++)S+=b/E**(e-1+v);return u/E**(m-1+v)+S-b*(1-v)}},tn={description:a("Annual yield of a security paying periodic interest."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n price (number) ${a("The price at which the security is bought per 100 face value.")}\n redemption (number) ${a("The redemption amount per 100 face value, or par.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n,r=0){r=r||0;const l=Math.trunc(de(e)),c=Math.trunc(de(t)),h=de(s),d=de(o),u=de(i),p=Math.trunc(de(n)),g=Math.trunc(de(r));ce((()=>c>l),a("The maturity (%s) must be strictly greater than the settlement (%s).",c.toString(),l.toString())),ce((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ce((()=>d>0),a("The price (%s) must be strictly positive.",d.toString())),ce((()=>u>0),a("The redemption (%s) must be strictly positive.",u.toString())),ce((()=>[1,2,4].includes(p)),a("The frequency (%s) must be one of %s.",p.toString(),[1,2,4].toString())),ce((()=>0<=g&&g<=4),a("The day_count_convention (%s) must between 0 and 4 inclusive.",g.toString()));const f=Bi.compute(l,c,g)*p,m=Math.ceil(f),v=f-Math.floor(f)||1,E=100*h/p;if(1===m){const e=d+E*(1-v);return(u+E-e)*p*(1/v)/e}const b=Gi((function(e){return function(e,t,s,o,i,n){let r=n-(e+i*(1-t))*o**(s-1+t);for(let e=1;e<=s;e++)r+=i*o**(e-1);return r}(d,v,m,e,E,u)}),(function(e){return function(e,t,s,o,i){let n=-(e+i*(1-t))*(s-1+t)*o**(s-2+t);for(let e=1;e<=s;e++)n+=i*(e-1)*o**(e-2);return n}(d,v,m,e,E)}),1+(h+1)/p,100,1e-5);return(b-1)*p}},sn={description:a("Annual yield of a security paying interest at maturity."),args:Oe(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n issue (date) ${a("The date the security was initially issued.")}\n rate (number) ${a("The annualized rate of interest.")}\n price (number) ${a("The price at which the security is bought.")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n=0){n=n||0;const r=Math.trunc(de(e)),l=Math.trunc(de(t)),c=Math.trunc(de(s)),h=de(o),d=de(i),u=Math.trunc(de(n));ce((()=>r>=c),a("The settlement (%s) must be greater than or equal to the issue (%s).",r.toString(),c.toString())),ce((()=>l>r),a("The maturity (%s) must be strictly greater than the settlement (%s).",l.toString(),r.toString())),ce((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ce((()=>d>0),a("The price (%s) must be strictly positive.",d.toString())),ce((()=>0<=u&&u<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",u.toString()));const p=Bi.compute(c,l,u),g=Bi.compute(c,r,u),f=Bi.compute(r,l,u);return(100*(1+h*p)/(d+100*h*g)-1)/f}};var on=Object.freeze({__proto__:null,DB:Wi,DURATION:qi,FV:ji,IRR:Xi,MDURATION:Yi,NPV:Ki,PDURATION:Qi,PV:Ji,PRICE:en,YIELD:tn,YIELDMAT:sn});const nn={description:a("Whether a value is an error."),args:Oe(`value (any, lazy) ${a("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},rn={description:a("Whether a value is `true` or `false`."),args:Oe(`value (any) ${a("The value to be verified as a logical TRUE or FALSE.")}`),returns:["BOOLEAN"],compute:function(e){return"boolean"==typeof e},isExported:!0},an={description:a("Whether a value is non-textual."),args:Oe(`value (any) ${a("The value to be checked.")}`),returns:["BOOLEAN"],compute:function(e){return"string"!=typeof e},isExported:!0},ln={description:a("Whether a value is a number."),args:Oe(`value (any) ${a("The value to be verified as a number.")}`),returns:["BOOLEAN"],compute:function(e){return"number"==typeof e},isExported:!0},cn={description:a("Whether a value is text."),args:Oe(`value (any) ${a("The value to be verified as text.")}`),returns:["BOOLEAN"],compute:function(e){return"string"==typeof e},isExported:!0};var hn=Object.freeze({__proto__:null,ISERROR:nn,ISLOGICAL:rn,ISNONTEXT:an,ISNUMBER:ln,ISTEXT:cn});const dn={description:a("Logical `and` operator."),args:Oe(`\n logical_expression1 (boolean, range<boolean>) ${a("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.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${a("More expressions that represent logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,s=!0;return Ie(e,(e=>(t=!0,s=s&&e,s))),ce((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0},un={description:a("Returns value depending on logical expression."),args:Oe(`\n logical_expression (boolean) ${a("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")}\n value_if_true (any, lazy) ${a("The value the function returns if logical_expression is TRUE.")}\n value_if_false (any, lazy, default=FALSE) ${a("The value the function returns if logical_expression is FALSE.")}\n `),returns:["ANY"],compute:function(e,t,s=(()=>!1)){const o=fe(e)?t():s();return null==o?"":o},isExported:!0},pn={description:a("Value if it is not an error, otherwise 2nd argument."),args:Oe(`\n value (any, lazy) ${a("The value to return if value itself is not an error.")}\n value_if_error (any, lazy, default=${a("An empty value")}) ${a("The value the function returns if value is an error.")}\n `),returns:["ANY"],compute:function(e,t=(()=>"")){let s;try{s=e()}catch(e){s=t()}return null==s?"":s},isExported:!0},gn={description:a("Returns a value depending on multiple logical expressions."),args:Oe(`\n condition1 (boolean, lazy) ${a("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")}\n value1 (any, lazy) ${a("The returned value if condition1 is TRUE.")}\n condition2 (boolean, lazy, repeating) ${a("Additional conditions to be evaluated if the previous ones are FALSE.")}\n value2 (any, lazy, repeating) ${a("Additional values to be returned if their corresponding conditions are TRUE.")}\n `),returns:["ANY"],compute:function(...e){ce((()=>e.length%2==0),a("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(fe(e[t]()))return e[t+1]();throw new Error(a("No match."))},isExported:!0},fn={description:a("Returns opposite of provided logical value."),args:Oe(`logical_expression (boolean) ${a("An expression or reference to a cell holding an expression that represents some logical value.")}\n `),returns:["BOOLEAN"],compute:function(e){return!fe(e)},isExported:!0},mn={description:a("Logical `or` operator."),args:Oe(`\n logical_expression1 (boolean, range<boolean>) ${a("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.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${a("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,s=!1;return Ie(e,(e=>(t=!0,s=s||e,!s))),ce((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0},vn={description:a("Logical `xor` operator."),args:Oe(`\n logical_expression1 (boolean, range<boolean>) ${a("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.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${a("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,s=!1;return Ie(e,(e=>(t=!0,s=s?!e:e,!0))),ce((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0};var En=Object.freeze({__proto__:null,AND:dn,IF:un,IFERROR:pn,IFS:gn,NOT:fn,OR:mn,XOR:vn});function bn(e,t){for(let s=0;s<e.length;s++)if(e[s]===t)return s;return-1}const Sn={description:a("Column number of a specified cell."),args:Oe(`cell_reference (meta, default=${a("The cell in which the formula is entered")}) ${a("The cell whose column number will be returned. Column A corresponds to 1.")}\n `),returns:["NUMBER"],compute:function(e){var t;e=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this)),ce((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return qs(e).left+1},isExported:!0},Cn={description:a("Number of columns in a specified array or range."),args:Oe(`range (meta) ${a("The range whose column count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=qs(e);return t.right-t.left+1},isExported:!0},yn={description:a("Horizontal lookup"),args:Oe(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n range (range) ${a("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")}\n index (number) ${a("The row index of the value to be returned, where the first row in range is numbered 1.")}\n is_sorted (boolean, default=true) ${a("Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.")}\n `),returns:["ANY"],compute:function(e,t,s,o=true){const i=Math.trunc(de(s));ce((()=>1<=i&&i<=t[0].length),a("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const n=fe(o),r=t.map((e=>e[0]));let l;return l=n?Le(r,e):bn(r,e),ce((()=>l>-1),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",pe(e))),t[l][i-1]},isExported:!0},wn={description:a("Look up a value."),args:Oe(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n search_array (range) ${a("One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.")}\n result_range (range, optional) ${a("The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.")}\n `),returns:["ANY"],compute:function(e,t,s){let o=t.length,i=t[0].length;const n=i>=o,r=Le(n?t[0]:t.map((e=>e[0])),e);return ce((()=>r>=0),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",pe(e))),void 0===s?n?t[o-1][r]:t[r][i-1]:(o=s.length,i=s[0].length,ce((()=>1===o||1===i),a("The result_range must be a single row or a single column.")),o>1?(ce((()=>r<=o-1),a("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(r+1).toString())),s[r][0]):(ce((()=>r<=i-1),a("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(r+1).toString())),s[0][r]))},isExported:!0},In={description:a("Position of item in range that matches value."),args:Oe(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${a("The one-dimensional array to be searched.")}\n search_type (number, default=1) ${a("The search method. 1 (default) finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1){let o=de(s);const i=t.length,n=t[0].length;ce((()=>1===i||1===n),a("The range must be a single row or a single column."));let r=-1;const l=t.flat();switch(o=Math.sign(o),o){case 1:r=Le(l,e);break;case 0:r=bn(l,e);break;case-1:r=function(e,t){const s=typeof t;let o,i,n,r,a,l,c=0,h=e.length-1;if(typeof e[c]===s&&t>e[c])return-1;if(typeof e[h]===s&&e[h]>t)return h;for(;h-c>=0;){for(n=Math.ceil((c+h)/2),r=n,a=e[r],l=typeof a;c<=r&&s!==l;)r--,a=e[r],l=typeof a;l===s&&a>=t&&(void 0===o||o>a||o===a&&i>r)&&(o=a,i=r),l===s&&a<=t?h=r-1:c=n+1}return void 0!==i?i:-1}(l,e)}return ce((()=>r>=0),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",pe(e))),r+1},isExported:!0},xn={description:a("Row number of a specified cell."),args:Oe(`cell_reference (meta, default=${a("The cell in which the formula is entered by default")}) ${a("The cell whose row number will be returned.")}`),returns:["NUMBER"],compute:function(e){var t;e=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this)),ce((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return qs(e).top+1},isExported:!0},Tn={description:a("Number of rows in a specified array or range."),args:Oe(`range (meta) ${a("The range whose row count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=qs(e);return t.bottom-t.top+1},isExported:!0},Rn={description:a("Vertical lookup."),args:Oe(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${a("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")}\n index (number) ${a("The column index of the value to be returned, where the first column in range is numbered 1.")}\n is_sorted (boolean, default=true) ${a("Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.")}\n `),returns:["ANY"],compute:function(e,t,s,o=true){const i=Math.trunc(de(s));ce((()=>1<=i&&i<=t.length),a("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const n=fe(o),r=t[0];let l;return l=n?Le(r,e):bn(r,e),ce((()=>l>-1),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",pe(e))),t[i-1][l]},isExported:!0};var Ln=Object.freeze({__proto__:null,COLUMN:Sn,COLUMNS:Cn,HLOOKUP:yn,LOOKUP:wn,MATCH:In,ROW:xn,ROWS:Tn,VLOOKUP:Rn});const Mn={description:a("Sum of two numbers."),args:Oe(`\n value1 (number) ${a("The first addend.")}\n value2 (number) ${a("The second addend.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return de(e)+de(t)}},An={description:a("Concatenation of two values."),args:Oe(`\n value1 (string) ${a("The value to which value2 will be appended.")}\n value2 (string) ${a("The value to append to value1.")}\n `),returns:["STRING"],compute:function(e,t){return pe(e)+pe(t)},isExported:!0},_n={description:a("One number divided by another."),args:Oe(`\n dividend (number) ${a("The number to be divided.")}\n divisor (number) ${a("The number to divide by.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){const s=de(t);return ce((()=>0!==s),a("The divisor must be different from zero.")),de(e)/s}};function On(e){return null==e}const Nn={number:0,string:"",boolean:!1},kn={description:a("Equal."),args:Oe(`\n value1 (any) ${a("The first value.")}\n value2 (any) ${a("The value to test against value1 for equality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return e=On(e)?Nn[typeof t]:e,t=On(t)?Nn[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function Fn(e,t,s){e=On(e)?Nn[typeof t]:e,t=On(t)?Nn[typeof e]:t,"number"!=typeof e&&(e=pe(e).toUpperCase()),"number"!=typeof t&&(t=pe(t).toUpperCase());const o=typeof e,i=typeof t;return"string"===o&&"number"===i||("string"!==i||"number"!==o)&&s(e,t)}const $n={description:a("Strictly greater than."),args:Oe(`\n value1 (any) ${a("The value to test as being greater than value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return Fn(e,t,((e,t)=>e>t))}},Dn={description:a("Greater than or equal to."),args:Oe(`\n value1 (any) ${a("The value to test as being greater than or equal to value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return Fn(e,t,((e,t)=>e>=t))}},Pn={description:a("Less than."),args:Oe(`\n value1 (any) ${a("The value to test as being less than value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!Dn.compute(e,t)}},Un={description:a("Less than or equal to."),args:Oe(`\n value1 (any) ${a("The value to test as being less than or equal to value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!$n.compute(e,t)}},Vn={description:a("Difference of two numbers."),args:Oe(`\n value1 (number) ${a("The minuend, or number to be subtracted from.")}\n value2 (number) ${a("The subtrahend, or number to subtract from value1.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return de(e)-de(t)}},Bn={description:a("Product of two numbers"),args:Oe(`\n factor1 (number) ${a("The first multiplicand.")}\n factor2 (number) ${a("The second multiplicand.")}\n `),returns:["NUMBER"],returnFormat:He.FormatFromArgument,compute:function(e,t){return de(e)*de(t)}},Hn={description:a("Not equal."),args:Oe(`\n value1 (any) ${a("The first value.")}\n value2 (any) ${a("The value to test against value1 for inequality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!kn.compute(e,t)}},zn={description:a("A number raised to a power."),args:Oe(`\n base (number) ${a("The number to raise to the exponent power.")}\n exponent (number) ${a("The exponent to raise base to.")}\n `),returns:["NUMBER"],compute:function(e,t){return Mt.compute(e,t)}},Zn={description:a("A number with the sign reversed."),args:Oe(`\n value (number) ${a("The number to have its sign reversed. Equivalently, the number to multiply by -1.")}\n `),returnFormat:He.FormatFromArgument,returns:["NUMBER"],compute:function(e){return-de(e)}},Gn={description:a("Value interpreted as a percentage."),args:Oe(`\n percentage (number) ${a("The value to interpret as a percentage.")}\n `),returns:["NUMBER"],compute:function(e){return de(e)/100}},Wn={description:a("A specified number, unchanged."),args:Oe(`\n value (any) ${a("The number to return.")}\n `),returnFormat:He.FormatFromArgument,returns:["ANY"],compute:function(e){return e}};var qn=Object.freeze({__proto__:null,ADD:Mn,CONCAT:An,DIVIDE:_n,EQ:kn,GT:$n,GTE:Dn,LT:Pn,LTE:Un,MINUS:Vn,MULTIPLY:Bn,NE:Hn,POW:zn,UMINUS:Zn,UNARY_PERCENT:Gn,UPLUS:Wn});const jn={description:a("Gets character associated with number."),args:Oe(`\n table_number (number) ${a("The number of the character to look up from the current Unicode table in decimal format.")}\n `),returns:["STRING"],compute:function(e){const t=Math.trunc(de(e));return ce((()=>t>=1),a("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},Xn={description:a("Appends strings to one another."),args:Oe(`\n string1 (string, range<string>) ${a("The initial string.")}\n string2 (string, range<string>, repeating) ${a("More strings to append in sequence.")}\n `),returns:["STRING"],compute:function(...e){return Ce(e,((e,t)=>e+pe(t)),"")},isExported:!0},Yn={description:a("Tests whether two strings are identical."),args:Oe(`\n string1 (string) ${a("The first string to compare.")}\n string2 (string) ${a("The second string to compare.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return pe(e)===pe(t)},isExported:!0},Kn={description:a("First position of string found in text, case-sensitive."),args:Oe(`\n search_for (string) ${a("The string to look for within text_to_search.")}\n text_to_search (string) ${a("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${a("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1){const o=pe(e),i=pe(t),n=de(s);ce((()=>""!==i),a("The text_to_search must be non-empty.")),ce((()=>n>=1),a("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const r=i.indexOf(o,n-1);return ce((()=>r>=0),a("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o.toString(),i)),r+1},isExported:!0},Qn={description:a("Concatenates elements of arrays with delimiter."),args:Oe(`\n delimiter (string) ${a("The character or string to place between each concatenated value.")}\n value_or_array1 (string, range<string>) ${a("The value or values to be appended using delimiter.")}\n value_or_array2 (string, range<string>, repeating) ${a("More values to be appended using delimiter.")}\n `),returns:["STRING"],compute:function(e,...t){const s=pe(e);return Ce(t,((e,t)=>(e?e+s:"")+pe(t)),"")}},Jn={description:a("Substring from beginning of specified string."),args:Oe(`\n text (string) ${a("The string from which the left portion will be returned.")}\n number_of_characters (number, optional) ${a("The number of characters to return from the left side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const s=t.length?de(t[0]):1;return ce((()=>s>=0),a("The number_of_characters (%s) must be positive or null.",s.toString())),pe(e).substring(0,s)},isExported:!0},er={description:a("Length of a string."),args:Oe(`\n text (string) ${a("The string whose length will be returned.")}\n `),returns:["NUMBER"],compute:function(e){return pe(e).length},isExported:!0},tr={description:a("Converts a specified string to lowercase."),args:Oe(`\n text (string) ${a("The string to convert to lowercase.")}\n `),returns:["STRING"],compute:function(e){return pe(e).toLowerCase()},isExported:!0},sr={description:a("Replaces part of a text string with different text."),args:Oe(`\n text (string) ${a("The text, a part of which will be replaced.")}\n position (number) ${a("The position where the replacement will begin (starting from 1).")}\n length (number) ${a("The number of characters in the text to be replaced.")}\n new_text (string) ${a("The text which will be inserted into the original text.")}\n `),returns:["STRING"],compute:function(e,t,s,o){const i=de(t);ce((()=>i>=1),a("The position (%s) must be greater than or equal to 1.",i.toString()));const n=pe(e),r=de(s),l=pe(o);return n.substring(0,i-1)+l+n.substring(i-1+r)},isExported:!0},or={description:a("A substring from the end of a specified string."),args:Oe(`\n text (string) ${a("The string from which the right portion will be returned.")}\n number_of_characters (number, optional) ${a("The number of characters to return from the right side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const s=t.length?de(t[0]):1;ce((()=>s>=0),a("The number_of_characters (%s) must be positive or null.",s.toString()));const o=pe(e),i=o.length;return o.substring(i-s,i)},isExported:!0},ir={description:a("First position of string found in text, ignoring case."),args:Oe(`\n search_for (string) ${a("The string to look for within text_to_search.")}\n text_to_search (string) ${a("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${a("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1){const o=pe(e).toLowerCase(),i=pe(t).toLowerCase(),n=de(s);ce((()=>""!==i),a("The text_to_search must be non-empty.")),ce((()=>n>=1),a("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const r=i.indexOf(o,n-1);return ce((()=>r>=0),a("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,i)),r+1},isExported:!0},nr={description:a("Replaces existing text with new text in a string."),args:Oe(`\n text_to_search (string) ${a("The text within which to search and replace.")}\n search_for (string) ${a("The string to search for within text_to_search.")}\n replace_with (string) ${a("The string that will replace search_for.")}\n occurrence_number (number, optional) ${a("The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o){const i=de(o);ce((()=>i>=0),a("The occurrenceNumber (%s) must be positive or null.",i.toString()));const n=pe(e),r=pe(t);if(""===r)return n;const l=pe(s),c=new RegExp(ps(r),"g");if(0===i)return n.replace(c,l);let h=0;return n.replace(c,(e=>++h===i?l:e))},isExported:!0},rr={description:a("Combines text from multiple strings and/or arrays."),args:Oe(`\n delimiter (string) ${a(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")}\n ignore_empty (boolean) ${a("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")}\n text1 (string, range<string>) ${a("Any text item. This could be a string, or an array of strings in a range.")}\n text2 (string, range<string>, repeating) ${a("Additional text item(s).")}\n `),returns:["STRING"],compute:function(e,t,...s){const o=pe(e),i=fe(t);let n=0;return Ce(s,((e,t)=>i&&""===pe(t)?e:(n++?e+o:"")+pe(t)),"")},isExported:!0},ar={description:a("Removes space characters."),args:Oe(`\n text (string) ${a("The text or reference to a cell containing text to be trimmed.")}\n `),returns:["STRING"],compute:function(e){return pe(e).trim()},isExported:!0},lr={description:a("Converts a specified string to uppercase."),args:Oe(`\n text (string) ${a("The string to convert to uppercase.")}\n `),returns:["STRING"],compute:function(e){return pe(e).toUpperCase()},isExported:!0};const cr={database:fi,date:Hi,financial:on,info:hn,lookup:Ln,logical:En,math:qt,operators:qn,statistical:ei,text:Object.freeze({__proto__:null,CHAR:jn,CONCATENATE:Xn,EXACT:Yn,FIND:Kn,JOIN:Qn,LEFT:Jn,LEN:er,LOWER:tr,REPLACE:sr,RIGHT:or,SEARCH:ir,SUBSTITUTE:nr,TEXTJOIN:rr,TRIM:ar,UPPER:lr}),engineering:Zi};const hr=new class extends Me{constructor(){super(...arguments),this.mapping={}}add(e,t){e=e.toUpperCase().replace("_",".");const s=ke(t);return function(e){let t=!1,s=!1,o=!1;for(let i of e){if(i.type.includes("META")&&i.type.length>1)throw new Error(a("Function ${name} has an argument that has been declared with more than one type whose type 'META'. The 'META' type can only be declared alone."));if(t&&!i.repeating)throw new Error(a("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=s||t||o,n=!(i.optional||i.repeating||i.default);if(e&&n)throw new Error(a("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=i.repeating,s=i.optional,o=i.default}}(s.args),this.mapping[e]=s.compute,super.add(e,s),this}};for(let e in cr){const t=cr[e];for(let s in t){const o=t[s];o.category=e,hr.add(s,{isExported:!1,...o})}}const dr=hr.content,ur="+,-,*,/,:,=,<>,>=,>,<=,<,%,^,&".split(",");function pr(e){const t=e.split(""),s=[];for(;t.length;){let e=Ir(t)||mr(t)||Er(t)||Sr(t)||gr(t)||xr(t)||br(t)||yr(t);e||(e={type:"UNKNOWN",value:t.shift()}),s.push(e)}return s}function gr(e){return"?"===e[0]?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const fr={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function mr(e){if(e[0]in fr){const t=e.shift();return{type:fr[t],value:t}}return null}function vr(e,t){for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;return!0}function Er(e){for(let t of ur)if(vr(e,t))return e.splice(0,t.length),{type:"OPERATOR",value:t};return null}function br(e){const t=function(e){let t="";for(let s=0,o=e.length;s<o;s++)t+=e[s];return t}(e).match(Q);return t?(e.splice(0,t[0].length),{type:"NUMBER",value:t[0]}):null}function Sr(e){if('"'===e[0]){const t=e.shift();let s=t;for(;e[0]&&(e[0]!==t||"\\"===s[s.length-1]);)s+=e.shift();return'"'===e[0]&&(s+=e.shift()),{type:"STRING",value:s}}return null}const Cr=/\w|\.|!|\$/;function yr(e){let t="";if("'"===e[0]){let s=e.shift();for(t+=s;e[0];)if(s=e.shift(),t+=s,"'"===s){if(!e[0]||"'"!==e[0])break;s=e.shift(),t+=s}if("'"!==s)return{type:"UNKNOWN",value:t}}for(;e[0]&&e[0].match(Cr);)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in dr)return{type:"FUNCTION",value:e};return e.match(es)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}const wr=/\s/;function Ir(e){let t=0;for(;e[0]&&e[0].match(wr);)t++,e.shift();return t?{type:"SPACE",value:" ".repeat(t)}:null}function xr(e){return vr(e,O)?(e.splice(0,O.length),{type:"INVALID_REFERENCE",value:O}):null}const Tr=["-","+"],Rr=["*","+","&"],Lr={"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10},Mr=6;function Ar(e){switch(e.type){case"NUMBER":case"SYMBOL":case"REFERENCE":return 0;case"COMMA":return 3;case"LEFT_PAREN":case"RIGHT_PAREN":return 5;case"OPERATOR":return Lr[e.value]||15}throw new Error(a("Unknown token: %s",e.value))}function _r(e,t,s){if("OPERATOR"===t.type){const o=Or(s,Ar(t));return{type:"BIN_OPERATION",value:t.value,left:e,right:o}}throw new Error(k)}function Or(e,t){const s=e.shift();if(!s)throw new Error(k);let o=function(e,t){var s,o,i;switch(e.type){case"DEBUGGER":const n=Or(t,1e3);return n.debug=!0,n;case"NUMBER":return{type:"NUMBER",value:se(e.value)};case"STRING":return{type:"STRING",value:us(e.value)};case"FUNCTION":if("LEFT_PAREN"!==t.shift().type)throw new Error(a("Wrong function call"));{const o=[];if(t[0]&&"RIGHT_PAREN"!==t[0].type)for("COMMA"===t[0].type?o.push({type:"UNKNOWN",value:""}):o.push(Or(t,Mr));"COMMA"===(null===(s=t[0])||void 0===s?void 0:s.type);){t.shift();const e=t[0];if("RIGHT_PAREN"===(null==e?void 0:e.type)){o.push({type:"UNKNOWN",value:""});break}"COMMA"===(null==e?void 0:e.type)?o.push({type:"UNKNOWN",value:""}):o.push(Or(t,Mr))}const i=t.shift();if(!i||"RIGHT_PAREN"!==i.type)throw new Error(a("Wrong function call"));return{type:"FUNCALL",value:e.value,args:o}}case"INVALID_REFERENCE":throw new Error(a("Invalid reference"));case"REFERENCE":if(":"===(null===(o=t[0])||void 0===o?void 0:o.value)&&"REFERENCE"===(null===(i=t[1])||void 0===i?void 0:i.type)){t.shift();const s=t.shift();return{type:"REFERENCE",value:`${e.value}:${null==s?void 0:s.value}`}}return{type:"REFERENCE",value:e.value};case"SYMBOL":if(["TRUE","FALSE"].includes(e.value.toUpperCase()))return{type:"BOOLEAN",value:"TRUE"===e.value.toUpperCase()};if(e.value)throw new Error(a("Invalid formula"));return{type:"STRING",value:e.value};case"LEFT_PAREN":const r=Or(t,5);if(!t.length||"RIGHT_PAREN"!==t[0].type)throw new Error(a("Unmatched left parenthesis"));return t.shift(),r;default:if("OPERATOR"===e.type&&Tr.includes(e.value))return{type:"UNARY_OPERATION",value:e.value,right:Or(t,Lr[e.value])};throw new Error(a("Unexpected token: %s",e.value))}}(s,e);for(;e[0]&&Ar(e[0])>t;)o=_r(o,e.shift(),e);return o}function Nr(e){return kr(pr(e))}function kr(e){"OPERATOR"===(e=e.filter((e=>"SPACE"!==e.type)))[0].type&&"="===e[0].value&&e.splice(0,1);const t=Or(e,0);if(e.length)throw new Error(k);return t}function Fr(e,t,s){switch(t===e.type&&(e=s(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>Fr(e,t,s)))};case"UNARY_OPERATION":return{...e,right:Fr(e.right,t,s)};case"BIN_OPERATION":return{...e,right:Fr(e.right,t,s),left:Fr(e.left,t,s)};default:return e}}function $r(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>$r(e)));return`${e.value}(${t.join(",")})`;case"NUMBER":return e.value.toString();case"REFERENCE":default:return e.value;case"STRING":return`"${e.value}"`;case"BOOLEAN":return e.value?"TRUE":"FALSE";case"UNARY_OPERATION":return e.value+Dr(e);case"BIN_OPERATION":return function(e){const t=e.value,s=e.left,o=s.value;return"BIN_OPERATION"===s.type&&Lr[o]<Lr[t]?`(${$r(s)})`:$r(s)}(e)+e.value+Dr(e)}}function Dr(e){const t=e.value,s=e.right,o=Lr[s.value],i=Lr[t];let n=!1;return"BIN_OPERATION"!==s.type?n=!1:o<i?n=!0:o!==i||Rr.includes(t)||(n=!0),n?`(${$r(s)})`:$r(s)}function Pr(e,t=!1){let s,o,i,n;const r=()=>{n=void 0,o=void 0,s=void 0,i=void 0};for(let a=0;a<e.length;a++){const l=e[a];if(n)if(o){if("SPACE"===l.type)continue;if("OPERATOR"===l.type&&":"===l.value)s=a;else if(s&&"REFERENCE"===l.type)i=a;else if(n&&o&&s&&i){const s={type:"REFERENCE",value:e.slice(n,a).filter((e=>!t||"SPACE"!==e.type)).map((e=>e.value)).join("")};e.splice(n,a-n,s),a=n+1,r()}else"REFERENCE"===l.type?(n=a,o=a,s=void 0):r()}else"REFERENCE"===l.type?(o=a,s=i=void 0):r();else["SPACE","REFERENCE"].includes(l.type)?(n=a,o="REFERENCE"===l.type?a:void 0,s=i=void 0):r()}const a=e.length-1;if(n&&o&&s&&i){const s={type:"REFERENCE",value:e.slice(n,a+1).filter((e=>!t||"SPACE"!==e.type)).map((e=>e.value)).join("")};e.splice(n,a-n+1,s)}return e}function Ur(e){return Pr(pr(e),!0)}const Vr=hr.content,Br={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},Hr={"-":"UMINUS","+":"UPLUS"};function zr(e){return e.join("\n").split("\n").filter((e=>""!==e.trim()))}const Zr={};function Gr(e){const t=Ur(e),{dependencies:s,constantValues:o}=function(e){const t={numbers:[],strings:[]},s=[];for(const o of e)switch(o.type){case"REFERENCE":s.push(o.value);break;case"STRING":const e=us(o.value);t.strings.includes(e)||t.strings.push(e);break;case"NUMBER":{const e=se(o.value);t.numbers.includes(e)||t.numbers.push(e);break}}return{dependencies:s,constantValues:t}}(t),i=function(e,t,s){return e.map((e=>{switch(e.type){case"STRING":const o=us(e.value);return`|S${s.strings.indexOf(o)}|`;case"NUMBER":return`|N${s.numbers.indexOf(se(e.value))}|`;case"REFERENCE":return`|${t.indexOf(e.value)}|`;default:return e.value}})).join("")}(t,s,o);if(!Zr[i]){const n=kr([...t]);let r=1;if("BIN_OPERATION"===n.type&&":"===n.value)throw new Error(a("Invalid formula"));if("UNKNOWN"===n.type)throw new Error(a("Invalid formula"));const l=u(n),c=zr([`// ${i}`,l.code,`return ${l.id};`]).join("\n");let h=new Function("deps","sheetId","ref","range","ctx",c);function d(e){const t=Vr[e.value.toUpperCase()],s=e.args,o=s.length;if(o<t.minArgRequired)throw new Error(a("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",e.value.toUpperCase(),t.minArgRequired.toString(),o.toString()));if(o>t.maxArgPossible)throw new Error(a("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",e.value.toUpperCase(),t.maxArgPossible.toString(),o.toString()));const i=t.nbrArgRepeating;if(i>1){const s=t.args.length-i;if((o-s)%i!=0)throw new Error(a("Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments",e.value.toUpperCase(),s.toString(),i.toString()))}let n=[];for(let i=0;i<o;i++){const o=t.getArgToFocus(i+1)-1;if(0<=o&&o<t.args.length){const r=s[i],l=t.args[o],c=l.type||[],h=c.includes("META"),d=l.lazy,p=c.some((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e)),g=c.every((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e));if(g&&"REFERENCE"!==r.type)throw new Error(a("Function %s expects the parameter %s to be reference to a cell or range, not a %s.",e.value.toUpperCase(),(i+1).toString(),r.type.toLowerCase()));const f=u(r,d,h,p,{functionName:e.value.toUpperCase(),paramIndex:i+1});n.push(f)}}return n}function u(e,t=!1,i=!1,n=!1,l={}){const c=[];let h,p,g;if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&i)throw new Error(a("Argument must be a reference to a cell or range."));switch(e.debug&&c.push("debugger;"),e.type){case"BOOLEAN":if(!t)return{id:`${e.value}`,code:""};h=r++,g=`${e.value}`;break;case"NUMBER":h=r++,g=`this.constantValues.numbers[${o.numbers.indexOf(e.value)}]`;break;case"STRING":h=r++,g=`this.constantValues.strings[${o.strings.indexOf(e.value)}]`;break;case"REFERENCE":const a=s.indexOf(e.value);h=r++,g=n?`range(${a}, deps, sheetId)`:`ref(${a}, deps, sheetId, ${i?"true":"false"}, "${l.functionName||Br["="]}", ${l.paramIndex})`;break;case"FUNCALL":h=r++;const f=d(e);c.push(f.map((e=>e.code)).join("\n")),p=e.value.toUpperCase(),c.push(`ctx.__lastFnCalled = '${p}';`),g=`ctx['${p}'](${f.map((e=>e.id))})`;break;case"UNARY_OPERATION":{h=r++,p=Hr[e.value];const t=u(e.right,!1,!1,!1,{functionName:p});c.push(t.code),c.push(`ctx.__lastFnCalled = '${p}';`),g=`ctx['${p}']( ${t.id})`;break}case"BIN_OPERATION":{h=r++,p=Br[e.value];const t=u(e.left,!1,!1,!1,{functionName:p}),s=u(e.right,!1,!1,!1,{functionName:p});c.push(t.code),c.push(s.code),c.push(`ctx.__lastFnCalled = '${p}';`),g=`ctx['${p}'](${t.id}, ${s.id})`;break}case"UNKNOWN":if(!t)return{id:"undefined",code:""};h=r++,g="undefined"}if(t){return{id:`_${h}`,code:`const _${h} = () => {\n\t${zr(c).join("\n\t")}\n\treturn ${g};\n}`}}return c.push(`let _${h} = ${g};`),{id:`_${h}`,code:c.join("\n")}}function p(e){let t;switch(e.type){case"REFERENCE":return[s.indexOf(e.value)];case"FUNCALL":if(t=Vr[e.value.toUpperCase()],t.returnFormat){if("FormatFromArgument"!==t.returnFormat)return[t.returnFormat.specificFormat];if(e.args.length>0){const s=0;if(!t.args[s].type.includes("META"))return p(e.args[s])}}break;case"UNARY_OPERATION":return p(e.right);case"BIN_OPERATION":if(t=Vr[Br[e.value]],t.returnFormat){if("FormatFromArgument"===t.returnFormat){const t=p(e.left);if("string"==typeof t[t.length-1])return t;const s=p(e.right);return t.concat(s)}return[t.returnFormat.specificFormat]}}return[]}Zr[i]={execute:h,dependenciesFormat:p(n)}}return{dependenciesFormat:Zr[i].dependenciesFormat,execute:Zr[i].execute,dependencies:s,constantValues:o,tokens:t}}function Wr(e){return function(e){let t=[],s="";return e.map(((e,o)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(s=""),e.type){case"FUNCTION":s=e.value;break;case"LEFT_PAREN":t.push({parent:s,argPosition:0}),s="";break;case"RIGHT_PAREN":t.pop();break;case"COMMA":t.length&&t[t.length-1].argPosition++}if(t.length){const s=t[t.length-1];s.parent&&(e.functionContext=Object.assign({},s))}return e}))}(function(e){let t=1;const s=[];return e.map((e=>("LEFT_PAREN"===e.type?(s.push(t),e.parenIndex=t,t++):"RIGHT_PAREN"===e.type&&(e.parenIndex=s.pop()),e)))}(function(e){let t=0;return e.map((e=>{const s=e.value.toString().length,o=Object.assign({},e,{start:t,end:t+s,length:s});return t=o.end,o}))}(Pr(pr(e)))))}const qr=new Me;function jr(e,t){switch(typeof e){case"string":return e;case"boolean":return e?"TRUE":"FALSE";case"number":return(null==t?void 0:t.match(_))?X({value:e,format:t}):t?function(e,t){const s=t.split(";"),o=s.length;return e<0?o>1?le(-e,s[1]):"-"+le(-e,s[0]):le(e,s[3===o&&0===e?2:0])}(e,t):ie(e);case"object":return"0"}}function Xr(e){return""===e?"":ee(e)?se(e):Cs(e)?"TRUE"===e.toUpperCase():ys(e)?W(e).value:e}class Yr{constructor(e,t,s){this.id=e,this.evaluated=t,this.style=s.style,this.format=s.format}isFormula(){return!1}isLink(){return!1}isEmpty(){return!1}get formattedValue(){return jr(this.evaluated.value,this.format)}get composerContent(){return this.content}get defaultAlign(){switch(this.evaluated.type){case Fe.number:return"right";case Fe.boolean:case Fe.error:return"center";case Fe.text:case Fe.empty:return"left"}}get isAutoSummable(){var e;switch(this.evaluated.type){case Fe.empty:case Fe.text:return!0;case Fe.number:return!(null===(e=this.format)||void 0===e?void 0:e.match(_));case Fe.error:case Fe.boolean:return!1}}}class Kr extends Yr{constructor(e,t={}){super(e,{value:"",type:Fe.empty},t),this.content=""}isEmpty(){return!0}}class Qr extends Yr{constructor(e,t,s={}){super(e,{value:t,type:Fe.number},s),this.content=ie(this.evaluated.value)}}class Jr extends Yr{constructor(e,t,s={}){super(e,{value:t,type:Fe.boolean},s),this.content=this.evaluated.value?"TRUE":"FALSE"}}class ea extends Yr{constructor(e,t,s={}){super(e,{value:t,type:Fe.text},s),this.content=this.evaluated.value}}class ta extends Qr{constructor(e,t,s){super(e,t,s),this.format=s.format}get composerContent(){return jr(this.evaluated.value,this.format)}}class sa extends Yr{constructor(e,t,s={}){var o;const i=Rs(t);s={...s,style:{...s.style,textColor:(null===(o=s.style)||void 0===o?void 0:o.textColor)||A,underline:!0}},super(e,{value:i.label,type:Fe.text},s),this.link=i,this.content=t}isLink(){return!0}get composerContent(){return this.link.label}}class oa extends sa{constructor(e,t,s={}){super(e,t,s),this.link.url=this.withHttp(this.link.url),this.link.isExternal=!0,this.content=Ts(this.link.label,this.link.url),this.urlRepresentation=this.link.url,this.isUrlEditable=!0}action(e){window.open(this.link.url,"_blank")}withHttp(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}}class ia extends sa{constructor(e,t,s={},o){super(e,t,s),this.sheetName=o,this.sheetId=As(this.link.url),this.isUrlEditable=!1}action(e){e.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}get urlRepresentation(){return this.sheetName(this.sheetId)||a("Invalid sheet")}}class na extends Yr{constructor(e,t,s,o,i,n){super(t,{value:"Loading...",type:Fe.text},n),this.buildFormulaString=e,this.normalizedText=s,this.compiledFormula=o,this.dependencies=i}get content(){return this.buildFormulaString(this)}isFormula(){return!0}assignValue(e){switch(typeof e){case"number":this.evaluated={value:e,type:Fe.number};break;case"boolean":this.evaluated={value:e,type:Fe.boolean};break;case"string":this.evaluated={value:e,type:Fe.text};break;case"object":case"undefined":this.evaluated={value:e,type:Fe.empty}}}assignError(e,t){this.evaluated={value:e,error:t,type:Fe.error}}}class ra extends Yr{constructor(e,t,s,o){super(e,{value:"#BAD_EXPR",type:Fe.error,error:s},o),this.content=t}}function aa(e){const t=Ur(e);let s=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&Jt.test(e.value)){const t=e.value.trim();return s.includes(t)||s.push(t),`${P}${s.indexOf(t)}${P}`}return e.value}))),dependencies:s}}qr.add("Formula",{sequence:10,match:e=>e.startsWith("="),createCell:(e,t,s,o,i)=>{const n=Gr(t),r=n.dependencies.map((e=>i.getRangeFromSheetXC(o,e))),a=s.format||i.inferFormulaFormat(n,r);return new na((e=>i.buildFormulaContent(o,e)),e,t,n,r,{...s,format:a})}}).add("Empty",{sequence:20,match:e=>""===e,createCell:(e,t,s)=>new Kr(e,s)}).add("Number",{sequence:30,match:e=>ee(e),createCell:(e,t,s)=>(!s.format&&t.includes("%")&&(s.format=t.includes(".")?"0.00%":"0%"),new Qr(e,se(t),s))}).add("Boolean",{sequence:40,match:e=>Cs(e),createCell:(e,t,s)=>new Jr(e,"TRUE"===t.toUpperCase(),s)}).add("DateTime",{sequence:50,match:e=>ys(e),createCell:(e,t,s)=>{const o=W(t),i=s.format||o.format;return new ta(e,o.value,{...s,format:i})}}).add("MarkdownSheetLink",{sequence:60,match:e=>Ms(e),createCell:(e,t,s,o,i)=>new ia(e,t,s,(e=>i.tryGetSheetName(e)))}).add("MarkdownLink",{sequence:70,match:e=>xs(e),createCell:(e,t,s)=>new oa(e,t,s)}).add("WebLink",{sequence:80,match:e=>{return t=e,Is.test(t);var t},createCell:(e,t,s)=>new oa(e,Ts(t,t),s)});const la=11,ca="Sheet1";function ha(e){return e?("version"in(e=JSON.parse(JSON.stringify(e)))&&e.version<la&&(e=function(e){for(let t=da.findIndex((t=>t.from===e.version));t<da.length;t++)e=da[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,s=new Hs;for(const o of e.sheets||[])for(const e of o.figures||[])t.has(e.id)&&(e.id+=s.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(fa(),e,{version:la}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(ga(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(ga(ca,"Sheet1"));return e}(e),e}(e),e):fa()}const da=[{description:"add the `activeSheet` field on data",from:1,to:2,applyMigration:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)},{description:"add an id field in each sheet",from:2,to:3,applyMigration(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}},{description:"activeSheet is now an id, not the name of a sheet",from:3,to:4,applyMigration(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find((t=>t.name===e.activeSheet));e.activeSheet=t.id}return e}},{description:"add figures object in each sheets",from:4,to:5,applyMigration(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}},{description:"normalize the content of the cell if it is a formula to avoid parsing all the formula that vary only by the cells they use",from:5,to:6,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const s=t.cells[e];s.content&&s.content.startsWith("=")&&(s.formula=aa(s.content))}return e}},{description:"transform chart data structure",from:6,to:7,applyMigration(e){for(let t of e.sheets||[])for(let e in t.figures||[]){const{dataSets:s,...o}=t.figures[e].data,i=[];for(let e of s)if(e.labelCell){const t=qs(e.dataRange),s=e.labelCell+":"+is(t.right,t.bottom);i.push(s)}else i.push(e.dataRange);o.dataSetsHaveTitle=Boolean(s[0].labelCell),o.dataSets=i,t.figures[e].data=o}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){var t;const s=[],o=new RegExp($,"g");for(let i of e.sheets||[]){if(!i.name)continue;const e=i.name,n=e.replace(o,"_");let r=1,a=n;for(;s.includes(a);)a=`${n}${r}`,r++;i.name=a,s.push(a);const l=t=>{if(void 0===t)return t;let s=t.replace(e,a),o=t;for(;o!==s;)o=s,s=o.replace(e,a);return o};for(let e in i.cells){const t=i.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(l))}for(let e of i.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(l),s=l(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:s}}for(let e of i.conditionalFormats||[]){e.ranges=e.ranges.map(l);for(const s of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===(null===(t=e.rule[s])||void 0===t?void 0:t.type)&&(e.rule[s].value=l(e.rule[s].value))}}return e}},{description:"transform chart data structure with design attributes",from:8,to:9,applyMigration(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=g,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stackedBar=!1;return e}},{description:"de-normalize formula to reduce exported json size (~30%)",from:9,to:10,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const s=t.cells[e];if(s.formula){let{text:e,dependencies:t}=s.formula;for(let[s,o]of Object.entries(t)){const t=`\\${P}${s}\\${P}`;e=e.replace(new RegExp(t,"g"),o)}s.content=e,delete s.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let s of e.sheets||[])for(let e in s.cells||[]){const o=s.cells[e];o.format&&(o.format=Ns(o.format,t))}return e.formats=t,e}}];function ua(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const s=[],o=[],i=e=>{if("CREATE_SHEET"===e.type)s.push(e.sheetId);else if("sheetId"in e&&!s.includes(e.sheetId))return{...e,sheetId:ca};return e};for(const e of t)"REMOTE_REVISION"===e.type?o.push({...e,commands:e.commands.map(i)}):o.push(e);return o}(e,t),t=pa(t,"SORT_CELLS"),t=pa(t,"SET_DECIMAL")}function pa(e,t){const s=[];for(const o of e)"REMOTE_REVISION"===o.type?s.push({...o,commands:o.commands.filter((e=>e.type!==t))}):s.push(o);return s}function ga(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[]}}function fa(e="Sheet1"){return{version:la,sheets:[ga(ca,e)],entities:{},styles:{},formats:{},borders:{},revisionId:N,uniqueFigureIds:!0}}class ma{constructor(e,t,s){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t,this.currentMode=s.mode}allowDispatch(e){return 0}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const s of e){let e=s.call(this,t);Array.isArray(e)||(e=[e]);const o=e.filter((e=>0!==e));if(o.length)return o}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}ma.getters=[],ma.modes=["headless","normal"];class va extends ma{constructor(e,t,s,o,i,n){super(t,o,i),this.dispatch=o,this.range=s,s.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=n}import(e){}export(e){}exportForExcel(e){}adaptRanges(e,t){}}class Ea extends va{constructor(){super(...arguments),this.borders={}}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":const t=this.borders[e.sheetId];if(t){const s=t.slice().map((e=>null==e?void 0:e.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,s)}break;case"DELETE_SHEET":const s={...this.borders};delete s[e.sheetId],this.history.update("borders",s);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_FORMATTING":if(e.border){const t=this.getters.getSheet(e.sheetId),s=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));this.setBorders(t,s,e.border)}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":for(let t of e.elements)"COL"===e.dimension?this.shiftBordersHorizontally(e.sheetId,t+1,-1):this.shiftBordersVertically(e.sheetId,t+1,-1);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumns(e):this.handleAddRows(e)}}handleAddColumns(e){const t=this.getters.getSheet(e.sheetId);let s,o;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),s=e.base-1,o=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),s=e.base,o=e.base+e.quantity+1),this.ensureColumnBorderContinuity(t,s,o)}handleAddRows(e){const t=this.getters.getSheet(e.sheetId);let s,o;"before"===e.position?(this.shiftBordersVertically(t.id,e.base,e.quantity,{moveFirstTopBorder:!0}),s=e.base-1,o=e.base+e.quantity):(this.shiftBordersVertically(t.id,e.base+1,e.quantity,{moveFirstTopBorder:!1}),s=e.base,o=e.base+e.quantity+1),this.ensureRowBorderContinuity(t,s,o)}getCellBorder(e,t,s){var o,i,n,r,a,l,c,h,d,u,p,g;const f={top:null===(n=null===(i=null===(o=this.borders[e])||void 0===o?void 0:o[t])||void 0===i?void 0:i[s])||void 0===n?void 0:n.horizontal,bottom:null===(l=null===(a=null===(r=this.borders[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[s+1])||void 0===l?void 0:l.horizontal,left:null===(d=null===(h=null===(c=this.borders[e])||void 0===c?void 0:c[t])||void 0===h?void 0:h[s])||void 0===d?void 0:d.vertical,right:null===(g=null===(p=null===(u=this.borders[e])||void 0===u?void 0:u[t+1])||void 0===p?void 0:p[s])||void 0===g?void 0:g.vertical};return f.bottom||f.left||f.right||f.top?f:null}ensureColumnBorderContinuity(e,t,s){const o=Es(t+1,s);for(let i=0;i<e.rows.length;i++){const n=this.getCellBorder(e.id,t,i),r=this.getCellBorder(e.id,s,i);if(n&&r){const t=this.getCommonSides(n,r);for(let s of o)this.addBorder(e.id,s,i,t)}}}ensureRowBorderContinuity(e,t,s){const o=Es(t+1,s);for(let i=0;i<e.cols.length;i++){const n=this.getCellBorder(e.id,i,t),r=this.getCellBorder(e.id,i,s);if(n&&r){const t=this.getCommonSides(n,r);for(let s of o)this.addBorder(e.id,i,s,t)}}}getCommonSides(e,t){const s={};for(let o of["top","bottom","left","right"])e[o]&&e[o]===t[o]&&(s[o]=e[o]);return s}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsRange(e){if(!this.borders[e])return[];return Es(0,this.getters.getSheet(e).rows.length+1)}shiftBordersHorizontally(e,t,s,{moveFirstLeftBorder:o}={}){this.borders[e]&&(s<0&&this.moveBordersOfColumn(e,t,s,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>s<0?e-t:t-e)).forEach((i=>{(i===t&&o||i!==t)&&this.moveBordersOfColumn(e,i,s,"vertical"),this.moveBordersOfColumn(e,i,s,"horizontal")})))}shiftBordersVertically(e,t,s,{moveFirstTopBorder:o}={}){this.borders[e]&&(s<0&&this.moveBordersOfRow(e,t,s,"horizontal",{destructive:!1}),this.getRowsRange(e).filter((e=>e>=t)).sort(((e,t)=>s<0?e-t:t-e)).forEach((i=>{(i===t&&o||i!==t)&&this.moveBordersOfRow(e,i,s,"horizontal"),this.moveBordersOfRow(e,i,s,"vertical")})))}moveBordersOfRow(e,t,s,o,{destructive:i}={destructive:!0}){const n=this.borders[e];n&&this.getColumnsWithBorders(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=n[r])||void 0===a?void 0:a[t+s])||void 0===l?void 0:l[o],u=null===(h=null===(c=n[r])||void 0===c?void 0:c[t])||void 0===h?void 0:h[o];this.history.update("borders",e,r,t+s,o,i?u:u||d),this.history.update("borders",e,r,t,o,void 0)}))}moveBordersOfColumn(e,t,s,o,{destructive:i}={destructive:!0}){const n=this.borders[e];n&&this.getRowsRange(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=n[t+s])||void 0===a?void 0:a[r])||void 0===l?void 0:l[o],u=null===(h=null===(c=n[t])||void 0===c?void 0:c[r])||void 0===h?void 0:h[o];this.history.update("borders",e,t+s,r,o,i?u:u||d),this.history.update("borders",e,t,r,o,void 0)}))}setBorder(e,t,s,o){this.history.update("borders",e,t,s,{vertical:null==o?void 0:o.left,horizontal:null==o?void 0:o.top}),this.history.update("borders",e,t+1,s,"vertical",null==o?void 0:o.right),this.history.update("borders",e,t,s+1,"horizontal",null==o?void 0:o.bottom)}clearBorders(e,t){for(let s of t){for(let t=s.top;t<=s.bottom;t++){this.history.update("borders",e,s.right+1,t,"vertical",void 0);for(let o=s.left;o<=s.right;o++)this.history.update("borders",e,o,t,void 0)}for(let t=s.left;t<=s.right;t++)this.history.update("borders",e,t,s.bottom+1,"horizontal",void 0)}}addBorder(e,t,s,o){this.setBorder(e,t,s,{...this.getCellBorder(e,t,s),...o})}setBorders(e,t,s){const o=e.id;if("clear"===s)return this.clearBorders(o,t);for(let e of t){if("h"===s||"hv"===s||"all"===s)for(let t=e.top+1;t<=e.bottom;t++)for(let s=e.left;s<=e.right;s++)this.addBorder(o,s,t,{top:M});if("v"===s||"hv"===s||"all"===s)for(let t=e.top;t<=e.bottom;t++)for(let s=e.left+1;s<=e.right;s++)this.addBorder(o,s,t,{left:M});if("left"===s||"all"===s||"external"===s)for(let t=e.top;t<=e.bottom;t++)this.addBorder(o,e.left,t,{left:M});if("right"===s||"all"===s||"external"===s)for(let t=e.top;t<=e.bottom;t++)this.addBorder(o,e.right+1,t,{left:M});if("top"===s||"all"===s||"external"===s)for(let t=e.left;t<=e.right;t++)this.addBorder(o,t,e.top,{top:M});if("bottom"===s||"all"===s||"external"===s)for(let t=e.left;t<=e.right;t++)this.addBorder(o,t,e.bottom+1,{top:M})}}addBordersToMerge(e,t){const s=this.getters.getSheet(e),{left:o,right:i,top:n,bottom:r}=t,a=this.getCellBorder(s.id,o,n),l=this.getCellBorder(s.id,i,r);this.clearBorders(e,[t]),(null==a?void 0:a.top)&&this.setBorders(s,[{...t,bottom:n}],"top"),(null==a?void 0:a.left)&&this.setBorders(s,[{...t,right:o}],"left"),((null==l?void 0:l.bottom)||(null==a?void 0:a.bottom))&&this.setBorders(s,[{...t,top:r}],"bottom"),((null==l?void 0:l.right)||(null==a?void 0:a.right))&&this.setBorders(s,[{...t,left:i}],"right")}import(e){if(e.borders)for(let t of e.sheets)for(let[s,o]of Object.entries(t.cells))if(null==o?void 0:o.border){const i=e.borders[o.border],[n,r]=os(s);this.setBorder(t.id,n,r,i)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,qs(e))}export(e){let t=0;const s={};function o(e){for(let[t,o]of Object.entries(s))if(ds(o)===ds(e))return parseInt(t,10);return s[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let s=0;s<t.rowNumber;s++){const i=this.getCellBorder(t.id,e,s);if(i){const n=is(e,s),r=t.cells[n],a=o(i);r?r.border=a:t.cells[n]={border:a}}}e.borders=s}exportForExcel(e){this.export(e)}}Ea.getters=["getCellBorder"];const ba=new RegExp(String.fromCharCode(160),"g");class Sa extends va{constructor(){super(...arguments),this.cells={},this.createCell=function(e){const t=qr.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(s,o,i,n){const r=t.find((e=>e.match(o)));if(!r)return new ea(s,o,i);try{return r.createCell(s,o,i,n,e)}catch(e){return new ra(s,o,e.message||k,i)}}}(this.getters)}adaptRanges(e,t){for(const s of Object.keys(this.cells))for(const o of Object.values(this.cells[s]||{}))if(o.isFormula())for(const i of o.dependencies)if(!t||i.sheetId===t){const t=e(i);"NONE"!==t.changeType&&this.history.update("cells",s,o.id,"dependencies",o.dependencies.indexOf(i),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":case"CLEAR_CELL":return this.checkCellOutOfSheet(e.sheetId,e.col,e.row);default:return 0}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearStyles(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case"UPDATE_CELL":this.updateCell(this.getters.getSheet(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:""})}}setFormatter(e,t,s){for(let o of t)for(let t=o.top;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:i,row:t,format:s})}clearStyles(e,t){for(let s of t)for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:null})}handleAddColumnsRows(e,t){const s=this.getters.getSheet(e.sheetId);let o,i;"before"===e.position?(o=Es(e.base,e.base+e.quantity),i=e.base+e.quantity):(o=Es(e.base+1,e.base+e.quantity+1),i=e.base),t(s,i,o)}import(e){for(let t of e.sheets){const s=this.getters.getSheet(t.id);for(let o in t.cells){const i=t.cells[o],[n,r]=os(o);if((null==i?void 0:i.content)||(null==i?void 0:i.format)||(null==i?void 0:i.style)){const o=this.importCell(s,i,e.styles,e.formats);this.history.update("cells",t.id,o.id,o),this.dispatch("UPDATE_CELL_POSITION",{cellId:o.id,col:n,row:r,sheetId:t.id})}}}}export(e){const t={},s={};for(let o of e.sheets){const e={},i=Object.keys(this.cells[o.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const{col:n,row:r}of i){const i=this.getters.getCell(o.id,n,r);e[is(n,r)]={style:i.style?Ns(i.style,t):void 0,format:i.format?Ns(i.format,s):void 0,content:i.content}}o.cells=e}e.styles=t,e.formats=s}importCell(e,t,s,o){const i=t.style&&s[t.style]||void 0,n=t.format&&o[t.format]||void 0,r=this.uuidGenerator.uuidv4(),a={format:n,style:i};return this.createCell(r,(null==t?void 0:t.content)||"",a,e.id)}exportForExcel(e){this.export(e);for(let t of e.sheets)for(const e in t.cells){const[s,o]=os(e),i=this.getters.getCell(t.id,s,o),n=t.cells[e];n.value=i.evaluated.value,n.isFormula=i.isFormula()}}getCells(e){return this.cells[e]||{}}getCellById(e){for(const t of Object.values(this.cells))if(t[e])return t[e]}inferFormulaFormat(e,t){const s=e.dependenciesFormat;for(let e of s)switch(typeof e){case"string":return e;case"number":const s=t[e];if(this.getters.tryGetSheet(s.sheetId)){const e=this.getters.getCell(s.sheetId,s.zone.left,s.zone.top);if(e&&e.format)return e.format}}return D}buildFormulaContent(e,t,s){const o=s||[...t.dependencies];return t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=o.shift();return this.getters.getRangeString(t,e)}return t.value})).join("")}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t)}getCellStyle(e){return e&&e.style||{}}zoneToXC(e,t,s=[{colFixed:!1,rowFixed:!1}]){const o=is((t=this.getters.expandZone(e,t)).left,t.top,s[0]),i=is(t.right,t.bottom,s.length>1?s[1]:s[0]),n=this.getters.getMainCell(e,t.left,t.top),r=this.getters.getMainCell(e,t.right,t.bottom),a=n[0]==r[0]&&n[1]==r[1];return o==i||a?o:o+":"+i}setStyle(e,t,s){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++){const o=this.getters.getCell(e,t,i);this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:s?{...null==o?void 0:o.style,...s}:void 0})}}copyColumnStyle(e,t,s){for(let o=0;o<e.rows.length;o++){const i=this.getFormat(e.id,t,o);if(i.style||i.format)for(let t of s)this.dispatch("UPDATE_CELL",{sheetId:e.id,col:t,row:o,...i})}}copyRowStyle(e,t,s){for(let o=0;o<e.cols.length;o++){const i=this.getFormat(e.id,o,t);if(i.style||i.format)for(let t of s)this.dispatch("UPDATE_CELL",{sheetId:e.id,col:o,row:t,...i})}}getFormat(e,t,s){const o={},[i,n]=this.getters.getMainCell(e,t,s),r=this.getters.getCell(e,i,n);return r&&(r.style&&(o.style=r.style),r.format&&(o.format=r.format)),o}updateCell(e,t,s,o){var i;const n=this.getters.getCell(e.id,t,s),r="content"in o||"formula"in o,a=r?(null===(i=o.content)||void 0===i?void 0:i.replace(ba,""))||"":(null==n?void 0:n.content)||"";let l;l=void 0!==o.style?o.style||void 0:n?n.style:void 0;let c=("format"in o?o.format:n&&n.format)||D;if((r&&!a&&!o.formula||!r&&(!n||n.isEmpty()))&&!l&&!c)return void(n&&(this.history.update("cells",e.id,n.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:s,sheetId:e.id})));const h=(null==n?void 0:n.id)||this.uuidGenerator.uuidv4(),d=r,u={format:c,style:l},p=this.createCell(h,a,u,e.id);n&&!d&&p.isFormula()&&(p.assignValue(n.evaluated.value),n.evaluated.type===Fe.error&&p.assignError(n.evaluated.value,n.evaluated.error)),this.history.update("cells",e.id,p.id,p),this.dispatch("UPDATE_CELL_POSITION",{cellId:p.id,col:t,row:s,sheetId:e.id})}checkCellOutOfSheet(e,t,s){const o=this.getters.tryGetSheet(e);if(!o)return 23;return to(t,s,{top:0,left:0,bottom:o.rows.length-1,right:o.cols.length-1})?0:18}}Sa.getters=["zoneToXC","getCells","getFormulaCellContent","inferFormulaFormat","getCellStyle","buildFormulaContent","getCellById"];class Ca extends va{constructor(){super(...arguments),this.chartFigures={}}adaptRanges(e){for(let[t,s]of Object.entries(this.chartFigures))s&&(this.adaptDataSetRanges(s,t,e),this.adaptLabelRanges(s,t,e))}adaptDataSetRanges(e,t,s){for(let o of e.dataSets){if(o.labelCell){const i=s(o.labelCell);switch(i.changeType){case"REMOVE":this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(o),"labelCell",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(o),"labelCell",i.range)}}const i=s(o.dataRange);switch(i.changeType){case"REMOVE":const s=e.dataSets.filter((e=>e!==o));this.history.update("chartFigures",t,"dataSets",s);break;case"RESIZE":case"MOVE":case"CHANGE":if(this.getters.getRangeString(i.range,i.range.sheetId)!==O)this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(o),"dataRange",i.range);else{const s=e.dataSets.filter((e=>e!==o));this.history.update("chartFigures",t,"dataSets",s)}}}}adaptLabelRanges(e,t,s){if(e.labelRange){const o=s(e.labelRange);switch(o.changeType){case"REMOVE":this.history.update("chartFigures",t,"labelRange",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("chartFigures",t,"labelRange",o.range)}}}allowDispatch(e){switch(e.type){case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.checkEmptyDataset,this.checkDataset,this.checkChartExists),this.checkLabelRange);case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.checkEmptyDataset,this.checkDataset,this.checkChartDuplicate),this.checkLabelRange);default:return 0}}handle(e){var t,s;switch(e.type){case"CREATE_CHART":const o=e.position?e.position.x:0,i=e.position?e.position.y:0;this.addChartFigure(e.sheetId,this.createChartDefinition(e.definition,e.sheetId),{id:e.id,x:o,y:i,height:335,width:536,tag:"chart"});break;case"UPDATE_CHART":this.updateChartDefinition(e.id,e.definition);break;case"DUPLICATE_SHEET":{const s=this.getters.getFigures(e.sheetId);for(const o of s)if("chart"===o.tag){const s=o.id.split("??").pop(),i=`${e.sheetIdTo}??${s}`,n={...gs(this.chartFigures[o.id]),id:i};n.sheetId=e.sheetIdTo,n.dataSets.forEach((t=>{var s;t.dataRange.sheetId===e.sheetId&&(t.dataRange.sheetId=e.sheetIdTo),(null===(s=t.labelCell)||void 0===s?void 0:s.sheetId)===e.sheetId&&(t.labelCell.sheetId=e.sheetIdTo)})),(null===(t=n.labelRange)||void 0===t?void 0:t.sheetId)===e.sheetId&&(n.labelRange.sheetId=e.sheetIdTo);const r={id:i,x:o.x,y:o.y,height:o.height,width:o.width,tag:"chart"};this.addChartFigure(e.sheetIdTo,n,r)}break}case"DELETE_FIGURE":this.history.update("chartFigures",e.id,void 0);break;case"DELETE_SHEET":for(let t of Object.keys(this.chartFigures))(null===(s=this.chartFigures[t])||void 0===s?void 0:s.sheetId)===e.sheetId&&this.history.update("chartFigures",t,void 0)}}getChartDefinition(e){return this.chartFigures[e]}getChartsIdBySheet(e){return Object.entries(this.chartFigures).filter((t=>t[1].sheetId===e)).map((e=>e[0]))}getChartDefinitionUI(e,t){const s=this.chartFigures[t];if(!s)return;const o=s.dataSets.map((t=>t?this.getters.getRangeString(t.dataRange,e):"")).filter((e=>""!==e));return{title:s&&s.title?s.title:"",dataSets:o,labelRange:s.labelRange?this.getters.getRangeString(s.labelRange,e):void 0,type:s?s.type:"bar",dataSetsHaveTitle:!(!s||0===o.length)&&Boolean(s.dataSets[0].labelCell),background:s.background,verticalAxisPosition:s.verticalAxisPosition,legendPosition:s.legendPosition,stackedBar:s.stackedBar}}getChartDefinitionExcel(e,t){const s=this.chartFigures[t],o=this.getChartDefinitionUI("forceSheetReference",t);if(!s||!o)return;const i=s.dataSets.map((e=>this.toExcelDataset(e))).filter((e=>""!==e.range));return{...o,backgroundColor:s.background,dataSets:i}}toExcelDataset(e){var t;const s=null===(t=e.labelCell)||void 0===t?void 0:t.zone;let o=e.dataRange.zone;if(s){const{height:e,width:t}=io(o);1===e?o={...o,left:o.left+1}:1===t&&(o={...o,top:o.top+1})}const i={...e.dataRange,zone:o};return{label:e.labelCell?this.getters.getRangeString(e.labelCell,"forceSheetReference"):void 0,range:this.getters.getRangeString(i,"forceSheetReference")}}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)if("chart"===e.tag){const s={...e.data};this.chartFigures[e.id]=this.createChartDefinition(s,t.id),delete e.data}}export(e){if(e.sheets)for(let t of e.sheets){const e=this.getters.getFigures(t.id),s=[];for(let o of e){const e=o;if(e&&"chart"===e.tag){const o=this.getChartDefinitionUI(t.id,e.id);o&&(e.data=o,s.push(e))}else s.push(e)}t.figures=s}}exportForExcel(e){for(let t of e.sheets){const e=this.getters.getFigures(t.id),s=[];for(let o of e){const e=o;if(e&&"chart"===e.tag){const o=this.getChartDefinitionExcel(t.id,e.id);o&&(e.data=o,s.push(e))}else s.push(e)}t.charts=s}}createChartDefinition(e,t){return{...e,dataSets:this.createDataSets(e.dataSets,t,e.dataSetsHaveTitle),labelRange:e.labelRange?this.getters.getRangeFromSheetXC(t,e.labelRange):void 0,sheetId:t}}updateChartDefinition(e,t){const s=this.chartFigures[e];if(!s)throw new Error(`There is no chart with the given id: ${e}`);if(void 0!==t.title&&this.history.update("chartFigures",e,"title",t.title),t.type&&this.history.update("chartFigures",e,"type",t.type),t.dataSets){const o=!!t.dataSetsHaveTitle,i=this.createDataSets(t.dataSets,s.sheetId,o);this.history.update("chartFigures",e,"dataSets",i)}if(void 0!==t.labelRange){const o=t.labelRange?this.getters.getRangeFromSheetXC(s.sheetId,t.labelRange):void 0;this.history.update("chartFigures",e,"labelRange",o)}t.background&&this.history.update("chartFigures",e,"background",t.background),t.verticalAxisPosition&&this.history.update("chartFigures",e,"verticalAxisPosition",t.verticalAxisPosition),t.legendPosition&&this.history.update("chartFigures",e,"legendPosition",t.legendPosition),void 0!==t.stackedBar&&this.history.update("chartFigures",e,"stackedBar",t.stackedBar)}createDataSets(e,t,s){const o=[];for(const i of e){const e=this.getters.getRangeFromSheetXC(t,i),{zone:n,sheetId:r,invalidSheetName:a}=e;if(!a)if(n.left!==n.right&&n.top!==n.bottom)for(let e=n.left;e<=n.right;e++){const t={left:e,right:e,top:n.top,bottom:n.bottom};o.push(this.createDataSet(r,t,s?{top:t.top,bottom:t.top,left:t.left,right:t.left}:void 0))}else n.left===n.right&&n.top===n.bottom?s||o.push(this.createDataSet(r,n,void 0)):o.push(this.createDataSet(r,n,s?{top:n.top,bottom:n.top,left:n.left,right:n.left}:void 0))}return o}addChartFigure(e,t,s){this.dispatch("CREATE_FIGURE",{sheetId:e,figure:s}),this.history.update("chartFigures",s.id,t)}createDataSet(e,t,s){if(t.left!==t.right&&t.top!==t.bottom)throw new Error(`Zone should be a single column or row: ${Xs(t)}`);if(s){const o=Xs(t),i=Xs(s);return{labelCell:this.getters.getRangeFromSheetXC(e,i),dataRange:this.getters.getRangeFromSheetXC(e,o)}}return{labelCell:void 0,dataRange:this.getters.getRangeFromSheetXC(e,Xs(t))}}checkEmptyDataset(e){return e.definition.dataSets&&0===e.definition.dataSets.length?27:0}checkDataset(e){if(!e.definition.dataSets)return 0;const t=void 0!==e.definition.dataSets.find((e=>!es.test(e)));return t?28:0}checkLabelRange(e){if(!e.definition.labelRange)return 0;return!es.test(e.definition.labelRange||"")?29:0}checkChartDuplicate(e){for(const t of this.getters.getSheets())if(this.getters.getFigure(t.id,e.id))return 57;return 0}checkChartExists(e){return this.getters.getFigure(e.sheetId,e.id)?0:58}}function ya(e){return""===e?NaN:Number(e)}Ca.getters=["getChartDefinition","getChartDefinitionUI","getChartsIdBySheet"];class wa extends va{constructor(){super(...arguments),this.cfRules={}}loopThroughRangesOfSheet(e,t){for(const s of this.cfRules[e])for(const o of s.ranges){const i=t(o);switch(i.changeType){case"REMOVE":let t=s.ranges.slice();t.splice(s.ranges.indexOf(o),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(s),"ranges",t):this.removeConditionalFormatting(s.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(s),"ranges",s.ranges.indexOf(o),i.range)}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(const t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){return"ADD_CONDITIONAL_FORMAT"===e.type?this.checkValidations(e,this.checkCFRule,this.checkEmptyRange):0}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const s={...e.cf,ranges:e.target.map(Xs)};this.addConditionalFormatting(s,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId)}}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){this.export(e)}getConditionalFormats(e){return this.cfRules[e].map((t=>this.mapToConditionalFormat(e,t)))||[]}getRulesSelection(e,t){const s=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{s.add(e)}))})),Array.from(s)}getRulesByZone(e,t){const s=new Set;for(let o=t.top;o<=t.bottom;o++)for(let i=t.left;i<=t.right;i++){this.getRulesByCell(e,i,o).forEach((e=>{s.add(e.id)}))}return s}getRulesByCell(e,t,s){const o=[];for(let i of this.cfRules[e])for(let e of i.ranges)to(t,s,e.zone)&&o.push(i);return new Set(o.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e)))}}mapToConditionalFormatInternal(e,t){const s={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return s}addConditionalFormatting(e,t){const s=this.cfRules[t].slice(),o=s.findIndex((t=>t.id===e.id)),i=this.mapToConditionalFormatInternal(t,e);o>-1?s.splice(o,1,i):s.push(i),this.history.update("cfRules",t,s)}checkEmptyRange(e){return e.target.length?0:21}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]));case"ColorScaleRule":return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case"IconSetRule":return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)))}return 0}checkOperatorArgsNumber(e,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return s=>{if(t.includes(s.operator)){const t=[],o=e=>void 0===e||""===e;return e>=1&&o(s.values[0])&&t.push(36),e>=2&&o(s.values[1])&&t.push(37),t.length?t:0}return 0}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return 38;case"max":return 40;case"mid":return 39;case"upperInflectionPoint":return 41;case"lowerInflectionPoint":return 42}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{Gr(e.value||"")}catch(e){switch(t){case"min":return 43;case"max":return 45;case"mid":return 44;case"upperInflectionPoint":return 46;case"lowerInflectionPoint":return 47}}return 0}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):0))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,s=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(s)?33:0}checkMinBiggerThanMax(e){const t=e.minimum.value,s=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&ya(t)>=ya(s)?32:0}checkMidBiggerThanMax(e){var t;const s=null===(t=e.midpoint)||void 0===t?void 0:t.value,o=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&ya(s)>=ya(o)?34:0}checkMinBiggerThanMid(e){var t;const s=e.minimum.value,o=null===(t=e.midpoint)||void 0===t?void 0:t.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&ya(s)>=ya(o)?35:0}removeConditionalFormatting(e,t){const s=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==s){const e=this.cfRules[t].slice();e.splice(s,1),this.history.update("cfRules",t,e)}}}wa.getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];class Ia extends va{constructor(){super(...arguments),this.figures={}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkFigureDuplicate(e.figure.id);case"UPDATE_FIGURE":case"DELETE_FIGURE":return this.checkFigureExists(e.sheetId,e.id);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:s,...o}=e,i=o;this.updateFigure(s,i);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId)}}updateFigure(e,t){if("id"in t)for(const[s,o]of Object.entries(t))switch(s){case"x":case"y":void 0!==o&&this.history.update("figures",e,t.id,s,Math.max(o,0));break;case"width":case"height":void 0!==o&&this.history.update("figures",e,t.id,s,o)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){var s;return void 0===(null===(s=this.figures[e])||void 0===s?void 0:s[t])?55:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>null==t?void 0:t[e]))?56:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(_s)}getFigure(e,t){var s;return null===(s=this.figures[e])||void 0===s?void 0:s[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>{var s;return void 0!==(null===(s=this.figures[t])||void 0===s?void 0:s[e])}))}import(e){for(let t of e.sheets){const e={};t.figures.forEach((t=>{e[t.id]=t})),this.figures[t.id]=e}}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const s=void 0;t.figures.push({...e,data:s})}}exportForExcel(e){this.export(e)}}Ia.getters=["getFigures","getFigure","getFigureSheetId"];class xa extends va{constructor(){super(...arguments),this.nextId=1,this.merges={},this.mergeCellMap={}}allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?0:this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;const s=this.getters.getSheet(e.sheetIdTo);for(const e of Object.values(t).filter(_s))this.addMerge(s,e.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(this.getters.getSheet(e.sheetId),t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){const s=t?[t]:Object.keys(this.merges);for(const t of s)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(_s)}getMerge(e,t,s){var o;const i=this.mergeCellMap[e],n=i?t in i&&(null===(o=i[t])||void 0===o?void 0:o[s]):void 0;return n?this.getMergeById(e,n):void 0}doesIntersectMerge(e,t){const{left:s,right:o,top:i,bottom:n}=t;for(let t=i;t<=n;t++)for(let i=s;i<=o;i++)if(this.getMerge(e,i,t))return!0;return!1}doesColumnsHaveCommonMerges(e,t,s){const o=this.getters.getSheet(e);for(let e=0;e<o.rows.length;e++)if(this.isInSameMerge(o.id,t,e,s,e))return!0;return!1}doesRowsHaveCommonMerges(e,t,s){const o=this.getters.getSheet(e);for(let e=0;e<=o.cols.length;e++)if(this.isInSameMerge(o.id,e,t,e,s))return!0;return!1}expandZone(e,t){let{left:s,right:o,top:i,bottom:n}=t,r={left:s,right:o,top:i,bottom:n};for(let t in this.merges[e]){const s=this.getMergeById(e,parseInt(t));s&&eo(s,r)&&(r=Qs(s,r))}return Js(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,s,o,i){const n=this.getMerge(e,t,s),r=this.getMerge(e,o,i);return!(!n||!r)&&Js(n,r)}isInMerge(e,t,s){var o;const i=this.mergeCellMap[e];return!!i&&(t in i&&Boolean(null===(o=i[t])||void 0===o?void 0:o[s]))}getMainCell(e,t,s){if(!this.isInMerge(e,t,s))return[t,s];const o=this.getMerge(e,t,s).topLeft;return[o.col,o.row]}getBottomLeftCell(e,t,s){if(!this.isInMerge(e,t,s))return[t,s];const{bottom:o,left:i}=this.getMerge(e,t,s);return[i,o]}isMergeHidden(e,t){const s=this.getters.getHiddenColsGroups(e),o=this.getters.getHiddenRowsGroups(e);for(let e of s)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of o)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const s=this.getMerge(e,t.left,t.top);if(s)return Js(t,s);const{width:o,height:i}=io(t);return 1===o&&1===i}isMergeDestructive(e,t){let{left:s,right:o,top:i,bottom:n}=t;o=ms(o,0,e.cols.length-1),n=ms(n,0,e.rows.length-1);for(let t=i;t<=n;t++)for(let n=s;n<=o;n++)if(n!==s||t!==i){const s=this.getters.getCell(e.id,n,t);if(s&&!s.isEmpty())return!0}return!1}getMergeById(e,t){var s;const o=null===(s=this.merges[e])||void 0===s?void 0:s[t];return void 0!==o?Ra(t,o):void 0}checkDestructiveMerge({sheetId:e,target:t}){const s=this.getters.tryGetSheet(e);if(!s)return 0;return t.some((e=>this.isMergeDestructive(s,e)))?3:0}checkOverlap({target:e}){for(const t of e)for(const s of e)if(t!==s&&eo(t,s))return 50;return 0}checkMergedContentUpdate(e){const{col:t,row:s,sheetId:o,content:i}=e;if(void 0===i)return 0;const[n,r]=this.getMainCell(o,t,s);return n===t&&r===s?0:4}checkMergeExists(e){const{sheetId:t,target:s}=e;for(const e of s){const{left:s,top:o}=e,i=this.getMerge(t,s,o);if(void 0===i||!Js(e,i))return 5}return 0}addMerge(e,t){let{left:s,right:o,top:i,bottom:n}=t;o=ms(o,0,e.cols.length-1),n=ms(n,0,e.rows.length-1);if(is(s,i)===is(o,n))return;const r=this.getters.getCell(e.id,s,i);let a=this.nextId++;this.history.update("merges",e.id,a,this.getters.getRangeFromSheetXC(e.id,Xs({left:s,top:i,right:o,bottom:n})));let l=new Set;for(let t=i;t<=n;t++)for(let n=s;n<=o;n++){n===s&&t===i||this.dispatch("UPDATE_CELL",{sheetId:e.id,col:n,row:t,style:r?r.style:null,content:void 0});const o=this.getMerge(e.id,n,t);o&&l.add(o.id),this.history.update("mergeCellMap",e.id,n,t,a)}for(let t of l){const{top:s,bottom:o,left:i,right:n}=this.getMergeById(e.id,t);for(let t=s;t<=o;t++)for(let s=i;s<=n;s++){const o=this.getMerge(e.id,s,t);o&&o.id===a||(this.history.update("mergeCellMap",e.id,s,t,void 0),this.dispatch("CLEAR_CELL",{sheetId:e.id,col:s,row:t}))}this.history.update("merges",e.id,t,void 0)}}removeMerge(e,t){const{left:s,top:o,bottom:i,right:n}=t,r=this.getMerge(e,s,o);if(void 0!==r&&Js(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=o;t<=i;t++)for(let o=s;o<=n;o++)this.history.update("mergeCellMap",e,o,t,void 0)}}applyRangeChangeOnSheet(e,t){const s=Object.entries(this.merges[e]||{});for(const[o,i]of s)if(i){const s=i.zone,n=t(i);switch(n.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,s);break;default:const{width:t,height:i}=io(n.range.zone);1===t&&1===i?this.removeMerge(e,s):this.history.update("merges",e,parseInt(o,10),n.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const[s,o]of ro(t))this.history.update("mergeCellMap",e,s,o,t.id)}import(e){const 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){const s=this.getters.getSheet(e);for(let e of t)this.addMerge(s,qs(e))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...Ta(e))}}exportForExcel(e){this.export(e)}}function Ta(e){return Object.entries(e).map((([e,t])=>t?Ra(parseInt(e,10),t):void 0)).filter(_s).map((e=>is(e.left,e.top)+":"+is(e.right,e.bottom)))}function Ra(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}xa.getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCell","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","isSingleCellOrMerge"];class La extends va{constructor(){super(...arguments),this.sheetIds={},this.visibleSheets=[],this.sheets={},this.cellPosition={}}allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZones)(e);if(0!==t)return t;switch(e.type){case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"MOVE_SHEET":const t=this.visibleSheets.findIndex((t=>t===e.sheetId));return"left"===e.direction&&0===t||"right"===e.direction&&t===this.visibleSheets.length-1?14:0;case"RENAME_SHEET":return this.isRenameAllowed(e);case"DELETE_SHEET":return this.visibleSheets.length>1?0:9;case"REMOVE_COLUMNS_ROWS":const s=this.getSheet(e.sheetId);return("COL"===e.dimension?s.cols.length:s.rows.length)>e.elements.length?0:8;case"HIDE_COLUMNS_ROWS":{const t=this.sheets[e.sheetId],s="COL"===e.dimension?t.hiddenColsGroups:t.hiddenRowsGroups,o="COL"===e.dimension?t.cols:t.rows;return(s||[]).flat().concat(e.elements).length<o.length?0:51}default:return 0}}handle(e){switch(e.type){case"SET_GRID_LINES_VISIBILITY":this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"CREATE_SHEET":const t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update("sheetIds",t.name,t.id);break;case"RESIZE_COLUMNS_ROWS":const s="COL"===e.dimension?"cols":"rows";for(let t of e.elements)this.setHeaderSize(this.getSheet(e.sheetId),s,t,e.size);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.direction);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.name);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],e.elements):this.removeRows(this.sheets[e.sheetId],e.elements);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case"HIDE_COLUMNS_ROWS":"COL"===e.dimension?this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"cols","hide"):this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"rows","hide");break;case"UNHIDE_COLUMNS_ROWS":"COL"===e.dimension?this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"cols","show"):this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"rows","show");break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e)}}import(e){for(let t of e.sheets)this.sheetIds[t.name]=t.id;for(let t of e.sheets){const e=t.name||r("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:s,rowNumber:o}=this.getImportedSheetSize(t),i={id:t.id,name:e,cols:Ps(t.cols||{},s),rows:Us(t.rows||{},o),hiddenColsGroups:[],hiddenRowsGroups:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible};this.visibleSheets.push(i.id),this.sheets[i.id]=i,this.updateHiddenElementsGroups(i.id,"cols"),this.updateHiddenElementsGroups(i.id,"rows")}}exportSheets(e,t=!1){e.sheets=this.visibleSheets.filter(_s).map((e=>{const s=this.sheets[e];return{id:s.id,name:s.name,colNumber:s.cols.length,rowNumber:s.rows.length,rows:Bs(s.rows,t),cols:Vs(s.cols,t),merges:[],cells:{},conditionalFormats:[],figures:[],areGridLinesVisible:void 0===s.areGridLinesVisible||s.areGridLinesVisible}}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e,!0)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}getSheetName(e){return this.getSheet(e).name}getCellsInZone(e,t){return ro(t).map((([t,s])=>this.getCell(e,t,s)))}tryGetSheetName(e){var t;return null===(t=this.tryGetSheet(e))||void 0===t?void 0:t.name}getSheetIdByName(e){if(e){const s=((t=e).startsWith("'")&&(t=t.slice(1,-1).replace(/''/g,"'")),t);for(const e in this.sheetIds)if(e.toUpperCase()===s.toUpperCase())return this.sheetIds[e]}var t}getSheets(){const{visibleSheets:e,sheets:t}=this;return e.map((e=>t[e])).filter(_s)}getVisibleSheets(){return this.visibleSheets}getEvaluationSheets(){return this.sheets}tryGetCol(e,t){var s;return null===(s=this.sheets[e])||void 0===s?void 0:s.cols[t]}getCol(e,t){const s=this.getSheet(e).cols[t];if(!s)throw new Error(`Col ${s} not found.`);return s}tryGetRow(e,t){var s;return null===(s=this.sheets[e])||void 0===s?void 0:s.rows[t]}getRow(e,t){const s=this.getSheet(e).rows[t];if(!s)throw new Error(`Row ${s} not found.`);return s}getCell(e,t,s){var o;const i=this.tryGetSheet(e),n=null===(o=null==i?void 0:i.rows[s])||void 0===o?void 0:o.cells[t];if(void 0!==n)return this.getters.getCellById(n)}getColCells(e,t){return this.getSheet(e).rows.map((e=>e.cells[t])).filter(_s).map((e=>this.getters.getCellById(e))).filter(_s)}getColsZone(e,t,s){return{top:0,bottom:this.getSheet(e).rows.length-1,left:t,right:s}}getRowsZone(e,t,s){return{top:t,bottom:s,left:0,right:this.getSheet(e).cols.length-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getHiddenColsGroups(e){var t;return(null===(t=this.sheets[e])||void 0===t?void 0:t.hiddenColsGroups)||[]}getHiddenRowsGroups(e){var t;return(null===(t=this.sheets[e])||void 0===t?void 0:t.hiddenRowsGroups)||[]}getNumberCols(e){return this.getSheet(e).cols.length}getNumberRows(e){return this.getSheet(e).rows.length}getNextSheetName(e="Sheet"){let t=1;const s=this.getSheets().map((e=>e.name));let o=`${e}${t}`;for(;s.includes(o);)o=`${e}${t}`,t++;return o}isEmpty(e,t){return this.getCellsInZone(e,t).flat().every((e=>!e||e.isEmpty()))}setHeaderSize(e,t,s,o){let i,n;const r=e[t],a=r[s],l=o-a.size;this.history.update("sheets",e.id,t,s,"size",o),a.isHidden||this.history.update("sheets",e.id,t,s,"end",a.end+l),i=a.end;for(let o=s+1;o<r.length;o++){const s=r[o];n=s.isHidden?i:i+s.size,this.history.update("sheets",e.id,t,o,"start",i),this.history.update("sheets",e.id,t,o,"end",n),i=n}}updateCellPosition(e){const{sheetId:t,cellId:s,col:o,row:i}=e;s?this.setNewPosition(s,t,o,i):this.clearPosition(t,o,i)}setNewPosition(e,t,s,o){const i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update("cellPosition",e,{row:o,col:s,sheetId:t}),this.history.update("sheets",t,"rows",o,"cells",s,e)}clearPosition(e,t,s){var o;const i=null===(o=this.sheets[e])||void 0===o?void 0:o.rows[s].cells[t];i&&(this.history.update("cellPosition",i,void 0),this.history.update("sheets",e,"rows",s,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let s of t)for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++){this.sheets[e].rows[o].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:o})}}createSheet(e,t,s,o,i){const n={id:e,name:t,cols:$s(s),rows:Ds(o),hiddenColsGroups:[],hiddenRowsGroups:[],areGridLinesVisible:!0},r=this.visibleSheets.slice();r.splice(i,0,n.id);const a=this.sheets;return this.history.update("visibleSheets",r),this.history.update("sheets",Object.assign({},a,{[n.id]:n})),n}moveSheet(e,t){const s=this.visibleSheets.slice(),o=s.findIndex((t=>t===e)),i=s.splice(o,1);s.splice(o+("left"===t?-1:1),0,i[0]),this.history.update("visibleSheets",s)}checkSheetName(e){const{visibleSheets:t,sheets:s}=this,o=e.name&&e.name.trim().toLowerCase();return t.find((e=>{var t;return(null===(t=s[e])||void 0===t?void 0:t.name.toLowerCase())===o}))?11:$.test(o)?13:0}checkSheetPosition(e){const{visibleSheets:t}=this;return e.position>t.length||e.position<0?15:0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const s=e.name;this.history.update("sheets",e.id,"name",t.trim());const o=Object.assign({},this.sheetIds);o[t]=e.id,delete o[s],this.history.update("sheetIds",o)}duplicateSheet(e,t){const s=this.getSheet(e),o=this.getDuplicateSheetName(s.name),i=JSON.parse(JSON.stringify(s));i.id=t,i.name=o;for(let e=0;e<=i.cols.length;e++)for(let t=0;t<=i.rows.length;t++)i.rows[t]&&(i.rows[t].cells[e]=void 0);const n=this.visibleSheets.slice(),r=n.findIndex((t=>t===e));n.splice(r+1,0,i.id),this.history.update("visibleSheets",n),this.history.update("sheets",Object.assign({},this.sheets,{[i.id]:i}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:s}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:i.id,col:e,row:s,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIds);a[i.name]=i.id,this.history.update("sheetIds",a)}getDuplicateSheetName(e){let t=1;const s=this.getters.getSheets().map((e=>e.name)),o=a("Copy of %s",e);let i=o.toString();for(;s.includes(i);)i=`${o} (${t})`,t++;return i}deleteSheet(e){const t=e.name,s=Object.assign({},this.sheets);delete s[e.id],this.history.update("sheets",s);const o=this.visibleSheets.slice(),i=o.findIndex((t=>t===e.id));o.splice(i,1),this.history.update("visibleSheets",o);const n=Object.assign({},this.sheetIds);delete n[t],this.history.update("sheetIds",n)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let s of t)this.moveCellOnColumnsDeletion(e,s);this.updateColumnsStructureOnDeletion(e,t)}removeRows(e,t){t.sort(((e,t)=>t-e));for(let s of bs(t))this.moveCellOnRowsDeletion(e,s[s.length-1],s[0]),s.map((t=>this.updateRowsStructureOnDeletion(t,e)))}addColumns(e,t,s,o){this.moveCellsOnAddition(e,"before"===s?t:t+1,o,"columns"),this.updateColumnsStructureOnAddition(e,t,o)}addRows(e,t,s,o){this.addEmptyRows(e,o),this.moveCellsOnAddition(e,"before"===s?t:t+1,o,"rows"),this.updateRowsStructureOnAddition(e,t,o)}moveCellOnColumnsDeletion(e,t){for(let[s,o]of Object.entries(e.rows)){const i=parseInt(s,10);for(let s in o.cells){const n=parseInt(s,10),r=o.cells[s];r&&(n===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:n,row:i}),n>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:n-1,row:i}))}}}moveCellsOnAddition(e,t,s,o){const i=[];for(const[n,r]of Object.entries(e.rows)){const a=parseInt(n,10);if("rows"!==o||a>=t)for(let n in r.cells){const l=parseInt(n,10),c=r.cells[n];c&&("rows"===o||l>=t)&&i.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c,col:l+("columns"===o?s:0),row:a+("rows"===o?s:0)})}}for(let e of i.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,s){const o=s-t+1;for(let[i,n]of Object.entries(e.rows)){const r=parseInt(i,10);if(r>=t&&r<=s)for(let t in n.cells){const s=parseInt(t,10);n.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:s,row:r})}if(r>s)for(let t in n.cells){const s=parseInt(t,10),i=n.cells[t];i&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:i,col:s,row:r-o})}}}updateColumnsStructureOnDeletion(e,t){const s=[];let o=0,i=0;for(let n in e.cols){if(t.includes(parseInt(n,10)))continue;const{size:r,isHidden:a}=e.cols[n],l=a?o:o+r;s.push({name:ss(i),size:r,start:o,end:l,isHidden:a}),o=l,i++}this.history.update("sheets",e.id,"cols",s),this.updateHiddenElementsGroups(e.id,"cols")}updateColumnsStructureOnAddition(e,t,s){const o=[];let i=0,n=0;for(let r in e.cols){if(parseInt(r,10)===t){const{size:t}=e.cols[n];for(let e=0;e<s;e++)o.push({name:ss(n),size:t,start:i,end:i+t}),i+=t,n++}const{size:a,isHidden:l}=e.cols[r],c=l?i:i+a;o.push({name:ss(n),size:a,start:i,end:c,isHidden:l}),i=c,n++}this.history.update("sheets",e.id,"cols",o),this.updateHiddenElementsGroups(e.id,"cols")}updateRowsStructureOnDeletion(e,t){const s=[];let o=0,i=0;const n=t.rows.map((e=>e.cells));for(let r in t.rows){const a=t.rows[r],{size:l,isHidden:c}=a,h=c?o:o+l;parseInt(r,10)!==e&&(i++,s.push({start:o,end:h,size:l,cells:n.shift(),name:String(i),isHidden:c}),o=h)}this.history.update("sheets",t.id,"rows",s),this.updateHiddenElementsGroups(t.id,"rows")}updateRowsStructureOnAddition(e,t,s){const o=[];let i=0,n=0,r=0;const a=e.rows.map((e=>e.cells));for(let l in e.rows){const{size:c,isHidden:h}=e.rows[r],d=h?i:i+c;(parseInt(l,10)<t||parseInt(l,10)>=t+s)&&r++,n++,o.push({start:i,end:d,size:c,cells:a.shift(),name:String(n),isHidden:h}),i=d}this.history.update("sheets",e.id,"rows",o),this.updateHiddenElementsGroups(e.id,"rows")}addEmptyRows(e,t){const s=e.rows[e.rows.length-1].end,o=e.rows.slice();for(let e=0;e<t;e++)o.push({start:s,end:s,size:0,name:(o.length+1).toString(),cells:{}});this.history.update("sheets",e.id,"rows",o)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(os);return{rowNumber:Math.max(e.rowNumber,...new Set(t.map((([e,t])=>t+1)))),colNumber:Math.max(e.colNumber,...new Set(t.map((([e,t])=>e+1))))}}setElementsVisibility(e,t,s,o){let i=0;const n="hide"===o;for(let o=0;o<e[s].length;o++){const{size:r,isHidden:a}=e[s][o],l=t.includes(o)?n:a||!1,c=l?i:i+r;this.history.update("sheets",e.id,s,o,"start",i),this.history.update("sheets",e.id,s,o,"end",c),this.history.update("sheets",e.id,s,o,"isHidden",l),i=c}this.updateHiddenElementsGroups(e.id,s)}updateHiddenElementsGroups(e,t){var s;const o="cols"===t?"hiddenColsGroups":"hiddenRowsGroups",i=((null===(s=this.sheets[e])||void 0===s?void 0:s[t])||[]).reduce(((e,t,s)=>{if(!t.isHidden)return e;const o=e[e.length-1];return o&&o[o.length-1]==s-1||e.push([]),e[e.length-1].push(s),e}),[]);this.history.update("sheets",e,o,i)}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?23:"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?12:0}checkZones(e){const t=[];if("zone"in e&&t.push(e.zone),"target"in e&&Array.isArray(e.target)&&t.push(...e.target),!t.every(js))return 22;if(t.length&&"sheetId"in e){const s=this.getSheet(e.sheetId),o={top:0,left:0,bottom:s.rows.length-1,right:s.cols.length-1};return t.every((e=>{return Js(Qs(t=o,e),t);var t}))?0:18}return 0}}La.getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheets","getVisibleSheets","getEvaluationSheets","tryGetCol","getCol","tryGetRow","getRow","getCell","getCellsInZone","getCellPosition","getColCells","getColsZone","getRowsZone","getNumberCols","getNumberRows","getHiddenColsGroups","getHiddenRowsGroups","getGridLinesVisibility","getNextSheetName","isEmpty"];const Ma=new Me;Ma.add("INCREMENT_MODIFIER",{apply:(e,t)=>{var s;e.current+=e.increment;const o=e.current.toString(),i=jr(e.current,null===(s=t.cell)||void 0===s?void 0:s.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:i}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,s)=>{var o,i;const n=(null===(o=t.cell)||void 0===o?void 0:o.content)||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:n},tooltip:n?{props:{content:null===(i=t.cell)||void 0===i?void 0:i.formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,s,o)=>{e.current+=e.increment;let i=0,n=0;switch(o){case 0:i=0,n=-e.current;break;case 1:i=0,n=e.current;break;case 2:i=-e.current,n=0;break;case 3:i=e.current,n=0}if(!t.cell||!t.cell.isFormula())return{cellData:{}};const r=t.sheetId,a=s.createAdaptedRanges(t.cell.dependencies,i,n,r),l=s.buildFormulaContent(r,t.cell,a);return{cellData:{border:t.border,style:t.cell.style,format:t.cell.format,content:l},tooltip:l?{props:{content:l}}:void 0}}});const Aa=new Me;Aa.add("simple_value_copy",{condition:(e,t)=>{var s;return 1===t.length&&!e.isFormula()&&!(null===(s=e.format)||void 0===s?void 0:s.match(_))},generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("copy_text",{condition:e=>!e.isFormula()&&e.evaluated.type===Fe.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_number",{condition:e=>e.evaluated.type===Fe.number,generateRule:(e,t)=>{const s=function(e,t){let s=[],o=!1;for(let i of t)if(i===e&&(o=!0),(null==i?void 0:i.evaluated.type)===Fe.number)s.push(i.evaluated.value);else{if(o)return s;s=[]}return s}(e,t);let o=1;return 2==s.length?o=2*(s[1]-s[0]):s.length>2&&(o=function(e){const t=[];let s=e[0];for(let o=1;o<e.length;o++){const i=e[o];t.push(i-s),s=i}return t.reduce(((e,t)=>e+t),0)/t.length}(s)*s.length),{type:"INCREMENT_MODIFIER",increment:o,current:e.evaluated.type===Fe.number?e.evaluated.value:0}},sequence:40});const _a=new Me,Oa=(new Me).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let s=e.base;"after"===e.position&&s++;for(let o=0;o<e.quantity;o++)t.push(o+s);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],s=[...e.elements].sort(((e,t)=>e-t));for(let o of bs(s)){const s=0===o[0]?0:o[0]-1,i=0===o[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:o.length,base:s,sheetId:e.sheetId,position:i})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",id:e.figure.id,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",id:e.id,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}));for(const e of Pe.values())Oa.contains(e)||Oa.add(e,Na);function Na(e){return[e]}const ka=e=>({isVisible:()=>!0,isEnabled:()=>!0,isReadonlyAllowed:!1,shortCut:"",action:!1,children:[],separator:!1,icon:!1,id:e});function Fa(e,t){return Object.assign({},ka(e),t)}class $a extends Me{add(e,t){return this.content[e]=Fa(e,t),this}addChild(e,t,s){const o=t.splice(0,1)[0];let i=this.content[o];if(!i)throw new Error(`Path ${o+":"+t.join(":")} not found`);for(let e of t)if(i="function"==typeof i.children?void 0:i.children.find((t=>t.id===e)),!i)throw new Error(`Path ${o+":"+t.join(":")} not found`);return i.children.push(Fa(e,s)),this}getChildren(e,t){return"function"==typeof e.children?e.children(t).sort(((e,t)=>e.sequence-t.sequence)):e.children.sort(((e,t)=>e.sequence-t.sequence))}getName(e,t){return"function"==typeof e.name?e.name(t):e.name}getShortCut(e){return e.shortCut?e.shortCut:""}getAll(){return super.getAll().sort(((e,t)=>e.sequence-t.sequence))}}const Da=[Fe.number,Fe.error,Fe.text,Fe.boolean];function Pa(e,t){return{index:t,type:e?e.evaluated.type:Fe.empty,value:e?e.evaluated.value:""}}function Ua(e,t,s,o,i){let n=Ve.Success,r=o.right>o.left;if(e.getters.doesIntersectMerge(t,o)){let s;r=!1;for(let i=o.top;i<=o.bottom;i++){s=[];for(let n=o.left;n<=o.right;n++){let o=e.getters.getMerge(t,n,i);o&&!s.includes(o.id.toString())&&s.push(o.id.toString())}if(s.length>=2){r=!0;break}}}const[l,c]=s;if(r)n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i});else{const s=e.getters.getContiguousZone(t,o);Js(s,o)?n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i}):e.askConfirmation(a("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?"),(()=>{o=s,n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i})}),(()=>{n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i})}))}n.isCancelledBecause(48)&&(e.dispatch("SET_SELECTION",{anchor:s,zones:[o],anchorZone:o}),e.notifyUser(a("Cannot sort. To sort, select only cells or only merges that have the same size.")))}function Va(e,t){t.isSuccessful||(t.reasons.includes(19)&&e.notifyUser(a("This operation is not allowed with multiple selections.")),t.reasons.includes(2)&&e.notifyUser(a("This operation is not possible due to a merge. Please remove the merges first than try again.")))}function Ba(e,t,s){const o=e.dispatch("PASTE",{target:t,pasteOption:s});Va(e,o)}function Ha(e){const t=e.getters.getActiveCols();if(t.size)return t.size;{const t=e.getters.getSelectedZones()[0];return t.right-t.left+1}}function za(e){const t=e.getters.getActiveRows();if(t.size)return t.size;{const t=e.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function Za(e,t){e.dispatch("SET_FORMATTING",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones(),format:t})}function Ga(e,t){e.dispatch("SET_FORMATTING",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones(),style:t})}const Wa=async e=>{e.dispatch("COPY",{target:e.getters.getSelectedZones()}),await e.clipboard.writeText(e.getters.getClipboardContent())},qa=async e=>{e.dispatch("CUT",{target:e.getters.getSelectedZones()}),await e.clipboard.writeText(e.getters.getClipboardContent())},ja=async e=>{const t=e.getters.getClipboardContent();let s;try{s=await e.clipboard.readText()}catch(e){console.warn("The OS clipboard could not be read."),console.error(e)}const o=e.getters.getSelectedZones();s&&s!==t?e.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:o,text:s}):Ba(e,o)},Xa=e=>e.dispatch("PASTE",{target:e.getters.getSelectedZones(),pasteOption:"onlyValue"}),Ya=e=>e.dispatch("PASTE",{target:e.getters.getSelectedZones(),pasteOption:"onlyFormat"}),Ka=e=>e.dispatch("DELETE_CONTENT",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones()}),Qa=e=>{let t,s;const o=e.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?a("Delete row %s",(t+1).toString()):a("Delete rows %s - %s",(t+1).toString(),(s+1).toString())},Ja=e=>{let t=[...e.getters.getActiveRows()];if(!t.length){const s=e.getters.getSelectedZones()[0];for(let e=s.top;e<=s.bottom;e++)t.push(e)}e.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"ROW",elements:t})},el=e=>{let t,s;const o=e.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?a("Delete column %s",ss(t)):a("Delete columns %s - %s",ss(t),ss(s))},tl=e=>{let t=[...e.getters.getActiveCols()];if(!t.length){const s=e.getters.getSelectedZones()[0];for(let e=s.left;e<=s.right;e++)t.push(e)}e.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"COL",elements:t})},sl=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});Va(e,s)},ol=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});Va(e,s)},il=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});Va(e,s)},nl=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});Va(e,s)},rl=e=>{const t=e.getters.getActiveRows();let s,o;if(t.size)s=Math.min(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.top,o=t.bottom-t.top+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"before",base:s,quantity:o,dimension:"ROW"})},al=e=>{const t=e.getters.getActiveRows();let s,o;if(t.size)s=Math.max(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.bottom,o=t.bottom-t.top+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"after",base:s,quantity:o,dimension:"ROW"})},ll=e=>{const t=e.getters.getActiveCols();let s,o;if(t.size)s=Math.min(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.left,o=t.right-t.left+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"before",dimension:"COL",base:s,quantity:o})},cl=e=>{const t=e.getters.getActiveCols();let s,o;if(t.size)s=Math.max(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.right,o=t.right-t.left+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"after",dimension:"COL",base:s,quantity:o})},hl=e=>{e.openSidePanel("ConditionalFormatting",{selection:e.getters.getSelectedZones()})},dl=e=>{e.openLinkEditor()},ul=e=>{const{anchor:t,zones:s}=e.getters.getSelection(),o=e.getters.getActiveSheetId();Ua(e,o,t,s[0],"ascending")},pl=e=>{const{anchor:t,zones:s}=e.getters.getSelection(),o=e.getters.getActiveSheetId();Ua(e,o,t,s[0],"descending")},gl=e=>1===e.getters.getSelectedZones().length,fl=new $a;fl.add("cut",{name:a("Cut"),shortCut:"Ctrl+X",sequence:10,action:qa}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Wa}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:ja,isVisible:gl}).add("paste_special",{name:a("Paste special"),sequence:40,separator:!0,isVisible:gl}).addChild("paste_value_only",["paste_special"],{name:a("Paste values only"),sequence:10,action:Xa}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Ya}).add("sort_range",{name:a("Sort range"),sequence:50,isVisible:gl,separator:!0}).addChild("sort_ascending",["sort_range"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:ul}).addChild("sort_descending",["sort_range"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:pl}).add("add_row_before",{name:e=>{const t=za(e);return 1===t?a("Insert row"):a("Insert %s rows",t.toString())},sequence:70,action:rl,isVisible:gl}).add("add_column_before",{name:e=>{const t=Ha(e);return 1===t?a("Insert column"):a("Insert %s columns",t.toString())},sequence:90,action:ll,isVisible:gl}).add("insert_cell",{name:a("Insert cells"),sequence:100,isVisible:gl,separator:!0}).addChild("insert_cell_down",["insert_cell"],{name:a("Shift down"),sequence:10,action:sl}).addChild("insert_cell_right",["insert_cell"],{name:a("Shift right"),sequence:20,action:ol}).add("delete_row",{name:Qa,sequence:110,action:Ja,isVisible:gl}).add("delete_column",{name:el,sequence:120,action:tl,isVisible:gl}).add("delete_cell",{name:a("Delete cells"),sequence:130,isVisible:gl}).addChild("delete_cell_up",["delete_cell"],{name:a("Shift up"),sequence:10,action:il}).addChild("delete_cell_down",["delete_cell"],{name:a("Shift left"),sequence:20,action:nl}).add("clear_cell",{name:a("Clear cells"),sequence:140,action:Ka,isEnabled:e=>{const t=e.getters.getActiveCell();return Boolean(t)},separator:!0}).add("insert_link",{name:a("Insert link"),separator:!0,sequence:150,action:dl}).add("conditional_formatting",{name:a("Conditional formatting"),sequence:160,action:hl,separator:!0});const ml=new $a;ml.add("cut",{name:a("Cut"),shortCut:"Ctrl+X",sequence:10,action:qa}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Wa}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:ja}).add("paste_special",{name:a("Paste special"),sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{name:a("Paste value only"),sequence:10,action:Xa}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Ya}).add("sort_columns",{name:e=>e.getters.getActiveCols().size>1?a("Sort columns"):a("Sort column"),sequence:50,isVisible:gl,separator:!0}).addChild("sort_ascending",["sort_columns"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:ul}).addChild("sort_descending",["sort_columns"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:pl}).add("add_column_before",{name:e=>{const t=Ha(e);return 1===t?a("Insert column left"):a("Insert %s columns left",t.toString())},sequence:70,action:ll}).add("add_column_after",{name:e=>{const t=Ha(e);return 1===t?a("Insert column right"):a("Insert %s columns right",t.toString())},sequence:80,action:cl}).add("delete_column",{name:el,sequence:90,action:tl}).add("clear_column",{name:e=>{let t,s;const o=e.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?a("Clear column %s",ss(t)):a("Clear columns %s - %s",ss(t),ss(s))},sequence:100,action:e=>{const t=e.getters.getActiveSheetId(),s=[...e.getters.getActiveCols()].map((s=>e.getters.getColsZone(t,s,s)));e.dispatch("DELETE_CONTENT",{target:s,sheetId:e.getters.getActiveSheetId()})}}).add("hide_columns",{name:e=>{const t=e.getters.getElementsFromSelection("COL");let s=t[0],o=t[t.length-1];return 1===t.length?a("Hide column %s",ss(s).toString()):o-s+1===t.length?a("Hide columns %s - %s",ss(s).toString(),ss(o).toString()):a("Hide columns")},sequence:85,action:e=>{const t=e.getters.getElementsFromSelection("COL");e.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.getters.getActiveSheet(),s=e.getters.getHiddenColsGroups(t.id).flat();return t.cols.length>s.length+e.getters.getElementsFromSelection("COL").length},separator:!0}).add("unhide_columns",{name:"Unhide columns",sequence:86,action:e=>{const t=e.getters.getElementsFromSelection("COL");e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.getters.getHiddenColsGroups(e.getters.getActiveSheetId()).flat();return e.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:a("Conditional formatting"),sequence:110,action:hl});const vl=new $a;vl.add("sheet",{name:a("Link sheet"),sequence:10,children:e=>e.getters.getSheets().map(((e,t)=>Fa(e.id,{name:e.name,sequence:t,action:()=>{return{link:{label:e.name,url:(t=e.id,`${Ls}${t}`)},urlRepresentation:e.name,isUrlEditable:!1};var t}})))});const El=new $a;function bl(e,t,s){const o=e.getters.getSheetName(t),i=a("Rename Sheet")+(s?" - "+s:"");e.editText(i,o,(s=>{if(null===s||s===o)return;""===s&&bl(e,t,a("The sheet name cannot be empty."));const i=e.dispatch("RENAME_SHEET",{sheetId:t,name:s});i.isSuccessful||(i.reasons.includes(11)&&bl(e,t,a("A sheet with the name %s already exists. Please select another name.",s)),i.reasons.includes(13)&&bl(e,t,a("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",F.join(" "))))}))}El.add("cut",{name:a("Cut"),sequence:10,shortCut:"Ctrl+X",action:qa}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Wa}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:ja}).add("paste_special",{name:a("Paste special"),sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{name:a("Paste value only"),sequence:10,action:Xa}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Ya}).add("add_row_before",{name:e=>{const t=za(e);return 1===t?a("Insert row above"):a("Insert %s rows above",t.toString())},sequence:50,action:rl}).add("add_row_after",{name:e=>{const t=za(e);return 1===t?a("Insert row below"):a("Insert %s rows below",t.toString())},sequence:60,action:al}).add("delete_row",{name:Qa,sequence:70,action:Ja}).add("clear_row",{name:e=>{let t,s;const o=e.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?a("Clear row %s",(t+1).toString()):a("Clear rows %s - %s",(t+1).toString(),(s+1).toString())},sequence:80,action:e=>{const t=e.getters.getActiveSheetId(),s=[...e.getters.getActiveRows()].map((s=>e.getters.getRowsZone(t,s,s)));e.dispatch("DELETE_CONTENT",{target:s,sheetId:e.getters.getActiveSheetId()})}}).add("hide_rows",{name:e=>{const t=e.getters.getElementsFromSelection("ROW");let s=t[0],o=t[t.length-1];return 1===t.length?a("Hide row %s",(s+1).toString()):o-s+1===t.length?a("Hide rows %s - %s",(s+1).toString(),(o+1).toString()):a("Hide rows")},sequence:85,action:e=>{const t=e.getters.getElementsFromSelection("ROW");e.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.getters.getActiveSheet(),s=e.getters.getHiddenRowsGroups(t.id).flat();return t.rows.length>s.length+e.getters.getElementsFromSelection("ROW").length},separator:!0}).add("unhide_rows",{name:"Unhide rows",sequence:86,action:e=>{const t=e.getters.getElementsFromSelection("ROW");e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.getters.getHiddenRowsGroups(e.getters.getActiveSheetId()).flat();return e.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:a("Conditional formatting"),sequence:90,action:hl});const Sl=new $a;Sl.add("delete",{name:a("Delete"),sequence:10,isVisible:e=>e.getters.getSheets().length>1,action:e=>e.askConfirmation(a("Are you sure you want to delete this sheet ?"),(()=>{e.dispatch("DELETE_SHEET",{sheetId:e.getters.getActiveSheetId()})}))}).add("duplicate",{name:a("Duplicate"),sequence:20,action:e=>{const t=e.getters.getActiveSheetId(),s=e.uuidGenerator.uuidv4();e.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:s}),e.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:s})}}).add("rename",{name:a("Rename"),sequence:30,action:e=>bl(e,e.getters.getActiveSheetId())}).add("move_right",{name:a("Move right"),sequence:40,isVisible:e=>{const t=e.getters.getActiveSheetId(),s=e.getters.getSheets();return s.findIndex((e=>e.id===t))!==s.length-1},action:e=>e.dispatch("MOVE_SHEET",{sheetId:e.getters.getActiveSheetId(),direction:"right"})}).add("move_left",{name:a("Move left"),sequence:50,isVisible:e=>{const t=e.getters.getActiveSheetId();return 0!==e.getters.getSheets().findIndex((e=>e.id===t))},action:e=>e.dispatch("MOVE_SHEET",{sheetId:e.getters.getActiveSheetId(),direction:"left"})});const Cl=new $a;Cl.add("file",{name:a("File"),sequence:10}).add("edit",{name:a("Edit"),sequence:20}).add("view",{name:a("View"),sequence:30}).add("insert",{name:a("Insert"),sequence:40}).add("format",{name:a("Format"),sequence:50}).add("data",{name:a("Data"),sequence:60}).addChild("save",["file"],{name:a("Save"),shortCut:"Ctrl+S",sequence:10,action:()=>console.log("Not implemented")}).addChild("undo",["edit"],{name:a("Undo"),shortCut:"Ctrl+Z",sequence:10,action:e=>e.dispatch("REQUEST_UNDO")}).addChild("redo",["edit"],{name:a("Redo"),shortCut:"Ctrl+Y",sequence:20,action:e=>e.dispatch("REQUEST_REDO"),separator:!0}).addChild("copy",["edit"],{name:a("Copy"),shortCut:"Ctrl+C",sequence:30,isReadonlyAllowed:!0,action:Wa}).addChild("cut",["edit"],{name:a("Cut"),shortCut:"Ctrl+X",sequence:40,action:qa}).addChild("paste",["edit"],{name:a("Paste"),shortCut:"Ctrl+V",sequence:50,action:ja}).addChild("paste_special",["edit"],{name:a("Paste special"),sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{name:a("Paste value only"),sequence:10,action:Xa}).addChild("paste_special_format",["edit","paste_special"],{name:a("Paste format only"),sequence:20,action:Ya}).addChild("sort_range",["edit"],{name:a("Sort range"),sequence:62,isVisible:gl,separator:!0}).addChild("sort_ascending",["edit","sort_range"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:ul}).addChild("sort_descending",["edit","sort_range"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:pl}).addChild("find_and_replace",["edit"],{name:a("Find and replace"),shortCut:"Ctrl+H",sequence:65,isReadonlyAllowed:!0,action:e=>{e.openSidePanel("FindAndReplace",{})},separator:!0}).addChild("edit_delete_cell_values",["edit"],{name:a("Delete values"),sequence:70,action:Ka}).addChild("edit_delete_row",["edit"],{name:Qa,sequence:80,action:Ja}).addChild("edit_delete_column",["edit"],{name:el,sequence:90,action:tl}).addChild("edit_delete_cell_shift_up",["edit"],{name:a("Delete cell and shift up"),sequence:93,action:il}).addChild("edit_delete_cell_shift_left",["edit"],{name:a("Delete cell and shift left"),sequence:97,action:nl}).addChild("edit_unhide_columns",["edit"],{name:a("Unhide all columns"),sequence:100,action:e=>{const t=e.getters.getActiveSheet();e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t.id,dimension:"COL",elements:Array.from(Array(t.cols.length).keys())})},isVisible:e=>e.getters.getHiddenColsGroups(e.getters.getActiveSheetId()).length>0}).addChild("edit_unhide_rows",["edit"],{name:a("Unhide all rows"),sequence:100,action:e=>{const t=e.getters.getActiveSheet();e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t.id,dimension:"ROW",elements:Array.from(Array(t.rows.length).keys())})},isVisible:e=>e.getters.getHiddenRowsGroups(e.getters.getActiveSheetId()).length>0}).addChild("insert_row_before",["insert"],{name:e=>{const t=za(e);return 1===t?a("Row above"):a("%s Rows above",t.toString())},sequence:10,action:rl,isVisible:e=>0===e.getters.getActiveCols().size}).addChild("insert_row_after",["insert"],{name:e=>{const t=za(e);return 1===t?a("Row below"):a("%s Rows below",t.toString())},sequence:20,action:al,isVisible:e=>0===e.getters.getActiveCols().size,separator:!0}).addChild("insert_column_before",["insert"],{name:e=>{const t=Ha(e);return 1===t?a("Column left"):a("%s Columns left",t.toString())},sequence:30,action:ll,isVisible:e=>0===e.getters.getActiveRows().size}).addChild("insert_column_after",["insert"],{name:e=>{const t=Ha(e);return 1===t?a("Column right"):a("%s Columns right",t.toString())},sequence:40,action:cl,isVisible:e=>0===e.getters.getActiveRows().size,separator:!0}).addChild("insert_insert_cell_shift_down",["insert"],{name:a("Insert cells and shift down"),sequence:43,action:sl}).addChild("insert_insert_cell_shift_right",["insert"],{name:a("Insert cells and shift right"),sequence:47,action:ol,separator:!0}).addChild("insert_chart",["insert"],{name:a("Chart"),sequence:50,action:e=>{var t,s;const o=e.getters.getSelectedZone();let i=o;const n=e.uuidGenerator.uuidv4();let r;o.left!==o.right&&(i={...o,left:o.left+1});const a=[Xs(i)],l=e.getters.getActiveSheetId(),c={x:(null===(t=e.getters.tryGetCol(l,o.right+1))||void 0===t?void 0:t.start)||0,y:(null===(s=e.getters.tryGetRow(l,o.top))||void 0===s?void 0:s.start)||0};let h=!1;for(let t=i.left;t<=i.right;t++){const s=e.getters.getCell(l,t,o.top);if(s&&s.evaluated.type!==Fe.number){h=!0;break}}o.left!==o.right&&(r=Xs({...o,right:o.left,top:h?o.top+1:o.top})),e.dispatch("CREATE_CHART",{sheetId:l,id:n,position:c,definition:{title:"",dataSets:a,labelRange:r,type:"bar",stackedBar:!1,dataSetsHaveTitle:h,background:g,verticalAxisPosition:"left",legendPosition:"top"}});const d=e.getters.getFigure(l,n);e.openSidePanel("ChartPanel",{figure:d})}}).addChild("insert_link",["insert"],{name:a("Link"),separator:!0,sequence:60,action:dl}).addChild("insert_sheet",["insert"],{name:a("New sheet"),sequence:70,action:e=>{const t=e.getters.getActiveSheetId(),s=e.getters.getVisibleSheets().findIndex((e=>e===t))+1,o=e.uuidGenerator.uuidv4();e.dispatch("CREATE_SHEET",{sheetId:o,position:s}),e.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},separator:!0}).addChild("view_gridlines",["view"],{name:e=>e.getters.getGridLinesVisibility(e.getters.getActiveSheetId())?a("Hide gridlines"):a("Show gridlines"),action:e=>{const t=e.getters.getActiveSheetId();e.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.getters.getGridLinesVisibility(t)})},sequence:5,separator:!0}).addChild("view_formulas",["view"],{name:e=>e.getters.shouldShowFormulas()?a("Hide formulas"):a("Show formulas"),action:e=>e.dispatch("SET_FORMULA_VISIBILITY",{show:!e.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,sequence:10}).addChild("format_number",["format"],{name:a("Numbers"),sequence:10,separator:!0}).addChild("format_number_general",["format","format_number"],{name:a("General"),sequence:10,separator:!0,action:e=>Za(e,"")}).addChild("format_number_number",["format","format_number"],{name:a("Number (1,000.12)"),sequence:20,action:e=>Za(e,"#,##0.00")}).addChild("format_number_percent",["format","format_number"],{name:a("Percent (10.12%)"),sequence:30,separator:!0,action:e=>Za(e,"0.00%")}).addChild("format_number_date",["format","format_number"],{name:a("Date (9/26/2008)"),sequence:40,action:e=>Za(e,"m/d/yyyy")}).addChild("format_number_time",["format","format_number"],{name:a("Time (10:43:00 PM)"),sequence:50,action:e=>Za(e,"hh:mm:ss a")}).addChild("format_number_date_time",["format","format_number"],{name:a("Date time (9/26/2008 22:43:00)"),sequence:60,action:e=>Za(e,"m/d/yyyy hh:mm:ss")}).addChild("format_number_duration",["format","format_number"],{name:a("Duration (27:51:38)"),sequence:70,separator:!0,action:e=>Za(e,"hhhh:mm:ss")}).addChild("format_bold",["format"],{name:a("Bold"),sequence:20,shortCut:"Ctrl+B",action:e=>Ga(e,{bold:!e.getters.getCurrentStyle().bold})}).addChild("format_italic",["format"],{name:a("Italic"),sequence:30,shortCut:"Ctrl+I",action:e=>Ga(e,{italic:!e.getters.getCurrentStyle().italic})}).addChild("format_underline",["format"],{name:a("Underline"),shortCut:"Ctrl+U",sequence:40,action:e=>Ga(e,{underline:!e.getters.getCurrentStyle().underline})}).addChild("format_strikethrough",["format"],{name:a("Strikethrough"),sequence:50,action:e=>Ga(e,{strikethrough:!e.getters.getCurrentStyle().strikethrough}),separator:!0}).addChild("format_font_size",["format"],{name:a("Font size"),sequence:60,separator:!0}).addChild("format_cf",["format"],{name:a("Conditional formatting"),sequence:70,action:hl,separator:!0});for(let e of cs)Cl.addChild(`format_font_size_${e.pt}`,["format","format_font_size"],{name:e.pt.toString(),sequence:e.pt,action:t=>Ga(t,{fontSize:e.pt})});const yl=new class extends Me{addTransformation(e,t,s){for(let o of t)this.content[o]||(this.content[o]=new Map),this.content[o].set(e,s);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},{css:wl,xml:Il}=t.tags,xl=[["#000000","#434343","#666666","#999999","#b7b7b7","#cccccc","#d9d9d9","#efefef","#f3f3f3","#ffffff"],["#980000","#ff0000","#ff9900","#ffff00","#00ff00","#00ffff","#4a86e8","#0000ff","#9900ff","#ff00ff"],["#e6b8af","#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#c9daf8","#cfe2f3","#d9d2e9","#ead1dc"],["#dd7e6b","#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#a4c2f4","#9fc5e8","#b4a7d6","#d5a6bd"],["#cc4125","#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6d9eeb","#6fa8dc","#8e7cc3","#c27ba0"],["#a61c00","#cc0000","#e69138","#f1c232","#6aa84f","#45818e","#3c78d8","#3d85c6","#674ea7","#a64d79"],["#85200c","#990000","#b45f06","#bf9000","#38761d","#134f5c","#1155cc","#0b5394","#351c75","#741b47"],["#5b0f00","#660000","#783f04","#7f6000","#274e13","#0c343d","#1c4587","#073763","#20124d","#4c1130"]],Tl=24*Math.max(...xl.map((e=>e.length)))+12;class Rl extends t.Component{constructor(){super(...arguments),this.COLORS=xl}onColorClick(e){const t=e.target.dataset.color;t&&this.props.onColorPicked(t)}}Rl.template=Il`
1
+ !function(e,t){"use strict";function s(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if("default"!==s){var o=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,o.get?o:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var o=s(t);let i=e=>e;function n(e,...t){if(1===t.length&&"object"==typeof t[0]){const s=t[0];e=e.replace(/\%\(?([^\)]+)\)s/g,((e,t)=>s[t]))}else t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));return e}const r=function(e,...t){return n(i(e),...t)},a=function(e,...t){return{toString:function(){return n(i(e),...t)}}},l="#f5f5f5",c="#F8F9FA",h="#E8EAED",d="#595959",u="#666666",p="#3266ca",g="#FFFFFF",f=11982760,m=26,v=48,E=63,b=96,S=23,C=15,y=14,w=4,I=200,x=1,T="400",R=10,L="'Roboto', arial",M=["thin","#000"],A="#00f",_=/[ymd:]/,O="#REF",N="START_REVISION",k=a("Invalid expression"),F=["'","*","?","/","\\","[","]"],$=/'|\*|\?|\/|\\|\[|\]/,D=void 0,P="|";class U{constructor(e,t,s,o=0,i=0,n=0){this.jsDate=new Date(Date.UTC(e,t,s,o,i,n,0))}static fromTimestamp(e){const t=new Date(e);return new U(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())}static now(){const e=new Date;return new U(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds())}toString(){return this.jsDate.toString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}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()}setDate(e){this.jsDate.setUTCDate(e)}setHours(e){this.jsDate.setUTCHours(e)}setMinutes(e){this.jsDate.setUTCMinutes(e)}setSeconds(e){this.jsDate.setUTCSeconds(e)}}const V=2e3,B=U.now().getFullYear(),H=new U(1899,11,30),z=U.fromTimestamp(0).getTime()-H.getTime(),Z=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,G=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,W=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function q(e){let t;const s=(e=e.trim()).match(W);if(s){if(t=function(e){if(e=e.trim(),W.test(e)){const t=/AM/i.test(e),s=/PM/i.test(e),o=(t||s?e.substring(0,e.length-2).trim():e).split(/:/),i=o.length>=2,n=3===o.length;let r=Number(o[0]),a=i?Number(o[1]):0,l=n?Number(o[2]):0,c=n?"hh:mm:ss":"hh:mm";if(t||s)c+=" a";else if(!i)return null;r>=12&&t?r-=12:r<12&&s&&(r+=12),a+=Math.floor(l/60),l%=60,r+=Math.floor(a/60),a%=60,r>=24&&(c="hhhh:mm:ss");return{value:r/24+a/1440+l/86400,format:c,jsDate:new U(1899,11,30,r,a,l)}}return null}(s[0]),null===t)return null;e=e.replace(s[0],"").trim()}let o;const i=e.match(Z),n=e.match(G);if(i||n){let t;if(i?(t=i[0],o=j(t,"mdy")):(t=n[0],o=j(t,"ymd")),null===o)return null;e=e.replace(t,"").trim()}return""!==e||!o&&!t?null:o&&t?{value:o.value+t.value,format:o.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new U(o.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,o.jsDate.getMonth()+t.jsDate.getMonth()-11,o.jsDate.getDate()+t.jsDate.getDate()-30,o.jsDate.getHours()+t.jsDate.getHours(),o.jsDate.getMinutes()+t.jsDate.getMinutes(),o.jsDate.getSeconds()+t.jsDate.getSeconds())}:o||t}function j(e,t){const s="mdy"===t;if(s||"ymd"===t){const t=e.split(/\/|-|\s/),o=s?0:1,i=s?1:2,n=s?2:0,r=Number(t[o]),a=Number(t[i]),l=2===t[o].length&&r<10||2===t[i].length&&a<10,c=t[n]?function(e){const t=Number(e);switch(e.length){case 1:return V+t;case 2:return V+(V+t>B+10?-100:0)+t;case 3:case 4:return t}return 0}(t[n]):B,h=new U(c,r-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==r-1||h.getDate()!==a)return null;const u=h.getTime()-H.getTime();let p=l?`mm${d}dd`:`m${d}d`;return t[n]&&(p=s?p+d+"yyyy":"yyyy"+d+p),{value:Math.round(u/864e5),format:p,jsDate:h}}return null}function X(e){const t=Math.trunc(e);let s=U.fromTimestamp(86400*t*1e3-z),o=e-t;o=o<0?1+o:o;const i=Math.round(24*o),n=Math.round(24*(o-i/24)*60),r=Math.round(24*(o-i/24-n/24/60)*60*60);return s.setHours(i),s.setMinutes(n),s.setSeconds(r),s}function Y(e){const t=e.format,s=e.jsDate||X(e.value),o=t.indexOf("h");let i="",n="";return o>0?(i=K(s,t.substring(0,o-1)),n=Q(s,t.substring(o))):0===o?n=Q(s,t):o<0&&(i=K(s,t)),i+(i&&n?" ":"")+n}function K(e,t){const s=t.match(/\/|-|\s/)[0];return t.split(s).map((s=>{switch(s){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"yyyy":return e.getFullYear();default:throw new Error(`invalid format: ${t}`)}})).join(s)}function Q(e,t){let s=t.split(/:|\s/);const o=e.getHours(),i="a"===s[s.length-1];let n=o,r="";return i&&(n=0===n?12:n>12?n-12:n,r=o>=12?" PM":" AM",s.pop()),s.map((s=>{switch(s){case"hhhh":return Math.floor((e.getTime()-H.getTime())/36e5).toString();case"hh":return n.toString().padStart(2,"0");case"mm":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");default:throw new Error(`invalid format: ${t}`)}})).join(":")+r}const J=/(^-?\d+(\.?\d*(e\d+)?)?(\s*%)?|^-?\.\d+(\s*%)?)(?!\w|!)/,ee=/^-?\d+(,\d+)*(\.?\d*(e\d+)?)?(\s*%)?$|^-?\.\d+(\s*%)?$/;function te(e){return ee.test(e.trim())}const se=/,/g;function oe(e){let t=Number(e.replace(se,""));return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}const ie=new Intl.NumberFormat("en-US",{useGrouping:!1,maximumFractionDigits:10});function ne(e){return Number.isInteger(e)?e.toString():ie.format(e)}let re=[];const ae=20;function le(e,t,s=""){if(e<0)return"-"+le(-e,t);const o=t>=ae?ae:t;let i=re[o];i||(i=new Intl.NumberFormat("en-US",{minimumFractionDigits:o,maximumFractionDigits:o,useGrouping:!1}),re[o]=i);let n=i.format(e);if(s){let e=n.indexOf(".");n=n.replace(/\d(?=(?:\d{3})+(?:\.|$))/g,((t,o)=>e<0||o<e?`${t}${s}`:t))}return n}function ce(e,t){const s=t.split("."),o=1===s.length?0:s[1].match(/0/g).length,i=s[0].includes(",")?",":"",n=t.includes("%");n&&(e*=100);const r=le(e,o,i);return n?r+"%":r}function he(e,t){if(!e())throw new Error(t)}const de=e=>a("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function ue(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(te(e)||""===e)return oe(e);const t=q(e);if(t)return t.value;throw new Error(de(e));default:return 0}}function pe(e){if(""===e)throw new Error(de(e));return ue(e)}function ge(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}const fe=e=>a("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function me(e){switch(typeof e){case"boolean":return e;case"string":if(e){let t=e.toUpperCase();if("TRUE"===t)return!0;if("FALSE"===t)return!1;throw new Error(fe(e))}return!1;case"number":return!!e;default:return!1}}function ve(e){return X(ue(e))}function Ee(e,t,s){for(let o of e)if(Array.isArray(o)){const e=o.length,s=o[0].length;for(let i=0;i<s;i++)for(let s=0;s<e;s++)t(o[s][i])}else s(o)}function be(e,t){Ee(e,t,t)}function Se(e,t){Ee(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(pe(e))}))}function Ce(e,t,s,o){let i=o;for(let o of e)if(Array.isArray(o)){const e=o.length,s=o[0].length;for(let n=0;n<s;n++)for(let s=0;s<e;s++)i=t(i,o[s][n])}else i=s(i,o);return i}function ye(e,t,s){return Ce(e,t,t,s)}function we(e,t,s){return Ce(e,((e,s)=>"number"==typeof s?t(e,s):e),((e,s)=>t(e,pe(s))),s)}function Ie(e,t,s){return Ce(e,((e,s)=>null!=s?t(e,"number"==typeof s?s:"boolean"==typeof s?ue(s):0):e),((e,s)=>t(e,ue(s))),s)}function xe(e,t){return function(e,t,s){for(let o of e)if(Array.isArray(o)){const e=o.length,s=o[0].length;for(let i=0;i<s;i++)for(let s=0;s<e;s++)if(!t(o[s][i]))return}else if(!s(o))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(fe(e));return me(e)}(e))))}function Te(e,t){let s,o,i=e.substring(0,2);"<="===i||">="===i||"<>"===i?(s=i,o=e.substring(2)):(i=e.substring(0,1),"<"===i||">"===i||"="===i?(s=i,o=e.substring(1)):(s="=",o=e)),te(o)?o=ue(o):"TRUE"!==o&&"FALSE"!==o||(o=me(o));const n={operator:s,operand:o};return"string"==typeof o&&(t&&(o+="*"),n.regexp=function(e){let t="",s="";for(let o of e)"?"===o&&"~"!==s?t+=".":"*"===o&&"~"!==s?t+=".*":("*"!==o&&"?"!==o||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(o)&&(t+="\\"),t+=o),s=o;return new RegExp("^"+t+"$","i")}(o)),n}function Re(e,t){const{operator:s,operand:o}=t;if(void 0===e||void 0===o)return!1;if("number"==typeof o&&"="===s)return ge(e)===ge(o);if("<>"===s||"="===s){let i;return i=typeof e==typeof o&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===o),"="===s?i:!i}if(typeof e==typeof o)switch(s){case"<":return e<o;case">":return e>o;case"<=":return e<=o;case">=":return e>=o}return!1}function Le(e,t,s=!1){const o=e.length;if(o%2==1)throw new Error(a("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const i=e[0].length,n=e[0][0].length;let r=[];for(let t=0;t<o-1;t+=2){const o=e[t];if(!Array.isArray(o)||o.length!==i||o[0].length!==n)throw new Error(a("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=ge(e[t+1]);r.push(Te(l,s))}for(let s=0;s<i;s++)for(let i=0;i<n;i++){let n=!0;for(let t=0;t<o-1;t+=2){if(n=Re(e[t][s][i],r[t/2]),!n)break}n&&t(s,i)}}function Me(e,t){if(void 0===t)return-1;const s=typeof t;let o,i,n,r,a,l,c=0,h=e.length-1;if(typeof e[c]===s&&t<e[c])return-1;if(typeof e[h]===s&&e[h]<=t)return h;for(;h-c>=0;){for(n=Math.ceil((c+h)/2),r=n,a=e[r],l=typeof a;c<=r&&s!==l;)r--,a=e[r],l=typeof a;l===s&&a<=t&&(void 0===o||o<a||o===a&&i<r)&&(o=a,i=r),l===s&&a>t?h=r-1:c=n+1}return void 0!==i?i:-1}class Ae{constructor(){this.content={}}add(e,t){return this.content[e]=t,this}get(e){const t=this.content[e];if(!t&&!(e in this.content))throw new Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}remove(e){delete this.content[e]}}const _e=/(.*?)\((.*?)\)(.*)/,Oe=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function Ne(e){let t=e.split("\n");const s=[];for(let e of t)e=e.trim(),e&&s.push(ke(e));return s}function ke(e){let t,s=e.match(_e),o=s[1].trim(),i=[],n=!1,r=!1,a=!1;for(let e of s[2].split(",")){const s=e.trim().toUpperCase();let o=Oe.find((e=>s===e));o?i.push(o):"RANGE<ANY>"===s?i.push("RANGE"):"OPTIONAL"===s?n=!0:"REPEATING"===s?r=!0:"LAZY"===s?a=!0:s.startsWith("DEFAULT=")&&(t=e.trim().slice(8))}const l={name:o,description:s[3].trim(),type:i};return n&&(l.optional=!0),r&&(l.repeating=!0),a&&(l.lazy=!0),void 0!==t&&(l.default=!0,l.defaultValue=t),l}function Fe(e){let t=0,s=0,o=0;for(let i of e.args)t++,i.optional||i.repeating||i.default||s++,i.repeating&&o++;const i=e;return i.minArgRequired=s,i.maxArgPossible=o?1/0:t,i.nbrArgRepeating=o,i.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const s=e-t;return e=>{if(e<=s)return e;return s+((e-s)%t||t)}}(t,o),i}var $e;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}($e||($e={}));const De=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),Pe=new Set(["START","ACTIVATE_SHEET","COPY","START_SELECTION","SET_SELECTION","ALTER_SELECTION","START_SELECTION_EXPANSION","PREPARE_SELECTION_EXPANSION","STOP_SELECTION","RESIZE_VIEWPORT","SET_VIEWPORT_OFFSET","SELECT_ALL","SELECT_CELL","SELECT_COLUMN","SELECT_ROW","MOVE_POSITION","SELECT_SEARCH_NEXT_MATCH","SELECT_SEARCH_PREVIOUS_MATCH","REFRESH_SEARCH","UPDATE_SEARCH","CLEAR_SEARCH","EVALUATE_CELLS","SET_CURRENT_CONTENT","SET_FORMULA_VISIBILITY"]),Ue=new Set(["UPDATE_CELL","UPDATE_CELL_POSITION","CLEAR_CELL","DELETE_CONTENT","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","RESIZE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","UNHIDE_COLUMNS_ROWS","SET_GRID_LINES_VISIBILITY","ADD_MERGE","REMOVE_MERGE","CREATE_SHEET","DELETE_SHEET","DUPLICATE_SHEET","MOVE_SHEET","RENAME_SHEET","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","CREATE_CHART","UPDATE_CHART"]);function Ve(e){return Ue.has(e.type)}class Be{constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new Be}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var He,ze,Ze,Ge;e.CommandResult=void 0,(He=e.CommandResult||(e.CommandResult={}))[He.Success=0]="Success",He[He.CancelledForUnknownReason=1]="CancelledForUnknownReason",He[He.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",He[He.MergeIsDestructive=3]="MergeIsDestructive",He[He.CellIsMerged=4]="CellIsMerged",He[He.InvalidTarget=5]="InvalidTarget",He[He.EmptyUndoStack=6]="EmptyUndoStack",He[He.EmptyRedoStack=7]="EmptyRedoStack",He[He.NotEnoughElements=8]="NotEnoughElements",He[He.NotEnoughSheets=9]="NotEnoughSheets",He[He.MissingSheetName=10]="MissingSheetName",He[He.DuplicatedSheetName=11]="DuplicatedSheetName",He[He.DuplicatedSheetId=12]="DuplicatedSheetId",He[He.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",He[He.WrongSheetMove=14]="WrongSheetMove",He[He.WrongSheetPosition=15]="WrongSheetPosition",He[He.InvalidAnchorZone=16]="InvalidAnchorZone",He[He.SelectionOutOfBound=17]="SelectionOutOfBound",He[He.TargetOutOfSheet=18]="TargetOutOfSheet",He[He.WrongPasteSelection=19]="WrongPasteSelection",He[He.EmptyClipboard=20]="EmptyClipboard",He[He.EmptyRange=21]="EmptyRange",He[He.InvalidRange=22]="InvalidRange",He[He.InvalidSheetId=23]="InvalidSheetId",He[He.InputAlreadyFocused=24]="InputAlreadyFocused",He[He.MaximumRangesReached=25]="MaximumRangesReached",He[He.InvalidChartDefinition=26]="InvalidChartDefinition",He[He.EmptyDataSet=27]="EmptyDataSet",He[He.InvalidDataSet=28]="InvalidDataSet",He[He.InvalidLabelRange=29]="InvalidLabelRange",He[He.InvalidAutofillSelection=30]="InvalidAutofillSelection",He[He.WrongComposerSelection=31]="WrongComposerSelection",He[He.MinBiggerThanMax=32]="MinBiggerThanMax",He[He.LowerBiggerThanUpper=33]="LowerBiggerThanUpper",He[He.MidBiggerThanMax=34]="MidBiggerThanMax",He[He.MinBiggerThanMid=35]="MinBiggerThanMid",He[He.FirstArgMissing=36]="FirstArgMissing",He[He.SecondArgMissing=37]="SecondArgMissing",He[He.MinNaN=38]="MinNaN",He[He.MidNaN=39]="MidNaN",He[He.MaxNaN=40]="MaxNaN",He[He.ValueUpperInflectionNaN=41]="ValueUpperInflectionNaN",He[He.ValueLowerInflectionNaN=42]="ValueLowerInflectionNaN",He[He.MinInvalidFormula=43]="MinInvalidFormula",He[He.MidInvalidFormula=44]="MidInvalidFormula",He[He.MaxInvalidFormula=45]="MaxInvalidFormula",He[He.ValueUpperInvalidFormula=46]="ValueUpperInvalidFormula",He[He.ValueLowerInvalidFormula=47]="ValueLowerInvalidFormula",He[He.InvalidSortZone=48]="InvalidSortZone",He[He.WaitingSessionConfirmation=49]="WaitingSessionConfirmation",He[He.MergeOverlap=50]="MergeOverlap",He[He.TooManyHiddenElements=51]="TooManyHiddenElements",He[He.Readonly=52]="Readonly",He[He.InvalidOffset=53]="InvalidOffset",He[He.InvalidViewportSize=54]="InvalidViewportSize",He[He.FigureDoesNotExist=55]="FigureDoesNotExist",He[He.DuplicatedFigureId=56]="DuplicatedFigureId",He[He.DuplicatedChartId=57]="DuplicatedChartId",He[He.ChartDoesNotExist=58]="ChartDoesNotExist",function(e){e.FormatFromArgument="FormatFromArgument"}(ze||(ze={})),function(e){e[e.UP=0]="UP",e[e.DOWN=1]="DOWN",e[e.LEFT=2]="LEFT",e[e.RIGHT=3]="RIGHT"}(Ze||(Ze={})),function(e){e[e.Background=0]="Background",e[e.Highlights=1]="Highlights",e[e.Clipboard=2]="Clipboard",e[e.Search=3]="Search",e[e.Chart=4]="Chart",e[e.Selection=5]="Selection",e[e.Autofill=6]="Autofill",e[e.Headers=7]="Headers"}(Ge||(Ge={}));const We={description:a("Absolute value of a number."),args:Ne(`\n value (number) ${a("The number of which to return the absolute value.")}\n `),returns:["NUMBER"],compute:function(e){return Math.abs(ue(e))},isExported:!0},qe={description:a("Inverse cosine of a value, in radians."),args:Ne(`\n value (number) ${a("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=ue(e);return he((()=>Math.abs(t)<=1),a("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},je={description:a("Inverse hyperbolic cosine of a number."),args:Ne(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.")}\n `),returns:["NUMBER"],compute:function(e){const t=ue(e);return he((()=>t>=1),a("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},Xe={description:a("Inverse cotangent of a value."),args:Ne(`\n value (number) ${a("The value for which to calculate the inverse cotangent.")}\n `),returns:["NUMBER"],compute:function(e){const t=ue(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Ye={description:a("Inverse hyperbolic cotangent of a value."),args:Ne(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=ue(e);return he((()=>Math.abs(t)>1),a("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},Ke={description:a("Inverse sine of a value, in radians."),args:Ne(`\n value (number) ${a("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=ue(e);return he((()=>Math.abs(t)<=1),a("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},Qe={description:a("Inverse hyperbolic sine of a number."),args:Ne(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic sine.")}\n `),returns:["NUMBER"],compute:function(e){return Math.asinh(ue(e))},isExported:!0},Je={description:a("Inverse tangent of a value, in radians."),args:Ne(`\n value (number) ${a("The value for which to calculate the inverse tangent.")}\n `),returns:["NUMBER"],compute:function(e){return Math.atan(ue(e))},isExported:!0},et={description:a("Angle from the X axis to a point (x,y), in radians."),args:Ne(`\n x (number) ${a("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")}\n y (number) ${a("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")}\n `),returns:["NUMBER"],compute:function(e,t){const s=ue(e),o=ue(t);return he((()=>0!==s||0!==o),a("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(o,s)},isExported:!0},tt={description:a("Inverse hyperbolic tangent of a number."),args:Ne(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=ue(e);return he((()=>Math.abs(t)<1),a("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},st={description:a("Rounds number up to nearest multiple of factor."),args:Ne(`\n value (number) ${a("The value to round up to the nearest integer multiple of factor.")}\n factor (number, default=1) ${a("The number to whose multiples value will be rounded.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t=1){const s=ue(e),o=ue(t);return he((()=>o>=0||s<=0),a("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),s.toString())),o?Math.ceil(s/o)*o:0},isExported:!0},ot={description:a("Rounds number up to nearest multiple of factor."),args:Ne(`\n number (number) ${a("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${a("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t=1,s=0){let o=ue(t);if(0===o)return 0;const i=ue(e);if(o=Math.abs(o),i>=0)return Math.ceil(i/o)*o;return 0===ue(s)?-Math.floor(Math.abs(i)/o)*o:-Math.ceil(Math.abs(i)/o)*o},isExported:!0},it={description:a("Rounds number up to nearest multiple of factor."),args:Ne(`\n number (number) ${a("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){return ot.compute(e,t,0)},isExported:!0},nt={description:a("Cosine of an angle provided in radians."),args:Ne(`\n angle (number) ${a("The angle to find the cosine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cos(ue(e))},isExported:!0},rt={description:a("Hyperbolic cosine of any real number."),args:Ne(`\n value (number) ${a("Any real value to calculate the hyperbolic cosine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cosh(ue(e))},isExported:!0},at={description:a("Cotangent of an angle provided in radians."),args:Ne(`\n angle (number) ${a("The angle to find the cotangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=ue(e);return he((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},lt={description:a("Hyperbolic cotangent of any real number."),args:Ne(`\n value (number) ${a("Any real value to calculate the hyperbolic cotangent of.")}\n `),returns:["NUMBER"],compute:function(e){const t=ue(e);return he((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},ct={description:a("Number of empty values."),args:Ne(`\n value1 (any, range) ${a("The first value or range in which to count the number of blanks.")}\n value2 (any, range, repeating) ${a("Additional values or ranges in which to count the number of blanks.")}\n `),returns:["NUMBER"],compute:function(...e){return ye(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},ht={description:a("A conditional count across a range."),args:Ne(`\n range (range) ${a("The range that is tested against criterion.")}\n criterion (string) ${a("The pattern or test to apply to range.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return Le(e,((e,s)=>{t+=1})),t},isExported:!0},dt={description:a("Count values depending on multiple criteria."),args:Ne(`\n criteria_range1 (range) ${a("The range to check against criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${a("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.")}\n criterion2 (string, repeating) ${a("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return Le(e,((e,s)=>{t+=1})),t},isExported:!0};function ut(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const pt={description:a("Counts number of unique values in a range."),args:Ne(`\n value1 (any, range) ${a("The first value or range to consider for uniqueness.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider for uniqueness.")}\n `),returns:["NUMBER"],compute:function(...e){return ye(e,((e,t)=>ut(t)?e.add(t):e),new Set).size}},gt={description:a("Counts number of unique values in a range, filtered by a set of criteria."),args:Ne(`\n range (range) ${a("The range of cells from which the number of unique values will be counted.")}\n criteria_range1 (range) ${a("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${a("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.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=new Set;return Le(t,((t,o)=>{const i=e[t][o];ut(i)&&s.add(i)})),s.size}},ft={description:a("Cosecant of an angle provided in radians."),args:Ne(`\n angle (number) ${a("The angle to find the cosecant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=ue(e);return he((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},mt={description:a("Hyperbolic cosecant of any real number."),args:Ne(`\n value (number) ${a("Any real value to calculate the hyperbolic cosecant of.")}\n `),returns:["NUMBER"],compute:function(e){const t=ue(e);return he((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},vt={description:a("Converts from another base to decimal."),args:Ne(`\n value (string) ${a("The number to convert.")},\n base (number) ${a("The base to convert the value from.")},\n `),returns:["NUMBER"],compute:function(e,t){let s=ue(t);s=Math.floor(s),he((()=>2<=s&&s<=36),a("The base (%s) must be between 2 and 36 inclusive.",s.toString()));const o=ge(e);if(""===o)return 0;he((()=>!!o.match(/^-?[a-z0-9]+$/i)),a("The value (%s) must be a valid base %s representation.",o,s.toString()));const i=parseInt(o,s);return he((()=>!isNaN(i)),a("The value (%s) must be a valid base %s representation.",o,s.toString())),i},isExported:!0},Et={description:a("Converts an angle value in radians to degrees."),args:Ne(`\n angle (number) ${a("The angle to convert from radians to degrees.")}\n `),returns:["NUMBER"],compute:function(e){return 180*ue(e)/Math.PI},isExported:!0},bt={description:a("Euler's number, e (~2.718) raised to a power."),args:Ne(`\n value (number) ${a("The exponent to raise e.")}\n `),returns:["NUMBER"],compute:function(e){return Math.exp(ue(e))},isExported:!0},St={description:a("Rounds number down to nearest multiple of factor."),args:Ne(`\n value (number) ${a("The value to round down to the nearest integer multiple of factor.")}\n factor (number, default=1) ${a("The number to whose multiples value will be rounded.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t=1){const s=ue(e),o=ue(t);return he((()=>o>=0||s<=0),a("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),s.toString())),o?Math.floor(s/o)*o:0},isExported:!0},Ct={description:a("Rounds number down to nearest multiple of factor."),args:Ne(`\n number (number) ${a("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${a("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t=1,s=0){let o=ue(t);if(0===o)return 0;const i=ue(e);if(o=Math.abs(o),i>=0)return Math.floor(i/o)*o;return 0===ue(s)?-Math.ceil(Math.abs(i)/o)*o:-Math.floor(Math.abs(i)/o)*o},isExported:!0},yt={description:a("Rounds number down to nearest multiple of factor."),args:Ne(`\n number (number) ${a("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t=1){return Ct.compute(e,t,0)},isExported:!0},wt={description:a("Whether the provided value is even."),args:Ne(`\n value (number) ${a("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=pe(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},It={description:a("Rounds number up to nearest multiple of factor."),args:Ne(`\n number (number) ${a("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${a("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t=1){return ot.compute(e,t,0)},isExported:!0},xt={description:a("Whether the provided value is even."),args:Ne(`\n value (number) ${a("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=pe(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},Tt={description:a("The logarithm of a number, base e (euler's number)."),args:Ne(`\n value (number) ${a("The value for which to calculate the logarithm, base e.")}\n `),returns:["NUMBER"],compute:function(e){const t=ue(e);return he((()=>t>0),a("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},Rt={description:a("Modulo (remainder) operator."),args:Ne(`\n dividend (number) ${a("The number to be divided to find the remainder.")}\n divisor (number) ${a("The number to divide by.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){const s=ue(t);he((()=>0!==s),a("The divisor must be different from 0."));const o=ue(e)%s;return o>0&&s<0||o<0&&s>0?o+s:o},isExported:!0},Lt={description:a("Rounds a number up to the nearest odd integer."),args:Ne(`\n value (number) ${a("The value to round to the next greatest odd number.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e){const t=ue(e);let s=Math.ceil(Math.abs(t));return s=1&s?s:s+1,t<0?-s:s},isExported:!0},Mt={description:a("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},At={description:a("A number raised to a power."),args:Ne(`\n base (number) ${a("The number to raise to the exponent power.")}\n exponent (number) ${a("The exponent to raise base to.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){const s=ue(e),o=ue(t);return he((()=>s>=0||Number.isInteger(o)),a("The exponent (%s) must be an integer when the base is negative.",o.toString())),Math.pow(s,o)},isExported:!0},_t={description:a("Result of multiplying a series of numbers together."),args:Ne(`\n factor1 (number, range<number>) ${a("The first number or range to calculate for the product.")}\n factor2 (number, range<number>, repeating) ${a("More numbers or ranges to calculate for the product.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(...e){let t=0,s=1;for(let o of e)if(Array.isArray(o))for(let e of o)for(let o of e)"number"==typeof o&&(s*=o,t+=1);else null!=o&&(s*=pe(o),t+=1);return 0===t?0:s},isExported:!0},Ot={description:a("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},Nt={description:a("Random integer between two values, inclusive."),args:Ne(`\n low (number) ${a("The low end of the random range.")}\n high (number) ${a("The high end of the random range.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){let s=ue(e);Number.isInteger(s)||(s=Math.ceil(s));let o=ue(t);return Number.isInteger(o)||(o=Math.floor(o)),he((()=>s<=o),a("The high (%s) must be greater than or equal to the low (%s).",o.toString(),s.toString())),s+Math.ceil((o-s+1)*Math.random())-1},isExported:!0},kt={description:a("Rounds a number according to standard rules."),args:Ne(`\n value (number) ${a("The value to round to places number of places.")}\n places (number, default=0) ${a("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t=0){const s=ue(e);let o=ue(t);const i=Math.abs(s);let n;return 0===o?n=Math.round(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.round(i*Math.pow(10,o))/Math.pow(10,o)),s>=0?n:-n},isExported:!0},Ft={description:a("Rounds down a number."),args:Ne(`\n value (number) ${a("The value to round to places number of places, always rounding down.")}\n places (number, default=0) ${a("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t=0){const s=ue(e);let o=ue(t);const i=Math.abs(s);let n;return 0===o?n=Math.floor(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.floor(i*Math.pow(10,o))/Math.pow(10,o)),s>=0?n:-n},isExported:!0},$t={description:a("Rounds up a number."),args:Ne(`\n value (number) ${a("The value to round to places number of places, always rounding up.")}\n places (number, default=0) ${a("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t=0){const s=ue(e);let o=ue(t);const i=Math.abs(s);let n;return 0===o?n=Math.ceil(i):(Number.isInteger(o)||(o=Math.trunc(o)),n=Math.ceil(i*Math.pow(10,o))/Math.pow(10,o)),s>=0?n:-n},isExported:!0},Dt={description:a("Secant of an angle provided in radians."),args:Ne(`\n angle (number) ${a("The angle to find the secant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cos(ue(e))},isExported:!0},Pt={description:a("Hyperbolic secant of any real number."),args:Ne(`\n value (number) ${a("Any real value to calculate the hyperbolic secant of.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cosh(ue(e))},isExported:!0},Ut={description:a("Sine of an angle provided in radians."),args:Ne(`\n angle (number) ${a("The angle to find the sine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sin(ue(e))},isExported:!0},Vt={description:a("Hyperbolic sine of any real number."),args:Ne(`\n value (number) ${a("Any real value to calculate the hyperbolic sine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sinh(ue(e))},isExported:!0},Bt={description:a("Positive square root of a positive number."),args:Ne(`\n value (number) ${a("The number for which to calculate the positive square root.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e){const t=ue(e);return he((()=>t>=0),a("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},Ht={description:a("Sum of a series of numbers and/or cells."),args:Ne(`\n value1 (number, range<number>) ${a("The first number or range to add together.")}\n value2 (number, range<number>, repeating) ${a("Additional numbers or ranges to add to value1.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(...e){return we(e,((e,t)=>e+t),0)},isExported:!0},zt={description:a("A conditional sum across a range."),args:Ne(`\n criteria_range (range) ${a("The range which is tested against criterion.")}\n criterion (string) ${a("The pattern or test to apply to range.")}\n sum_range (range, default=criteria_range) ${a("The range to be summed, if different from range.")}\n `),returns:["NUMBER"],compute:function(e,t,s){void 0===s&&(s=e);let o=0;return Le([e,t],((e,t)=>{const i=s[e][t];"number"==typeof i&&(o+=i)})),o},isExported:!0},Zt={description:a("Sums a range depending on multiple criteria."),args:Ne(`\n sum_range (range) ${a("The range to sum.")}\n criteria_range1 (range) ${a("The range to check against criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${a("Additional ranges to check.")}\n criterion2 (string, repeating) ${a("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=0;return Le(t,((t,o)=>{const i=e[t][o];"number"==typeof i&&(s+=i)})),s},isExported:!0},Gt={description:a("Tangent of an angle provided in radians."),args:Ne(`\n angle (number) ${a("The angle to find the tangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tan(ue(e))},isExported:!0},Wt={description:a("Hyperbolic tangent of any real number."),args:Ne(`\n value (number) ${a("Any real value to calculate the hyperbolic tangent of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tanh(ue(e))},isExported:!0},qt={description:a("Truncates a number."),args:Ne(`\n value (number) ${a("The value to be truncated.")}\n places (number, default=0) ${a("The number of significant digits to the right of the decimal point to retain.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t=0){const s=ue(e);let o=ue(t);return 0===o?Math.trunc(s):(Number.isInteger(o)||(o=Math.trunc(o)),Math.trunc(s*Math.pow(10,o))/Math.pow(10,o))},isExported:!0};var jt=Object.freeze({__proto__:null,ABS:We,ACOS:qe,ACOSH:je,ACOT:Xe,ACOTH:Ye,ASIN:Ke,ASINH:Qe,ATAN:Je,ATAN2:et,ATANH:tt,CEILING:st,CEILING_MATH:ot,CEILING_PRECISE:it,COS:nt,COSH:rt,COT:at,COTH:lt,COUNTBLANK:ct,COUNTIF:ht,COUNTIFS:dt,COUNTUNIQUE:pt,COUNTUNIQUEIFS:gt,CSC:ft,CSCH:mt,DECIMAL:vt,DEGREES:Et,EXP:bt,FLOOR:St,FLOOR_MATH:Ct,FLOOR_PRECISE:yt,ISEVEN:wt,ISO_CEILING:It,ISODD:xt,LN:Tt,MOD:Rt,ODD:Lt,PI:Mt,POWER:At,PRODUCT:_t,RAND:Ot,RANDBETWEEN:Nt,ROUND:kt,ROUNDDOWN:Ft,ROUNDUP:$t,SEC:Dt,SECH:Pt,SIN:Ut,SINH:Vt,SQRT:Bt,SUM:Ht,SUMIF:zt,SUMIFS:Zt,TAN:Gt,TANH:Wt,TRUNC:qt});const Xt=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function Yt(e){return e.toString(16).padStart(6,"0")}let Kt=0;function Qt(){return Kt=++Kt%Xt.length,Xt[Kt]}function Jt(e){return e.includes("rgb")?function(e){return e.slice(4,-1).split(",").map((e=>parseInt(e,10).toString(16).padStart(2,"0"))).join("").toUpperCase()}(e):(3===(e=e.replace("#","").toUpperCase()).length&&(e=e.split("").reduce(((e,t)=>e+t+t),"")),e)}const es=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),ts=new RegExp(/^\s*('.+'!|[^']+!)?\$?[A-Z]{1,3}\$?[0-9]{1,7}(\s*:\s*\$?[A-Z]{1,3}\$?[0-9]{1,7})?$/,"i");function ss(e){const t=e.split("!"),s=t.pop();return{sheetName:t.join("!")||void 0,xc:s}}function os(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):os(Math.floor(e/26)-1)+os(e%26)}function is(e){const t=(e=e.toUpperCase().trim()).match(es);if(null!==t){const[s,o,i]=t;if(s===e){const e=function(e){let t=0;const s=e.length;for(let o=0;o<s;o++)t+=(e.charCodeAt(o)-65+(o<s-1?1:0))*26**(s-o-1);return t}(o);return[e,parseInt(i,10)-1]}}throw new Error(`Invalid cell description: ${e}`)}function ns(e,t,s={colFixed:!1,rowFixed:!1}){return(s.colFixed?"$":"")+os(e)+(s.rowFixed?"$":"")+String(t+1)}const rs=140,as=20,ls=.035;function cs(e){return as+(rs-as)*Math.exp(-ls*(e-1))}const hs=[{pt:7.5,px:10},{pt:8,px:11},{pt:9,px:12},{pt:10,px:13},{pt:10.5,px:14},{pt:11,px:15},{pt:12,px:16},{pt:14,px:18.7},{pt:15,px:20},{pt:16,px:21.3},{pt:18,px:24},{pt:22,px:29.3},{pt:24,px:32},{pt:26,px:34.7},{pt:36,px:48}],ds={};for(let e of hs)ds[e.pt]=e.px;function us(e){return'"'===e[0]&&'"'===e[e.length-1]?e.slice(1).slice(0,e.length-2):e}function ps(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gs(e){const t=Array.isArray(e)?[]:{};switch(typeof e){case"object":if(null===e)return e;if(!(function(e){return"object"==typeof e&&(null==e?void 0:e.constructor)===Object}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");for(const s in e)t[s]=gs(e[s]);return t;case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function fs(e){var t;return(null===(t=e.match(/\w/g))||void 0===t?void 0:t.length)!==e.length&&(e=`'${e}'`),e}function ms(e,t,s){return e<t?t:e>s?s:e}function vs(e,t,s){const o=s.italic?"italic ":"",i=s.bold?"bold":T,n=s.fontSize||R,r=ds[n];return e.font=`${o}${i} ${r}px ${L}`,e.measureText(t).width}function Es(e,t,s=1){if(t<=e&&s>0)return[];if(0===s)throw new Error("range() step must not be zero");const o=Math.ceil(Math.abs((t-e)/s)),i=Array(o);for(let t=0;t<o;t++)i[t]=e+t*s;return i}function bs(e){return e.reduce(((e,t,s,o)=>{if(1===Math.abs(t-o[s-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*Ss(e,t){t.next();for(const s of e){const e=t.next();yield{...s,next:e.done?void 0:e.value}}}function Cs(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}function ys(e){return null!==q(e)}const ws=/^\[(.+)\]\((.+)\)$/,Is=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function xs(e){return ws.test(e)}function Ts(e,t){return`[${e}](${t})`}function Rs(e){const t=e.match(ws)||[],s=t[1],o=t[2];if(!s||!o)throw new Error(`Could not parse markdown link ${e}.`);return{label:s,url:o}}const Ls="o-spreadsheet://";function Ms(e){if(!xs(e))return!1;const{url:t}=Rs(e);return t.startsWith(Ls)}function As(e){if(e.startsWith(Ls))return e.substr(Ls.length);throw new Error(`${e} is not a valid sheet link`)}function _s(e){return void 0!==e}const Os={};function Ns(e,t){for(let[s,o]of Object.entries(t))if(Fs(o,e))return parseInt(s,10);const s=Object.keys(t),o=0===s.length?0:Math.max(...s.map((e=>parseInt(e,10))));return t[o+1]=e,o+1}function ks(e){let t,s=!1;const o=()=>(s||(t=e(),s=!0),t);return o.map=e=>ks((()=>e(o()))),o}function Fs(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;if(typeof e!=typeof t)return!1;if("object"!=typeof e)return e===t;const s=new Set;Object.keys(e).forEach((e=>s.add(e))),Object.keys(t).forEach((e=>s.add(e)));for(let o of s){if(typeof e[o]!=typeof e[o])return!1;if("object"==typeof e[o]){if(!Fs(e[o],t[o]))return!1}else if(e[o]!==t[o])return!1}return!0}function $s(e){const t=[];let s=0;for(let o=0;o<e;o++){const e={start:s,end:s+b,size:b,name:os(o)};t.push(e),s=e.end}return t}function Ds(e){const t=[];let s=0;for(let o=0;o<e;o++){const e={start:s,end:s+S,size:S,name:String(o+1),cells:{}};t.push(e),s=e.end}return t}function Ps(e,t){var s;const o=[];let i=0;for(let n=0;n<t;n++){const t=e[n]&&e[n].size||b,r=(null===(s=e[n])||void 0===s?void 0:s.isHidden)||!1,a={start:i,end:r?i:i+t,size:t,name:os(n)};r&&(a.isHidden=r),o.push(a),i=a.end}return o}function Us(e,t){var s;const o=[];let i=0;for(let n=0;n<t;n++){const t=e[n]&&e[n].size||S,r=(null===(s=e[n])||void 0===s?void 0:s.isHidden)||!1,a={start:i,end:r?i:i+t,size:t,name:String(n+1),cells:{}};r&&(a.isHidden=r),o.push(a),i=a.end}return o}function Vs(e,t=!1){const s={};for(let o in e){const i=e[o];(i.size!==b||t)&&(s[o]={size:i.size}),i.isHidden&&(s[o]=s[o]||{},s[o].isHidden=i.isHidden)}return s}function Bs(e,t=!1){const s={};for(let o in e){const i=e[o];(i.size!==S||t)&&(s[o]={size:i.size}),i.isHidden&&(s[o]=s[o]||{},s[o].isHidden=i.isHidden)}return s}class Hs{constructor(){this.isFastIdStrategy=!1,this.fastIdStart=0}setIsFastStrategy(e){this.isFastIdStrategy=e}uuidv4(){return this.isFastIdStrategy?(this.fastIdStart++,String(this.fastIdStart)):window.crypto&&window.crypto.getRandomValues?([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16))):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}}function zs(e,t,s){return[Zs(e,"cols",Es(t,e.cols.length)),Zs(e,"rows",Es(s,e.rows.length))]}function Zs(e,t,s){const o=e[t];return s.find((e=>!o[e].isHidden))}function Gs(e,t){let s=e[t].length-1;for(;s>=0&&!0===e[t][s].isHidden;)s--;return e[t][s]}function Ws(e){const t=(e=e.split("!").pop()).replace(/\$/g,"").split(":");let s,o,i,n,r=is(t[0].trim());if(i=n=r[0],s=o=r[1],2===t.length){let e=is(t[1].trim());n=e[0],o=e[1]}return{top:s,bottom:o,left:i,right:n}}function qs(e){let{top:t,bottom:s,left:o,right:i}=Ws(e);return i<o&&([i,o]=[o,i]),s<t&&([s,t]=[t,s]),{top:t,bottom:s,left:o,right:i}}function js(e){return!(isNaN(e.bottom)||isNaN(e.top)||isNaN(e.left)||isNaN(e.right))&&(!(e.top<0||e.left<0||e.right<0||e.bottom<0)&&(e.bottom>=e.top&&e.right>=e.left))}function Xs(e){const{top:t,bottom:s,left:o,right:i}=e;return t===s&&o===i?ns(o,t):`${ns(o,t)}:${ns(i,s)}`}function Ys(e,t,s,o,i){const n="left"===t?"columns":"rows",r="before"===o?s-1:s,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?ao(e,n,"RESIZE",i):r<e[t]?ao(e,n,"MOVE",i):{...e}}function Ks(e,t,s){const o="left"===t?"right":"bottom";let i=e[t],n=e[o];for(let r of s.sort(((e,t)=>t-e)))e[t]>r&&(i--,n--),e[t]<r&&e[o]>=r&&n--;return{...e,[t]:i,[o]:n}}function Qs(e,t){return{top:Math.min(e.top,t.top),left:Math.min(e.left,t.left),bottom:Math.max(e.bottom,t.bottom),right:Math.max(e.right,t.right)}}function Js(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function eo(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function to(e,t,s){const{left:o,right:i,top:n,bottom:r}=s;return e>=o&&e<=i&&t>=n&&t<=r}function so(e,t){const s={};for(let t of e)if(t){const e=qs(t);for(let t=e.left;t<=e.right;t++)void 0===s[t]&&(s[t]=[]),s[t].push({top:e.top,bottom:e.bottom,remove:!1})}for(let e of t){const t=qs(e);for(let e=t.left;e<=t.right;e++)void 0===s[e]&&(s[e]=[]),s[e].push({top:t.top,bottom:t.bottom,remove:!0})}const o=[];for(let[e,t]of Object.entries(s))o.push({col:parseInt(e),ranges:oo(t)});return function(e){const t=e.sort(((e,t)=>e.col-t.col)),s=[];let o=[],i=0;for(let e=0;e<=t.length-1;e++){let n=[];if(i+1===t[e].col)for(let s of t[e].ranges){let i=!1;for(let e of o)s.top==e.top&&s.bottom==e.bottom&&(n.push(e),i=!0);i||n.push({top:s.top,bottom:s.bottom,startCol:t[e].col})}else n=t[e].ranges.map((s=>({top:s.top,bottom:s.bottom,startCol:t[e].col})));const r=o.filter((e=>!n.includes(e)));for(let e of r)s.push({top:e.top,bottom:e.bottom,left:e.startCol,right:i});i=t[e].col,o=n}for(let e of o)s.push({top:e.top,bottom:e.bottom,left:e.startCol,right:i});return s}(o).map(Xs)}function oo(e){const t=new Set,s=new Set;for(let o of e)for(let e=o.top;e<=o.bottom;e++)o.remove?s.add(e):t.add(e);const o=[...t].filter((e=>!s.has(e))).sort(((e,t)=>e-t)),i=[];let n;for(let e of o)n?e===n.bottom+1?n.bottom=e:(i.push({top:n.top,bottom:n.bottom}),n={top:e,bottom:e}):n={top:e,bottom:e};return n&&i.push({top:n.top,bottom:n.bottom}),i}function io(e){return{height:e.bottom-e.top+1,width:e.right-e.left+1}}function no(e){const{width:t,height:s}=io(e);return 1===t||1===s}function ro(e){const t=[],[s,o]=[e.right,e.left].sort(((e,t)=>e-t)),[i,n]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of Es(s,o+1))for(const s of Es(i,n+1))t.push([e,s]);return t}function ao(e,t,s,o){const i="columns"===t?"right":"bottom",n={...e};return"MOVE"===s&&(n["columns"===t?"left":"top"]+=o),n[i]+=o,n}function lo(e){return e.reverse().filter(((e,t,s)=>t===s.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}function co(e){return{top:Math.min(e.top,e.bottom),bottom:Math.max(e.top,e.bottom),left:Math.min(e.left,e.right),right:Math.max(e.left,e.right)}}function ho(e,t,s){let o=[],i=[],n=0,r=0;be([e],(e=>{o.push(e),n+=1})),be([t],(e=>{i.push(e),r+=1})),he((()=>n===r),a("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",n.toString(),r.toString()));let l=0,c=0,h=0;for(let e=0;e<n;e++){const t=o[e],s=i[e];"number"==typeof t&&"number"==typeof s&&(l+=1,c+=t,h+=s)}he((()=>0!==l&&(!s||1!==l)),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const d=c/l,u=h/l;let p=0;for(let e=0;e<n;e++){const t=o[e],s=i[e];"number"==typeof t&&"number"==typeof s&&(p+=(t-d)*(s-u))}return p/(l-(s?1:0))}function uo(e,t,s){let o=0,i=0;const n=s?Ie:we;i=n(e,((e,t)=>(o+=1,e+t)),0),he((()=>0!==o&&(!t||1!==o)),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const r=i/o;return n(e,((e,t)=>e+Math.pow(t-r,2)),0)/(o-(t?1:0))}function po(e,t,s){const o=ue(t);he((()=>s?0<=o&&o<=1:0<o&&o<1),a("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let i,n=[],r=0;be(e,(e=>{"number"==typeof e&&(i=Me(n,e),n.splice(i+1,0,e),r++)})),he((()=>0!==r),a("[[FUNCTION_NAME]] has no valid input data."));let l=(r+(s?-1:1))*o;if(s||(he((()=>1<=l&&l<=r),a("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),l--),Number.isInteger(l))return n[l];const c=Math.ceil(l),h=Math.floor(l);return n[c]*(l-h)+n[h]*(c-l)}const go={description:a("Average magnitude of deviations from mean."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;const s=we(e,((e,s)=>(t+=1,e+s)),0);he((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const o=s/t;return we(e,((e,t)=>e+Math.abs(o-t)),0)/t},isExported:!0},fo={description:a("Numerical average value in a dataset, ignoring text."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the average value.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(...e){let t=0;const s=we(e,((e,s)=>(t+=1,e+s)),0);return he((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/t},isExported:!0},mo=a("[[FUNCTION_NAME]] has mismatched range sizes."),vo=a("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),Eo={description:a("Weighted average."),args:Ne(`\n values (number, range<number>) ${a("Values to average.")}\n weights (number, range<number>) ${a("Weights for each corresponding value.")}\n additional_values (number, range<number>, repeating) ${a("Additional values to average.")}\n additional_weights (number, range<number>, repeating) ${a("Additional weights.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(...e){let t,s,o=0,i=0;he((()=>e.length%2==0),a("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let n=0;n<e.length-1;n+=2)if(t=e[n],s=e[n+1],Array.isArray(t)){he((()=>Array.isArray(s)),mo);let e=t.length,n=t[0].length;he((()=>e===s.length&&n===s[0].length),mo);for(let r=0;r<e;r++)for(let e=0;e<n;e++){let n=t[r][e],l=s[r][e],c="number"==typeof n,h="number"==typeof l;he((()=>c===h),a("[[FUNCTION_NAME]] expects number values.")),h&&(he((()=>l>=0),vo),o+=n*l,i+=l)}}else s=ue(s),t=ue(t),he((()=>s>=0),vo),o+=t*s,i+=s;return he((()=>0!==i),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/i}},bo={description:a("Numerical average value in a dataset."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the average value.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(...e){let t=0;const s=Ie(e,((e,s)=>(t+=1,e+s)),0);return he((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/t},isExported:!0},So={description:a("Average of values depending on criteria."),args:Ne(`\n criteria_range (range) ${a("The range to check against criterion.")}\n criterion (string) ${a("The pattern or test to apply to criteria_range.")}\n average_range (range, default=criteria_range) ${a("The range to average. If not included, criteria_range is used for the average instead.")}\n `),returns:["NUMBER"],compute:function(e,t,s){null==s&&(s=e);let o=0,i=0;return Le([e,t],((t,n)=>{const r=(s||e)[t][n];"number"==typeof r&&(o+=1,i+=r)})),he((()=>0!==o),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/o},isExported:!0},Co={description:a("Average of values depending on multiple criteria."),args:Ne(`\n average_range (range) ${a("The range to average.")}\n criteria_range1 (range) ${a("The range to check against criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${a("Additional criteria_range and criterion to check.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=0,o=0;return Le(t,((t,i)=>{const n=e[t][i];"number"==typeof n&&(s+=1,o+=n)})),he((()=>0!==s),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/s},isExported:!0},yo={description:a("The number of numeric values in dataset."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range to consider when counting.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;for(let s of e)if(Array.isArray(s))for(let e of s)for(let s of e)"number"==typeof s&&(t+=1);else("string"!=typeof s||te(s)||q(s))&&(t+=1);return t},isExported:!0},wo={description:a("The number of values in a dataset."),args:Ne(`\n value1 (any, range) ${a("The first value or range to consider when counting.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){return ye(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},Io={description:a("The covariance of a dataset."),args:Ne(`\n data_y (any, range) ${a("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${a("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return ho(e,t,!1)},isExported:!0},xo={description:a("The covariance of a dataset."),args:Ne(`\n data_y (any, range) ${a("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${a("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return ho(e,t,!1)},isExported:!0},To={description:a("The sample covariance of a dataset."),args:Ne(`\n data_y (any, range) ${a("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${a("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return ho(e,t,!0)},isExported:!0},Ro={description:a("Nth largest element from a data set."),args:Ne(`\n data (any, range) ${a("Array or range containing the dataset to consider.")}\n n (number) ${a("The rank from largest to smallest of the element to return.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){const s=Math.trunc(ue(t));let o,i=[],n=0;be([e],(e=>{"number"==typeof e&&(o=Me(i,e),i.splice(o+1,0,e),n++,n>s&&(i.shift(),n--))}));const r=i.shift();return he((()=>void 0!==r),a("[[FUNCTION_NAME]] has no valid input data.")),he((()=>n>=s),a("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s.toString())),r},isExported:!0},Lo={description:a("Maximum value in a numeric dataset."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the maximum value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the maximum value.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(...e){const t=we(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},Mo={description:a("Maximum numeric value in a dataset."),args:Ne(`\n value1 (any, range) ${a("The first value or range to consider when calculating the maximum value.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider when calculating the maximum value.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(...e){const t=Ie(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},Ao={description:a("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:Ne(`\n range (range) ${a("The range of cells from which the maximum will be determined.")}\n criteria_range1 (range) ${a("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${a("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.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=-1/0;return Le(t,((t,o)=>{const i=e[t][o];"number"==typeof i&&(s=s<i?i:s)})),s===-1/0?0:s},isExported:!0},_o={description:a("Median value in a numeric dataset."),args:Ne(`\n value1 (any, range) ${a("The first value or range to consider when calculating the median value.")}\n value2 (any, range, repeating) ${a("Additional values or ranges to consider when calculating the median value.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(...e){let t=[];return Se(e,(e=>{t.push(e)})),po(t,.5,!0)},isExported:!0},Oo={description:a("Minimum value in a numeric dataset."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the minimum value.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(...e){const t=we(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},No={description:a("Minimum numeric value in a dataset."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to consider when calculating the minimum value.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(...e){const t=Ie(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},ko={description:a("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:Ne(`\n range (range) ${a("The range of cells from which the minimum will be determined.")}\n criteria_range1 (range) ${a("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${a("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${a("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.")}\n criterion2 (string, repeating) ${a("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let s=1/0;return Le(t,((t,o)=>{const i=e[t][o];"number"==typeof i&&(s=s>i?i:s)})),s===1/0?0:s},isExported:!0},Fo={description:a("Value at a given percentile of a dataset."),args:Ne(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n percentile (number) ${a("The percentile whose value within data will be calculated and returned.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){return Do.compute(e,t)},isExported:!0},$o={description:a("Value at a given percentile of a dataset exclusive of 0 and 1."),args:Ne(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n percentile (number) ${a("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){return po([e],t,!1)},isExported:!0},Do={description:a("Value at a given percentile of a dataset."),args:Ne(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n percentile (number) ${a("The percentile whose value within data will be calculated and returned.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){return po([e],t,!0)},isExported:!0},Po={description:a("Value nearest to a specific quartile of a dataset."),args:Ne(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n quartile_number (number) ${a("Which quartile value to return.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){return Vo.compute(e,t)},isExported:!0},Uo={description:a("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:Ne(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n quartile_number (number) ${a("Which quartile value, exclusive of 0 and 4, to return.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){return po([e],.25*Math.trunc(ue(t)),!1)},isExported:!0},Vo={description:a("Value nearest to a specific quartile of a dataset."),args:Ne(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n quartile_number (number) ${a("Which quartile value to return.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){return po([e],.25*Math.trunc(ue(t)),!0)},isExported:!0},Bo={description:a("Nth smallest element in a data set."),args:Ne(`\n data (any, range) ${a("The array or range containing the dataset to consider.")}\n n (number) ${a("The rank from smallest to largest of the element to return.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){const s=Math.trunc(ue(t));let o,i=[],n=0;be([e],(e=>{"number"==typeof e&&(o=Me(i,e),i.splice(o+1,0,e),n++,n>s&&(i.pop(),n--))}));const r=i.pop();return he((()=>void 0!==r),a("[[FUNCTION_NAME]] has no valid input data.")),he((()=>n>=s),a("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s.toString())),r},isExported:!0},Ho={description:a("Standard deviation."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(jo.compute(...e))},isExported:!0},zo={description:a("Standard deviation of entire population."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Xo.compute(...e))},isExported:!0},Zo={description:a("Standard deviation."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Yo.compute(...e))},isExported:!0},Go={description:a("Standard deviation of sample (text as 0)."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Ko.compute(...e))},isExported:!0},Wo={description:a("Standard deviation of entire population."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Qo.compute(...e))},isExported:!0},qo={description:a("Standard deviation of entire population (text as 0)."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(Jo.compute(...e))},isExported:!0},jo={description:a("Variance."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return uo(e,!0,!1)},isExported:!0},Xo={description:a("Variance of entire population."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return uo(e,!1,!1)},isExported:!0},Yo={description:a("Variance."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return uo(e,!0,!1)},isExported:!0},Ko={description:a("Variance of sample (text as 0)."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return uo(e,!0,!0)},isExported:!0},Qo={description:a("Variance of entire population."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return uo(e,!1,!1)},isExported:!0},Jo={description:a("Variance of entire population (text as 0)."),args:Ne(`\n value1 (number, range<number>) ${a("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${a("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return uo(e,!1,!0)},isExported:!0};var ei=Object.freeze({__proto__:null,AVEDEV:go,AVERAGE:fo,AVERAGE_WEIGHTED:Eo,AVERAGEA:bo,AVERAGEIF:So,AVERAGEIFS:Co,COUNT:yo,COUNTA:wo,COVAR:Io,COVARIANCE_P:xo,COVARIANCE_S:To,LARGE:Ro,MAX:Lo,MAXA:Mo,MAXIFS:Ao,MEDIAN:_o,MIN:Oo,MINA:No,MINIFS:ko,PERCENTILE:Fo,PERCENTILE_EXC:$o,PERCENTILE_INC:Do,QUARTILE:Po,QUARTILE_EXC:Uo,QUARTILE_INC:Vo,SMALL:Bo,STDEV:Ho,STDEV_P:zo,STDEV_S:Zo,STDEVA:Go,STDEVP:Wo,STDEVPA:qo,VAR:jo,VAR_P:Xo,VAR_S:Yo,VARA:Ko,VARP:Qo,VARPA:Jo});function ti(e,t,s){var o;const i=new Map,n=e.length;for(let t=n-1;t>=0;t--)i.set(ge(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(a("The field must be a number or a string"));let r;if("number"==typeof t){if(r=Math.trunc(t)-1,r<0||n-1<r)throw new Error(a("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),n.toString()))}else{const e=ge(t).toUpperCase();if(r=null!==(o=i.get(e))&&void 0!==o?o:-1,-1===r)throw new Error(a("The field (%s) must be one of %s.",ge(t),[...i.keys()].toString()))}const l=s[0].length;if(l<2)throw new Error(a("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const h=e[0].length;for(let t=1;t<l;t++){let o=[],n=!0;for(let r=0;r<s.length;r++){const a=ge(s[r][0]).toUpperCase(),l=i.get(a),c=s[r][t];if(void 0!==c){if(void 0===l){n=!1;break}o.push([e[l].slice(1,h)]),o.push(c)}}if(n){if(!(o.length>0)){c=new Set(Array(h-1).keys());break}Le(o,((e,t)=>{c.add(t)}),!0)}}const d=e[r];return[...c].map((e=>d[e+1]))}const si=Ne(`\n database (range) ${a("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.")}\n field (any) ${a("Indicates which column in database contains the values to be extracted and operated on.")}\n criteria (range) ${a("An array or range containing zero or more criteria to filter the database values by before operating.")}\n`),oi={description:a("Average of a set of values from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return fo.compute([o])},isExported:!0},ii={description:a("Counts values from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return yo.compute([o])},isExported:!0},ni={description:a("Counts values and text from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return wo.compute([o])},isExported:!0},ri={description:a("Single value from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return he((()=>1===o.length),a("More than one match found in DGET evaluation.")),o[0]},isExported:!0},ai={description:a("Maximum of values from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return Lo.compute([o])},isExported:!0},li={description:a("Minimum of values from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return Oo.compute([o])},isExported:!0},ci={description:a("Product of values from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return _t.compute([o])},isExported:!0},hi={description:a("Standard deviation of population sample from table."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return Ho.compute([o])},isExported:!0},di={description:a("Standard deviation of entire population from table."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return Wo.compute([o])},isExported:!0},ui={description:a("Sum of values from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return Ht.compute([o])},isExported:!0},pi={description:a("Variance of population sample from table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return jo.compute([o])},isExported:!0},gi={description:a("Variance of a population from a table-like range."),args:si,returns:["NUMBER"],compute:function(e,t,s){const o=ti(e,t,s);return Qo.compute([o])},isExported:!0};var fi=Object.freeze({__proto__:null,DAVERAGE:oi,DCOUNT:ii,DCOUNTA:ni,DGET:ri,DMAX:ai,DMIN:li,DPRODUCT:ci,DSTDEV:hi,DSTDEVP:di,DSUM:ui,DVAR:pi,DVARP:gi});const mi=new U(1899,11,30);function vi(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}const Ei={description:a("Converts year/month/day into a date."),args:Ne(`\n year (number) ${a("The year component of the date.")}\n month (number) ${a("The month component of the date.")}\n day (number) ${a("The day component of the date.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t,s){let o=Math.trunc(ue(e));const i=Math.trunc(ue(t)),n=Math.trunc(ue(s));he((()=>0<=o&&o<=9999),a("The year (%s) must be between 0 and 9999 inclusive.",o.toString())),o<1900&&(o+=1900);const r=new U(o,i-1,n).getTime()-mi.getTime();return he((()=>r>=0),a("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),Math.round(r/864e5)},isExported:!0},bi={description:a("Converts a date string to a date value."),args:Ne(`\n date_string (string) ${a("The string representing the date.")}\n `),returns:["NUMBER"],compute:function(e){const t=ge(e),s=q(t);return he((()=>null!==s),a("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(s.value)},isExported:!0},Si={description:a("Day of the month that a specific date falls on."),args:Ne(`\n date (string) ${a("The date from which to extract the day.")}\n `),returns:["NUMBER"],compute:function(e){return ve(e).getDate()},isExported:!0},Ci={description:a("Number of days between two dates."),args:Ne(`\n end_date (date) ${a("The end of the date range.")}\n start_date (date) ${a("The start of the date range.")}\n `),returns:["NUMBER"],compute:function(e,t){const s=ve(e),o=ve(t),i=s.getTime()-o.getTime();return Math.round(i/864e5)},isExported:!0},yi={description:a("Date a number of months before/after another date."),args:Ne(`\n start_date (date) ${a("The date from which to calculate the result.")}\n months (number) ${a("The number of months before (negative) or after (positive) 'start_date' to calculate.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t){const s=ve(e),o=Math.trunc(ue(t)),i=s.getFullYear(),n=s.getMonth(),r=s.getDate(),a=new U(i,n+o,r).getTime()-mi.getTime();return Math.round(a/864e5)},isExported:!0},wi={description:a("Last day of a month before or after a date."),args:Ne(`\n start_date (date) ${a("The date from which to calculate the result.")}\n months (number) ${a("The number of months before (negative) or after (positive) 'start_date' to consider.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t){const s=ve(e),o=Math.trunc(ue(t)),i=s.getFullYear(),n=s.getMonth(),r=new U(i,n+o+1,0).getTime()-mi.getTime();return Math.round(r/864e5)},isExported:!0},Ii={description:a("Hour component of a specific time."),args:Ne(`\n time (date) ${a("The time from which to calculate the hour component.")}\n `),returns:["NUMBER"],compute:function(e){return ve(e).getHours()},isExported:!0},xi={description:a("ISO week number of the year."),args:Ne(`\n date (date) ${a("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.")}\n `),returns:["NUMBER"],compute:function(e){const t=ve(e),s=t.getFullYear();let o=1;for(;4!==new U(s,0,o).getDay();)o+=1;const i=new U(s,0,o-3);let n=31;for(;4!==new U(s,11,n).getDay();)n-=1;const r=new U(s,11,n+3);let a,l;switch(a=i.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=i;break;case 1:l=new U(s,11,n+3+1);break;case-1:let e=1;for(;4!==new U(s-1,0,e).getDay();)e+=1;l=new U(s-1,0,e-3)}const c=(t.getTime()-l.getTime())/864e5;return Math.floor(c/7)+1},isExported:!0},Ti={description:a("Minute component of a specific time."),args:Ne(`\n time (date) ${a("The time from which to calculate the minute component.")}\n `),returns:["NUMBER"],compute:function(e){return ve(e).getMinutes()},isExported:!0},Ri={description:a("Month of the year a specific date falls in"),args:Ne(`\n date (date) ${a("The date from which to extract the month.")}\n `),returns:["NUMBER"],compute:function(e){return ve(e).getMonth()+1},isExported:!0},Li={description:a("Net working days between two provided days."),args:Ne(`\n start_date (date) ${a("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${a("The end date of the period from which to calculate the number of net working days.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the date serial numbers to consider holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,s){return Ai.compute(e,t,1,s)},isExported:!0};function Mi(e){if("string"==typeof e){he((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),a('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let s=0;s<7;s++)"1"===e[s]&&t.push((s+1)%7);return t}if("number"==typeof e)return he((()=>1<=e&&e<=7||11<=e&&e<=17),a("The weekend (%s) must be a string or a number in the range 1-7 or 11-17.",e.toString())),e<=7?[e-2==-1?6:e-2,e-1]:[e-11];throw Error(a("The weekend (%s) must be a number or a string.",e.toString()))}const Ai={description:a("Net working days between two dates (specifying weekends)."),args:Ne(`\n start_date (date) ${a("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${a("The end date of the period from which to calculate the number of net working days.")}\n weekend (any, default=1) ${a("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the dates to consider as holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1,o){const i=ve(e),n=ve(t),r=Mi(s);let a=new Set;void 0!==o&&be([o],(e=>{const t=ve(e);a.add(t.getTime())}));const l=i.getTime()>n.getTime(),c=U.fromTimestamp((l?i:n).getTime());let h=U.fromTimestamp((l?n:i).getTime());const d=c.getTime();let u=h.getTime(),p=0;for(;u<=d;)r.includes(h.getDay())||a.has(u)||(p+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-p:p},isExported:!0},_i={description:a("Current date and time as a date value."),args:[],returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy hh:mm:ss"},compute:function(){let e=U.now();const t=e.getTime()-mi.getTime(),s=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/864e5)+s},isExported:!0},Oi={description:a("Minute component of a specific time."),args:Ne(`\n time (date) ${a("The time from which to calculate the second component.")}\n `),returns:["NUMBER"],compute:function(e){return ve(e).getSeconds()},isExported:!0},Ni={description:a("Converts hour/minute/second into a time."),args:Ne(`\n hour (number) ${a("The hour component of the time.")}\n minute (number) ${a("The minute component of the time.")}\n second (number) ${a("The second component of the time.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"hh:mm:ss a"},compute:function(e,t,s){let o=Math.trunc(ue(e)),i=Math.trunc(ue(t)),n=Math.trunc(ue(s));return i+=Math.floor(n/60),n=n%60+(n<0?60:0),o+=Math.floor(i/60),i=i%60+(i<0?60:0),o%=24,he((()=>o>=0),a("The function [[FUNCTION_NAME]] result cannot be negative")),o/24+i/1440+n/86400},isExported:!0},ki={description:a("Converts a time string into its serial number representation."),args:Ne(`\n time_string (string) ${a("The string that holds the time representation.")}\n `),returns:["NUMBER"],compute:function(e){const t=ge(e),s=q(t);he((()=>null!==s),a("The time_string (%s) cannot be parsed to date/time.",t));const o=s.value-Math.trunc(s.value);return o<0?1+o:o},isExported:!0},Fi={description:a("Current date as a date value."),args:[],returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(){const e=U.now(),t=new U(e.getFullYear(),e.getMonth(),e.getDate()).getTime()-mi.getTime();return Math.round(t/864e5)},isExported:!0},$i={description:a("Day of the week of the date provided (as number)."),args:Ne(`\n date (date) ${a("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.")}\n type (number, default=1) ${a("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.")}\n `),returns:["NUMBER"],compute:function(e,t=1){const s=ve(e),o=Math.round(ue(t)),i=s.getDay();return he((()=>[1,2,3].includes(o)),a("The type (%s) must be 1, 2 or 3.",o.toString())),1===o?i+1:2===o?0===i?7:i:0===i?6:i-1},isExported:!0},Di={description:a("Week number of the year."),args:Ne(`\n date (date) ${a("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.")}\n type (number, default=1) ${a("A number representing the day that a week starts on. Sunday = 1.")}\n `),returns:["NUMBER"],compute:function(e,t=1){const s=ve(e),o=Math.round(ue(t));if(he((()=>1===o||2===o||11<=o&&o<=17||21===o),a("The type (%s) is out of range.",o.toString())),21===o)return xi.compute(e);let i;i=1===o||2===o?o-1:o-10==7?0:o-10;const n=s.getFullYear();let r=1,l=new U(n,0,r);for(;l.getDay()!==i;)r+=1,l=new U(n,0,r);const c=(s.getTime()-l.getTime())/864e5;return c<0?1:Math.floor(c/7)+(1===r?1:2)},isExported:!0},Pi={description:a("Number of working days from start date."),args:Ne(`\n start_date (date) ${a("The date from which to begin counting.")}\n num_days (number) ${a("The number of working days to advance from start_date. If negative, counts backwards.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the dates to consider holidays.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t,s){return Ui.compute(e,t,1,s)},isExported:!0},Ui={description:a("Net working days between two dates (specifying weekends)."),args:Ne(`\n start_date (date) ${a("The date from which to begin counting.")}\n num_days (number) ${a("The number of working days to advance from start_date. If negative, counts backwards.")}\n weekend (any, default=1) ${a("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${a("A range or array constant containing the dates to consider holidays.")}\n `),returns:["DATE"],returnFormat:{specificFormat:"m/d/yyyy"},compute:function(e,t,s=1,o){let i=ve(e),n=Math.trunc(ue(t));"string"==typeof s&&he((()=>"1111111"!==s),a("The weekend (%s) must be different from '1111111'.",s));const r=Mi(s);let l=new Set;void 0!==o&&be([o],(e=>{const t=ve(e);l.add(t.getTime())}));let c=U.fromTimestamp(i.getTime()),h=c.getTime();const d=Math.sign(n);let u=Math.abs(n);for(;u>0;)c.setDate(c.getDate()+d),h=c.getTime(),r.includes(c.getDay())||l.has(h)||(u-=1);const p=h-mi.getTime();return Math.round(p/864e5)},isExported:!0},Vi={description:a("Year specified by a given date."),args:Ne(`\n date (date) ${a("The date from which to extract the year.")}\n `),returns:["NUMBER"],compute:function(e){return ve(e).getFullYear()},isExported:!0},Bi={description:a("Exact number of years between two dates."),args:Ne(`\n start_date (date) ${a("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.")}\n end_date (date) ${a("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.")}\n day_count_convention (number, default=0) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s=0){let o=Math.trunc(ue(e)),i=Math.trunc(ue(t));const n=Math.trunc(ue(s));if(he((()=>o>=0),a("The start_date (%s) must be positive or null.",o.toString())),he((()=>i>=0),a("The end_date (%s) must be positive or null.",i.toString())),he((()=>0<=n&&n<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",n.toString())),o===i)return 0;if(o>i){const e=i;i=o,o=e}const r=ve(o),l=ve(i);let c=r.getDate(),h=l.getDate();const d=r.getMonth(),u=l.getMonth(),p=r.getFullYear(),g=l.getFullYear();let f=0,m=0;switch(n){case 0:31===c&&(c=30),30===c&&31===h&&(h=30),1===d&&c===(vi(p)?29:28)&&(c=30,1===u&&h===(vi(g)?29:28)&&(h=30)),f=p+(30*d+c)/360,m=g+(30*u+h)/360;break;case 1:let e=365;const t=p===g;if(!t&&!(p+1===g)||!t&&d<u||!t&&d===u&&c<h){let t=0,s=0;for(let e=p;e<=g;e++)t++,s+=vi(e)?366:365;e=s/t}else t?vi(p)&&(e=366):(vi(p)&&d<2&&(e=366),vi(g)&&(u>1||1===u&&29===h)&&(e=366));f=o/e,m=i/e;break;case 2:f=o/360,m=i/360;break;case 3:f=o/365,m=i/365;break;case 4:31===c&&(c=30),31===h&&(h=30),f=p+(30*d+c)/360,m=g+(30*u+h)/360}return m-f}};var Hi=Object.freeze({__proto__:null,DATE:Ei,DATEVALUE:bi,DAY:Si,DAYS:Ci,EDATE:yi,EOMONTH:wi,HOUR:Ii,ISOWEEKNUM:xi,MINUTE:Ti,MONTH:Ri,NETWORKDAYS:Li,NETWORKDAYS_INTL:Ai,NOW:_i,SECOND:Oi,TIME:Ni,TIMEVALUE:ki,TODAY:Fi,WEEKDAY:$i,WEEKNUM:Di,WORKDAY:Pi,WORKDAY_INTL:Ui,YEAR:Vi,YEARFRAC:Bi});const zi={description:a("Compare two numeric values, returning 1 if they're equal."),args:Ne(`\n number1 (number) ${a("The first number to compare.")}\n number2 (number, default=0) ${a("The second number to compare.")}\n `),returns:["NUMBER"],compute:function(e,t=0){return ue(e)===ue(t)?1:0},isExported:!0};var Zi=Object.freeze({__proto__:null,DELTA:zi});function Gi(e,t,s,o,i=1e-10){let n,r,l,c=s,h=!1,d=0;do{l=e(c),n=c-l/t(c),r=Math.abs(n-c),c=n,h=r<i||Math.abs(l)<i,he((()=>d<o),a("Function [[FUNCTION_NAME]] didn't find any result")),d++}while(!h);return c}const Wi={description:a("Depreciation via declining balance method."),args:Ne(`\n cost (number) ${a("The initial cost of the asset.")}\n salvage (number) ${a("The value of the asset at the end of depreciation.")}\n life (number) ${a("The number of periods over which the asset is depreciated.")}\n period (number) ${a("The single period within life for which to calculate depreciation.")}\n month (number, optional) ${a("The number of months in the first year of depreciation.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,t,s,o,...i){const n=ue(e),r=ue(t),l=ue(s),c=Math.trunc(ue(o)),h=i.length?Math.trunc(ue(i[0])):12,d=l+(12===h?0:1);he((()=>n>0),a("The cost (%s) must be strictly positive.",n.toString())),he((()=>r>=0),a("The salvage (%s) must be positive or null.",r.toString())),he((()=>l>0),a("The life (%s) must be strictly positive.",l.toString())),he((()=>c>0),a("The period (%s) must be strictly positive.",c.toString())),he((()=>1<=h&&h<=12),a("The month (%s) must be between 1 and 12 inclusive.",h.toString())),he((()=>c<=d),a("The period (%s) must be less than or equal to %s.",c.toString(),d.toString()));const u=h/12;let p=1-Math.pow(r/n,1/l);p=Math.round(1e3*p)/1e3;let g=n,f=n*(1-p*u);for(let e=1;e<c;e++)g=f,f=g*(1-p),e===l&&(f=g*(1-p*(1-u)));return g-f}},qi={description:a("Number of periods for an investment to reach a value."),args:Ne(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n yield (number) ${a("The expected annual yield of the security.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n=0){n=n||0;const r=Math.trunc(ue(e)),l=Math.trunc(ue(t)),c=ue(s),h=ue(o),d=Math.trunc(ue(i)),u=Math.trunc(ue(n));he((()=>r<l),a("The maturity (%s) must be strictly greater than the settlement (%s).",l.toString(),r.toString())),he((()=>c>=0),a("The rate (%s) must be positive or null.",c.toString())),he((()=>h>=0),a("The yield (%s) must be positive or null.",h.toString())),he((()=>[1,2,4].includes(d)),a("The frequency (%s) must be one of %s",d.toString(),[1,2,4].toString())),he((()=>0<=u&&u<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",u.toString()));const p=Bi.compute(r,l,u),g=p-Math.trunc(p)||1/d,f=Math.ceil(p*d),m=c/d,v=h/d;let E=0,b=0;for(let e=1;e<=f;e++){const t=(m+(e===f?1:0))/(1+v)**e;b+=(g+(e-1)/d)*t,E+=t}return 0===E?0:b/E}},ji={description:a("Future value of an annuity investment."),args:Ne(`\n rate (number) ${a("The interest rate.")}\n number_of_periods (number) ${a("The number of payments to be made.")}\n payment_amount (number) ${a("The amount per period to be paid.")}\n present_value (number, default=0) ${a("The current value of the annuity.")}\n end_or_beginning (number, default=0) ${a("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,t,s,o=0,i=0){o=o||0,i=i||0;const n=ue(e),r=ue(t),a=ue(s),l=ue(o),c=me(i)?1:0;return n?-l*(1+n)**r-a*(1+n*c)*((1+n)**r-1)/n:-(l+a*r)}},Xi={description:a("Internal rate of return given periodic cashflows."),args:Ne(`\n cashflow_amounts (number, range<number>) ${a("An array or range containing the income or payments associated with the investment.")}\n rate_guess (number, default=0.1) ${a("An estimate for what the internal rate of return will be.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"0%"},compute:function(e,t=.1){const s=ue(t);he((()=>s>-1),a("The rate_guess (%s) must be strictly greater than -1.",s.toString()));let o=!1,i=!1,n=[];Se([e],(e=>{e>0&&(o=!0),e<0&&(i=!0),n.push(e)})),he((()=>o&&i),a("The cashflow_amounts must include negative and positive values."));const r=n.shift();return Gi((function(e){return function(e,t,s){const o=s.length;let i=0;return s.reduce(((t,s)=>(i++,t+s*e**(o-i))),t*e**o)}(e,r,n)}),(function(e){return function(e,t,s){const o=s.length;let i=0;return s.reduce(((t,s)=>(i++,t+s*(o-i)*e**(o-i-1))),t*o*e**(o-1))}(e,r,n)}),s+1,20,1e-5)-1}},Yi={description:a("Modified Macaulay duration."),args:Ne(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n yield (number) ${a("The expected annual yield of the security.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n=0){return qi.compute(e,t,s,o,i,n)/(1+ue(o)/Math.trunc(ue(i)))}};const Ki={description:a("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:Ne(`\n discount (number) ${a("The discount rate of the investment over one period.")}\n cashflow1 (number, range<number>) ${a("The first future cash flow.")}\n cashflow2 (number, range<number>, repeating) ${a("Additional future cash flows.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,...t){const s=ue(e);return he((()=>-1!==s),a("The discount (%s) must be different from -1.",s.toString())),function(e,t,s){let o=0;return we(s,((t,s)=>(o++,t+s/(1+e)**o)),t)}(s,0,t)}},Qi={description:a("Computes the number of periods needed for an investment to reach a value."),args:Ne(`\n rate (number) ${a("The rate at which the investment grows each period.")}\n present_value (number) ${a("The investment's current value.")}\n future_value (number) ${a("The investment's desired future value.")}\n `),returns:["NUMBER"],compute:function(e,t,s){const o=ue(e),i=ue(t),n=ue(s);return he((()=>o>0),a("The rate (%s) must be strictly positive.",o.toString())),he((()=>i>0),a("The present_value (%s) must be strictly positive.",i.toString())),he((()=>n>0),a("The future_value (%s) must be strictly positive.",n.toString())),(Math.log(n)-Math.log(i))/Math.log(1+o)}},Ji={description:a("Present value of an annuity investment."),args:Ne(`\n rate (number) ${a("The interest rate.")}\n number_of_periods (number) ${a("The number of payments to be made.")}\n payment_amount (number) ${a("The amount per period to be paid.")}\n future_value (number, default=0) ${a("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${a("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],returnFormat:{specificFormat:"#,##0.00"},compute:function(e,t,s,o=0,i=0){o=o||0,i=i||0;const n=ue(e),r=ue(t),a=ue(s),l=ue(o),c=me(i)?1:0;return n?-(a*(1+n*c)*((1+n)**r-1)/n+l)/(1+n)**r:-(l+a*r)}},en={description:a("Price of a security paying periodic interest."),args:Ne(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n yield (number) ${a("The expected annual yield of the security.")}\n redemption (number) ${a("The redemption amount per 100 face value, or par.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n,r=0){r=r||0;const l=Math.trunc(ue(e)),c=Math.trunc(ue(t)),h=ue(s),d=ue(o),u=ue(i),p=Math.trunc(ue(n)),g=Math.trunc(ue(r));he((()=>c>l),a("The maturity (%s) must be strictly greater than the settlement (%s).",c.toString(),l.toString())),he((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),he((()=>d>=0),a("The yield (%s) must be positive or null.",d.toString())),he((()=>u>0),a("The redemption (%s) must be strictly positive.",u.toString())),he((()=>[1,2,4].includes(p)),a("The frequency (%s) must be one of %s.",p.toString(),[1,2,4].toString())),he((()=>0<=g&&g<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",g.toString()));const f=Bi.compute(l,c,g)*p,m=Math.ceil(f),v=f-Math.floor(f)||1,E=1+d/p,b=100*h/p;if(1===m)return(b+u)/(v*d/p+1)-b*(1-v);let S=0;for(let e=1;e<=m;e++)S+=b/E**(e-1+v);return u/E**(m-1+v)+S-b*(1-v)}},tn={description:a("Annual yield of a security paying periodic interest."),args:Ne(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${a("The annualized rate of interest.")}\n price (number) ${a("The price at which the security is bought per 100 face value.")}\n redemption (number) ${a("The redemption amount per 100 face value, or par.")}\n frequency (number) ${a("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n,r=0){r=r||0;const l=Math.trunc(ue(e)),c=Math.trunc(ue(t)),h=ue(s),d=ue(o),u=ue(i),p=Math.trunc(ue(n)),g=Math.trunc(ue(r));he((()=>c>l),a("The maturity (%s) must be strictly greater than the settlement (%s).",c.toString(),l.toString())),he((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),he((()=>d>0),a("The price (%s) must be strictly positive.",d.toString())),he((()=>u>0),a("The redemption (%s) must be strictly positive.",u.toString())),he((()=>[1,2,4].includes(p)),a("The frequency (%s) must be one of %s.",p.toString(),[1,2,4].toString())),he((()=>0<=g&&g<=4),a("The day_count_convention (%s) must between 0 and 4 inclusive.",g.toString()));const f=Bi.compute(l,c,g)*p,m=Math.ceil(f),v=f-Math.floor(f)||1,E=100*h/p;if(1===m){const e=d+E*(1-v);return(u+E-e)*p*(1/v)/e}const b=Gi((function(e){return function(e,t,s,o,i,n){let r=n-(e+i*(1-t))*o**(s-1+t);for(let e=1;e<=s;e++)r+=i*o**(e-1);return r}(d,v,m,e,E,u)}),(function(e){return function(e,t,s,o,i){let n=-(e+i*(1-t))*(s-1+t)*o**(s-2+t);for(let e=1;e<=s;e++)n+=i*(e-1)*o**(e-2);return n}(d,v,m,e,E)}),1+(h+1)/p,100,1e-5);return(b-1)*p}},sn={description:a("Annual yield of a security paying interest at maturity."),args:Ne(`\n settlement (date) ${a("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${a("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n issue (date) ${a("The date the security was initially issued.")}\n rate (number) ${a("The annualized rate of interest.")}\n price (number) ${a("The price at which the security is bought.")}\n day_count_convention (number, default=0 ) ${a("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o,i,n=0){n=n||0;const r=Math.trunc(ue(e)),l=Math.trunc(ue(t)),c=Math.trunc(ue(s)),h=ue(o),d=ue(i),u=Math.trunc(ue(n));he((()=>r>=c),a("The settlement (%s) must be greater than or equal to the issue (%s).",r.toString(),c.toString())),he((()=>l>r),a("The maturity (%s) must be strictly greater than the settlement (%s).",l.toString(),r.toString())),he((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),he((()=>d>0),a("The price (%s) must be strictly positive.",d.toString())),he((()=>0<=u&&u<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",u.toString()));const p=Bi.compute(c,l,u),g=Bi.compute(c,r,u),f=Bi.compute(r,l,u);return(100*(1+h*p)/(d+100*h*g)-1)/f}};var on=Object.freeze({__proto__:null,DB:Wi,DURATION:qi,FV:ji,IRR:Xi,MDURATION:Yi,NPV:Ki,PDURATION:Qi,PV:Ji,PRICE:en,YIELD:tn,YIELDMAT:sn});const nn={description:a("Whether a value is an error."),args:Ne(`value (any, lazy) ${a("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},rn={description:a("Whether a value is `true` or `false`."),args:Ne(`value (any) ${a("The value to be verified as a logical TRUE or FALSE.")}`),returns:["BOOLEAN"],compute:function(e){return"boolean"==typeof e},isExported:!0},an={description:a("Whether a value is non-textual."),args:Ne(`value (any) ${a("The value to be checked.")}`),returns:["BOOLEAN"],compute:function(e){return"string"!=typeof e},isExported:!0},ln={description:a("Whether a value is a number."),args:Ne(`value (any) ${a("The value to be verified as a number.")}`),returns:["BOOLEAN"],compute:function(e){return"number"==typeof e},isExported:!0},cn={description:a("Whether a value is text."),args:Ne(`value (any) ${a("The value to be verified as text.")}`),returns:["BOOLEAN"],compute:function(e){return"string"==typeof e},isExported:!0};var hn=Object.freeze({__proto__:null,ISERROR:nn,ISLOGICAL:rn,ISNONTEXT:an,ISNUMBER:ln,ISTEXT:cn});const dn={description:a("Logical `and` operator."),args:Ne(`\n logical_expression1 (boolean, range<boolean>) ${a("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.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${a("More expressions that represent logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,s=!0;return xe(e,(e=>(t=!0,s=s&&e,s))),he((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0},un={description:a("Returns value depending on logical expression."),args:Ne(`\n logical_expression (boolean) ${a("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")}\n value_if_true (any, lazy) ${a("The value the function returns if logical_expression is TRUE.")}\n value_if_false (any, lazy, default=FALSE) ${a("The value the function returns if logical_expression is FALSE.")}\n `),returns:["ANY"],compute:function(e,t,s=(()=>!1)){const o=me(e)?t():s();return null==o?"":o},isExported:!0},pn={description:a("Value if it is not an error, otherwise 2nd argument."),args:Ne(`\n value (any, lazy) ${a("The value to return if value itself is not an error.")}\n value_if_error (any, lazy, default=${a("An empty value")}) ${a("The value the function returns if value is an error.")}\n `),returns:["ANY"],compute:function(e,t=(()=>"")){let s;try{s=e()}catch(e){s=t()}return null==s?"":s},isExported:!0},gn={description:a("Returns a value depending on multiple logical expressions."),args:Ne(`\n condition1 (boolean, lazy) ${a("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")}\n value1 (any, lazy) ${a("The returned value if condition1 is TRUE.")}\n condition2 (boolean, lazy, repeating) ${a("Additional conditions to be evaluated if the previous ones are FALSE.")}\n value2 (any, lazy, repeating) ${a("Additional values to be returned if their corresponding conditions are TRUE.")}\n `),returns:["ANY"],compute:function(...e){he((()=>e.length%2==0),a("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(me(e[t]()))return e[t+1]();throw new Error(a("No match."))},isExported:!0},fn={description:a("Returns opposite of provided logical value."),args:Ne(`logical_expression (boolean) ${a("An expression or reference to a cell holding an expression that represents some logical value.")}\n `),returns:["BOOLEAN"],compute:function(e){return!me(e)},isExported:!0},mn={description:a("Logical `or` operator."),args:Ne(`\n logical_expression1 (boolean, range<boolean>) ${a("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.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${a("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,s=!1;return xe(e,(e=>(t=!0,s=s||e,!s))),he((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0},vn={description:a("Logical `xor` operator."),args:Ne(`\n logical_expression1 (boolean, range<boolean>) ${a("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.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${a("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,s=!1;return xe(e,(e=>(t=!0,s=s?!e:e,!0))),he((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0};var En=Object.freeze({__proto__:null,AND:dn,IF:un,IFERROR:pn,IFS:gn,NOT:fn,OR:mn,XOR:vn});function bn(e,t){for(let s=0;s<e.length;s++)if(e[s]===t)return s;return-1}const Sn={description:a("Column number of a specified cell."),args:Ne(`cell_reference (meta, default=${a("The cell in which the formula is entered")}) ${a("The cell whose column number will be returned. Column A corresponds to 1.")}\n `),returns:["NUMBER"],compute:function(e){var t;e=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this)),he((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return qs(e).left+1},isExported:!0},Cn={description:a("Number of columns in a specified array or range."),args:Ne(`range (meta) ${a("The range whose column count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=qs(e);return t.right-t.left+1},isExported:!0},yn={description:a("Horizontal lookup"),args:Ne(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n range (range) ${a("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")}\n index (number) ${a("The row index of the value to be returned, where the first row in range is numbered 1.")}\n is_sorted (boolean, default=true) ${a("Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.")}\n `),returns:["ANY"],compute:function(e,t,s,o=true){const i=Math.trunc(ue(s));he((()=>1<=i&&i<=t[0].length),a("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const n=me(o),r=t.map((e=>e[0]));let l;return l=n?Me(r,e):bn(r,e),he((()=>l>-1),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",ge(e))),t[l][i-1]},isExported:!0},wn={description:a("Look up a value."),args:Ne(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n search_array (range) ${a("One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.")}\n result_range (range, optional) ${a("The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.")}\n `),returns:["ANY"],compute:function(e,t,s){let o=t.length,i=t[0].length;const n=i>=o,r=Me(n?t[0]:t.map((e=>e[0])),e);return he((()=>r>=0),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",ge(e))),void 0===s?n?t[o-1][r]:t[r][i-1]:(o=s.length,i=s[0].length,he((()=>1===o||1===i),a("The result_range must be a single row or a single column.")),o>1?(he((()=>r<=o-1),a("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(r+1).toString())),s[r][0]):(he((()=>r<=i-1),a("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(r+1).toString())),s[0][r]))},isExported:!0},In={description:a("Position of item in range that matches value."),args:Ne(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${a("The one-dimensional array to be searched.")}\n search_type (number, default=1) ${a("The search method. 1 (default) finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1){let o=ue(s);const i=t.length,n=t[0].length;he((()=>1===i||1===n),a("The range must be a single row or a single column."));let r=-1;const l=t.flat();switch(o=Math.sign(o),o){case 1:r=Me(l,e);break;case 0:r=bn(l,e);break;case-1:r=function(e,t){const s=typeof t;let o,i,n,r,a,l,c=0,h=e.length-1;if(typeof e[c]===s&&t>e[c])return-1;if(typeof e[h]===s&&e[h]>t)return h;for(;h-c>=0;){for(n=Math.ceil((c+h)/2),r=n,a=e[r],l=typeof a;c<=r&&s!==l;)r--,a=e[r],l=typeof a;l===s&&a>=t&&(void 0===o||o>a||o===a&&i>r)&&(o=a,i=r),l===s&&a<=t?h=r-1:c=n+1}return void 0!==i?i:-1}(l,e)}return he((()=>r>=0),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",ge(e))),r+1},isExported:!0},xn={description:a("Row number of a specified cell."),args:Ne(`cell_reference (meta, default=${a("The cell in which the formula is entered by default")}) ${a("The cell whose row number will be returned.")}`),returns:["NUMBER"],compute:function(e){var t;e=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this)),he((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return qs(e).top+1},isExported:!0},Tn={description:a("Number of rows in a specified array or range."),args:Ne(`range (meta) ${a("The range whose row count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=qs(e);return t.bottom-t.top+1},isExported:!0},Rn={description:a("Vertical lookup."),args:Ne(`\n search_key (any) ${a("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${a("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")}\n index (number) ${a("The column index of the value to be returned, where the first column in range is numbered 1.")}\n is_sorted (boolean, default=true) ${a("Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.")}\n `),returns:["ANY"],compute:function(e,t,s,o=true){const i=Math.trunc(ue(s));he((()=>1<=i&&i<=t.length),a("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const n=me(o),r=t[0];let l;return l=n?Me(r,e):bn(r,e),he((()=>l>-1),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",ge(e))),t[i-1][l]},isExported:!0};var Ln=Object.freeze({__proto__:null,COLUMN:Sn,COLUMNS:Cn,HLOOKUP:yn,LOOKUP:wn,MATCH:In,ROW:xn,ROWS:Tn,VLOOKUP:Rn});const Mn={description:a("Sum of two numbers."),args:Ne(`\n value1 (number) ${a("The first addend.")}\n value2 (number) ${a("The second addend.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){return ue(e)+ue(t)}},An={description:a("Concatenation of two values."),args:Ne(`\n value1 (string) ${a("The value to which value2 will be appended.")}\n value2 (string) ${a("The value to append to value1.")}\n `),returns:["STRING"],compute:function(e,t){return ge(e)+ge(t)},isExported:!0},_n={description:a("One number divided by another."),args:Ne(`\n dividend (number) ${a("The number to be divided.")}\n divisor (number) ${a("The number to divide by.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){const s=ue(t);return he((()=>0!==s),a("The divisor must be different from zero.")),ue(e)/s}};function On(e){return null==e}const Nn={number:0,string:"",boolean:!1},kn={description:a("Equal."),args:Ne(`\n value1 (any) ${a("The first value.")}\n value2 (any) ${a("The value to test against value1 for equality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return e=On(e)?Nn[typeof t]:e,t=On(t)?Nn[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function Fn(e,t,s){e=On(e)?Nn[typeof t]:e,t=On(t)?Nn[typeof e]:t,"number"!=typeof e&&(e=ge(e).toUpperCase()),"number"!=typeof t&&(t=ge(t).toUpperCase());const o=typeof e,i=typeof t;return"string"===o&&"number"===i||("string"!==i||"number"!==o)&&s(e,t)}const $n={description:a("Strictly greater than."),args:Ne(`\n value1 (any) ${a("The value to test as being greater than value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return Fn(e,t,((e,t)=>e>t))}},Dn={description:a("Greater than or equal to."),args:Ne(`\n value1 (any) ${a("The value to test as being greater than or equal to value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return Fn(e,t,((e,t)=>e>=t))}},Pn={description:a("Less than."),args:Ne(`\n value1 (any) ${a("The value to test as being less than value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!Dn.compute(e,t)}},Un={description:a("Less than or equal to."),args:Ne(`\n value1 (any) ${a("The value to test as being less than or equal to value2.")}\n value2 (any) ${a("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!$n.compute(e,t)}},Vn={description:a("Difference of two numbers."),args:Ne(`\n value1 (number) ${a("The minuend, or number to be subtracted from.")}\n value2 (number) ${a("The subtrahend, or number to subtract from value1.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){return ue(e)-ue(t)}},Bn={description:a("Product of two numbers"),args:Ne(`\n factor1 (number) ${a("The first multiplicand.")}\n factor2 (number) ${a("The second multiplicand.")}\n `),returns:["NUMBER"],returnFormat:ze.FormatFromArgument,compute:function(e,t){return ue(e)*ue(t)}},Hn={description:a("Not equal."),args:Ne(`\n value1 (any) ${a("The first value.")}\n value2 (any) ${a("The value to test against value1 for inequality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!kn.compute(e,t)}},zn={description:a("A number raised to a power."),args:Ne(`\n base (number) ${a("The number to raise to the exponent power.")}\n exponent (number) ${a("The exponent to raise base to.")}\n `),returns:["NUMBER"],compute:function(e,t){return At.compute(e,t)}},Zn={description:a("A number with the sign reversed."),args:Ne(`\n value (number) ${a("The number to have its sign reversed. Equivalently, the number to multiply by -1.")}\n `),returnFormat:ze.FormatFromArgument,returns:["NUMBER"],compute:function(e){return-ue(e)}},Gn={description:a("Value interpreted as a percentage."),args:Ne(`\n percentage (number) ${a("The value to interpret as a percentage.")}\n `),returns:["NUMBER"],compute:function(e){return ue(e)/100}},Wn={description:a("A specified number, unchanged."),args:Ne(`\n value (any) ${a("The number to return.")}\n `),returnFormat:ze.FormatFromArgument,returns:["ANY"],compute:function(e){return e}};var qn=Object.freeze({__proto__:null,ADD:Mn,CONCAT:An,DIVIDE:_n,EQ:kn,GT:$n,GTE:Dn,LT:Pn,LTE:Un,MINUS:Vn,MULTIPLY:Bn,NE:Hn,POW:zn,UMINUS:Zn,UNARY_PERCENT:Gn,UPLUS:Wn});const jn={description:a("Gets character associated with number."),args:Ne(`\n table_number (number) ${a("The number of the character to look up from the current Unicode table in decimal format.")}\n `),returns:["STRING"],compute:function(e){const t=Math.trunc(ue(e));return he((()=>t>=1),a("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},Xn={description:a("Appends strings to one another."),args:Ne(`\n string1 (string, range<string>) ${a("The initial string.")}\n string2 (string, range<string>, repeating) ${a("More strings to append in sequence.")}\n `),returns:["STRING"],compute:function(...e){return ye(e,((e,t)=>e+ge(t)),"")},isExported:!0},Yn={description:a("Tests whether two strings are identical."),args:Ne(`\n string1 (string) ${a("The first string to compare.")}\n string2 (string) ${a("The second string to compare.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return ge(e)===ge(t)},isExported:!0},Kn={description:a("First position of string found in text, case-sensitive."),args:Ne(`\n search_for (string) ${a("The string to look for within text_to_search.")}\n text_to_search (string) ${a("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${a("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1){const o=ge(e),i=ge(t),n=ue(s);he((()=>""!==i),a("The text_to_search must be non-empty.")),he((()=>n>=1),a("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const r=i.indexOf(o,n-1);return he((()=>r>=0),a("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o.toString(),i)),r+1},isExported:!0},Qn={description:a("Concatenates elements of arrays with delimiter."),args:Ne(`\n delimiter (string) ${a("The character or string to place between each concatenated value.")}\n value_or_array1 (string, range<string>) ${a("The value or values to be appended using delimiter.")}\n value_or_array2 (string, range<string>, repeating) ${a("More values to be appended using delimiter.")}\n `),returns:["STRING"],compute:function(e,...t){const s=ge(e);return ye(t,((e,t)=>(e?e+s:"")+ge(t)),"")}},Jn={description:a("Substring from beginning of specified string."),args:Ne(`\n text (string) ${a("The string from which the left portion will be returned.")}\n number_of_characters (number, optional) ${a("The number of characters to return from the left side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const s=t.length?ue(t[0]):1;return he((()=>s>=0),a("The number_of_characters (%s) must be positive or null.",s.toString())),ge(e).substring(0,s)},isExported:!0},er={description:a("Length of a string."),args:Ne(`\n text (string) ${a("The string whose length will be returned.")}\n `),returns:["NUMBER"],compute:function(e){return ge(e).length},isExported:!0},tr={description:a("Converts a specified string to lowercase."),args:Ne(`\n text (string) ${a("The string to convert to lowercase.")}\n `),returns:["STRING"],compute:function(e){return ge(e).toLowerCase()},isExported:!0},sr={description:a("Replaces part of a text string with different text."),args:Ne(`\n text (string) ${a("The text, a part of which will be replaced.")}\n position (number) ${a("The position where the replacement will begin (starting from 1).")}\n length (number) ${a("The number of characters in the text to be replaced.")}\n new_text (string) ${a("The text which will be inserted into the original text.")}\n `),returns:["STRING"],compute:function(e,t,s,o){const i=ue(t);he((()=>i>=1),a("The position (%s) must be greater than or equal to 1.",i.toString()));const n=ge(e),r=ue(s),l=ge(o);return n.substring(0,i-1)+l+n.substring(i-1+r)},isExported:!0},or={description:a("A substring from the end of a specified string."),args:Ne(`\n text (string) ${a("The string from which the right portion will be returned.")}\n number_of_characters (number, optional) ${a("The number of characters to return from the right side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const s=t.length?ue(t[0]):1;he((()=>s>=0),a("The number_of_characters (%s) must be positive or null.",s.toString()));const o=ge(e),i=o.length;return o.substring(i-s,i)},isExported:!0},ir={description:a("First position of string found in text, ignoring case."),args:Ne(`\n search_for (string) ${a("The string to look for within text_to_search.")}\n text_to_search (string) ${a("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${a("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,s=1){const o=ge(e).toLowerCase(),i=ge(t).toLowerCase(),n=ue(s);he((()=>""!==i),a("The text_to_search must be non-empty.")),he((()=>n>=1),a("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const r=i.indexOf(o,n-1);return he((()=>r>=0),a("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,i)),r+1},isExported:!0},nr={description:a("Replaces existing text with new text in a string."),args:Ne(`\n text_to_search (string) ${a("The text within which to search and replace.")}\n search_for (string) ${a("The string to search for within text_to_search.")}\n replace_with (string) ${a("The string that will replace search_for.")}\n occurrence_number (number, optional) ${a("The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.")}\n `),returns:["NUMBER"],compute:function(e,t,s,o){const i=ue(o);he((()=>i>=0),a("The occurrenceNumber (%s) must be positive or null.",i.toString()));const n=ge(e),r=ge(t);if(""===r)return n;const l=ge(s),c=new RegExp(ps(r),"g");if(0===i)return n.replace(c,l);let h=0;return n.replace(c,(e=>++h===i?l:e))},isExported:!0},rr={description:a("Combines text from multiple strings and/or arrays."),args:Ne(`\n delimiter (string) ${a(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")}\n ignore_empty (boolean) ${a("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")}\n text1 (string, range<string>) ${a("Any text item. This could be a string, or an array of strings in a range.")}\n text2 (string, range<string>, repeating) ${a("Additional text item(s).")}\n `),returns:["STRING"],compute:function(e,t,...s){const o=ge(e),i=me(t);let n=0;return ye(s,((e,t)=>i&&""===ge(t)?e:(n++?e+o:"")+ge(t)),"")},isExported:!0},ar={description:a("Removes space characters."),args:Ne(`\n text (string) ${a("The text or reference to a cell containing text to be trimmed.")}\n `),returns:["STRING"],compute:function(e){return ge(e).trim()},isExported:!0},lr={description:a("Converts a specified string to uppercase."),args:Ne(`\n text (string) ${a("The string to convert to uppercase.")}\n `),returns:["STRING"],compute:function(e){return ge(e).toUpperCase()},isExported:!0};const cr={database:fi,date:Hi,financial:on,info:hn,lookup:Ln,logical:En,math:jt,operators:qn,statistical:ei,text:Object.freeze({__proto__:null,CHAR:jn,CONCATENATE:Xn,EXACT:Yn,FIND:Kn,JOIN:Qn,LEFT:Jn,LEN:er,LOWER:tr,REPLACE:sr,RIGHT:or,SEARCH:ir,SUBSTITUTE:nr,TEXTJOIN:rr,TRIM:ar,UPPER:lr}),engineering:Zi};const hr=new class extends Ae{constructor(){super(...arguments),this.mapping={}}add(e,t){e=e.toUpperCase().replace("_",".");const s=Fe(t);return function(e){let t=!1,s=!1,o=!1;for(let i of e){if(i.type.includes("META")&&i.type.length>1)throw new Error(a("Function ${name} has an argument that has been declared with more than one type whose type 'META'. The 'META' type can only be declared alone."));if(t&&!i.repeating)throw new Error(a("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=s||t||o,n=!(i.optional||i.repeating||i.default);if(e&&n)throw new Error(a("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=i.repeating,s=i.optional,o=i.default}}(s.args),this.mapping[e]=s.compute,super.add(e,s),this}};for(let e in cr){const t=cr[e];for(let s in t){const o=t[s];o.category=e,hr.add(s,{isExported:!1,...o})}}const dr=hr.content,ur="+,-,*,/,:,=,<>,>=,>,<=,<,%,^,&".split(",");function pr(e){const t=e.split(""),s=[];for(;t.length;){let e=Ir(t)||mr(t)||Er(t)||Sr(t)||gr(t)||xr(t)||br(t)||yr(t);e||(e={type:"UNKNOWN",value:t.shift()}),s.push(e)}return s}function gr(e){return"?"===e[0]?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const fr={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function mr(e){if(e[0]in fr){const t=e.shift();return{type:fr[t],value:t}}return null}function vr(e,t){for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;return!0}function Er(e){for(let t of ur)if(vr(e,t))return e.splice(0,t.length),{type:"OPERATOR",value:t};return null}function br(e){const t=function(e){let t="";for(let s=0,o=e.length;s<o;s++)t+=e[s];return t}(e).match(J);return t?(e.splice(0,t[0].length),{type:"NUMBER",value:t[0]}):null}function Sr(e){if('"'===e[0]){const t=e.shift();let s=t;for(;e[0]&&(e[0]!==t||"\\"===s[s.length-1]);)s+=e.shift();return'"'===e[0]&&(s+=e.shift()),{type:"STRING",value:s}}return null}const Cr=/\w|\.|!|\$/;function yr(e){let t="";if("'"===e[0]){let s=e.shift();for(t+=s;e[0];)if(s=e.shift(),t+=s,"'"===s){if(!e[0]||"'"!==e[0])break;s=e.shift(),t+=s}if("'"!==s)return{type:"UNKNOWN",value:t}}for(;e[0]&&e[0].match(Cr);)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in dr)return{type:"FUNCTION",value:e};return e.match(ts)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}const wr=/\s/;function Ir(e){let t=0;for(;e[0]&&e[0].match(wr);)t++,e.shift();return t?{type:"SPACE",value:" ".repeat(t)}:null}function xr(e){return vr(e,O)?(e.splice(0,O.length),{type:"INVALID_REFERENCE",value:O}):null}const Tr=["-","+"],Rr=["*","+","&"],Lr={"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10},Mr=6;function Ar(e){switch(e.type){case"NUMBER":case"SYMBOL":case"REFERENCE":return 0;case"COMMA":return 3;case"LEFT_PAREN":case"RIGHT_PAREN":return 5;case"OPERATOR":return Lr[e.value]||15}throw new Error(a("Unknown token: %s",e.value))}function _r(e,t,s){if("OPERATOR"===t.type){const o=Or(s,Ar(t));return{type:"BIN_OPERATION",value:t.value,left:e,right:o}}throw new Error(k)}function Or(e,t){const s=e.shift();if(!s)throw new Error(k);let o=function(e,t){var s,o,i;switch(e.type){case"DEBUGGER":const n=Or(t,1e3);return n.debug=!0,n;case"NUMBER":return{type:"NUMBER",value:oe(e.value)};case"STRING":return{type:"STRING",value:us(e.value)};case"FUNCTION":if("LEFT_PAREN"!==t.shift().type)throw new Error(a("Wrong function call"));{const o=[];if(t[0]&&"RIGHT_PAREN"!==t[0].type)for("COMMA"===t[0].type?o.push({type:"UNKNOWN",value:""}):o.push(Or(t,Mr));"COMMA"===(null===(s=t[0])||void 0===s?void 0:s.type);){t.shift();const e=t[0];if("RIGHT_PAREN"===(null==e?void 0:e.type)){o.push({type:"UNKNOWN",value:""});break}"COMMA"===(null==e?void 0:e.type)?o.push({type:"UNKNOWN",value:""}):o.push(Or(t,Mr))}const i=t.shift();if(!i||"RIGHT_PAREN"!==i.type)throw new Error(a("Wrong function call"));return{type:"FUNCALL",value:e.value,args:o}}case"INVALID_REFERENCE":throw new Error(a("Invalid reference"));case"REFERENCE":if(":"===(null===(o=t[0])||void 0===o?void 0:o.value)&&"REFERENCE"===(null===(i=t[1])||void 0===i?void 0:i.type)){t.shift();const s=t.shift();return{type:"REFERENCE",value:`${e.value}:${null==s?void 0:s.value}`}}return{type:"REFERENCE",value:e.value};case"SYMBOL":if(["TRUE","FALSE"].includes(e.value.toUpperCase()))return{type:"BOOLEAN",value:"TRUE"===e.value.toUpperCase()};if(e.value)throw new Error(a("Invalid formula"));return{type:"STRING",value:e.value};case"LEFT_PAREN":const r=Or(t,5);if(!t.length||"RIGHT_PAREN"!==t[0].type)throw new Error(a("Unmatched left parenthesis"));return t.shift(),r;default:if("OPERATOR"===e.type&&Tr.includes(e.value))return{type:"UNARY_OPERATION",value:e.value,right:Or(t,Lr[e.value])};throw new Error(a("Unexpected token: %s",e.value))}}(s,e);for(;e[0]&&Ar(e[0])>t;)o=_r(o,e.shift(),e);return o}function Nr(e){return kr(pr(e))}function kr(e){"OPERATOR"===(e=e.filter((e=>"SPACE"!==e.type)))[0].type&&"="===e[0].value&&e.splice(0,1);const t=Or(e,0);if(e.length)throw new Error(k);return t}function Fr(e,t,s){switch(t===e.type&&(e=s(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>Fr(e,t,s)))};case"UNARY_OPERATION":return{...e,right:Fr(e.right,t,s)};case"BIN_OPERATION":return{...e,right:Fr(e.right,t,s),left:Fr(e.left,t,s)};default:return e}}function $r(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>$r(e)));return`${e.value}(${t.join(",")})`;case"NUMBER":return e.value.toString();case"REFERENCE":default:return e.value;case"STRING":return`"${e.value}"`;case"BOOLEAN":return e.value?"TRUE":"FALSE";case"UNARY_OPERATION":return e.value+Dr(e);case"BIN_OPERATION":return function(e){const t=e.value,s=e.left,o=s.value;return"BIN_OPERATION"===s.type&&Lr[o]<Lr[t]?`(${$r(s)})`:$r(s)}(e)+e.value+Dr(e)}}function Dr(e){const t=e.value,s=e.right,o=Lr[s.value],i=Lr[t];let n=!1;return"BIN_OPERATION"!==s.type?n=!1:o<i?n=!0:o!==i||Rr.includes(t)||(n=!0),n?`(${$r(s)})`:$r(s)}function Pr(e,t=!1){let s,o,i,n;const r=()=>{n=void 0,o=void 0,s=void 0,i=void 0};for(let a=0;a<e.length;a++){const l=e[a];if(n)if(o){if("SPACE"===l.type)continue;if("OPERATOR"===l.type&&":"===l.value)s=a;else if(s&&"REFERENCE"===l.type)i=a;else if(n&&o&&s&&i){const s={type:"REFERENCE",value:e.slice(n,a).filter((e=>!t||"SPACE"!==e.type)).map((e=>e.value)).join("")};e.splice(n,a-n,s),a=n+1,r()}else"REFERENCE"===l.type?(n=a,o=a,s=void 0):r()}else"REFERENCE"===l.type?(o=a,s=i=void 0):r();else["SPACE","REFERENCE"].includes(l.type)?(n=a,o="REFERENCE"===l.type?a:void 0,s=i=void 0):r()}const a=e.length-1;if(n&&o&&s&&i){const s={type:"REFERENCE",value:e.slice(n,a+1).filter((e=>!t||"SPACE"!==e.type)).map((e=>e.value)).join("")};e.splice(n,a-n+1,s)}return e}function Ur(e){return Pr(pr(e),!0)}const Vr=hr.content,Br={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},Hr={"-":"UMINUS","+":"UPLUS"};function zr(e){return e.join("\n").split("\n").filter((e=>""!==e.trim()))}const Zr={};function Gr(e){const t=Ur(e),{dependencies:s,constantValues:o}=function(e){const t={numbers:[],strings:[]},s=[];for(const o of e)switch(o.type){case"REFERENCE":s.push(o.value);break;case"STRING":const e=us(o.value);t.strings.includes(e)||t.strings.push(e);break;case"NUMBER":{const e=oe(o.value);t.numbers.includes(e)||t.numbers.push(e);break}}return{dependencies:s,constantValues:t}}(t),i=function(e,t,s){return e.map((e=>{switch(e.type){case"STRING":const o=us(e.value);return`|S${s.strings.indexOf(o)}|`;case"NUMBER":return`|N${s.numbers.indexOf(oe(e.value))}|`;case"REFERENCE":return`|${t.indexOf(e.value)}|`;default:return e.value}})).join("")}(t,s,o);if(!Zr[i]){const n=kr([...t]);let r=1;if("BIN_OPERATION"===n.type&&":"===n.value)throw new Error(a("Invalid formula"));if("UNKNOWN"===n.type)throw new Error(a("Invalid formula"));const l=u(n),c=zr([`// ${i}`,l.code,`return ${l.id};`]).join("\n");let h=new Function("deps","sheetId","ref","range","ctx",c);function d(e){const t=Vr[e.value.toUpperCase()],s=e.args,o=s.length;if(o<t.minArgRequired)throw new Error(a("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",e.value.toUpperCase(),t.minArgRequired.toString(),o.toString()));if(o>t.maxArgPossible)throw new Error(a("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",e.value.toUpperCase(),t.maxArgPossible.toString(),o.toString()));const i=t.nbrArgRepeating;if(i>1){const s=t.args.length-i;if((o-s)%i!=0)throw new Error(a("Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments",e.value.toUpperCase(),s.toString(),i.toString()))}let n=[];for(let i=0;i<o;i++){const o=t.getArgToFocus(i+1)-1;if(0<=o&&o<t.args.length){const r=s[i],l=t.args[o],c=l.type||[],h=c.includes("META"),d=l.lazy,p=c.some((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e)),g=c.every((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e));if(g&&"REFERENCE"!==r.type)throw new Error(a("Function %s expects the parameter %s to be reference to a cell or range, not a %s.",e.value.toUpperCase(),(i+1).toString(),r.type.toLowerCase()));const f=u(r,d,h,p,{functionName:e.value.toUpperCase(),paramIndex:i+1});n.push(f)}}return n}function u(e,t=!1,i=!1,n=!1,l={}){const c=[];let h,p,g;if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&i)throw new Error(a("Argument must be a reference to a cell or range."));switch(e.debug&&c.push("debugger;"),e.type){case"BOOLEAN":if(!t)return{id:`${e.value}`,code:""};h=r++,g=`${e.value}`;break;case"NUMBER":h=r++,g=`this.constantValues.numbers[${o.numbers.indexOf(e.value)}]`;break;case"STRING":h=r++,g=`this.constantValues.strings[${o.strings.indexOf(e.value)}]`;break;case"REFERENCE":const a=s.indexOf(e.value);h=r++,g=n?`range(${a}, deps, sheetId)`:`ref(${a}, deps, sheetId, ${i?"true":"false"}, "${l.functionName||Br["="]}", ${l.paramIndex})`;break;case"FUNCALL":h=r++;const f=d(e);c.push(f.map((e=>e.code)).join("\n")),p=e.value.toUpperCase(),c.push(`ctx.__lastFnCalled = '${p}';`),g=`ctx['${p}'](${f.map((e=>e.id))})`;break;case"UNARY_OPERATION":{h=r++,p=Hr[e.value];const t=u(e.right,!1,!1,!1,{functionName:p});c.push(t.code),c.push(`ctx.__lastFnCalled = '${p}';`),g=`ctx['${p}']( ${t.id})`;break}case"BIN_OPERATION":{h=r++,p=Br[e.value];const t=u(e.left,!1,!1,!1,{functionName:p}),s=u(e.right,!1,!1,!1,{functionName:p});c.push(t.code),c.push(s.code),c.push(`ctx.__lastFnCalled = '${p}';`),g=`ctx['${p}'](${t.id}, ${s.id})`;break}case"UNKNOWN":if(!t)return{id:"undefined",code:""};h=r++,g="undefined"}if(t){return{id:`_${h}`,code:`const _${h} = () => {\n\t${zr(c).join("\n\t")}\n\treturn ${g};\n}`}}return c.push(`let _${h} = ${g};`),{id:`_${h}`,code:c.join("\n")}}function p(e){let t;switch(e.type){case"REFERENCE":return[s.indexOf(e.value)];case"FUNCALL":if(t=Vr[e.value.toUpperCase()],t.returnFormat){if("FormatFromArgument"!==t.returnFormat)return[t.returnFormat.specificFormat];if(e.args.length>0){const s=0;if(!t.args[s].type.includes("META"))return p(e.args[s])}}break;case"UNARY_OPERATION":return p(e.right);case"BIN_OPERATION":if(t=Vr[Br[e.value]],t.returnFormat){if("FormatFromArgument"===t.returnFormat){const t=p(e.left);if("string"==typeof t[t.length-1])return t;const s=p(e.right);return t.concat(s)}return[t.returnFormat.specificFormat]}}return[]}Zr[i]={execute:h,dependenciesFormat:p(n)}}return{dependenciesFormat:Zr[i].dependenciesFormat,execute:Zr[i].execute,dependencies:s,constantValues:o,tokens:t}}function Wr(e){return function(e){let t=[],s="";return e.map(((e,o)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(s=""),e.type){case"FUNCTION":s=e.value;break;case"LEFT_PAREN":t.push({parent:s,argPosition:0}),s="";break;case"RIGHT_PAREN":t.pop();break;case"COMMA":t.length&&t[t.length-1].argPosition++}if(t.length){const s=t[t.length-1];s.parent&&(e.functionContext=Object.assign({},s))}return e}))}(function(e){let t=1;const s=[];return e.map((e=>("LEFT_PAREN"===e.type?(s.push(t),e.parenIndex=t,t++):"RIGHT_PAREN"===e.type&&(e.parenIndex=s.pop()),e)))}(function(e){let t=0;return e.map((e=>{const s=e.value.toString().length,o=Object.assign({},e,{start:t,end:t+s,length:s});return t=o.end,o}))}(Pr(pr(e)))))}const qr=new Ae;function jr(e,t){switch(typeof e){case"string":return e;case"boolean":return e?"TRUE":"FALSE";case"number":return(null==t?void 0:t.match(_))?Y({value:e,format:t}):t?function(e,t){const s=t.split(";"),o=s.length;return e<0?o>1?ce(-e,s[1]):"-"+ce(-e,s[0]):ce(e,s[3===o&&0===e?2:0])}(e,t):ne(e);case"object":return"0"}}function Xr(e){return""===e?"":te(e)?oe(e):Cs(e)?"TRUE"===e.toUpperCase():ys(e)?q(e).value:e}class Yr{constructor(e,t,s){this.id=e,this.evaluated=t,this.style=s.style,this.format=s.format}isFormula(){return!1}isLink(){return!1}isEmpty(){return!1}get formattedValue(){return jr(this.evaluated.value,this.format)}get composerContent(){return this.content}get defaultAlign(){switch(this.evaluated.type){case $e.number:return"right";case $e.boolean:case $e.error:return"center";case $e.text:case $e.empty:return"left"}}get isAutoSummable(){var e;switch(this.evaluated.type){case $e.empty:case $e.text:return!0;case $e.number:return!(null===(e=this.format)||void 0===e?void 0:e.match(_));case $e.error:case $e.boolean:return!1}}}class Kr extends Yr{constructor(e,t={}){super(e,{value:"",type:$e.empty},t),this.content=""}isEmpty(){return!0}}class Qr extends Yr{constructor(e,t,s={}){super(e,{value:t,type:$e.number},s),this.content=ne(this.evaluated.value)}}class Jr extends Yr{constructor(e,t,s={}){super(e,{value:t,type:$e.boolean},s),this.content=this.evaluated.value?"TRUE":"FALSE"}}class ea extends Yr{constructor(e,t,s={}){super(e,{value:t,type:$e.text},s),this.content=this.evaluated.value}}class ta extends Qr{constructor(e,t,s){super(e,t,s),this.format=s.format}get composerContent(){return jr(this.evaluated.value,this.format)}}class sa extends Yr{constructor(e,t,s={}){var o;const i=Rs(t);s={...s,style:{...s.style,textColor:(null===(o=s.style)||void 0===o?void 0:o.textColor)||A,underline:!0}},super(e,{value:i.label,type:$e.text},s),this.link=i,this.content=t}isLink(){return!0}get composerContent(){return this.link.label}}class oa extends sa{constructor(e,t,s={}){super(e,t,s),this.link.url=this.withHttp(this.link.url),this.link.isExternal=!0,this.content=Ts(this.link.label,this.link.url),this.urlRepresentation=this.link.url,this.isUrlEditable=!0}action(e){window.open(this.link.url,"_blank")}withHttp(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}}class ia extends sa{constructor(e,t,s={},o){super(e,t,s),this.sheetName=o,this.sheetId=As(this.link.url),this.isUrlEditable=!1}action(e){e.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}get urlRepresentation(){return this.sheetName(this.sheetId)||a("Invalid sheet")}}class na extends Yr{constructor(e,t,s,o,i,n){super(t,{value:"Loading...",type:$e.text},n),this.buildFormulaString=e,this.normalizedText=s,this.compiledFormula=o,this.dependencies=i}get content(){return this.buildFormulaString(this)}isFormula(){return!0}assignValue(e){switch(typeof e){case"number":this.evaluated={value:e,type:$e.number};break;case"boolean":this.evaluated={value:e,type:$e.boolean};break;case"string":this.evaluated={value:e,type:$e.text};break;case"object":case"undefined":this.evaluated={value:e,type:$e.empty}}}assignError(e,t){this.evaluated={value:e,error:t,type:$e.error}}}class ra extends Yr{constructor(e,t,s,o){super(e,{value:"#BAD_EXPR",type:$e.error,error:s},o),this.content=t}}function aa(e){const t=Ur(e);let s=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&es.test(e.value)){const t=e.value.trim();return s.includes(t)||s.push(t),`${P}${s.indexOf(t)}${P}`}return e.value}))),dependencies:s}}qr.add("Formula",{sequence:10,match:e=>e.startsWith("="),createCell:(e,t,s,o,i)=>{const n=Gr(t),r=n.dependencies.map((e=>i.getRangeFromSheetXC(o,e))),a=s.format||i.inferFormulaFormat(n,r);return new na((e=>i.buildFormulaContent(o,e)),e,t,n,r,{...s,format:a})}}).add("Empty",{sequence:20,match:e=>""===e,createCell:(e,t,s)=>new Kr(e,s)}).add("Number",{sequence:30,match:e=>te(e),createCell:(e,t,s)=>(!s.format&&t.includes("%")&&(s.format=t.includes(".")?"0.00%":"0%"),new Qr(e,oe(t),s))}).add("Boolean",{sequence:40,match:e=>Cs(e),createCell:(e,t,s)=>new Jr(e,"TRUE"===t.toUpperCase(),s)}).add("DateTime",{sequence:50,match:e=>ys(e),createCell:(e,t,s)=>{const o=q(t),i=s.format||o.format;return new ta(e,o.value,{...s,format:i})}}).add("MarkdownSheetLink",{sequence:60,match:e=>Ms(e),createCell:(e,t,s,o,i)=>new ia(e,t,s,(e=>i.tryGetSheetName(e)))}).add("MarkdownLink",{sequence:70,match:e=>xs(e),createCell:(e,t,s)=>new oa(e,t,s)}).add("WebLink",{sequence:80,match:e=>{return t=e,Is.test(t);var t},createCell:(e,t,s)=>new oa(e,Ts(t,t),s)});const la=11,ca="Sheet1";function ha(e){return e?("version"in(e=JSON.parse(JSON.stringify(e)))&&e.version<la&&(e=function(e){for(let t=da.findIndex((t=>t.from===e.version));t<da.length;t++)e=da[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,s=new Hs;for(const o of e.sheets||[])for(const e of o.figures||[])t.has(e.id)&&(e.id+=s.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(fa(),e,{version:la}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(ga(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(ga(ca,"Sheet1"));return e}(e),e}(e),e):fa()}const da=[{description:"add the `activeSheet` field on data",from:1,to:2,applyMigration:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)},{description:"add an id field in each sheet",from:2,to:3,applyMigration(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}},{description:"activeSheet is now an id, not the name of a sheet",from:3,to:4,applyMigration(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find((t=>t.name===e.activeSheet));e.activeSheet=t.id}return e}},{description:"add figures object in each sheets",from:4,to:5,applyMigration(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}},{description:"normalize the content of the cell if it is a formula to avoid parsing all the formula that vary only by the cells they use",from:5,to:6,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const s=t.cells[e];s.content&&s.content.startsWith("=")&&(s.formula=aa(s.content))}return e}},{description:"transform chart data structure",from:6,to:7,applyMigration(e){for(let t of e.sheets||[])for(let e in t.figures||[]){const{dataSets:s,...o}=t.figures[e].data,i=[];for(let e of s)if(e.labelCell){const t=qs(e.dataRange),s=e.labelCell+":"+ns(t.right,t.bottom);i.push(s)}else i.push(e.dataRange);o.dataSetsHaveTitle=Boolean(s[0].labelCell),o.dataSets=i,t.figures[e].data=o}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){var t;const s=[],o=new RegExp($,"g");for(let i of e.sheets||[]){if(!i.name)continue;const e=i.name,n=e.replace(o,"_");let r=1,a=n;for(;s.includes(a);)a=`${n}${r}`,r++;i.name=a,s.push(a);const l=t=>{if(void 0===t)return t;let s=t.replace(e,a),o=t;for(;o!==s;)o=s,s=o.replace(e,a);return o};for(let e in i.cells){const t=i.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(l))}for(let e of i.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(l),s=l(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:s}}for(let e of i.conditionalFormats||[]){e.ranges=e.ranges.map(l);for(const s of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===(null===(t=e.rule[s])||void 0===t?void 0:t.type)&&(e.rule[s].value=l(e.rule[s].value))}}return e}},{description:"transform chart data structure with design attributes",from:8,to:9,applyMigration(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=g,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stackedBar=!1;return e}},{description:"de-normalize formula to reduce exported json size (~30%)",from:9,to:10,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const s=t.cells[e];if(s.formula){let{text:e,dependencies:t}=s.formula;for(let[s,o]of Object.entries(t)){const t=`\\${P}${s}\\${P}`;e=e.replace(new RegExp(t,"g"),o)}s.content=e,delete s.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let s of e.sheets||[])for(let e in s.cells||[]){const o=s.cells[e];o.format&&(o.format=Ns(o.format,t))}return e.formats=t,e}}];function ua(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const s=[],o=[],i=e=>{if("CREATE_SHEET"===e.type)s.push(e.sheetId);else if("sheetId"in e&&!s.includes(e.sheetId))return{...e,sheetId:ca};return e};for(const e of t)"REMOTE_REVISION"===e.type?o.push({...e,commands:e.commands.map(i)}):o.push(e);return o}(e,t),t=pa(t,"SORT_CELLS"),t=pa(t,"SET_DECIMAL")}function pa(e,t){const s=[];for(const o of e)"REMOTE_REVISION"===o.type?s.push({...o,commands:o.commands.filter((e=>e.type!==t))}):s.push(o);return s}function ga(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[]}}function fa(e="Sheet1"){return{version:la,sheets:[ga(ca,e)],entities:{},styles:{},formats:{},borders:{},revisionId:N,uniqueFigureIds:!0}}class ma{constructor(e,t,s){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t,this.currentMode=s.mode}allowDispatch(e){return 0}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const s of e){let e=s.call(this,t);Array.isArray(e)||(e=[e]);const o=e.filter((e=>0!==e));if(o.length)return o}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}ma.getters=[],ma.modes=["headless","normal"];class va extends ma{constructor(e,t,s,o,i,n){super(t,o,i),this.dispatch=o,this.range=s,s.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=n}import(e){}export(e){}exportForExcel(e){}adaptRanges(e,t){}}class Ea extends va{constructor(){super(...arguments),this.borders={}}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":const t=this.borders[e.sheetId];if(t){const s=t.slice().map((e=>null==e?void 0:e.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,s)}break;case"DELETE_SHEET":const s={...this.borders};delete s[e.sheetId],this.history.update("borders",s);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_FORMATTING":if(e.border){const t=this.getters.getSheet(e.sheetId),s=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));this.setBorders(t,s,e.border)}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":for(let t of e.elements)"COL"===e.dimension?this.shiftBordersHorizontally(e.sheetId,t+1,-1):this.shiftBordersVertically(e.sheetId,t+1,-1);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumns(e):this.handleAddRows(e)}}handleAddColumns(e){const t=this.getters.getSheet(e.sheetId);let s,o;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),s=e.base-1,o=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),s=e.base,o=e.base+e.quantity+1),this.ensureColumnBorderContinuity(t,s,o)}handleAddRows(e){const t=this.getters.getSheet(e.sheetId);let s,o;"before"===e.position?(this.shiftBordersVertically(t.id,e.base,e.quantity,{moveFirstTopBorder:!0}),s=e.base-1,o=e.base+e.quantity):(this.shiftBordersVertically(t.id,e.base+1,e.quantity,{moveFirstTopBorder:!1}),s=e.base,o=e.base+e.quantity+1),this.ensureRowBorderContinuity(t,s,o)}getCellBorder(e,t,s){var o,i,n,r,a,l,c,h,d,u,p,g;const f={top:null===(n=null===(i=null===(o=this.borders[e])||void 0===o?void 0:o[t])||void 0===i?void 0:i[s])||void 0===n?void 0:n.horizontal,bottom:null===(l=null===(a=null===(r=this.borders[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[s+1])||void 0===l?void 0:l.horizontal,left:null===(d=null===(h=null===(c=this.borders[e])||void 0===c?void 0:c[t])||void 0===h?void 0:h[s])||void 0===d?void 0:d.vertical,right:null===(g=null===(p=null===(u=this.borders[e])||void 0===u?void 0:u[t+1])||void 0===p?void 0:p[s])||void 0===g?void 0:g.vertical};return f.bottom||f.left||f.right||f.top?f:null}ensureColumnBorderContinuity(e,t,s){const o=Es(t+1,s);for(let i=0;i<e.rows.length;i++){const n=this.getCellBorder(e.id,t,i),r=this.getCellBorder(e.id,s,i);if(n&&r){const t=this.getCommonSides(n,r);for(let s of o)this.addBorder(e.id,s,i,t)}}}ensureRowBorderContinuity(e,t,s){const o=Es(t+1,s);for(let i=0;i<e.cols.length;i++){const n=this.getCellBorder(e.id,i,t),r=this.getCellBorder(e.id,i,s);if(n&&r){const t=this.getCommonSides(n,r);for(let s of o)this.addBorder(e.id,i,s,t)}}}getCommonSides(e,t){const s={};for(let o of["top","bottom","left","right"])e[o]&&e[o]===t[o]&&(s[o]=e[o]);return s}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsRange(e){if(!this.borders[e])return[];return Es(0,this.getters.getSheet(e).rows.length+1)}shiftBordersHorizontally(e,t,s,{moveFirstLeftBorder:o}={}){this.borders[e]&&(s<0&&this.moveBordersOfColumn(e,t,s,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>s<0?e-t:t-e)).forEach((i=>{(i===t&&o||i!==t)&&this.moveBordersOfColumn(e,i,s,"vertical"),this.moveBordersOfColumn(e,i,s,"horizontal")})))}shiftBordersVertically(e,t,s,{moveFirstTopBorder:o}={}){this.borders[e]&&(s<0&&this.moveBordersOfRow(e,t,s,"horizontal",{destructive:!1}),this.getRowsRange(e).filter((e=>e>=t)).sort(((e,t)=>s<0?e-t:t-e)).forEach((i=>{(i===t&&o||i!==t)&&this.moveBordersOfRow(e,i,s,"horizontal"),this.moveBordersOfRow(e,i,s,"vertical")})))}moveBordersOfRow(e,t,s,o,{destructive:i}={destructive:!0}){const n=this.borders[e];n&&this.getColumnsWithBorders(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=n[r])||void 0===a?void 0:a[t+s])||void 0===l?void 0:l[o],u=null===(h=null===(c=n[r])||void 0===c?void 0:c[t])||void 0===h?void 0:h[o];this.history.update("borders",e,r,t+s,o,i?u:u||d),this.history.update("borders",e,r,t,o,void 0)}))}moveBordersOfColumn(e,t,s,o,{destructive:i}={destructive:!0}){const n=this.borders[e];n&&this.getRowsRange(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=n[t+s])||void 0===a?void 0:a[r])||void 0===l?void 0:l[o],u=null===(h=null===(c=n[t])||void 0===c?void 0:c[r])||void 0===h?void 0:h[o];this.history.update("borders",e,t+s,r,o,i?u:u||d),this.history.update("borders",e,t,r,o,void 0)}))}setBorder(e,t,s,o){this.history.update("borders",e,t,s,{vertical:null==o?void 0:o.left,horizontal:null==o?void 0:o.top}),this.history.update("borders",e,t+1,s,"vertical",null==o?void 0:o.right),this.history.update("borders",e,t,s+1,"horizontal",null==o?void 0:o.bottom)}clearBorders(e,t){for(let s of t){for(let t=s.top;t<=s.bottom;t++){this.history.update("borders",e,s.right+1,t,"vertical",void 0);for(let o=s.left;o<=s.right;o++)this.history.update("borders",e,o,t,void 0)}for(let t=s.left;t<=s.right;t++)this.history.update("borders",e,t,s.bottom+1,"horizontal",void 0)}}addBorder(e,t,s,o){this.setBorder(e,t,s,{...this.getCellBorder(e,t,s),...o})}setBorders(e,t,s){const o=e.id;if("clear"===s)return this.clearBorders(o,t);for(let e of t){if("h"===s||"hv"===s||"all"===s)for(let t=e.top+1;t<=e.bottom;t++)for(let s=e.left;s<=e.right;s++)this.addBorder(o,s,t,{top:M});if("v"===s||"hv"===s||"all"===s)for(let t=e.top;t<=e.bottom;t++)for(let s=e.left+1;s<=e.right;s++)this.addBorder(o,s,t,{left:M});if("left"===s||"all"===s||"external"===s)for(let t=e.top;t<=e.bottom;t++)this.addBorder(o,e.left,t,{left:M});if("right"===s||"all"===s||"external"===s)for(let t=e.top;t<=e.bottom;t++)this.addBorder(o,e.right+1,t,{left:M});if("top"===s||"all"===s||"external"===s)for(let t=e.left;t<=e.right;t++)this.addBorder(o,t,e.top,{top:M});if("bottom"===s||"all"===s||"external"===s)for(let t=e.left;t<=e.right;t++)this.addBorder(o,t,e.bottom+1,{top:M})}}addBordersToMerge(e,t){const s=this.getters.getSheet(e),{left:o,right:i,top:n,bottom:r}=t,a=this.getCellBorder(s.id,o,n),l=this.getCellBorder(s.id,i,r);this.clearBorders(e,[t]),(null==a?void 0:a.top)&&this.setBorders(s,[{...t,bottom:n}],"top"),(null==a?void 0:a.left)&&this.setBorders(s,[{...t,right:o}],"left"),((null==l?void 0:l.bottom)||(null==a?void 0:a.bottom))&&this.setBorders(s,[{...t,top:r}],"bottom"),((null==l?void 0:l.right)||(null==a?void 0:a.right))&&this.setBorders(s,[{...t,left:i}],"right")}import(e){if(e.borders)for(let t of e.sheets)for(let[s,o]of Object.entries(t.cells))if(null==o?void 0:o.border){const i=e.borders[o.border],[n,r]=is(s);this.setBorder(t.id,n,r,i)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,qs(e))}export(e){let t=0;const s={};function o(e){for(let[t,o]of Object.entries(s))if(Fs(o,e))return parseInt(t,10);return s[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let s=0;s<t.rowNumber;s++){const i=this.getCellBorder(t.id,e,s);if(i){const n=ns(e,s),r=t.cells[n],a=o(i);r?r.border=a:t.cells[n]={border:a}}}e.borders=s}exportForExcel(e){this.export(e)}}Ea.getters=["getCellBorder"];const ba=new RegExp(String.fromCharCode(160),"g");class Sa extends va{constructor(){super(...arguments),this.cells={},this.createCell=function(e){const t=qr.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(s,o,i,n){const r=t.find((e=>e.match(o)));if(!r)return new ea(s,o,i);try{return r.createCell(s,o,i,n,e)}catch(e){return new ra(s,o,e.message||k,i)}}}(this.getters)}adaptRanges(e,t){for(const s of Object.keys(this.cells))for(const o of Object.values(this.cells[s]||{}))if(o.isFormula())for(const i of o.dependencies)if(!t||i.sheetId===t){const t=e(i);"NONE"!==t.changeType&&this.history.update("cells",s,o.id,"dependencies",o.dependencies.indexOf(i),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":case"CLEAR_CELL":return this.checkCellOutOfSheet(e.sheetId,e.col,e.row);default:return 0}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearStyles(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case"UPDATE_CELL":this.updateCell(this.getters.getSheet(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:""})}}setFormatter(e,t,s){for(let o of t)for(let t=o.top;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:i,row:t,format:s})}clearStyles(e,t){for(let s of t)for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:null})}handleAddColumnsRows(e,t){const s=this.getters.getSheet(e.sheetId);let o,i;"before"===e.position?(o=Es(e.base,e.base+e.quantity),i=e.base+e.quantity):(o=Es(e.base+1,e.base+e.quantity+1),i=e.base),t(s,i,o)}import(e){for(let t of e.sheets){const s=this.getters.getSheet(t.id);for(let o in t.cells){const i=t.cells[o],[n,r]=is(o);if((null==i?void 0:i.content)||(null==i?void 0:i.format)||(null==i?void 0:i.style)){const o=this.importCell(s,i,e.styles,e.formats);this.history.update("cells",t.id,o.id,o),this.dispatch("UPDATE_CELL_POSITION",{cellId:o.id,col:n,row:r,sheetId:t.id})}}}}export(e){const t={},s={};for(let o of e.sheets){const e={},i=Object.keys(this.cells[o.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const{col:n,row:r}of i){const i=this.getters.getCell(o.id,n,r);e[ns(n,r)]={style:i.style?Ns(i.style,t):void 0,format:i.format?Ns(i.format,s):void 0,content:i.content}}o.cells=e}e.styles=t,e.formats=s}importCell(e,t,s,o){const i=t.style&&s[t.style]||void 0,n=t.format&&o[t.format]||void 0,r=this.uuidGenerator.uuidv4(),a={format:n,style:i};return this.createCell(r,(null==t?void 0:t.content)||"",a,e.id)}exportForExcel(e){this.export(e);for(let t of e.sheets)for(const e in t.cells){const[s,o]=is(e),i=this.getters.getCell(t.id,s,o),n=t.cells[e];n.value=i.evaluated.value,n.isFormula=i.isFormula()}}getCells(e){return this.cells[e]||{}}getCellById(e){const t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}inferFormulaFormat(e,t){const s=e.dependenciesFormat;for(let e of s)switch(typeof e){case"string":return e;case"number":const s=t[e];if(this.getters.tryGetSheet(s.sheetId)){const e=this.getters.getCell(s.sheetId,s.zone.left,s.zone.top);if(e&&e.format)return e.format}}return D}buildFormulaContent(e,t,s){const o=s||[...t.dependencies];return t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=o.shift();return this.getters.getRangeString(t,e)}return t.value})).join("")}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t)}getCellStyle(e){return e&&e.style||{}}zoneToXC(e,t,s=[{colFixed:!1,rowFixed:!1}]){const o=ns((t=this.getters.expandZone(e,t)).left,t.top,s[0]),i=ns(t.right,t.bottom,s.length>1?s[1]:s[0]),n=this.getters.getMainCell(e,t.left,t.top),r=this.getters.getMainCell(e,t.right,t.bottom),a=n[0]==r[0]&&n[1]==r[1];return o==i||a?o:o+":"+i}setStyle(e,t,s){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++){const o=this.getters.getCell(e,t,i);this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:s?{...null==o?void 0:o.style,...s}:void 0})}}copyColumnStyle(e,t,s){for(let o=0;o<e.rows.length;o++){const i=this.getFormat(e.id,t,o);if(i.style||i.format)for(let t of s)this.dispatch("UPDATE_CELL",{sheetId:e.id,col:t,row:o,...i})}}copyRowStyle(e,t,s){for(let o=0;o<e.cols.length;o++){const i=this.getFormat(e.id,o,t);if(i.style||i.format)for(let t of s)this.dispatch("UPDATE_CELL",{sheetId:e.id,col:o,row:t,...i})}}getFormat(e,t,s){const o={},[i,n]=this.getters.getMainCell(e,t,s),r=this.getters.getCell(e,i,n);return r&&(r.style&&(o.style=r.style),r.format&&(o.format=r.format)),o}updateCell(e,t,s,o){var i;const n=this.getters.getCell(e.id,t,s),r="content"in o||"formula"in o,a=r?(null===(i=o.content)||void 0===i?void 0:i.replace(ba,""))||"":(null==n?void 0:n.content)||"";let l;l=void 0!==o.style?o.style||void 0:n?n.style:void 0;let c=("format"in o?o.format:n&&n.format)||D;if((r&&!a&&!o.formula||!r&&(!n||n.isEmpty()))&&!l&&!c)return void(n&&(this.history.update("cells",e.id,n.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:s,sheetId:e.id})));const h=(null==n?void 0:n.id)||this.uuidGenerator.uuidv4(),d=r,u={format:c,style:l},p=this.createCell(h,a,u,e.id);n&&!d&&p.isFormula()&&(p.assignValue(n.evaluated.value),n.evaluated.type===$e.error&&p.assignError(n.evaluated.value,n.evaluated.error)),this.history.update("cells",e.id,p.id,p),this.dispatch("UPDATE_CELL_POSITION",{cellId:p.id,col:t,row:s,sheetId:e.id})}checkCellOutOfSheet(e,t,s){const o=this.getters.tryGetSheet(e);if(!o)return 23;return to(t,s,{top:0,left:0,bottom:o.rows.length-1,right:o.cols.length-1})?0:18}}Sa.getters=["zoneToXC","getCells","getFormulaCellContent","inferFormulaFormat","getCellStyle","buildFormulaContent","getCellById"];class Ca extends va{constructor(){super(...arguments),this.chartFigures={}}adaptRanges(e){for(let[t,s]of Object.entries(this.chartFigures))s&&(this.adaptDataSetRanges(s,t,e),this.adaptLabelRanges(s,t,e))}adaptDataSetRanges(e,t,s){for(let o of e.dataSets){if(o.labelCell){const i=s(o.labelCell);switch(i.changeType){case"REMOVE":this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(o),"labelCell",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(o),"labelCell",i.range)}}const i=s(o.dataRange);switch(i.changeType){case"REMOVE":const s=e.dataSets.filter((e=>e!==o));this.history.update("chartFigures",t,"dataSets",s);break;case"RESIZE":case"MOVE":case"CHANGE":if(this.getters.getRangeString(i.range,i.range.sheetId)!==O)this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(o),"dataRange",i.range);else{const s=e.dataSets.filter((e=>e!==o));this.history.update("chartFigures",t,"dataSets",s)}}}}adaptLabelRanges(e,t,s){if(e.labelRange){const o=s(e.labelRange);switch(o.changeType){case"REMOVE":this.history.update("chartFigures",t,"labelRange",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("chartFigures",t,"labelRange",o.range)}}}allowDispatch(e){switch(e.type){case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.checkEmptyDataset,this.checkDataset,this.checkChartExists),this.checkLabelRange);case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.checkEmptyDataset,this.checkDataset,this.checkChartDuplicate),this.checkLabelRange);default:return 0}}handle(e){var t,s;switch(e.type){case"CREATE_CHART":const o=e.position?e.position.x:0,i=e.position?e.position.y:0;this.addChartFigure(e.sheetId,this.createChartDefinition(e.definition,e.sheetId),{id:e.id,x:o,y:i,height:335,width:536,tag:"chart"});break;case"UPDATE_CHART":this.updateChartDefinition(e.id,e.definition);break;case"DUPLICATE_SHEET":{const s=this.getters.getFigures(e.sheetId);for(const o of s)if("chart"===o.tag){const s=o.id.split("??").pop(),i=`${e.sheetIdTo}??${s}`,n={...gs(this.chartFigures[o.id]),id:i};n.sheetId=e.sheetIdTo,n.dataSets.forEach((t=>{var s;t.dataRange.sheetId===e.sheetId&&(t.dataRange.sheetId=e.sheetIdTo),(null===(s=t.labelCell)||void 0===s?void 0:s.sheetId)===e.sheetId&&(t.labelCell.sheetId=e.sheetIdTo)})),(null===(t=n.labelRange)||void 0===t?void 0:t.sheetId)===e.sheetId&&(n.labelRange.sheetId=e.sheetIdTo);const r={id:i,x:o.x,y:o.y,height:o.height,width:o.width,tag:"chart"};this.addChartFigure(e.sheetIdTo,n,r)}break}case"DELETE_FIGURE":this.history.update("chartFigures",e.id,void 0);break;case"DELETE_SHEET":for(let t of Object.keys(this.chartFigures))(null===(s=this.chartFigures[t])||void 0===s?void 0:s.sheetId)===e.sheetId&&this.history.update("chartFigures",t,void 0)}}getChartDefinition(e){return this.chartFigures[e]}getChartsIdBySheet(e){return Object.entries(this.chartFigures).filter((t=>t[1].sheetId===e)).map((e=>e[0]))}getChartDefinitionUI(e,t){const s=this.chartFigures[t];if(!s)return;const o=s.dataSets.map((t=>t?this.getters.getRangeString(t.dataRange,e):"")).filter((e=>""!==e));return{title:s&&s.title?s.title:"",dataSets:o,labelRange:s.labelRange?this.getters.getRangeString(s.labelRange,e):void 0,type:s?s.type:"bar",dataSetsHaveTitle:!(!s||0===o.length)&&Boolean(s.dataSets[0].labelCell),background:s.background,verticalAxisPosition:s.verticalAxisPosition,legendPosition:s.legendPosition,stackedBar:s.stackedBar}}getChartDefinitionExcel(e,t){const s=this.chartFigures[t],o=this.getChartDefinitionUI("forceSheetReference",t);if(!s||!o)return;const i=s.dataSets.map((e=>this.toExcelDataset(e))).filter((e=>""!==e.range));return{...o,backgroundColor:s.background,dataSets:i}}toExcelDataset(e){var t;const s=null===(t=e.labelCell)||void 0===t?void 0:t.zone;let o=e.dataRange.zone;if(s){const{height:e,width:t}=io(o);1===e?o={...o,left:o.left+1}:1===t&&(o={...o,top:o.top+1})}const i={...e.dataRange,zone:o};return{label:e.labelCell?this.getters.getRangeString(e.labelCell,"forceSheetReference"):void 0,range:this.getters.getRangeString(i,"forceSheetReference")}}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)if("chart"===e.tag){const s={...e.data};this.chartFigures[e.id]=this.createChartDefinition(s,t.id),delete e.data}}export(e){if(e.sheets)for(let t of e.sheets){const e=this.getters.getFigures(t.id),s=[];for(let o of e){const e=o;if(e&&"chart"===e.tag){const o=this.getChartDefinitionUI(t.id,e.id);o&&(e.data=o,s.push(e))}else s.push(e)}t.figures=s}}exportForExcel(e){for(let t of e.sheets){const e=this.getters.getFigures(t.id),s=[];for(let o of e){const e=o;if(e&&"chart"===e.tag){const o=this.getChartDefinitionExcel(t.id,e.id);o&&(e.data=o,s.push(e))}else s.push(e)}t.charts=s}}createChartDefinition(e,t){return{...e,dataSets:this.createDataSets(e.dataSets,t,e.dataSetsHaveTitle),labelRange:e.labelRange?this.getters.getRangeFromSheetXC(t,e.labelRange):void 0,sheetId:t}}updateChartDefinition(e,t){const s=this.chartFigures[e];if(!s)throw new Error(`There is no chart with the given id: ${e}`);if(void 0!==t.title&&this.history.update("chartFigures",e,"title",t.title),t.type&&this.history.update("chartFigures",e,"type",t.type),t.dataSets){const o=!!t.dataSetsHaveTitle,i=this.createDataSets(t.dataSets,s.sheetId,o);this.history.update("chartFigures",e,"dataSets",i)}if(void 0!==t.labelRange){const o=t.labelRange?this.getters.getRangeFromSheetXC(s.sheetId,t.labelRange):void 0;this.history.update("chartFigures",e,"labelRange",o)}t.background&&this.history.update("chartFigures",e,"background",t.background),t.verticalAxisPosition&&this.history.update("chartFigures",e,"verticalAxisPosition",t.verticalAxisPosition),t.legendPosition&&this.history.update("chartFigures",e,"legendPosition",t.legendPosition),void 0!==t.stackedBar&&this.history.update("chartFigures",e,"stackedBar",t.stackedBar)}createDataSets(e,t,s){const o=[];for(const i of e){const e=this.getters.getRangeFromSheetXC(t,i),{zone:n,sheetId:r,invalidSheetName:a}=e;if(!a)if(n.left!==n.right&&n.top!==n.bottom)for(let e=n.left;e<=n.right;e++){const t={left:e,right:e,top:n.top,bottom:n.bottom};o.push(this.createDataSet(r,t,s?{top:t.top,bottom:t.top,left:t.left,right:t.left}:void 0))}else n.left===n.right&&n.top===n.bottom?s||o.push(this.createDataSet(r,n,void 0)):o.push(this.createDataSet(r,n,s?{top:n.top,bottom:n.top,left:n.left,right:n.left}:void 0))}return o}addChartFigure(e,t,s){this.dispatch("CREATE_FIGURE",{sheetId:e,figure:s}),this.history.update("chartFigures",s.id,t)}createDataSet(e,t,s){if(t.left!==t.right&&t.top!==t.bottom)throw new Error(`Zone should be a single column or row: ${Xs(t)}`);if(s){const o=Xs(t),i=Xs(s);return{labelCell:this.getters.getRangeFromSheetXC(e,i),dataRange:this.getters.getRangeFromSheetXC(e,o)}}return{labelCell:void 0,dataRange:this.getters.getRangeFromSheetXC(e,Xs(t))}}checkEmptyDataset(e){return e.definition.dataSets&&0===e.definition.dataSets.length?27:0}checkDataset(e){if(!e.definition.dataSets)return 0;const t=void 0!==e.definition.dataSets.find((e=>!ts.test(e)));return t?28:0}checkLabelRange(e){if(!e.definition.labelRange)return 0;return!ts.test(e.definition.labelRange||"")?29:0}checkChartDuplicate(e){for(const t of this.getters.getSheets())if(this.getters.getFigure(t.id,e.id))return 57;return 0}checkChartExists(e){return this.getters.getFigure(e.sheetId,e.id)?0:58}}function ya(e){return""===e?NaN:Number(e)}Ca.getters=["getChartDefinition","getChartDefinitionUI","getChartsIdBySheet"];class wa extends va{constructor(){super(...arguments),this.cfRules={}}loopThroughRangesOfSheet(e,t){for(const s of this.cfRules[e])for(const o of s.ranges){const i=t(o);switch(i.changeType){case"REMOVE":let t=s.ranges.slice();t.splice(s.ranges.indexOf(o),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(s),"ranges",t):this.removeConditionalFormatting(s.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(s),"ranges",s.ranges.indexOf(o),i.range)}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(const t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){return"ADD_CONDITIONAL_FORMAT"===e.type?this.checkValidations(e,this.checkCFRule,this.checkEmptyRange):0}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const s={...e.cf,ranges:e.target.map(Xs)};this.addConditionalFormatting(s,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId)}}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){this.export(e)}getConditionalFormats(e){return this.cfRules[e].map((t=>this.mapToConditionalFormat(e,t)))||[]}getRulesSelection(e,t){const s=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{s.add(e)}))})),Array.from(s)}getRulesByZone(e,t){const s=new Set;for(let o=t.top;o<=t.bottom;o++)for(let i=t.left;i<=t.right;i++){this.getRulesByCell(e,i,o).forEach((e=>{s.add(e.id)}))}return s}getRulesByCell(e,t,s){const o=[];for(let i of this.cfRules[e])for(let e of i.ranges)to(t,s,e.zone)&&o.push(i);return new Set(o.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e)))}}mapToConditionalFormatInternal(e,t){const s={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return s}addConditionalFormatting(e,t){const s=this.cfRules[t].slice(),o=s.findIndex((t=>t.id===e.id)),i=this.mapToConditionalFormatInternal(t,e);o>-1?s.splice(o,1,i):s.push(i),this.history.update("cfRules",t,s)}checkEmptyRange(e){return e.target.length?0:21}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]));case"ColorScaleRule":return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case"IconSetRule":return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)))}return 0}checkOperatorArgsNumber(e,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return s=>{if(t.includes(s.operator)){const t=[],o=e=>void 0===e||""===e;return e>=1&&o(s.values[0])&&t.push(36),e>=2&&o(s.values[1])&&t.push(37),t.length?t:0}return 0}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return 38;case"max":return 40;case"mid":return 39;case"upperInflectionPoint":return 41;case"lowerInflectionPoint":return 42}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{Gr(e.value||"")}catch(e){switch(t){case"min":return 43;case"max":return 45;case"mid":return 44;case"upperInflectionPoint":return 46;case"lowerInflectionPoint":return 47}}return 0}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):0))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,s=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(s)?33:0}checkMinBiggerThanMax(e){const t=e.minimum.value,s=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&ya(t)>=ya(s)?32:0}checkMidBiggerThanMax(e){var t;const s=null===(t=e.midpoint)||void 0===t?void 0:t.value,o=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&ya(s)>=ya(o)?34:0}checkMinBiggerThanMid(e){var t;const s=e.minimum.value,o=null===(t=e.midpoint)||void 0===t?void 0:t.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&ya(s)>=ya(o)?35:0}removeConditionalFormatting(e,t){const s=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==s){const e=this.cfRules[t].slice();e.splice(s,1),this.history.update("cfRules",t,e)}}}wa.getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];class Ia extends va{constructor(){super(...arguments),this.figures={}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkFigureDuplicate(e.figure.id);case"UPDATE_FIGURE":case"DELETE_FIGURE":return this.checkFigureExists(e.sheetId,e.id);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:s,...o}=e,i=o;this.updateFigure(s,i);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId)}}updateFigure(e,t){if("id"in t)for(const[s,o]of Object.entries(t))switch(s){case"x":case"y":void 0!==o&&this.history.update("figures",e,t.id,s,Math.max(o,0));break;case"width":case"height":void 0!==o&&this.history.update("figures",e,t.id,s,o)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){var s;return void 0===(null===(s=this.figures[e])||void 0===s?void 0:s[t])?55:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>null==t?void 0:t[e]))?56:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(_s)}getFigure(e,t){var s;return null===(s=this.figures[e])||void 0===s?void 0:s[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>{var s;return void 0!==(null===(s=this.figures[t])||void 0===s?void 0:s[e])}))}import(e){for(let t of e.sheets){const e={};t.figures.forEach((t=>{e[t.id]=t})),this.figures[t.id]=e}}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const s=void 0;t.figures.push({...e,data:s})}}exportForExcel(e){this.export(e)}}Ia.getters=["getFigures","getFigure","getFigureSheetId"];class xa extends va{constructor(){super(...arguments),this.nextId=1,this.merges={},this.mergeCellMap={}}allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?0:this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;const s=this.getters.getSheet(e.sheetIdTo);for(const e of Object.values(t).filter(_s))this.addMerge(s,e.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(this.getters.getSheet(e.sheetId),t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){const s=t?[t]:Object.keys(this.merges);for(const t of s)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(_s)}getMerge(e,t,s){var o;const i=this.mergeCellMap[e],n=i?t in i&&(null===(o=i[t])||void 0===o?void 0:o[s]):void 0;return n?this.getMergeById(e,n):void 0}doesIntersectMerge(e,t){const{left:s,right:o,top:i,bottom:n}=t;for(let t=i;t<=n;t++)for(let i=s;i<=o;i++)if(this.getMerge(e,i,t))return!0;return!1}doesColumnsHaveCommonMerges(e,t,s){const o=this.getters.getSheet(e);for(let e=0;e<o.rows.length;e++)if(this.isInSameMerge(o.id,t,e,s,e))return!0;return!1}doesRowsHaveCommonMerges(e,t,s){const o=this.getters.getSheet(e);for(let e=0;e<=o.cols.length;e++)if(this.isInSameMerge(o.id,e,t,e,s))return!0;return!1}expandZone(e,t){let{left:s,right:o,top:i,bottom:n}=t,r={left:s,right:o,top:i,bottom:n};for(let t in this.merges[e]){const s=this.getMergeById(e,parseInt(t));s&&eo(s,r)&&(r=Qs(s,r))}return Js(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,s,o,i){const n=this.getMerge(e,t,s),r=this.getMerge(e,o,i);return!(!n||!r)&&Js(n,r)}isInMerge(e,t,s){var o;const i=this.mergeCellMap[e];return!!i&&(t in i&&Boolean(null===(o=i[t])||void 0===o?void 0:o[s]))}getMainCell(e,t,s){if(!this.isInMerge(e,t,s))return[t,s];const o=this.getMerge(e,t,s).topLeft;return[o.col,o.row]}getBottomLeftCell(e,t,s){if(!this.isInMerge(e,t,s))return[t,s];const{bottom:o,left:i}=this.getMerge(e,t,s);return[i,o]}isMergeHidden(e,t){const s=this.getters.getHiddenColsGroups(e),o=this.getters.getHiddenRowsGroups(e);for(let e of s)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of o)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const s=this.getMerge(e,t.left,t.top);if(s)return Js(t,s);const{width:o,height:i}=io(t);return 1===o&&1===i}isMergeDestructive(e,t){let{left:s,right:o,top:i,bottom:n}=t;o=ms(o,0,e.cols.length-1),n=ms(n,0,e.rows.length-1);for(let t=i;t<=n;t++)for(let n=s;n<=o;n++)if(n!==s||t!==i){const s=this.getters.getCell(e.id,n,t);if(s&&!s.isEmpty())return!0}return!1}getMergeById(e,t){var s;const o=null===(s=this.merges[e])||void 0===s?void 0:s[t];return void 0!==o?Ra(t,o):void 0}checkDestructiveMerge({sheetId:e,target:t}){const s=this.getters.tryGetSheet(e);if(!s)return 0;return t.some((e=>this.isMergeDestructive(s,e)))?3:0}checkOverlap({target:e}){for(const t of e)for(const s of e)if(t!==s&&eo(t,s))return 50;return 0}checkMergedContentUpdate(e){const{col:t,row:s,sheetId:o,content:i}=e;if(void 0===i)return 0;const[n,r]=this.getMainCell(o,t,s);return n===t&&r===s?0:4}checkMergeExists(e){const{sheetId:t,target:s}=e;for(const e of s){const{left:s,top:o}=e,i=this.getMerge(t,s,o);if(void 0===i||!Js(e,i))return 5}return 0}addMerge(e,t){let{left:s,right:o,top:i,bottom:n}=t;o=ms(o,0,e.cols.length-1),n=ms(n,0,e.rows.length-1);if(ns(s,i)===ns(o,n))return;const r=this.getters.getCell(e.id,s,i);let a=this.nextId++;this.history.update("merges",e.id,a,this.getters.getRangeFromSheetXC(e.id,Xs({left:s,top:i,right:o,bottom:n})));let l=new Set;for(let t=i;t<=n;t++)for(let n=s;n<=o;n++){n===s&&t===i||this.dispatch("UPDATE_CELL",{sheetId:e.id,col:n,row:t,style:r?r.style:null,content:void 0});const o=this.getMerge(e.id,n,t);o&&l.add(o.id),this.history.update("mergeCellMap",e.id,n,t,a)}for(let t of l){const{top:s,bottom:o,left:i,right:n}=this.getMergeById(e.id,t);for(let t=s;t<=o;t++)for(let s=i;s<=n;s++){const o=this.getMerge(e.id,s,t);o&&o.id===a||(this.history.update("mergeCellMap",e.id,s,t,void 0),this.dispatch("CLEAR_CELL",{sheetId:e.id,col:s,row:t}))}this.history.update("merges",e.id,t,void 0)}}removeMerge(e,t){const{left:s,top:o,bottom:i,right:n}=t,r=this.getMerge(e,s,o);if(void 0!==r&&Js(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=o;t<=i;t++)for(let o=s;o<=n;o++)this.history.update("mergeCellMap",e,o,t,void 0)}}applyRangeChangeOnSheet(e,t){const s=Object.entries(this.merges[e]||{});for(const[o,i]of s)if(i){const s=i.zone,n=t(i);switch(n.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,s);break;default:const{width:t,height:i}=io(n.range.zone);1===t&&1===i?this.removeMerge(e,s):this.history.update("merges",e,parseInt(o,10),n.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const[s,o]of ro(t))this.history.update("mergeCellMap",e,s,o,t.id)}import(e){const 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){const s=this.getters.getSheet(e);for(let e of t)this.addMerge(s,qs(e))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...Ta(e))}}exportForExcel(e){this.export(e)}}function Ta(e){return Object.entries(e).map((([e,t])=>t?Ra(parseInt(e,10),t):void 0)).filter(_s).map((e=>ns(e.left,e.top)+":"+ns(e.right,e.bottom)))}function Ra(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}xa.getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCell","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","isSingleCellOrMerge"];class La extends va{constructor(){super(...arguments),this.sheetIds={},this.visibleSheets=[],this.sheets={},this.cellPosition={}}allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZones)(e);if(0!==t)return t;switch(e.type){case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"MOVE_SHEET":const t=this.visibleSheets.findIndex((t=>t===e.sheetId));return"left"===e.direction&&0===t||"right"===e.direction&&t===this.visibleSheets.length-1?14:0;case"RENAME_SHEET":return this.isRenameAllowed(e);case"DELETE_SHEET":return this.visibleSheets.length>1?0:9;case"REMOVE_COLUMNS_ROWS":const s=this.getSheet(e.sheetId);return("COL"===e.dimension?s.cols.length:s.rows.length)>e.elements.length?0:8;case"HIDE_COLUMNS_ROWS":{const t=this.sheets[e.sheetId],s="COL"===e.dimension?t.hiddenColsGroups:t.hiddenRowsGroups,o="COL"===e.dimension?t.cols:t.rows;return(s||[]).flat().concat(e.elements).length<o.length?0:51}default:return 0}}handle(e){switch(e.type){case"SET_GRID_LINES_VISIBILITY":this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"CREATE_SHEET":const t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update("sheetIds",t.name,t.id);break;case"RESIZE_COLUMNS_ROWS":const s="COL"===e.dimension?"cols":"rows";for(let t of e.elements)this.setHeaderSize(this.getSheet(e.sheetId),s,t,e.size);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.direction);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.name);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],e.elements):this.removeRows(this.sheets[e.sheetId],e.elements);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case"HIDE_COLUMNS_ROWS":"COL"===e.dimension?this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"cols","hide"):this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"rows","hide");break;case"UNHIDE_COLUMNS_ROWS":"COL"===e.dimension?this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"cols","show"):this.setElementsVisibility(this.sheets[e.sheetId],e.elements,"rows","show");break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e)}}import(e){for(let t of e.sheets)this.sheetIds[t.name]=t.id;for(let t of e.sheets){const e=t.name||r("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:s,rowNumber:o}=this.getImportedSheetSize(t),i={id:t.id,name:e,cols:Ps(t.cols||{},s),rows:Us(t.rows||{},o),hiddenColsGroups:[],hiddenRowsGroups:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible};this.visibleSheets.push(i.id),this.sheets[i.id]=i,this.updateHiddenElementsGroups(i.id,"cols"),this.updateHiddenElementsGroups(i.id,"rows")}}exportSheets(e,t=!1){e.sheets=this.visibleSheets.filter(_s).map((e=>{const s=this.sheets[e];return{id:s.id,name:s.name,colNumber:s.cols.length,rowNumber:s.rows.length,rows:Bs(s.rows,t),cols:Vs(s.cols,t),merges:[],cells:{},conditionalFormats:[],figures:[],areGridLinesVisible:void 0===s.areGridLinesVisible||s.areGridLinesVisible}}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e,!0)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}getSheetName(e){return this.getSheet(e).name}getCellsInZone(e,t){return ro(t).map((([t,s])=>this.getCell(e,t,s)))}tryGetSheetName(e){var t;return null===(t=this.tryGetSheet(e))||void 0===t?void 0:t.name}getSheetIdByName(e){if(e){const s=((t=e).startsWith("'")&&(t=t.slice(1,-1).replace(/''/g,"'")),t);for(const e in this.sheetIds)if(e.toUpperCase()===s.toUpperCase())return this.sheetIds[e]}var t}getSheets(){const{visibleSheets:e,sheets:t}=this;return e.map((e=>t[e])).filter(_s)}getVisibleSheets(){return this.visibleSheets}getEvaluationSheets(){return this.sheets}tryGetCol(e,t){var s;return null===(s=this.sheets[e])||void 0===s?void 0:s.cols[t]}getCol(e,t){const s=this.getSheet(e).cols[t];if(!s)throw new Error(`Col ${s} not found.`);return s}tryGetRow(e,t){var s;return null===(s=this.sheets[e])||void 0===s?void 0:s.rows[t]}getRow(e,t){const s=this.getSheet(e).rows[t];if(!s)throw new Error(`Row ${s} not found.`);return s}getCell(e,t,s){var o;const i=this.tryGetSheet(e),n=null===(o=null==i?void 0:i.rows[s])||void 0===o?void 0:o.cells[t];if(void 0!==n)return this.getters.getCellById(n)}getColCells(e,t){return this.getSheet(e).rows.map((e=>e.cells[t])).filter(_s).map((e=>this.getters.getCellById(e))).filter(_s)}getColsZone(e,t,s){return{top:0,bottom:this.getSheet(e).rows.length-1,left:t,right:s}}getRowsZone(e,t,s){return{top:t,bottom:s,left:0,right:this.getSheet(e).cols.length-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getHiddenColsGroups(e){var t;return(null===(t=this.sheets[e])||void 0===t?void 0:t.hiddenColsGroups)||[]}getHiddenRowsGroups(e){var t;return(null===(t=this.sheets[e])||void 0===t?void 0:t.hiddenRowsGroups)||[]}getNumberCols(e){return this.getSheet(e).cols.length}getNumberRows(e){return this.getSheet(e).rows.length}getNextSheetName(e="Sheet"){let t=1;const s=this.getSheets().map((e=>e.name));let o=`${e}${t}`;for(;s.includes(o);)o=`${e}${t}`,t++;return o}isEmpty(e,t){return this.getCellsInZone(e,t).flat().every((e=>!e||e.isEmpty()))}setHeaderSize(e,t,s,o){let i,n;const r=e[t],a=r[s],l=o-a.size;this.history.update("sheets",e.id,t,s,"size",o),a.isHidden||this.history.update("sheets",e.id,t,s,"end",a.end+l),i=a.end;for(let o=s+1;o<r.length;o++){const s=r[o];n=s.isHidden?i:i+s.size,this.history.update("sheets",e.id,t,o,"start",i),this.history.update("sheets",e.id,t,o,"end",n),i=n}}updateCellPosition(e){const{sheetId:t,cellId:s,col:o,row:i}=e;s?this.setNewPosition(s,t,o,i):this.clearPosition(t,o,i)}setNewPosition(e,t,s,o){const i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update("cellPosition",e,{row:o,col:s,sheetId:t}),this.history.update("sheets",t,"rows",o,"cells",s,e)}clearPosition(e,t,s){var o;const i=null===(o=this.sheets[e])||void 0===o?void 0:o.rows[s].cells[t];i&&(this.history.update("cellPosition",i,void 0),this.history.update("sheets",e,"rows",s,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let s of t)for(let t=s.left;t<=s.right;t++)for(let o=s.top;o<=s.bottom;o++){this.sheets[e].rows[o].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:o})}}createSheet(e,t,s,o,i){const n={id:e,name:t,cols:$s(s),rows:Ds(o),hiddenColsGroups:[],hiddenRowsGroups:[],areGridLinesVisible:!0},r=this.visibleSheets.slice();r.splice(i,0,n.id);const a=this.sheets;return this.history.update("visibleSheets",r),this.history.update("sheets",Object.assign({},a,{[n.id]:n})),n}moveSheet(e,t){const s=this.visibleSheets.slice(),o=s.findIndex((t=>t===e)),i=s.splice(o,1);s.splice(o+("left"===t?-1:1),0,i[0]),this.history.update("visibleSheets",s)}checkSheetName(e){const{visibleSheets:t,sheets:s}=this,o=e.name&&e.name.trim().toLowerCase();return t.find((e=>{var t;return(null===(t=s[e])||void 0===t?void 0:t.name.toLowerCase())===o}))?11:$.test(o)?13:0}checkSheetPosition(e){const{visibleSheets:t}=this;return e.position>t.length||e.position<0?15:0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const s=e.name;this.history.update("sheets",e.id,"name",t.trim());const o=Object.assign({},this.sheetIds);o[t]=e.id,delete o[s],this.history.update("sheetIds",o)}duplicateSheet(e,t){const s=this.getSheet(e),o=this.getDuplicateSheetName(s.name),i=JSON.parse(JSON.stringify(s));i.id=t,i.name=o;for(let e=0;e<=i.cols.length;e++)for(let t=0;t<=i.rows.length;t++)i.rows[t]&&(i.rows[t].cells[e]=void 0);const n=this.visibleSheets.slice(),r=n.findIndex((t=>t===e));n.splice(r+1,0,i.id),this.history.update("visibleSheets",n),this.history.update("sheets",Object.assign({},this.sheets,{[i.id]:i}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:s}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:i.id,col:e,row:s,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIds);a[i.name]=i.id,this.history.update("sheetIds",a)}getDuplicateSheetName(e){let t=1;const s=this.getters.getSheets().map((e=>e.name)),o=a("Copy of %s",e);let i=o.toString();for(;s.includes(i);)i=`${o} (${t})`,t++;return i}deleteSheet(e){const t=e.name,s=Object.assign({},this.sheets);delete s[e.id],this.history.update("sheets",s);const o=this.visibleSheets.slice(),i=o.findIndex((t=>t===e.id));o.splice(i,1),this.history.update("visibleSheets",o);const n=Object.assign({},this.sheetIds);delete n[t],this.history.update("sheetIds",n)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let s of t)this.moveCellOnColumnsDeletion(e,s);this.updateColumnsStructureOnDeletion(e,t)}removeRows(e,t){t.sort(((e,t)=>t-e));for(let s of bs(t))this.moveCellOnRowsDeletion(e,s[s.length-1],s[0]),s.map((t=>this.updateRowsStructureOnDeletion(t,e)))}addColumns(e,t,s,o){this.moveCellsOnAddition(e,"before"===s?t:t+1,o,"columns"),this.updateColumnsStructureOnAddition(e,t,o)}addRows(e,t,s,o){this.addEmptyRows(e,o),this.moveCellsOnAddition(e,"before"===s?t:t+1,o,"rows"),this.updateRowsStructureOnAddition(e,t,o)}moveCellOnColumnsDeletion(e,t){for(let[s,o]of Object.entries(e.rows)){const i=parseInt(s,10);for(let s in o.cells){const n=parseInt(s,10),r=o.cells[s];r&&(n===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:n,row:i}),n>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:n-1,row:i}))}}}moveCellsOnAddition(e,t,s,o){const i=[];for(const[n,r]of Object.entries(e.rows)){const a=parseInt(n,10);if("rows"!==o||a>=t)for(let n in r.cells){const l=parseInt(n,10),c=r.cells[n];c&&("rows"===o||l>=t)&&i.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c,col:l+("columns"===o?s:0),row:a+("rows"===o?s:0)})}}for(let e of i.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,s){const o=s-t+1;for(let[i,n]of Object.entries(e.rows)){const r=parseInt(i,10);if(r>=t&&r<=s)for(let t in n.cells){const s=parseInt(t,10);n.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:s,row:r})}if(r>s)for(let t in n.cells){const s=parseInt(t,10),i=n.cells[t];i&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:i,col:s,row:r-o})}}}updateColumnsStructureOnDeletion(e,t){const s=[];let o=0,i=0;for(let n in e.cols){if(t.includes(parseInt(n,10)))continue;const{size:r,isHidden:a}=e.cols[n],l=a?o:o+r;s.push({name:os(i),size:r,start:o,end:l,isHidden:a}),o=l,i++}this.history.update("sheets",e.id,"cols",s),this.updateHiddenElementsGroups(e.id,"cols")}updateColumnsStructureOnAddition(e,t,s){const o=[];let i=0,n=0;for(let r in e.cols){if(parseInt(r,10)===t){const{size:t}=e.cols[n];for(let e=0;e<s;e++)o.push({name:os(n),size:t,start:i,end:i+t}),i+=t,n++}const{size:a,isHidden:l}=e.cols[r],c=l?i:i+a;o.push({name:os(n),size:a,start:i,end:c,isHidden:l}),i=c,n++}this.history.update("sheets",e.id,"cols",o),this.updateHiddenElementsGroups(e.id,"cols")}updateRowsStructureOnDeletion(e,t){const s=[];let o=0,i=0;const n=t.rows.map((e=>e.cells));for(let r in t.rows){const a=t.rows[r],{size:l,isHidden:c}=a,h=c?o:o+l;parseInt(r,10)!==e&&(i++,s.push({start:o,end:h,size:l,cells:n.shift(),name:String(i),isHidden:c}),o=h)}this.history.update("sheets",t.id,"rows",s),this.updateHiddenElementsGroups(t.id,"rows")}updateRowsStructureOnAddition(e,t,s){const o=[];let i=0,n=0,r=0;const a=e.rows.map((e=>e.cells));for(let l in e.rows){const{size:c,isHidden:h}=e.rows[r],d=h?i:i+c;(parseInt(l,10)<t||parseInt(l,10)>=t+s)&&r++,n++,o.push({start:i,end:d,size:c,cells:a.shift(),name:String(n),isHidden:h}),i=d}this.history.update("sheets",e.id,"rows",o),this.updateHiddenElementsGroups(e.id,"rows")}addEmptyRows(e,t){const s=e.rows[e.rows.length-1].end,o=e.rows.slice();for(let e=0;e<t;e++)o.push({start:s,end:s,size:0,name:(o.length+1).toString(),cells:{}});this.history.update("sheets",e.id,"rows",o)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(is);return{rowNumber:Math.max(e.rowNumber,...new Set(t.map((([e,t])=>t+1)))),colNumber:Math.max(e.colNumber,...new Set(t.map((([e,t])=>e+1))))}}setElementsVisibility(e,t,s,o){let i=0;const n="hide"===o;for(let o=0;o<e[s].length;o++){const{size:r,isHidden:a}=e[s][o],l=t.includes(o)?n:a||!1,c=l?i:i+r;this.history.update("sheets",e.id,s,o,"start",i),this.history.update("sheets",e.id,s,o,"end",c),this.history.update("sheets",e.id,s,o,"isHidden",l),i=c}this.updateHiddenElementsGroups(e.id,s)}updateHiddenElementsGroups(e,t){var s;const o="cols"===t?"hiddenColsGroups":"hiddenRowsGroups",i=((null===(s=this.sheets[e])||void 0===s?void 0:s[t])||[]).reduce(((e,t,s)=>{if(!t.isHidden)return e;const o=e[e.length-1];return o&&o[o.length-1]==s-1||e.push([]),e[e.length-1].push(s),e}),[]);this.history.update("sheets",e,o,i)}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?23:"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?12:0}checkZones(e){const t=[];if("zone"in e&&t.push(e.zone),"target"in e&&Array.isArray(e.target)&&t.push(...e.target),!t.every(js))return 22;if(t.length&&"sheetId"in e){const s=this.getSheet(e.sheetId),o={top:0,left:0,bottom:s.rows.length-1,right:s.cols.length-1};return t.every((e=>{return Js(Qs(t=o,e),t);var t}))?0:18}return 0}}La.getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheets","getVisibleSheets","getEvaluationSheets","tryGetCol","getCol","tryGetRow","getRow","getCell","getCellsInZone","getCellPosition","getColCells","getColsZone","getRowsZone","getNumberCols","getNumberRows","getHiddenColsGroups","getHiddenRowsGroups","getGridLinesVisibility","getNextSheetName","isEmpty"];const Ma=new Ae;Ma.add("INCREMENT_MODIFIER",{apply:(e,t)=>{var s;e.current+=e.increment;const o=e.current.toString(),i=jr(e.current,null===(s=t.cell)||void 0===s?void 0:s.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:i}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,s)=>{var o,i;const n=(null===(o=t.cell)||void 0===o?void 0:o.content)||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:n},tooltip:n?{props:{content:null===(i=t.cell)||void 0===i?void 0:i.formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,s,o)=>{e.current+=e.increment;let i=0,n=0;switch(o){case 0:i=0,n=-e.current;break;case 1:i=0,n=e.current;break;case 2:i=-e.current,n=0;break;case 3:i=e.current,n=0}if(!t.cell||!t.cell.isFormula())return{cellData:{}};const r=t.sheetId,a=s.createAdaptedRanges(t.cell.dependencies,i,n,r),l=s.buildFormulaContent(r,t.cell,a);return{cellData:{border:t.border,style:t.cell.style,format:t.cell.format,content:l},tooltip:l?{props:{content:l}}:void 0}}});const Aa=new Ae;Aa.add("simple_value_copy",{condition:(e,t)=>{var s;return 1===t.length&&!e.isFormula()&&!(null===(s=e.format)||void 0===s?void 0:s.match(_))},generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("copy_text",{condition:e=>!e.isFormula()&&e.evaluated.type===$e.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_number",{condition:e=>e.evaluated.type===$e.number,generateRule:(e,t)=>{const s=function(e,t){let s=[],o=!1;for(let i of t)if(i===e&&(o=!0),(null==i?void 0:i.evaluated.type)===$e.number)s.push(i.evaluated.value);else{if(o)return s;s=[]}return s}(e,t);let o=1;return 2==s.length?o=2*(s[1]-s[0]):s.length>2&&(o=function(e){const t=[];let s=e[0];for(let o=1;o<e.length;o++){const i=e[o];t.push(i-s),s=i}return t.reduce(((e,t)=>e+t),0)/t.length}(s)*s.length),{type:"INCREMENT_MODIFIER",increment:o,current:e.evaluated.type===$e.number?e.evaluated.value:0}},sequence:40});const _a=new Ae,Oa=(new Ae).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let s=e.base;"after"===e.position&&s++;for(let o=0;o<e.quantity;o++)t.push(o+s);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],s=[...e.elements].sort(((e,t)=>e-t));for(let o of bs(s)){const s=0===o[0]?0:o[0]-1,i=0===o[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:o.length,base:s,sheetId:e.sheetId,position:i})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",id:e.figure.id,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",id:e.id,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}));for(const e of Ue.values())Oa.contains(e)||Oa.add(e,Na);function Na(e){return[e]}const ka=e=>({isVisible:()=>!0,isEnabled:()=>!0,isReadonlyAllowed:!1,shortCut:"",action:!1,children:[],separator:!1,icon:!1,id:e});function Fa(e,t){return Object.assign({},ka(e),t)}class $a extends Ae{add(e,t){return this.content[e]=Fa(e,t),this}addChild(e,t,s){const o=t.splice(0,1)[0];let i=this.content[o];if(!i)throw new Error(`Path ${o+":"+t.join(":")} not found`);for(let e of t)if(i="function"==typeof i.children?void 0:i.children.find((t=>t.id===e)),!i)throw new Error(`Path ${o+":"+t.join(":")} not found`);return i.children.push(Fa(e,s)),this}getChildren(e,t){return"function"==typeof e.children?e.children(t).sort(((e,t)=>e.sequence-t.sequence)):e.children.sort(((e,t)=>e.sequence-t.sequence))}getName(e,t){return"function"==typeof e.name?e.name(t):e.name}getShortCut(e){return e.shortCut?e.shortCut:""}getAll(){return super.getAll().sort(((e,t)=>e.sequence-t.sequence))}}const Da=[$e.number,$e.error,$e.text,$e.boolean];function Pa(e,t){return{index:t,type:e?e.evaluated.type:$e.empty,value:e?e.evaluated.value:""}}function Ua(e,t,s,o,i){let n=Be.Success,r=o.right>o.left;if(e.getters.doesIntersectMerge(t,o)){let s;r=!1;for(let i=o.top;i<=o.bottom;i++){s=[];for(let n=o.left;n<=o.right;n++){let o=e.getters.getMerge(t,n,i);o&&!s.includes(o.id.toString())&&s.push(o.id.toString())}if(s.length>=2){r=!0;break}}}const[l,c]=s;if(r)n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i});else{const s=e.getters.getContiguousZone(t,o);Js(s,o)?n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i}):e.askConfirmation(a("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?"),(()=>{o=s,n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i})}),(()=>{n=e.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:i})}))}n.isCancelledBecause(48)&&(e.dispatch("SET_SELECTION",{anchor:s,zones:[o],anchorZone:o}),e.notifyUser(a("Cannot sort. To sort, select only cells or only merges that have the same size.")))}function Va(e,t){t.isSuccessful||(t.reasons.includes(19)&&e.notifyUser(a("This operation is not allowed with multiple selections.")),t.reasons.includes(2)&&e.notifyUser(a("This operation is not possible due to a merge. Please remove the merges first than try again.")))}function Ba(e,t,s){const o=e.dispatch("PASTE",{target:t,pasteOption:s});Va(e,o)}function Ha(e){const t=e.getters.getActiveCols();if(t.size)return t.size;{const t=e.getters.getSelectedZones()[0];return t.right-t.left+1}}function za(e){const t=e.getters.getActiveRows();if(t.size)return t.size;{const t=e.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function Za(e,t){e.dispatch("SET_FORMATTING",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones(),format:t})}function Ga(e,t){e.dispatch("SET_FORMATTING",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones(),style:t})}const Wa=async e=>{e.dispatch("COPY",{target:e.getters.getSelectedZones()}),await e.clipboard.writeText(e.getters.getClipboardContent())},qa=async e=>{e.dispatch("CUT",{target:e.getters.getSelectedZones()}),await e.clipboard.writeText(e.getters.getClipboardContent())},ja=async e=>{const t=e.getters.getClipboardContent();let s;try{s=await e.clipboard.readText()}catch(e){console.warn("The OS clipboard could not be read."),console.error(e)}const o=e.getters.getSelectedZones();s&&s!==t?e.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:o,text:s}):Ba(e,o)},Xa=e=>e.dispatch("PASTE",{target:e.getters.getSelectedZones(),pasteOption:"onlyValue"}),Ya=e=>e.dispatch("PASTE",{target:e.getters.getSelectedZones(),pasteOption:"onlyFormat"}),Ka=e=>e.dispatch("DELETE_CONTENT",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones()}),Qa=e=>{let t,s;const o=e.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?a("Delete row %s",(t+1).toString()):a("Delete rows %s - %s",(t+1).toString(),(s+1).toString())},Ja=e=>{let t=[...e.getters.getActiveRows()];if(!t.length){const s=e.getters.getSelectedZones()[0];for(let e=s.top;e<=s.bottom;e++)t.push(e)}e.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"ROW",elements:t})},el=e=>{let t,s;const o=e.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?a("Delete column %s",os(t)):a("Delete columns %s - %s",os(t),os(s))},tl=e=>{let t=[...e.getters.getActiveCols()];if(!t.length){const s=e.getters.getSelectedZones()[0];for(let e=s.left;e<=s.right;e++)t.push(e)}e.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"COL",elements:t})},sl=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});Va(e,s)},ol=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});Va(e,s)},il=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});Va(e,s)},nl=e=>{const t=e.getters.getSelectedZone(),s=e.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});Va(e,s)},rl=e=>{const t=e.getters.getActiveRows();let s,o;if(t.size)s=Math.min(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.top,o=t.bottom-t.top+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"before",base:s,quantity:o,dimension:"ROW"})},al=e=>{const t=e.getters.getActiveRows();let s,o;if(t.size)s=Math.max(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.bottom,o=t.bottom-t.top+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"after",base:s,quantity:o,dimension:"ROW"})},ll=e=>{const t=e.getters.getActiveCols();let s,o;if(t.size)s=Math.min(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.left,o=t.right-t.left+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"before",dimension:"COL",base:s,quantity:o})},cl=e=>{const t=e.getters.getActiveCols();let s,o;if(t.size)s=Math.max(...t),o=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.right,o=t.right-t.left+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"after",dimension:"COL",base:s,quantity:o})},hl=e=>{e.openSidePanel("ConditionalFormatting",{selection:e.getters.getSelectedZones()})},dl=e=>{e.openLinkEditor()},ul=e=>{const{anchor:t,zones:s}=e.getters.getSelection(),o=e.getters.getActiveSheetId();Ua(e,o,t,s[0],"ascending")},pl=e=>{const{anchor:t,zones:s}=e.getters.getSelection(),o=e.getters.getActiveSheetId();Ua(e,o,t,s[0],"descending")},gl=e=>1===e.getters.getSelectedZones().length,fl=new $a;fl.add("cut",{name:a("Cut"),shortCut:"Ctrl+X",sequence:10,action:qa}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Wa}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:ja,isVisible:gl}).add("paste_special",{name:a("Paste special"),sequence:40,separator:!0,isVisible:gl}).addChild("paste_value_only",["paste_special"],{name:a("Paste values only"),sequence:10,action:Xa}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Ya}).add("sort_range",{name:a("Sort range"),sequence:50,isVisible:gl,separator:!0}).addChild("sort_ascending",["sort_range"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:ul}).addChild("sort_descending",["sort_range"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:pl}).add("add_row_before",{name:e=>{const t=za(e);return 1===t?a("Insert row"):a("Insert %s rows",t.toString())},sequence:70,action:rl,isVisible:gl}).add("add_column_before",{name:e=>{const t=Ha(e);return 1===t?a("Insert column"):a("Insert %s columns",t.toString())},sequence:90,action:ll,isVisible:gl}).add("insert_cell",{name:a("Insert cells"),sequence:100,isVisible:gl,separator:!0}).addChild("insert_cell_down",["insert_cell"],{name:a("Shift down"),sequence:10,action:sl}).addChild("insert_cell_right",["insert_cell"],{name:a("Shift right"),sequence:20,action:ol}).add("delete_row",{name:Qa,sequence:110,action:Ja,isVisible:gl}).add("delete_column",{name:el,sequence:120,action:tl,isVisible:gl}).add("delete_cell",{name:a("Delete cells"),sequence:130,isVisible:gl}).addChild("delete_cell_up",["delete_cell"],{name:a("Shift up"),sequence:10,action:il}).addChild("delete_cell_down",["delete_cell"],{name:a("Shift left"),sequence:20,action:nl}).add("clear_cell",{name:a("Clear cells"),sequence:140,action:Ka,isEnabled:e=>{const t=e.getters.getActiveCell();return Boolean(t)},separator:!0}).add("insert_link",{name:a("Insert link"),separator:!0,sequence:150,action:dl}).add("conditional_formatting",{name:a("Conditional formatting"),sequence:160,action:hl,separator:!0});const ml=new $a;ml.add("cut",{name:a("Cut"),shortCut:"Ctrl+X",sequence:10,action:qa}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Wa}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:ja}).add("paste_special",{name:a("Paste special"),sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{name:a("Paste value only"),sequence:10,action:Xa}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Ya}).add("sort_columns",{name:e=>e.getters.getActiveCols().size>1?a("Sort columns"):a("Sort column"),sequence:50,isVisible:gl,separator:!0}).addChild("sort_ascending",["sort_columns"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:ul}).addChild("sort_descending",["sort_columns"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:pl}).add("add_column_before",{name:e=>{const t=Ha(e);return 1===t?a("Insert column left"):a("Insert %s columns left",t.toString())},sequence:70,action:ll}).add("add_column_after",{name:e=>{const t=Ha(e);return 1===t?a("Insert column right"):a("Insert %s columns right",t.toString())},sequence:80,action:cl}).add("delete_column",{name:el,sequence:90,action:tl}).add("clear_column",{name:e=>{let t,s;const o=e.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?a("Clear column %s",os(t)):a("Clear columns %s - %s",os(t),os(s))},sequence:100,action:e=>{const t=e.getters.getActiveSheetId(),s=[...e.getters.getActiveCols()].map((s=>e.getters.getColsZone(t,s,s)));e.dispatch("DELETE_CONTENT",{target:s,sheetId:e.getters.getActiveSheetId()})}}).add("hide_columns",{name:e=>{const t=e.getters.getElementsFromSelection("COL");let s=t[0],o=t[t.length-1];return 1===t.length?a("Hide column %s",os(s).toString()):o-s+1===t.length?a("Hide columns %s - %s",os(s).toString(),os(o).toString()):a("Hide columns")},sequence:85,action:e=>{const t=e.getters.getElementsFromSelection("COL");e.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.getters.getActiveSheet(),s=e.getters.getHiddenColsGroups(t.id).flat();return t.cols.length>s.length+e.getters.getElementsFromSelection("COL").length},separator:!0}).add("unhide_columns",{name:"Unhide columns",sequence:86,action:e=>{const t=e.getters.getElementsFromSelection("COL");e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.getters.getHiddenColsGroups(e.getters.getActiveSheetId()).flat();return e.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:a("Conditional formatting"),sequence:110,action:hl});const vl=new $a;vl.add("sheet",{name:a("Link sheet"),sequence:10,children:e=>e.getters.getSheets().map(((e,t)=>Fa(e.id,{name:e.name,sequence:t,action:()=>{return{link:{label:e.name,url:(t=e.id,`${Ls}${t}`)},urlRepresentation:e.name,isUrlEditable:!1};var t}})))});const El=new $a;function bl(e,t,s){const o=e.getters.getSheetName(t),i=a("Rename Sheet")+(s?" - "+s:"");e.editText(i,o,(s=>{if(null===s||s===o)return;""===s&&bl(e,t,a("The sheet name cannot be empty."));const i=e.dispatch("RENAME_SHEET",{sheetId:t,name:s});i.isSuccessful||(i.reasons.includes(11)&&bl(e,t,a("A sheet with the name %s already exists. Please select another name.",s)),i.reasons.includes(13)&&bl(e,t,a("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",F.join(" "))))}))}El.add("cut",{name:a("Cut"),sequence:10,shortCut:"Ctrl+X",action:qa}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Wa}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:ja}).add("paste_special",{name:a("Paste special"),sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{name:a("Paste value only"),sequence:10,action:Xa}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Ya}).add("add_row_before",{name:e=>{const t=za(e);return 1===t?a("Insert row above"):a("Insert %s rows above",t.toString())},sequence:50,action:rl}).add("add_row_after",{name:e=>{const t=za(e);return 1===t?a("Insert row below"):a("Insert %s rows below",t.toString())},sequence:60,action:al}).add("delete_row",{name:Qa,sequence:70,action:Ja}).add("clear_row",{name:e=>{let t,s;const o=e.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),s=Math.max(...o);else{const o=e.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?a("Clear row %s",(t+1).toString()):a("Clear rows %s - %s",(t+1).toString(),(s+1).toString())},sequence:80,action:e=>{const t=e.getters.getActiveSheetId(),s=[...e.getters.getActiveRows()].map((s=>e.getters.getRowsZone(t,s,s)));e.dispatch("DELETE_CONTENT",{target:s,sheetId:e.getters.getActiveSheetId()})}}).add("hide_rows",{name:e=>{const t=e.getters.getElementsFromSelection("ROW");let s=t[0],o=t[t.length-1];return 1===t.length?a("Hide row %s",(s+1).toString()):o-s+1===t.length?a("Hide rows %s - %s",(s+1).toString(),(o+1).toString()):a("Hide rows")},sequence:85,action:e=>{const t=e.getters.getElementsFromSelection("ROW");e.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.getters.getActiveSheet(),s=e.getters.getHiddenRowsGroups(t.id).flat();return t.rows.length>s.length+e.getters.getElementsFromSelection("ROW").length},separator:!0}).add("unhide_rows",{name:"Unhide rows",sequence:86,action:e=>{const t=e.getters.getElementsFromSelection("ROW");e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.getters.getHiddenRowsGroups(e.getters.getActiveSheetId()).flat();return e.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:a("Conditional formatting"),sequence:90,action:hl});const Sl=new $a;Sl.add("delete",{name:a("Delete"),sequence:10,isVisible:e=>e.getters.getSheets().length>1,action:e=>e.askConfirmation(a("Are you sure you want to delete this sheet ?"),(()=>{e.dispatch("DELETE_SHEET",{sheetId:e.getters.getActiveSheetId()})}))}).add("duplicate",{name:a("Duplicate"),sequence:20,action:e=>{const t=e.getters.getActiveSheetId(),s=e.uuidGenerator.uuidv4();e.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:s}),e.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:s})}}).add("rename",{name:a("Rename"),sequence:30,action:e=>bl(e,e.getters.getActiveSheetId())}).add("move_right",{name:a("Move right"),sequence:40,isVisible:e=>{const t=e.getters.getActiveSheetId(),s=e.getters.getSheets();return s.findIndex((e=>e.id===t))!==s.length-1},action:e=>e.dispatch("MOVE_SHEET",{sheetId:e.getters.getActiveSheetId(),direction:"right"})}).add("move_left",{name:a("Move left"),sequence:50,isVisible:e=>{const t=e.getters.getActiveSheetId();return 0!==e.getters.getSheets().findIndex((e=>e.id===t))},action:e=>e.dispatch("MOVE_SHEET",{sheetId:e.getters.getActiveSheetId(),direction:"left"})});const Cl=new $a;Cl.add("file",{name:a("File"),sequence:10}).add("edit",{name:a("Edit"),sequence:20}).add("view",{name:a("View"),sequence:30}).add("insert",{name:a("Insert"),sequence:40}).add("format",{name:a("Format"),sequence:50}).add("data",{name:a("Data"),sequence:60}).addChild("save",["file"],{name:a("Save"),shortCut:"Ctrl+S",sequence:10,action:()=>console.log("Not implemented")}).addChild("undo",["edit"],{name:a("Undo"),shortCut:"Ctrl+Z",sequence:10,action:e=>e.dispatch("REQUEST_UNDO")}).addChild("redo",["edit"],{name:a("Redo"),shortCut:"Ctrl+Y",sequence:20,action:e=>e.dispatch("REQUEST_REDO"),separator:!0}).addChild("copy",["edit"],{name:a("Copy"),shortCut:"Ctrl+C",sequence:30,isReadonlyAllowed:!0,action:Wa}).addChild("cut",["edit"],{name:a("Cut"),shortCut:"Ctrl+X",sequence:40,action:qa}).addChild("paste",["edit"],{name:a("Paste"),shortCut:"Ctrl+V",sequence:50,action:ja}).addChild("paste_special",["edit"],{name:a("Paste special"),sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{name:a("Paste value only"),sequence:10,action:Xa}).addChild("paste_special_format",["edit","paste_special"],{name:a("Paste format only"),sequence:20,action:Ya}).addChild("sort_range",["edit"],{name:a("Sort range"),sequence:62,isVisible:gl,separator:!0}).addChild("sort_ascending",["edit","sort_range"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:ul}).addChild("sort_descending",["edit","sort_range"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:pl}).addChild("find_and_replace",["edit"],{name:a("Find and replace"),shortCut:"Ctrl+H",sequence:65,isReadonlyAllowed:!0,action:e=>{e.openSidePanel("FindAndReplace",{})},separator:!0}).addChild("edit_delete_cell_values",["edit"],{name:a("Delete values"),sequence:70,action:Ka}).addChild("edit_delete_row",["edit"],{name:Qa,sequence:80,action:Ja}).addChild("edit_delete_column",["edit"],{name:el,sequence:90,action:tl}).addChild("edit_delete_cell_shift_up",["edit"],{name:a("Delete cell and shift up"),sequence:93,action:il}).addChild("edit_delete_cell_shift_left",["edit"],{name:a("Delete cell and shift left"),sequence:97,action:nl}).addChild("edit_unhide_columns",["edit"],{name:a("Unhide all columns"),sequence:100,action:e=>{const t=e.getters.getActiveSheet();e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t.id,dimension:"COL",elements:Array.from(Array(t.cols.length).keys())})},isVisible:e=>e.getters.getHiddenColsGroups(e.getters.getActiveSheetId()).length>0}).addChild("edit_unhide_rows",["edit"],{name:a("Unhide all rows"),sequence:100,action:e=>{const t=e.getters.getActiveSheet();e.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t.id,dimension:"ROW",elements:Array.from(Array(t.rows.length).keys())})},isVisible:e=>e.getters.getHiddenRowsGroups(e.getters.getActiveSheetId()).length>0}).addChild("insert_row_before",["insert"],{name:e=>{const t=za(e);return 1===t?a("Row above"):a("%s Rows above",t.toString())},sequence:10,action:rl,isVisible:e=>0===e.getters.getActiveCols().size}).addChild("insert_row_after",["insert"],{name:e=>{const t=za(e);return 1===t?a("Row below"):a("%s Rows below",t.toString())},sequence:20,action:al,isVisible:e=>0===e.getters.getActiveCols().size,separator:!0}).addChild("insert_column_before",["insert"],{name:e=>{const t=Ha(e);return 1===t?a("Column left"):a("%s Columns left",t.toString())},sequence:30,action:ll,isVisible:e=>0===e.getters.getActiveRows().size}).addChild("insert_column_after",["insert"],{name:e=>{const t=Ha(e);return 1===t?a("Column right"):a("%s Columns right",t.toString())},sequence:40,action:cl,isVisible:e=>0===e.getters.getActiveRows().size,separator:!0}).addChild("insert_insert_cell_shift_down",["insert"],{name:a("Insert cells and shift down"),sequence:43,action:sl}).addChild("insert_insert_cell_shift_right",["insert"],{name:a("Insert cells and shift right"),sequence:47,action:ol,separator:!0}).addChild("insert_chart",["insert"],{name:a("Chart"),sequence:50,action:e=>{var t,s;const o=e.getters.getSelectedZone();let i=o;const n=e.uuidGenerator.uuidv4();let r;o.left!==o.right&&(i={...o,left:o.left+1});const a=[Xs(i)],l=e.getters.getActiveSheetId(),c={x:(null===(t=e.getters.tryGetCol(l,o.right+1))||void 0===t?void 0:t.start)||0,y:(null===(s=e.getters.tryGetRow(l,o.top))||void 0===s?void 0:s.start)||0};let h=!1;for(let t=i.left;t<=i.right;t++){const s=e.getters.getCell(l,t,o.top);if(s&&s.evaluated.type!==$e.number){h=!0;break}}o.left!==o.right&&(r=Xs({...o,right:o.left,top:h?o.top+1:o.top})),e.dispatch("CREATE_CHART",{sheetId:l,id:n,position:c,definition:{title:"",dataSets:a,labelRange:r,type:"bar",stackedBar:!1,dataSetsHaveTitle:h,background:g,verticalAxisPosition:"left",legendPosition:"top"}});const d=e.getters.getFigure(l,n);e.openSidePanel("ChartPanel",{figure:d})}}).addChild("insert_link",["insert"],{name:a("Link"),separator:!0,sequence:60,action:dl}).addChild("insert_sheet",["insert"],{name:a("New sheet"),sequence:70,action:e=>{const t=e.getters.getActiveSheetId(),s=e.getters.getVisibleSheets().findIndex((e=>e===t))+1,o=e.uuidGenerator.uuidv4();e.dispatch("CREATE_SHEET",{sheetId:o,position:s}),e.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},separator:!0}).addChild("view_gridlines",["view"],{name:e=>e.getters.getGridLinesVisibility(e.getters.getActiveSheetId())?a("Hide gridlines"):a("Show gridlines"),action:e=>{const t=e.getters.getActiveSheetId();e.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.getters.getGridLinesVisibility(t)})},sequence:5,separator:!0}).addChild("view_formulas",["view"],{name:e=>e.getters.shouldShowFormulas()?a("Hide formulas"):a("Show formulas"),action:e=>e.dispatch("SET_FORMULA_VISIBILITY",{show:!e.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,sequence:10}).addChild("format_number",["format"],{name:a("Numbers"),sequence:10,separator:!0}).addChild("format_number_general",["format","format_number"],{name:a("General"),sequence:10,separator:!0,action:e=>Za(e,"")}).addChild("format_number_number",["format","format_number"],{name:a("Number (1,000.12)"),sequence:20,action:e=>Za(e,"#,##0.00")}).addChild("format_number_percent",["format","format_number"],{name:a("Percent (10.12%)"),sequence:30,separator:!0,action:e=>Za(e,"0.00%")}).addChild("format_number_date",["format","format_number"],{name:a("Date (9/26/2008)"),sequence:40,action:e=>Za(e,"m/d/yyyy")}).addChild("format_number_time",["format","format_number"],{name:a("Time (10:43:00 PM)"),sequence:50,action:e=>Za(e,"hh:mm:ss a")}).addChild("format_number_date_time",["format","format_number"],{name:a("Date time (9/26/2008 22:43:00)"),sequence:60,action:e=>Za(e,"m/d/yyyy hh:mm:ss")}).addChild("format_number_duration",["format","format_number"],{name:a("Duration (27:51:38)"),sequence:70,separator:!0,action:e=>Za(e,"hhhh:mm:ss")}).addChild("format_bold",["format"],{name:a("Bold"),sequence:20,shortCut:"Ctrl+B",action:e=>Ga(e,{bold:!e.getters.getCurrentStyle().bold})}).addChild("format_italic",["format"],{name:a("Italic"),sequence:30,shortCut:"Ctrl+I",action:e=>Ga(e,{italic:!e.getters.getCurrentStyle().italic})}).addChild("format_underline",["format"],{name:a("Underline"),shortCut:"Ctrl+U",sequence:40,action:e=>Ga(e,{underline:!e.getters.getCurrentStyle().underline})}).addChild("format_strikethrough",["format"],{name:a("Strikethrough"),sequence:50,action:e=>Ga(e,{strikethrough:!e.getters.getCurrentStyle().strikethrough}),separator:!0}).addChild("format_font_size",["format"],{name:a("Font size"),sequence:60,separator:!0}).addChild("format_cf",["format"],{name:a("Conditional formatting"),sequence:70,action:hl,separator:!0});for(let e of hs)Cl.addChild(`format_font_size_${e.pt}`,["format","format_font_size"],{name:e.pt.toString(),sequence:e.pt,action:t=>Ga(t,{fontSize:e.pt})});const yl=new class extends Ae{addTransformation(e,t,s){for(let o of t)this.content[o]||(this.content[o]=new Map),this.content[o].set(e,s);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},{css:wl,xml:Il}=t.tags,xl=[["#000000","#434343","#666666","#999999","#b7b7b7","#cccccc","#d9d9d9","#efefef","#f3f3f3","#ffffff"],["#980000","#ff0000","#ff9900","#ffff00","#00ff00","#00ffff","#4a86e8","#0000ff","#9900ff","#ff00ff"],["#e6b8af","#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#c9daf8","#cfe2f3","#d9d2e9","#ead1dc"],["#dd7e6b","#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#a4c2f4","#9fc5e8","#b4a7d6","#d5a6bd"],["#cc4125","#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6d9eeb","#6fa8dc","#8e7cc3","#c27ba0"],["#a61c00","#cc0000","#e69138","#f1c232","#6aa84f","#45818e","#3c78d8","#3d85c6","#674ea7","#a64d79"],["#85200c","#990000","#b45f06","#bf9000","#38761d","#134f5c","#1155cc","#0b5394","#351c75","#741b47"],["#5b0f00","#660000","#783f04","#7f6000","#274e13","#0c343d","#1c4587","#073763","#20124d","#4c1130"]],Tl=24*Math.max(...xl.map((e=>e.length)))+12;class Rl extends t.Component{constructor(){super(...arguments),this.COLORS=xl}onColorClick(e){const t=e.target.dataset.color;t&&this.props.onColorPicked(t)}}Rl.template=Il`
2
2
  <div class="o-color-picker"
3
3
  t-att-class="props.dropdownDirection || 'right'"
4
4
  t-on-click="onColorClick">
@@ -946,7 +946,7 @@
946
946
  }
947
947
  }
948
948
  }
949
- `;class uh extends t.Component{constructor(e,s){super(e,s),this.icons=Yl,this.iconSets=Kl,this.reverseIcon='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon refresh" viewBox="0 0 512 512"><path fill="currentColor" d="M440.65 12.57l4 82.77A247.16 247.16 0 0 0 255.83 8C134.73 8 33.91 94.92 12.29 209.82A12 12 0 0 0 24.09 224h49.05a12 12 0 0 0 11.67-9.26 175.91 175.91 0 0 1 317-56.94l-101.46-4.86a12 12 0 0 0-12.57 12v47.41a12 12 0 0 0 12 12H500a12 12 0 0 0 12-12V12a12 12 0 0 0-12-12h-47.37a12 12 0 0 0-11.98 12.57zM255.83 432a175.61 175.61 0 0 1-146-77.8l101.8 4.87a12 12 0 0 0 12.57-12v-47.4a12 12 0 0 0-12-12H12a12 12 0 0 0-12 12V500a12 12 0 0 0 12 12h47.35a12 12 0 0 0 12-12.6l-4.15-82.57A247.17 247.17 0 0 0 255.83 504c121.11 0 221.93-86.92 243.55-201.82a12 12 0 0 0-11.8-14.18h-49.05a12 12 0 0 0-11.67 9.26A175.86 175.86 0 0 1 255.83 432z"></path></svg>',this.trashIcon='<svg xmlns ="http://www.w3.org/2000/svg" class="o-cf-icon trash" viewBox = "0 0 448 512" > <path fill="currentColor" d = "M432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16zM53.2 467a48 48 0 0 0 47.9 45h245.8a48 48 0 0 0 47.9-45L416 128H32z" > </path></svg >',this.cellIsOperators=Sc,this.getTextDecoration=Gc,this.colorNumberString=Xt,this.getters=this.env.getters,this.state=t.useState({mode:"list",errors:[],rules:this.getDefaultRules()}),this.activeSheetId=this.getters.getActiveSheetId();const o=this.getters.getRulesSelection(this.activeSheetId,s.selection||[]);if(1===o.length){const e=this.conditionalFormats.find((e=>e.id===o[0]));e&&this.editConditionalFormat(e)}}setup(){lh((e=>{const t=this.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.getters.getActiveSheetId(),s=this.getters.getRulesSelection(t,e.selection||[]);if(1===s.length){const e=this.conditionalFormats.find((e=>e.id===s[0]));e&&this.editConditionalFormat(e)}else this.switchToList()}})),ch(window,"click",this.closeMenus)}get conditionalFormats(){return this.getters.getConditionalFormats(this.getters.getActiveSheetId())}get isRangeValid(){return this.state.errors.includes(21)}errorMessage(e){return this.env._t(ac.Errors[e]||ac.Errors.unexpected)}switchToList(){this.state.mode="list",this.state.currentCF=void 0,this.state.currentCFType=void 0,this.state.errors=[],this.state.rules=this.getDefaultRules()}getStyle(e){if("CellIsRule"===e.type){return`font-weight:${e.style.bold?"bold":"normal"};\n text-decoration:${Gc(e.style)};\n font-style:${e.style.italic?"italic":"normal"};\n color:${e.style.textColor||"none"};\n background-color:${e.style.fillColor||"none"};`}if("ColorScaleRule"===e.type){const t=Xt(e.minimum.color),s=e.midpoint?Xt(e.midpoint.color):null,o=Xt(e.maximum.color),i="background-image: linear-gradient(to right, #";return s?i+t+", #"+s+", #"+o+")":i+t+", #"+o+")"}return""}getDescription(e){switch(e.rule.type){case"CellIsRule":return Sc[e.rule.operator];case"ColorScaleRule":return this.env._t("Color scale");case"IconSetRule":return this.env._t("Icon Set");default:return""}}saveConditionalFormat(){if(this.state.currentCF){if(this.state.currentCF.ranges.some((e=>!e.match(es))))return void(this.state.errors=[22]);const e=this.env.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:this.getEditorRule(),id:"edit"===this.state.mode?this.state.currentCF.id:this.env.uuidGenerator.uuidv4()},target:this.state.currentCF.ranges.map(qs),sheetId:this.getters.getActiveSheetId()});e.isSuccessful?this.switchToList():this.state.errors=e.reasons}}getEditorRule(){switch(this.state.currentCFType){case"CellIsRule":return this.state.rules.cellIs;case"ColorScaleRule":return this.state.rules.colorScale;case"IconSetRule":return this.state.rules.iconSet}throw new Error(`Invalid cf type: ${this.state.currentCFType}`)}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"IsNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:16777215},midpoint:void 0,maximum:{type:"value",color:6989903}},iconSet:{type:"IconSetRule",icons:{upper:"arrowGood",middle:"arrowNeutral",lower:"arrowBad"},upperInflectionPoint:{type:"percentage",value:"66",operator:"gt"},lowerInflectionPoint:{type:"percentage",value:"33",operator:"gt"}}}}addConditionalFormat(){this.state.mode="add",this.state.currentCFType="CellIsRule",this.state.currentCF={id:this.env.uuidGenerator.uuidv4(),ranges:this.getters.getSelectedZones().map((e=>this.getters.zoneToXC(this.getters.getActiveSheetId(),e)))}}deleteConditionalFormat(e){this.env.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:e.id,sheetId:this.getters.getActiveSheetId()})}editConditionalFormat(e){switch(this.state.mode="edit",this.state.currentCF=e,this.state.currentCFType=e.rule.type,e.rule.type){case"CellIsRule":this.state.rules.cellIs=e.rule;break;case"ColorScaleRule":this.state.rules.colorScale=e.rule;break;case"IconSetRule":this.state.rules.iconSet=e.rule}}changeRuleType(e){this.state.currentCFType!==e&&this.state.rules&&(this.state.errors=[],this.state.currentCFType=e)}onRangesChanged({detail:e}){this.state.currentCF&&(this.state.currentCF.ranges=e.ranges)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(36))}get isValue2Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(37))}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.closeMenus()}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.closeMenus()}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes(43)||this.state.errors.includes(35)||this.state.errors.includes(32)||this.state.errors.includes(38);case"midpoint":return this.state.errors.includes(44)||this.state.errors.includes(39)||this.state.errors.includes(34);case"maximum":return this.state.errors.includes(45)||this.state.errors.includes(40);default:return!1}}setColorScaleColor(e,t){const s=this.state.rules.colorScale[e];s&&(s.color=Number.parseInt(t.substr(1),16)),this.closeMenus()}getPreviewGradient(){var e;const t=this.state.rules.colorScale,s=Xt(t.minimum.color),o=Xt((null===(e=t.midpoint)||void 0===e?void 0:e.color)||f),i=Xt(t.maximum.color),n="background-image: linear-gradient(to right, #";return void 0===t.midpoint?n+s+", #"+i+")":n+s+", #"+o+", #"+i+")"}getThresholdColor(e){return Xt(e?e.color:f)}onMidpointChange(e){const t=e.target.value,s=this.state.rules.colorScale;s.midpoint="none"===t?void 0:{color:f,value:"",...s.midpoint,type:t}}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes(42)||this.state.errors.includes(47)||this.state.errors.includes(33);case"upperInflectionPoint":return this.state.errors.includes(41)||this.state.errors.includes(46)||this.state.errors.includes(33);default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad}setIcon(e,t){this.state.rules.iconSet.icons[e]=t}}uh.template=hh,uh.style=dh,uh.components={SelectionInput:rc,IconPicker:jc,ColorPicker:Rl};const{onMounted:ph,onWillUnmount:gh}=t.hooks,{xml:fh,css:mh}=t.tags,vh=fh`
949
+ `;class uh extends t.Component{constructor(e,s){super(e,s),this.icons=Yl,this.iconSets=Kl,this.reverseIcon='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon refresh" viewBox="0 0 512 512"><path fill="currentColor" d="M440.65 12.57l4 82.77A247.16 247.16 0 0 0 255.83 8C134.73 8 33.91 94.92 12.29 209.82A12 12 0 0 0 24.09 224h49.05a12 12 0 0 0 11.67-9.26 175.91 175.91 0 0 1 317-56.94l-101.46-4.86a12 12 0 0 0-12.57 12v47.41a12 12 0 0 0 12 12H500a12 12 0 0 0 12-12V12a12 12 0 0 0-12-12h-47.37a12 12 0 0 0-11.98 12.57zM255.83 432a175.61 175.61 0 0 1-146-77.8l101.8 4.87a12 12 0 0 0 12.57-12v-47.4a12 12 0 0 0-12-12H12a12 12 0 0 0-12 12V500a12 12 0 0 0 12 12h47.35a12 12 0 0 0 12-12.6l-4.15-82.57A247.17 247.17 0 0 0 255.83 504c121.11 0 221.93-86.92 243.55-201.82a12 12 0 0 0-11.8-14.18h-49.05a12 12 0 0 0-11.67 9.26A175.86 175.86 0 0 1 255.83 432z"></path></svg>',this.trashIcon='<svg xmlns ="http://www.w3.org/2000/svg" class="o-cf-icon trash" viewBox = "0 0 448 512" > <path fill="currentColor" d = "M432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16zM53.2 467a48 48 0 0 0 47.9 45h245.8a48 48 0 0 0 47.9-45L416 128H32z" > </path></svg >',this.cellIsOperators=Sc,this.getTextDecoration=Gc,this.colorNumberString=Yt,this.getters=this.env.getters,this.state=t.useState({mode:"list",errors:[],rules:this.getDefaultRules()}),this.activeSheetId=this.getters.getActiveSheetId();const o=this.getters.getRulesSelection(this.activeSheetId,s.selection||[]);if(1===o.length){const e=this.conditionalFormats.find((e=>e.id===o[0]));e&&this.editConditionalFormat(e)}}setup(){lh((e=>{const t=this.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.getters.getActiveSheetId(),s=this.getters.getRulesSelection(t,e.selection||[]);if(1===s.length){const e=this.conditionalFormats.find((e=>e.id===s[0]));e&&this.editConditionalFormat(e)}else this.switchToList()}})),ch(window,"click",this.closeMenus)}get conditionalFormats(){return this.getters.getConditionalFormats(this.getters.getActiveSheetId())}get isRangeValid(){return this.state.errors.includes(21)}errorMessage(e){return this.env._t(ac.Errors[e]||ac.Errors.unexpected)}switchToList(){this.state.mode="list",this.state.currentCF=void 0,this.state.currentCFType=void 0,this.state.errors=[],this.state.rules=this.getDefaultRules()}getStyle(e){if("CellIsRule"===e.type){return`font-weight:${e.style.bold?"bold":"normal"};\n text-decoration:${Gc(e.style)};\n font-style:${e.style.italic?"italic":"normal"};\n color:${e.style.textColor||"none"};\n background-color:${e.style.fillColor||"none"};`}if("ColorScaleRule"===e.type){const t=Yt(e.minimum.color),s=e.midpoint?Yt(e.midpoint.color):null,o=Yt(e.maximum.color),i="background-image: linear-gradient(to right, #";return s?i+t+", #"+s+", #"+o+")":i+t+", #"+o+")"}return""}getDescription(e){switch(e.rule.type){case"CellIsRule":return Sc[e.rule.operator];case"ColorScaleRule":return this.env._t("Color scale");case"IconSetRule":return this.env._t("Icon Set");default:return""}}saveConditionalFormat(){if(this.state.currentCF){if(this.state.currentCF.ranges.some((e=>!e.match(ts))))return void(this.state.errors=[22]);const e=this.env.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:this.getEditorRule(),id:"edit"===this.state.mode?this.state.currentCF.id:this.env.uuidGenerator.uuidv4()},target:this.state.currentCF.ranges.map(qs),sheetId:this.getters.getActiveSheetId()});e.isSuccessful?this.switchToList():this.state.errors=e.reasons}}getEditorRule(){switch(this.state.currentCFType){case"CellIsRule":return this.state.rules.cellIs;case"ColorScaleRule":return this.state.rules.colorScale;case"IconSetRule":return this.state.rules.iconSet}throw new Error(`Invalid cf type: ${this.state.currentCFType}`)}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"IsNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:16777215},midpoint:void 0,maximum:{type:"value",color:6989903}},iconSet:{type:"IconSetRule",icons:{upper:"arrowGood",middle:"arrowNeutral",lower:"arrowBad"},upperInflectionPoint:{type:"percentage",value:"66",operator:"gt"},lowerInflectionPoint:{type:"percentage",value:"33",operator:"gt"}}}}addConditionalFormat(){this.state.mode="add",this.state.currentCFType="CellIsRule",this.state.currentCF={id:this.env.uuidGenerator.uuidv4(),ranges:this.getters.getSelectedZones().map((e=>this.getters.zoneToXC(this.getters.getActiveSheetId(),e)))}}deleteConditionalFormat(e){this.env.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:e.id,sheetId:this.getters.getActiveSheetId()})}editConditionalFormat(e){switch(this.state.mode="edit",this.state.currentCF=e,this.state.currentCFType=e.rule.type,e.rule.type){case"CellIsRule":this.state.rules.cellIs=e.rule;break;case"ColorScaleRule":this.state.rules.colorScale=e.rule;break;case"IconSetRule":this.state.rules.iconSet=e.rule}}changeRuleType(e){this.state.currentCFType!==e&&this.state.rules&&(this.state.errors=[],this.state.currentCFType=e)}onRangesChanged({detail:e}){this.state.currentCF&&(this.state.currentCF.ranges=e.ranges)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(36))}get isValue2Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(37))}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.closeMenus()}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.closeMenus()}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes(43)||this.state.errors.includes(35)||this.state.errors.includes(32)||this.state.errors.includes(38);case"midpoint":return this.state.errors.includes(44)||this.state.errors.includes(39)||this.state.errors.includes(34);case"maximum":return this.state.errors.includes(45)||this.state.errors.includes(40);default:return!1}}setColorScaleColor(e,t){const s=this.state.rules.colorScale[e];s&&(s.color=Number.parseInt(t.substr(1),16)),this.closeMenus()}getPreviewGradient(){var e;const t=this.state.rules.colorScale,s=Yt(t.minimum.color),o=Yt((null===(e=t.midpoint)||void 0===e?void 0:e.color)||f),i=Yt(t.maximum.color),n="background-image: linear-gradient(to right, #";return void 0===t.midpoint?n+s+", #"+i+")":n+s+", #"+o+", #"+i+")"}getThresholdColor(e){return Yt(e?e.color:f)}onMidpointChange(e){const t=e.target.value,s=this.state.rules.colorScale;s.midpoint="none"===t?void 0:{color:f,value:"",...s.midpoint,type:t}}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes(42)||this.state.errors.includes(47)||this.state.errors.includes(33);case"upperInflectionPoint":return this.state.errors.includes(41)||this.state.errors.includes(46)||this.state.errors.includes(33);default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad}setIcon(e,t){this.state.rules.iconSet.icons[e]=t}}uh.template=hh,uh.style=dh,uh.components={SelectionInput:rc,IconPicker:jc,ColorPicker:Rl};const{onMounted:ph,onWillUnmount:gh}=t.hooks,{xml:fh,css:mh}=t.tags,vh=fh`
950
950
  <div class="o-find-and-replace" tabindex="0" t-on-focusin="onFocusSidePanel">
951
951
  <div class="o-section">
952
952
  <div class="o-section-title" t-esc="env._t('${yc}')"/>
@@ -1045,14 +1045,14 @@
1045
1045
  }
1046
1046
  }
1047
1047
  }
1048
- `;class bh extends t.Component{constructor(){super(...arguments),this.getters=this.env.getters,this.state=t.useState(this.initialState())}get hasSearchResult(){return null!==this.env.getters.getCurrentSelectedMatchIndex()}setup(){ph((()=>this.focusInput())),gh((()=>this.env.dispatch("CLEAR_SEARCH")))}onInput(e){this.state.toSearch=e.target.value,this.debouncedUpdateSearch()}onKeydownSearch(e){"Enter"===e.key&&(e.preventDefault(),this.onSelectNextCell())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),this.replace())}onFocusSidePanel(){this.state.searchOptions.searchFormulas=this.getters.shouldShowFormulas(),this.state.replaceOptions.modifyFormulas=this.state.searchOptions.searchFormulas?this.state.searchOptions.searchFormulas:this.state.replaceOptions.modifyFormulas,this.env.dispatch("REFRESH_SEARCH")}searchFormulas(){this.env.dispatch("SET_FORMULA_VISIBILITY",{show:this.state.searchOptions.searchFormulas}),this.state.replaceOptions.modifyFormulas=this.state.searchOptions.searchFormulas,this.updateSearch()}onSelectPreviousCell(){this.env.dispatch("SELECT_SEARCH_PREVIOUS_MATCH")}onSelectNextCell(){this.env.dispatch("SELECT_SEARCH_NEXT_MATCH")}updateSearch(){this.env.dispatch("UPDATE_SEARCH",{toSearch:this.state.toSearch,searchOptions:this.state.searchOptions})}debouncedUpdateSearch(){clearTimeout(this.inDebounce),this.inDebounce=setTimeout((()=>this.updateSearch.call(this)),400)}replace(){this.env.dispatch("REPLACE_SEARCH",{replaceWith:this.state.replaceWith,replaceOptions:this.state.replaceOptions})}replaceAll(){this.env.dispatch("REPLACE_ALL_SEARCH",{replaceWith:this.state.replaceWith,replaceOptions:this.state.replaceOptions})}focusInput(){const e=this.el.querySelector("input");e&&e.focus()}initialState(){return{toSearch:"",replaceWith:"",searchOptions:{matchCase:!1,exactMatch:!1,searchFormulas:!1},replaceOptions:{modifyFormulas:!1}}}}bh.template=vh,bh.style=Eh;const Sh=new Me;Sh.add("ConditionalFormatting",{title:a("Conditional formatting"),Body:uh}),Sh.add("ChartPanel",{title:a("Chart"),Body:zc}),Sh.add("FindAndReplace",{title:a("Find and Replace"),Body:bh});const Ch=new Me;class yh extends ma{constructor(e,t,s,o){super(t,s,o),this.getters=e,this.ui=o}drawGrid(e,t){}}yh.layers=[];class wh{constructor(e,t,s){this.index=0,this.cells=e,this.getters=t,this.direction=s}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:s,tooltip:o}=Ma.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:s,tooltip:o,origin:{col:e.data.col,row:e.data.row}}}}class Ih extends yh{constructor(){super(...arguments),this.lastCellSelected={}}allowDispatch(e){switch(e.type){case"AUTOFILL_SELECT":const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:ms(e.col,0,this.getters.getSheet(t).cols.length),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:ms(e.row,0,this.getters.getSheet(t).rows.length),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:30;case"AUTOFILL_AUTO":const s=this.getters.getSelectedZone();return s.top===s.bottom?0:1}return 0}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;case"AUTOFILL_CELL":this.autoFillMerge(e.originCol,e.originRow,e.col,e.row);const t=this.getters.getActiveSheetId();this.dispatch("UPDATE_CELL",{sheetId:t,col:e.col,row:e.row,style:e.style||null,content:e.content||"",format:e.format||""}),this.dispatch("SET_BORDER",{sheetId:t,col:e.col,row:e.row,border:e.border})}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),s=this.autofillZone;switch(this.direction){case 1:for(let o=t.left;o<=t.right;o++){const i=[];for(let e=t.top;e<=t.bottom;e++)i.push(is(o,e));const n=this.createGenerator(i);for(let t=s.top;t<=s.bottom;t++)this.computeNewCell(n,o,t,e)}break;case 0:for(let o=t.left;o<=t.right;o++){const i=[];for(let e=t.bottom;e>=t.top;e--)i.push(is(o,e));const n=this.createGenerator(i);for(let t=s.bottom;t>=s.top;t--)this.computeNewCell(n,o,t,e)}break;case 2:for(let o=t.top;o<=t.bottom;o++){const i=[];for(let e=t.right;e>=t.left;e--)i.push(is(e,o));const n=this.createGenerator(i);for(let t=s.right;t>=s.left;t--)this.computeNewCell(n,t,o,e)}break;case 3:for(let o=t.top;o<=t.bottom;o++){const i=[];for(let e=t.left;e<=t.right;e++)i.push(is(e,o));const n=this.createGenerator(i);for(let t=s.left;t<=s.right;t++)this.computeNewCell(n,t,o,e)}}if(e){const e=Qs(this.getters.getSelectedZone(),this.autofillZone);this.autofillZone=void 0,this.lastCellSelected={},this.direction=void 0,this.tooltip=void 0,this.dispatch("SET_SELECTION",{zones:[e],anchor:[e.left,e.top],anchorZone:e})}}select(e,t){const s=this.getters.getSelectedZone();if(to(e,t,s))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case 0:this.saveZone(t,s.top-1,s.left,s.right);break;case 1:this.saveZone(s.bottom+1,t,s.left,s.right);break;case 2:this.saveZone(s.top,s.bottom,e,s.left-1);break;case 3:this.saveZone(s.top,s.bottom,s.right+1,e)}this.autofill(!1)}}autofillAuto(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let s=e.left,o=e.bottom;if(s>0){let e=this.getters.getCell(t,s-1,o);for(;e&&!e.isEmpty();)o+=1,e=this.getters.getCell(t,s-1,o)}if(o===e.bottom&&(s=e.right,s<=this.getters.getActiveSheet().cols.length)){let e=this.getters.getCell(t,s+1,o);for(;e&&!e.isEmpty();)o+=1,e=this.getters.getCell(t,s+1,o)}o!==e.bottom&&(this.select(e.left,o-1),this.autofill(!0))}computeNewCell(e,t,s,o){const{cellData:i,tooltip:n,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=i;this.tooltip=n,o&&this.dispatch("AUTOFILL_CELL",{originCol:r.col,originRow:r.row,col:t,row:s,content:a,style:l,border:c,format:h})}getRule(e,t){const s=Aa.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((s=>s.condition(e,t)));return s&&s.generateRule(e,t)}createGenerator(e){const t=[],s=[],o=this.getters.getActiveSheetId();for(let t of e){const[e,i]=os(t),n=this.getters.getCell(o,e,i);s.push({col:e,row:i,cell:n,sheetId:o})}const i=s.map((e=>e.cell));for(let e of s){let s={type:"COPY_MODIFIER"};if(e&&e.cell){s=this.getRule(e.cell,i)||s}const{sheetId:o,col:n,row:r}=e,a=this.getters.getCellBorder(o,n,r)||void 0;t.push({data:{...e,border:a},rule:s})}return new wh(t,this.getters,this.direction)}saveZone(e,t,s,o){this.autofillZone={top:e,bottom:t,left:s,right:o}}getDirection(e,t){const s=this.getters.getSelectedZone(),o={up:{number:s.top-t,value:0},down:{number:t-s.bottom,value:1},left:{number:s.left-e,value:2},right:{number:e-s.right,value:3}};if(1===Object.values(o).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(o).find((e=>e.number>0?1:0)).value;const i=o.up.number>0?"up":"down",n=o.left.number>0?"left":"right";return Math.abs(o[i].number)>=Math.abs(o[n].number)?o[i].value:o[n].value}autoFillMerge(e,t,s,o){const i=this.getters.getActiveSheet();if(this.getters.isInMerge(i.id,s,o)&&!this.getters.isInMerge(i.id,e,t)){const e=this.getters.getMerge(i.id,s,o);e&&this.dispatch("REMOVE_MERGE",{sheetId:i.id,target:[e]})}const n=this.getters.getMerge(i.id,e,t);(null==n?void 0:n.topLeft.col)===e&&(null==n?void 0:n.topLeft.row)===t&&this.dispatch("ADD_MERGE",{sheetId:i.id,target:[{top:o,bottom:o+n.bottom-n.top,left:s,right:s+n.right-n.left}]})}drawGrid(e){if(!this.autofillZone)return;const{viewport:t,ctx:s,thinLineWidth:o}=e,[i,n,r,a]=this.getters.getRect(this.autofillZone,t);r>0&&a>0&&(s.strokeStyle="black",s.lineWidth=o,s.setLineDash([3]),s.strokeRect(i,n,r,a),s.setLineDash([]))}}Ih.layers=[6],Ih.getters=["getAutofillTooltip"],Ih.modes=["normal"];class xh extends yh{handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:s}=this.getters.getSelection();for(const o of t){const t=this.getAutomaticSums(e,o,s);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,s){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,s):this.sumData(e,t)}sumData(e,t){const s=this.dimensionsToSum(e,t),o=this.sumDimensions(e,t,s).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return s.has("ROW")&&s.has("COL")&&o.push(this.sumTotal(t)),o}sumAdjacentData(e,t,s){const[o,i]=to(s[0],s[1],t)?s:[t.left,t.top],n=this.findAdjacentData(e,o,i);return n?this.getters.isSingleCellOrMerge(e,t)||no(Qs(n,t))?[{position:[o,i],zone:n}]:this.sumDimensions(e,Qs(n,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,s){const o=this.getters.getSheet(e),i=this.findSuitableZoneToSum(o,...this.getters.getMainCell(e,t,s));if(i)return this.getters.expandZone(e,i)}findSuitableZoneToSum(e,t,s){const o=this.getters.getCell(e.id,t,s-1),i=this.getters.getCell(e.id,t-1,s);if(this.isNumber(i)&&!this.isNumber(o))return this.findHorizontalZone(e,t,s);const n=this.findVerticalZone(e,t,s);if(this.isZoneValid(n))return n;const r=this.findHorizontalZone(e,t,s);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,s){const o={top:0,bottom:s-1,left:t,right:t},i=this.reduceZoneStart(e,o,o.bottom);return{...o,top:i}}findHorizontalZone(e,t,s){const o={top:s,bottom:s,left:0,right:t-1},i=this.reduceZoneStart(e,o,o.right);return{...o,left:i}}reduceZoneStart(e,t,s){const o=this.getters.getCellsInZone(e.id,t),i=Es(s,-1,-1),n=i.filter((e=>{var t;return o[e]&&!(null===(t=o[e])||void 0===t?void 0:t.isAutoSummable)})),r=Math.max(...n),a=bs(i.filter((e=>this.isNumber(o[e]))))[0]||[];return Math.max(...a)<r?1/0:Math.min(...a)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){var t;return(null==e?void 0:e.evaluated.type)===Fe.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(_))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){const s=new Set;return no(t)?(s.add(1===io(t).width?"COL":"ROW"),s):(this.lastColIsEmpty(e,t)&&s.add("ROW"),this.lastRowIsEmpty(e,t)&&s.add("COL"),0===s.size&&s.add("COL"),s)}sumDimensions(e,t,s){return[...s.has("COL")?this.sumColumns(t,e):[],...s.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:s}=e;return{position:[s,t],zone:{...e,top:t,right:s-1}}}sumColumns(e,t){const s=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,s.bottom-1)},ro(s).map((t=>({position:t,zone:{...e,right:t[0],left:t[0]}})))}sumRows(e,t){const s=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,s.right-1)},ro(s).map((t=>({position:t,zone:{...e,top:t[1],bottom:t[1]}})))}dispatchCellUpdates(e,t){for(const s of t){const[t,o]=s.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:`=SUM(${this.getters.zoneToXC(e,s.zone)})`})}}nextEmptyRow(e,t){let s=t.bottom+1;const{left:o,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:s,top:s,left:o,right:i});)s++;return{...t,top:s,bottom:s}}nextEmptyCol(e,t){let s=t.right+1;const{top:o,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:s,right:s,top:o,bottom:i});)s++;return{...t,left:s,right:s}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}xh.getters=["getAutomaticSums"],xh.modes=["normal","headless"];class Th extends yh{constructor(){super(...arguments),this.status="invisible",this._isPaintingFormat=!1}allowDispatch(e){switch(e.type){case"PASTE":return this.isPasteAllowed(this.state,e.target,!!e.force);case"INSERT_CELL":{const{cut:t,paste:s}=this.getInsertCellsTargets(e.zone,e.shiftDimension),o=this.getClipboardState(t,"CUT");return this.isPasteAllowed(o,s,!1)}case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),o=this.getClipboardState(t,"CUT");return this.isPasteAllowed(o,s,!1)}}return 0}handle(e){var t,s;switch(e.type){case"COPY":case"CUT":this.state=this.getClipboardState(e.target,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const o=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1;const i=this.state.cells.length,n=this.state.cells[0].length;this.paste(this.state,e.target,o),this.selectPastedZone(n,i,e.target),this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!js(t[0])){for(const[t,s]of ro(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:s,sheetId:this.getters.getActiveSheetId()});break}const o=this.getClipboardState(t,"CUT");this.paste(o,s);break}case"INSERT_CELL":{const{cut:t,paste:s}=this.getInsertCellsTargets(e.zone,e.shiftDimension),o=this.getClipboardState(t,"CUT");this.paste(o,s);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(t=this.state)||void 0===t?void 0:t.operation))return;this.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.state=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(s=this.state)||void 0===s?void 0:s.operation))return;for(let t of e.elements){if(this.isColRowDirtyingClipboard(t,e.dimension)){this.state=void 0;break}}this.status="invisible";break;case"PASTE_FROM_OS_CLIPBOARD":this.pasteFromClipboard(e.target,e.text);break;case"ACTIVATE_PAINT_FORMAT":this.state=this.getClipboardState(e.target,"COPY"),this._isPaintingFormat=!0,this.status="visible";break;default:Ue(e)&&(this.status="invisible")}}getClipboardContent(){return this.state&&this.state.cells.length&&this.state.cells.map((e=>e.map((e=>e.cell?this.getters.getCellText(e.cell,this.getters.shouldShowFormulas()):"")).join("\t"))).join("\n")||"\t"}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const s=this.getters.getActiveSheet();let o;return o="COL"===t?{...e,left:e.right+1,right:s.cols.length-1}:{...e,top:e.bottom+1,bottom:s.rows.length-1},{cut:[o],paste:[e]}}getInsertCellsTargets(e,t){const s=this.getters.getActiveSheet();let o,i;return"COL"===t?(o={...e,right:s.cols.length-1},i={...e,left:e.right+1,right:e.right+1}):(o={...e,bottom:s.rows.length-1},i={...e,top:e.bottom+1,bottom:s.rows.length-1}),{cut:[o],paste:[i]}}removeMergeIfTopLeft(e){const{sheetId:t,col:s,row:o}=e,[i,n]=this.getters.getMainCell(t,s,o);if(n===o&&i===s){const e=this.getters.getMerge(t,s,o);e&&this.dispatch("REMOVE_MERGE",{sheetId:t,target:[e]})}}pasteMergeIfExist(e,t){let{sheetId:s,col:o,row:i}=e;const[n,r]=this.getters.getMainCell(s,o,i);if(n===o&&r===i){const e=this.getters.getMerge(s,o,i);if(!e)return;({sheetId:s,col:o,row:i}=t),this.dispatch("ADD_MERGE",{sheetId:s,force:!0,target:[{left:o,top:i,right:o+e.right-e.left,bottom:i+e.bottom-e.top}]})}}getPasteZones(e,t){if(!t.length||!t[0].length)return e;const s=[],o=t.length,i=t[0].length,n=e[e.length-1],r=n.left,a=n.top,l=Math.max(1,Math.floor((n.right+1-r)/i)),c=Math.max(1,Math.floor((n.bottom+1-a)/o));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)s.push({left:r,top:a,right:r-1+e*i,bottom:a-1+t*o});return s}getClipboardState(e,t){const s=new Set(e.map((e=>e.left))),o=new Set(e.map((e=>e.right))),i=new Set(e.map((e=>e.top))),n=new Set(e.map((e=>e.bottom))),r=1===i.size&&1===n.size||1===s.size&&1===o.size?function(e){return e.reduce(((e,t)=>{const s=e.length;for(let o=0;o<s;o++)if(eo(e[o],t))return e[o]=Qs(e[o],t),e;return e[s]=t,e}),[])}(e):[e[e.length-1]],a=r.map((e=>ro(e))).flat(),l=[...new Set(a.map((e=>e[0])))].sort(((e,t)=>e-t)),c=[...new Set(a.map((e=>e[1])))].sort(((e,t)=>e-t)),h=[],d=[],u=this.getters.getActiveSheetId();for(let e of c){let t=[];for(let s of l){t.push({cell:this.getters.getCell(u,s,e),border:this.getters.getCellBorder(u,s,e)||void 0,position:{col:s,row:e,sheetId:u}});const o=this.getters.getMerge(u,s,e);o&&o.top===e&&o.left===s&&d.push(o)}h.push(t)}return{cells:h,operation:t,sheetId:u,zones:r,merges:d}}pasteFromClipboard(e,t){this.status="invisible";const s=t.replace(/\r/g,"").split("\n").map((e=>e.split("\t"))),{left:o,top:i}=e[0],n=Math.max.apply(Math,s.map((e=>e.length))),r=s.length,a=this.getters.getActiveSheet();this.addMissingDimensions(a,n,r,o,i);for(let e=0;e<s.length;e++)for(let t=0;t<s[e].length;t++)this.dispatch("UPDATE_CELL",{row:i+e,col:o+t,content:s[e][t],sheetId:a.id});const l={left:o,top:i,right:o+n-1,bottom:i+r-1};this.dispatch("SET_SELECTION",{anchor:[o,i],zones:[l],anchorZone:l})}isPasteAllowed(e,t,s){const o=this.getters.getActiveSheetId();if(!e)return 20;if(t.length>1&&(e.cells.length>1||e.cells[0].length>1))return 19;if(!s)for(let s of this.getPasteZones(t,e.cells))if(this.getters.doesIntersectMerge(o,s))return 2;return 0}paste(e,t,s){if("CUT"===e.operation&&this.clearClippedZones(e),t.length>1)for(const o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++)this.pasteZone(e,t,i,s);else{const o=e.cells.length,i=e.cells[0].length,n=t[0],r=Math.max(1,Math.floor((n.right+1-n.left)/i)),a=Math.max(1,Math.floor((n.bottom+1-n.top)/o));for(let t=0;t<r;t++)for(let r=0;r<a;r++)this.pasteZone(e,n.left+t*i,n.top+r*o,s)}"CUT"===e.operation&&(this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:e.merges}),this.state=void 0)}selectPastedZone(e,t,s){const o=s[0],i=o.left,n=o.top,r=Math.max(1,Math.floor((o.right+1-o.left)/e)),a=Math.max(1,Math.floor((o.bottom+1-o.top)/t));if(t>1||e>1){const s={left:i,top:n,right:i+r*e-1,bottom:n+a*t-1},[o,l]=this.getters.getSelection().anchor,c=ms(o,i,i+r*e-1),h=ms(l,n,n+a*t-1);this.dispatch("SET_SELECTION",{anchor:[c,h],zones:[s],anchorZone:s})}}clearClippedZones(e){for(const t of e.cells)for(const e of t)e.cell&&this.dispatch("CLEAR_CELL",e.position);this.dispatch("CLEAR_FORMATTING",{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,s,o){const i=e.cells.length,n=e.cells[0].length,r="onlyValue"!==o&&this.state&&this.state===e,a=this.getters.getActiveSheet();this.addMissingDimensions(a,n,i,t,s);for(let l=0;l<i;l++){const i=e.cells[l];for(let c=0;c<n;c++){const n=i[c],h={col:t+c,row:s+l,sheetId:a.id};this.removeMergeIfTopLeft(h),this.pasteMergeIfExist(n.position,h),this.pasteCell(n,h,e.operation,e.zones,o),r&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:n.position,target:h,operation:e.operation})}}}addMissingDimensions(e,t,s,o,i){const{cols:n,rows:r,id:a}=e,l=s+i-r.length;l>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:r.length-1,sheetId:a,quantity:l,position:"after"});const c=t+o-n.length;c>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:n.length-1,sheetId:a,quantity:c,position:"after"})}pasteCell(e,t,s,o,i){const{sheetId:n,col:r,row:a}=t,l=this.getters.getCell(n,r,a);if("onlyValue"!==i&&this.dispatch("SET_BORDER",{sheetId:n,col:r,row:a,border:e.border}),e.cell){if("onlyFormat"===i)return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.cell.format});if("onlyValue"===i){const s=jr(e.cell.evaluated.value);return void this.dispatch("UPDATE_CELL",{...t,content:s})}let l=e.cell.content;if(e.cell.isFormula()){const t=r-e.position.col,i=a-e.position.row;l=this.getUpdatedContent(n,e.cell,t,i,o,s)}this.dispatch("UPDATE_CELL",{...t,content:l,style:e.cell.style||null,format:e.cell.format})}else l&&("onlyValue"===i?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===i?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,s,o,i,n){if("CUT"===n){const n=[];for(const r of t.dependencies)this.isZoneOverlapClippedZone(i,r.zone)?n.push(...this.getters.createAdaptedRanges([r],s,o,e)):n.push(r);return this.getters.buildFormulaContent(e,t,n)}const r=this.getters.createAdaptedRanges(t.dependencies,s,o,e);return this.getters.buildFormulaContent(e,t,r)}isZoneOverlapClippedZone(e,t){return e.some((e=>eo(t,e)))}isColRowDirtyingClipboard(e,t){if(!this.state||!this.state.zones)return!1;for(let s of this.state.zones){if("COL"===t&&e<=s.right)return!0;if("ROW"===t&&e<=s.bottom)return!0}return!1}drawGrid(e){const{viewport:t,ctx:s,thinLineWidth:o}=e;if("visible"===this.status&&this.state&&this.state.zones&&this.state.zones.length&&this.state.sheetId===this.getters.getActiveSheetId()){s.setLineDash([8,5]),s.strokeStyle=p,s.lineWidth=3.3*o;for(const e of this.state.zones){const[o,i,n,r]=this.getters.getRect(e,t);n>0&&r>0&&s.strokeRect(o,i,n,r)}}}}Th.layers=[2],Th.getters=["getClipboardContent","isPaintingFormat"],Th.modes=["normal"];const Rh=[{name:a("Sum"),types:[Fe.number],compute:e=>Bt.compute([e])},{name:a("Avg"),types:[Fe.number],compute:e=>fo.compute([e])},{name:a("Min"),types:[Fe.number],compute:e=>Oo.compute([e])},{name:a("Max"),types:[Fe.number],compute:e=>Lo.compute([e])},{name:a("Count"),types:[Fe.number,Fe.text,Fe.boolean,Fe.error],compute:e=>wo.compute([e])},{name:a("Count Numbers"),types:[Fe.number,Fe.text,Fe.boolean,Fe.error],compute:e=>yo.compute([e])}];var Lh;!function(e){e[e.idle=0]="idle",e[e.selecting=1]="selecting",e[e.readyToExpand=2]="readyToExpand",e[e.expanding=3]="expanding"}(Lh||(Lh={}));class Mh extends yh{constructor(e,t,s,o){super(e,t,s,o),this.selection={zones:[{top:0,left:0,bottom:0,right:0}],anchor:[0,0],anchorZone:{top:0,left:0,bottom:0,right:0}},this.selectedFigureId=null,this.activeCol=0,this.activeRow=0,this.mode=Lh.idle,this.sheetsData={},this.activeSheet=null,this.moveClient=o.moveClient}allowDispatch(e){switch(e.type){case"SET_SELECTION":if(-1===e.zones.findIndex((t=>Js(t,e.anchorZone))))return 16;break;case"ALTER_SELECTION":if(e.delta){const{left:t,right:s,top:o,bottom:i}=this.getSelectedZone(),n=this.getters.getActiveSheet(),r=Zs(n,"cols",Es(t,s+1)),a=Zs(n,"rows",Es(o,i+1));if(0!==e.delta[0]&&void 0===a||0!==e.delta[1]&&void 0===r)return 17}break;case"MOVE_POSITION":{const{cols:t,rows:s}=this.getters.getActiveSheet();if(0!==e.deltaX&&s[this.activeRow].isHidden||0!==e.deltaY&&t[this.activeCol].isHidden)return 17;const{col:o,row:i}=this.getNextAvailablePosition(e.deltaX,e.deltaY);if(i<0||i>s.length-1||o<0||o>t.length-1)return 17;break}case"SELECT_COLUMN":{const{index:t}=e;if(t<0||t>=this.getters.getActiveSheet().cols.length)return 17;break}case"SELECT_ROW":{const{index:t}=e;if(t<0||t>=this.getters.getActiveSheet().rows.length)return 17;break}case"ACTIVATE_SHEET":try{this.getters.getSheet(e.sheetIdTo);break}catch(e){return 23}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return 0}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":case"CREATE_FIGURE":case"CREATE_CHART":case"UPDATE_FIGURE":case"EVALUATE_CELLS":case"DISABLE_SELECTION_INPUT":case"ENABLE_NEW_SELECTION_INPUT":case"RESIZE_VIEWPORT":break;case"DELETE_FIGURE":this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;default:this.selectedFigureId=null}switch(e.type){case"START":const t=zs(this.getters.getSheets()[0],0,0);this.activeCol=t[0],this.activeRow=t[1],this.dispatch("ACTIVATE_SHEET",{sheetIdTo:this.getters.getSheets()[0].id,sheetIdFrom:this.getters.getSheets()[0].id}),this.selectCell(...t);break;case"ACTIVATE_SHEET":this.setActiveSheet(e.sheetIdTo),this.sheetsData[e.sheetIdFrom]={selection:JSON.parse(JSON.stringify(this.selection)),activeCol:this.activeCol,activeRow:this.activeRow},e.sheetIdTo in this.sheetsData?Object.assign(this,this.sheetsData[e.sheetIdTo]):this.selectCell(...zs(this.getters.getSheet(e.sheetIdTo),0,0));break;case"SET_SELECTION":this.setSelection(e.anchor,e.zones,e.anchorZone,e.strict);break;case"START_SELECTION":this.mode=Lh.selecting;break;case"PREPARE_SELECTION_EXPANSION":this.mode=Lh.readyToExpand;break;case"START_SELECTION_EXPANSION":this.mode=Lh.expanding;break;case"STOP_SELECTION":this.mode=Lh.idle;break;case"MOVE_POSITION":this.movePosition(e.deltaX,e.deltaY);break;case"SELECT_CELL":this.selectCell(e.col,e.row);break;case"SELECT_COLUMN":this.selectColumn(e.index,e.createRange||!1,e.updateRange||!1);break;case"SELECT_ROW":this.selectRow(e.index,e.createRange||!1,e.updateRange||!1);break;case"SELECT_ALL":this.selectAll();break;case"ALTER_SELECTION":e.delta&&this.moveSelection(e.delta[0],e.delta[1]),e.cell&&this.addCellToSelection(...e.cell);break;case"UNDO":case"REDO":case"DELETE_SHEET":if(!this.getters.tryGetSheet(this.getActiveSheetId())){const e=this.getters.getVisibleSheets();this.activeSheet=this.getters.getSheet(e[0]),this.selectCell(0,0)}this.ensureSelectionValidity();break;case"REMOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&("COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e));break;case"ADD_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onAddElements(e);break;case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"UPDATE_CHART":case"SELECT_FIGURE":this.selectedFigureId=e.id;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left")}}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveCell(){const e=this.getters.getActiveSheetId(),[t,s]=this.getters.getMainCell(e,this.activeCol,this.activeRow);return this.getters.getCell(e,t,s)}getActiveCols(){const e=new Set;for(let t of this.selection.zones)if(0===t.top&&t.bottom===this.getters.getActiveSheet().rows.length-1)for(let s=t.left;s<=t.right;s++)e.add(s);return e}getActiveRows(){const e=new Set;for(let t of this.selection.zones)if(0===t.left&&t.right===this.getters.getActiveSheet().cols.length-1)for(let s=t.top;s<=t.bottom;s++)e.add(s);return e}getCurrentStyle(){const e=this.getters.getActiveCell();return e?this.getters.getCellStyle(e):{}}getSelectedZones(){return this.selection.zones}getSelectedZone(){return this.selection.anchorZone}getSelection(){return this.selection}getSelectedFigureId(){return this.selectedFigureId}getPosition(){return[this.activeCol,this.activeRow]}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getPosition();{const t=this.sheetsData[e];return t?[t.activeCol,t.activeRow]:zs(this.getters.getSheet(e),0,0)}}getStatisticFnResults(){const e=new Set(this.selection.zones.map((e=>this.getters.getCellsInZone(this.getters.getActiveSheetId(),e))).flat().filter((e=>void 0!==e)));let t=new Set,s=[];for(let o of e)t.add(o.evaluated.type),s.push(o.evaluated.value);let o={};for(let e of Rh){let i;e.types.some((e=>t.has(e)))&&(i=e.compute(s)),o[e.name]=i}return o}getSelectionMode(){return this.mode}isSelected(e){return!!this.getters.getSelectedZones().find((t=>Js(t,e)))}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],s=this.getters.getFigures(e),{offsetX:o,offsetY:i}=this.getters.getActiveSnappedViewport(),{width:n,height:r}=this.getters.getViewportDimensionWithHeaders();for(let e of s)e.x>=o+n||e.x+e.width<=o||e.y>=i+r||e.y+e.height<=i||t.push(e);return t}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let s=[];const o="COL"===e?"left":"top",i="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[i]-e[o]+1},((t,s)=>e[o]+s));s=s.concat(t)}return[...new Set(s)].sort()}selectColumn(e,t,s){const o=this.getters.getActiveSheet().rows.length-1;let i={left:e,right:e,top:0,bottom:o};const n=this.selection.zones;let r,a;const l=this.getters.getActiveSheet().rows.findIndex((e=>!e.isHidden));if(s){const[e,t]=this.selection.anchor;i=Qs(i,{left:e,right:e,top:l,bottom:o}),r=this.updateSelectionZones(i),a=[e,t]}else r=t?n.concat(i):[i],a=[e,l];this.dispatch("SET_SELECTION",{zones:r,anchor:a,strict:!0,anchorZone:i})}selectRow(e,t,s){const o=this.getters.getActiveSheet().cols.length-1;let i={top:e,bottom:e,left:0,right:o};const n=this.selection.zones;let r,a;const l=this.getters.getActiveSheet().cols.findIndex((e=>!e.isHidden));if(s){const[e,t]=this.selection.anchor;i=Qs(i,{left:l,right:o,top:t,bottom:t}),r=this.updateSelectionZones(i),a=[e,t]}else r=t?n.concat(i):[i],a=[l,e];this.dispatch("SET_SELECTION",{zones:r,anchor:a,strict:!0,anchorZone:i})}selectAll(){const e={left:0,top:0,bottom:this.getters.getActiveSheet().rows.length-1,right:this.getters.getActiveSheet().cols.length-1};this.dispatch("SET_SELECTION",{zones:[e],anchor:[0,0],anchorZone:e})}selectCell(e,t){const s=this.getters.getActiveSheet();this.moveClient({sheetId:s.id,col:e,row:t});const o=this.getters.expandZone(s.id,{left:e,right:e,top:t,bottom:t});let i;i=this.mode===Lh.expanding?lo([...this.selection.zones,o]):[o],this.selection=this.clipSelection(s.id,{anchor:[e,t],zones:i,anchorZone:o}),this.activeCol=this.selection.anchor[0],this.activeRow=this.selection.anchor[1]}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}getNextAvailablePosition(e,t){return{col:this.getNextAvailableCol(e,this.activeCol,this.activeRow),row:this.getNextAvailableRow(t,this.activeCol,this.activeRow)}}getNextAvailableCol(e,t,s){const{cols:o,id:i}=this.getActiveSheet(),n={col:t,row:s};return this.getNextAvailableHeader(e,o,t,n,(e=>this.getters.isInSameMerge(i,t,s,e,s)))}getNextAvailableRow(e,t,s){const{rows:o,id:i}=this.getActiveSheet(),n={col:t,row:s};return this.getNextAvailableHeader(e,o,s,n,(e=>this.getters.isInSameMerge(i,t,s,t,e)))}getNextAvailableHeader(e,t,s,o,i){var n,r,a;const l=this.getters.getActiveSheetId(),{col:c,row:h}=o;if(0===e)return s;let d=s+e;if(this.getters.isInMerge(l,c,h)){for(;i(d);)d+=e;for(;null===(n=t[d])||void 0===n?void 0:n.isHidden;)d+=e}else if(null===(r=t[d])||void 0===r?void 0:r.isHidden)for(;null===(a=t[d])||void 0===a?void 0:a.isHidden;)d+=e;return d<0||d>t.length-1?t[s].isHidden?this.getNextAvailableHeader(-e,t,s,o,i):s:d}movePosition(e,t){const{col:s,row:o}=this.getNextAvailablePosition(e,t);this.selectCell(s,o)}setSelection(e,t,s,o=!1){this.selectCell(...e);const i=this.getters.getActiveSheetId();let n;t=lo(t),n=o?{zones:t,anchorZone:s,anchor:e}:{anchor:e,zones:t.map((e=>this.getters.expandZone(i,e))),anchorZone:this.getters.expandZone(i,s)},this.selection=this.clipSelection(i,n)}getReferencePosition(){const e=this.getters.getActiveSheet(),t=this.selection,{left:s,right:o,top:i,bottom:n}=t.anchorZone,[r,a]=t.anchor;return{col:e.cols[r].isHidden&&Zs(e,"cols",Es(s,o+1))||r,row:e.rows[a].isHidden&&Zs(e,"rows",Es(i,n+1))||a}}moveSelection(e,t){const s=this.selection;let o=[];const[i,n]=s.anchor,{left:r,right:a,top:l,bottom:c}=s.anchorZone;let h=s.anchorZone;const d=this.getters.getActiveSheet(),u=e=>{const{left:t,right:s,top:o,bottom:i}=this.getters.expandZone(d.id,e);return{left:Math.max(0,t),right:Math.min(d.cols.length-1,s),top:Math.max(0,o),bottom:Math.min(d.rows.length-1,i)}},{col:p,row:g}=this.getReferencePosition();let f=0;for(;null!==h;){if(f++,e<0){const t=this.getNextAvailableCol(e,a-(f-1),g);h=p<=a-f?u({top:l,left:r,bottom:c,right:t}):null}if(e>0){const t=this.getNextAvailableCol(e,r+(f-1),g);h=r+f<=p?u({top:l,left:t,bottom:c,right:a}):null}if(t<0){const e=this.getNextAvailableRow(t,p,c-(f-1));h=g<=c-f?u({top:l,left:r,bottom:e,right:a}):null}if(t>0){const e=this.getNextAvailableRow(t,p,l+(f-1));h=l+f<=g?u({top:e,left:r,bottom:c,right:a}):null}if(h=h?co(h):h,h&&!Js(h,s.anchorZone))return o=this.updateSelectionZones(h),void this.dispatch("SET_SELECTION",{zones:o,anchor:[i,n],anchorZone:h})}h=u(Qs({top:n,bottom:n,left:i,right:i},co({top:this.getNextAvailableRow(t,p,l),left:this.getNextAvailableCol(e,r,g),bottom:this.getNextAvailableRow(t,p,c),right:this.getNextAvailableCol(e,a,g)}))),Js(h,s.anchorZone)||(o=this.updateSelectionZones(h),this.dispatch("SET_SELECTION",{zones:o,anchor:[i,n],anchorZone:h}))}addCellToSelection(e,t){const s=this.selection,[o,i]=s.anchor,n={left:Math.min(o,e),top:Math.min(i,t),right:Math.max(o,e),bottom:Math.max(i,t)},r=this.updateSelectionZones(n);this.dispatch("SET_SELECTION",{zones:r,anchor:[o,i],anchorZone:n})}ensureSelectionValidity(){const{anchor:e,zones:t,anchorZone:s}=this.clipSelection(this.getActiveSheetId(),this.selection);this.setSelection(e,t,s);const o=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of o)delete this.sheetsData[e];for(const e in this.sheetsData){const{anchor:t,zones:s,anchorZone:o}=this.clipSelection(e,this.sheetsData[e].selection);this.sheetsData[e]={selection:{anchor:t,zones:s,anchorZone:o},activeCol:t[0],activeRow:t[1]}}}clipSelection(e,t){const s=this.getters.getSheet(e),o=s.cols.length-1,i=s.rows.length-1,n=t.zones.map((e=>({left:ms(e.left,0,o),right:ms(e.right,0,o),top:ms(e.top,0,i),bottom:ms(e.bottom,0,i)})));return{anchor:[ms(t.anchor[0],0,o),ms(t.anchor[1],0,i)],zones:n,anchorZone:{left:ms(t.anchorZone.left,0,o),right:ms(t.anchorZone.right,0,o),top:ms(t.anchorZone.top,0,i),bottom:ms(t.anchorZone.bottom,0,i)}}}onColumnsRemoved(e){const t=Ks(this.getSelectedZone(),"left",e.elements);this.setSelection([t.left,t.top],[t],t,!0),this.ensureSelectionValidity()}onRowsRemoved(e){const t=Ks(this.getSelectedZone(),"top",e.elements);this.setSelection([t.left,t.top],[t],t,!0),this.ensureSelectionValidity()}onAddElements(e){const t=Ys(this.getSelectedZone(),"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.setSelection([t.left,t.top],[t],t,!0)}updateSelectionZones(e){let t=[...this.selection.zones];const s=this.selection.anchorZone,o=t.findIndex((e=>Js(e,s)));return o>=0&&(t[o]=e),t}activateNextSheet(e){const t=this.getters.getSheets().map((e=>e.id)),s=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[s]})}onMoveElements(e){const t=e.elements.length;this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:"before"});const s="COL"===e.dimension,o=e.elements[0],i=e.elements[t-1],n=e.base<o,r=n&&s?t:0,a=n&&!s?t:0,l=this.getters.getSheet(e.sheetId);this.dispatch("CUT",{target:[{left:s?o+r:0,right:s?i+r:l.cols.length-1,top:s?0:o+a,bottom:s?l.rows.length-1:i+a}]}),this.dispatch("PASTE",{target:[{left:s?e.base:0,right:s?e.base+t-1:l.cols.length-1,top:s?0:e.base,bottom:s?l.rows.length-1:e.base+t-1}]});const c=n?e.elements.map((e=>e+t)):e.elements;let h=e.base;for(const t of c){const s="COL"===e.dimension?this.getters.getCol(e.sheetId,t).size:this.getters.getRow(e.sheetId,t).size;this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:s,elements:[h]}),h+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:c})}isMoveElementAllowed(e){const t="COL"===e.dimension,s=e.elements[0],o=e.elements[e.elements.length-1],i=e.sheetId,n=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;return n(i,s-1,s)||n(i,o,o+1)||n(i,e.base-1,e.base)?2:0}drawGrid(e){if("inactive"!==this.getters.getEditionMode())return;const{viewport:t,ctx:s,thinLineWidth:o}=e,i=this.getSelectedZones();s.fillStyle="#f3f7fe";const n=1===i.length&&i[0].left===i[0].right&&i[0].top===i[0].bottom;s.fillStyle=n?"#f3f7fe":"#e9f0ff",s.strokeStyle=p,s.lineWidth=1.5*o,s.globalCompositeOperation="multiply";for(const e of i){const[o,i,n,r]=this.getters.getRect(e,t);s.fillRect(o,i,n,r),s.strokeRect(o,i,n,r)}s.globalCompositeOperation="source-over";const r=this.getters.getActiveSheetId(),[a,l]=this.getPosition();let c;s.strokeStyle=p,s.lineWidth=3*o,c=this.getters.isInMerge(r,a,l)?this.getters.getMerge(r,a,l):{top:l,bottom:l,left:a,right:a};const[h,d,u,g]=this.getters.getRect(c,t);u>0&&g>0&&s.strokeRect(h,d,u,g)}}Mh.layers=[5],Mh.modes=["normal"],Mh.getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getStatisticFnResults","getSelectedFigureId","getVisibleFigures","getSelection","getPosition","getSheetPosition","getSelectionMode","isSelected","getElementsFromSelection"];const Ah=a("The cell you are trying to edit has been deleted.");class _h extends yh{constructor(){super(...arguments),this.col=0,this.row=0,this.mode="inactive",this.sheet="",this.currentContent="",this.currentTokens=[],this.selectionStart=0,this.selectionEnd=0,this.selectionInitialStart=0,this.multiSelectionInitialStart=0,this.initialContent="",this.previousRef="",this.previousRange=void 0,this.colorIndexByRange={}}allowDispatch(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":return this.validateSelection(this.currentContent.length,e.start,e.end);case"SET_CURRENT_CONTENT":return e.selection?this.validateSelection(e.content.length,e.selection.start,e.selection.end):0;case"START_EDITION":if(e.selection){const t=this.getters.getActiveCell(),s=e.text||(null==t?void 0:t.composerContent)||"";return this.validateSelection(s.length,e.selection.start,e.selection.end)}return 0;default:return 0}}handle(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":this.selectionStart=e.start,this.selectionEnd=e.end;break;case"STOP_COMPOSER_RANGE_SELECTION":this.isSelectingForComposer()&&(this.mode="editing");break;case"START_EDITION":this.startEdition(e.text,e.selection);break;case"STOP_EDITION":e.cancel?(this.cancelEdition(),this.resetContent()):this.stopEdition();break;case"SET_CURRENT_CONTENT":this.setContent(e.content,e.selection,!0);break;case"REPLACE_COMPOSER_CURSOR_SELECTION":this.replaceSelection(e.text);break;case"SELECT_FIGURE":this.cancelEdition(),this.resetContent();break;case"SELECT_CELL":case"SET_SELECTION":case"MOVE_POSITION":switch(this.mode){case"editing":this.dispatch("STOP_EDITION");break;case"waitingForRangeSelection":this.insertSelectedRange();break;case"rangeSelected":switch(e.type){case"MOVE_POSITION":this.replaceAllSelectedRanges();break;case"SELECT_CELL":this.getters.getSelectionMode()===Lh.expanding?this.insertSelectedRange():this.replaceAllSelectedRanges();break;case"SET_SELECTION":e.strict?this.getters.getSelectionMode()===Lh.expanding?this.insertSelectedRange():this.replaceAllSelectedRanges():this.replaceSelectedRange()}}break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"START_CHANGE_HIGHLIGHT":this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((t=>{let s=t.value;const{xc:o,sheetName:i}=ts(s),n=i||this.getters.getSheetName(this.sheet),r=this.getters.getActiveSheetId();return Js(this.getters.expandZone(r,qs(o)),e.zone)&&this.getters.getSheetName(r)===n}));this.previousRef=t.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=t.start;break;case"CHANGE_HIGHLIGHT":const s=this.getZoneReference(e.zone,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(s),this.previousRef=s,this.selectionStart=this.currentContent.length,this.selectionEnd=this.currentContent.length;break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheet)||"inactive"===this.mode||(this.cancelEdition(),this.resetContent(),this.ui.notifyUI({type:"NOTIFICATION",text:Ah}))}}getEditionMode(){return this.mode}getCurrentContent(){if("inactive"===this.mode){const e=this.getters.getActiveCell();return(null==e?void 0:e.composerContent)||""}return this.currentContent}getEditionSheet(){return this.sheet}getComposerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}isSelectingForComposer(){return"waitingForRangeSelection"===this.mode||"rangeSelected"===this.mode||"resettingPosition"===this.mode}getCurrentTokens(){return this.currentTokens}getTokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find((s=>s.start<=e&&s.end>=t))}validateSelection(e,t,s){return t>=0&&t<=e&&s>=0&&s<=e?0:31}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"NOTIFICATION",text:Ah});const{top:t,left:s}=Ks({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",e.elements);this.col=s,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"NOTIFICATION",text:Ah});const{top:t,left:s}=Ks({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",e.elements);this.col=s,this.row=t}onAddElements(e){const{top:t,left:s}=Ys({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=s,this.row=t}startComposerRangeSelection(){this.mode="resettingPosition",this.sheet===this.getters.getActiveSheetId()&&this.dispatch("SELECT_CELL",{col:this.col,row:this.row}),this.mode="waitingForRangeSelection",this.multiSelectionInitialStart=this.selectionStart}startEdition(e,t){const s=this.getters.getActiveCell();this.initialContent=(null==s?void 0:s.composerContent)||"",this.mode="editing";const[o,i]=this.getters.getPosition();this.col=o,this.row=i,this.sheet=this.getters.getActiveSheetId(),this.setContent(e||this.initialContent,t),this.colorIndexByRange={}}stopEdition(){if("inactive"!==this.mode){this.cancelEdition();const e=this.getters.getActiveSheetId(),t=this.getters.getSheets().find((e=>e.id===this.sheet)).id,[s,o]=this.getters.getMainCell(t,this.col,this.row);let i=this.currentContent;if(!(this.initialContent!==i))return;if(i){const t=this.getters.getCell(e,s,o);if(i.startsWith("=")){const e=this.currentTokens.filter((e=>"LEFT_PAREN"===e.type)).length,t=this.currentTokens.filter((e=>"RIGHT_PAREN"===e.type)).length,s=e-t;s>0&&(i+=new Array(s).fill(")").join(""))}else(null==t?void 0:t.isLink())&&(i=Ts(i,t.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheet,col:s,row:o,content:i})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheet,content:"",col:s,row:o});e!==this.sheet&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheet}),this.setContent("")}}cancelEdition(){this.mode="inactive"}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,s){e=e.replace(/[\r\n]/g,"");const o=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(o||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?Wr(e):[],this.currentTokens.length>100&&s&&this.ui.notifyUI({type:"NOTIFICATION",text:a("This formula has over 100 parts. It can't be processed properly, consider splitting it into multiple cells")})),this.canStartComposerRangeSelection()&&this.startComposerRangeSelection()}insertSelectedRange(){const e=Math.min(this.selectionStart,this.selectionEnd),t=this.getZoneReference(this.getters.getSelectedZone());if("waitingForRangeSelection"===this.mode)return this.insertText(t,e),this.selectionInitialStart=e,void(this.mode="rangeSelected");this.insertText(","+t,e),this.selectionInitialStart=e+1}replaceSelectedRange(){const{end:e}=this.getters.getComposerSelection();this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:this.selectionInitialStart,end:e}),this.replaceSelection(this.getZoneReference(this.getters.getSelectedZone()))}replaceAllSelectedRanges(){const{end:e}=this.getters.getComposerSelection();this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:this.multiSelectionInitialStart,end:e}),this.replaceSelection(this.getZoneReference(this.getters.getSelectedZone())),this.selectionInitialStart=this.multiSelectionInitialStart}getZoneReference(e,t=[{colFixed:!1,rowFixed:!1}]){const s=this.getters.getActiveSheetId();let o=this.getters.zoneToXC(s,e,t);if(this.getters.getEditionSheet()!==this.getters.getActiveSheetId()){o=`${fs(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${o}`}return o}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),s=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,s)}replaceText(e,t,s){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(s,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const s=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),o=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:s,selection:{start:o,end:o}})}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=[],t={};for(let s of this.currentTokens.filter((e=>"REFERENCE"===e.type))){let o=s.value;const{xc:i,sheetName:n}=ts(o);if(es.test(i)){const s=(n?`${n}!`:`${this.getters.getSheetName(this.getters.getEditionSheet())}!`)+i.replace(/\$/g,"");e.push(s);const o=this.colorIndexByRange[s];void 0!==o&&(t[s]=o)}}this.colorIndexByRange=t;let s=Object.values(t),o=0;return e.map((e=>{if(void 0===this.colorIndexByRange[e]){for(;s.includes(o);)o++;s.push(o),this.colorIndexByRange[e]=o}return[e,jt[this.colorIndexByRange[e]%jt.length]]}))}canStartComposerRangeSelection(){if("editing"!==this.mode&&this.selectionStart===this.selectionEnd)return!1;if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(e){const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let s=t,o=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(o.type);){if("SPACE"!==o.type||s<1)return!1;s--,o=this.currentTokens[s]}for(s=t+1,o=this.currentTokens[s];o&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(o.type);){if("SPACE"!==o.type)return!1;s++,o=this.currentTokens[s]}s++,o=this.currentTokens[s]}return!0}return!1}}_h.getters=["getEditionMode","isSelectingForComposer","getCurrentContent","getEditionSheet","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights"],_h.modes=["normal"];const Oh=hr.mapping;class Nh extends yh{constructor(e,t,s,o){super(e,t,s,o),this.isUpToDate=new Set,this.evalContext=o.evalContext,o.dataSources.on("data-loaded",this,(()=>{this.dispatch("EVALUATE_CELLS",{sheetId:this.getters.getActiveSheetId()})}))}handle(e){switch($e.has(e.type)&&this.isUpToDate.clear(),e.type){case"UPDATE_CELL":"content"in e&&this.isUpToDate.clear();break;case"ACTIVATE_SHEET":this.evaluate(e.sheetIdTo),this.isUpToDate.add(e.sheetIdTo);break;case"EVALUATE_CELLS":this.evaluate(e.sheetId),this.isUpToDate.add(e.sheetId);break;case"EVALUATE_ALL_SHEETS":this.evaluateAllSheets()}}finalize(){const e=this.getters.getActiveSheetId();this.isUpToDate.has(e)||(this.evaluate(e),this.isUpToDate.add(e))}evaluateFormula(e,t=this.getters.getActiveSheetId()){const s=Gr(e),o=this.getFormulaParameters((()=>{})),i=[];for(let e of s.dependencies)i.push(this.getters.getRangeFromSheetXC(t,e));return s.execute(i,t,...o)}getRangeFormattedValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getCellsInZone(t.id,e.zone).map((e=>(null==e?void 0:e.formattedValue)||""))}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getCellsInZone(t.id,e.zone).map((e=>null==e?void 0:e.evaluated.value))}evaluate(e){const t=this.getters.getCells(e),s=this.getFormulaParameters(i),o={};for(let s of Object.values(t))i(s,e);function i(e,t){if(!e.isFormula())return;const i=e.id;if(i in o)null===o[i]&&e.assignError("#CYCLE",a("Circular reference"));else{o[i]=null;try{if(s[2].__originCellXC=()=>{const e=s[2].getters.getCellPosition(i);return is(e.col,e.row)},e.assignValue(e.compiledFormula.execute(e.dependencies,t,...s)),Array.isArray(e.evaluated.value))throw new Error(a("This formula depends on invalid values"))}catch(t){!function(e,t){if(e instanceof Error||(e=new Error(e)),"#CYCLE"!==t.evaluated.value){t.assignValue("#ERROR");const o=s[2].__lastFnCalled||"";t.assignError("#ERROR",e.message.replace("[[FUNCTION_NAME]]",o))}}(t,e)}o[i]=!0}}}getFormulaParameters(e){const t=Object.assign(Object.create(Oh),this.evalContext,{getters:this.getters}),s=this.getters;function o(t,s){if(e(t,s),t.evaluated.type===Fe.error)throw new Error(a("This formula depends on invalid values"));return t.evaluated.value}function i(e){const i=e.sheetId;if(!js(e.zone))throw new Error(a("Invalid reference"));const n={top:0,bottom:s.getNumberRows(i)-1,left:0,right:s.getNumberCols(i)-1},r=[],l=function(e,t){if(eo(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)}}(e.zone,n);if(!l)return r.push([]),r;for(let s=l.left;s<=l.right;s++){const i=[];for(let n=l.top;n<=l.bottom;n++){const r=t.getters.getCell(e.sheetId,s,n);i.push(r?o(r,e.sheetId):void 0)}r.push(i)}return r}return[function(e,i,n,r,l,c){const h=i[e];if(r)return t.getters.getRangeString(h,n);if(!js(h.zone))throw new Error(a("Invalid reference"));if(h.zone.bottom!==h.zone.top||h.zone.left!==h.zone.right)throw new Error(c?a("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",l.toString(),c.toString()):a("Function %s expects its parameters to be single values or single cell references, not ranges.",l.toString()));if(h.invalidSheetName)throw new Error(a("Invalid sheet name: %s",h.invalidSheetName));return function(e){let t;if(!s.tryGetSheet(e.sheetId))throw new Error(a("Invalid sheet name"));return t=s.getCell(e.sheetId,e.zone.left,e.zone.top),!t||t.isEmpty()?null:o(t,e.sheetId)}(h)},function(e,t,s){return i(t[e])},t]}evaluateAllSheets(){for(const e of this.getters.getVisibleSheets())this.evaluate(e),this.isUpToDate.add(e)}}Nh.getters=["evaluateFormula","getRangeFormattedValues","getRangeValues"],Nh.modes=["normal"];const kh=["rgb(31,119,180)","rgb(255,127,14)","rgb(174,199,232)","rgb(255,187,120)","rgb(44,160,44)","rgb(152,223,138)","rgb(214,39,40)","rgb(255,152,150)","rgb(148,103,189)","rgb(197,176,213)","rgb(140,86,75)","rgb(196,156,148)","rgb(227,119,194)","rgb(247,182,210)","rgb(127,127,127)","rgb(199,199,199)","rgb(188,189,34)","rgb(219,219,141)","rgb(23,190,207)","rgb(158,218,229)"];class Fh{constructor(){this.graphColorIndex=0}next(){return kh[this.graphColorIndex++%kh.length]}}class $h extends yh{constructor(){super(...arguments),this.chartRuntime={},this.outOfDate=new Set}handle(e){if($e.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&"content"in e)for(let e of Object.keys(this.chartRuntime))this.outOfDate.add(e);switch(e.type){case"UPDATE_CHART":case"CREATE_CHART":const t=this.getters.getChartDefinition(e.id);this.chartRuntime[e.id]=this.mapDefinitionToRuntime(t);break;case"DELETE_FIGURE":delete this.chartRuntime[e.id];break;case"REFRESH_CHART":this.evaluateUsedSheets([e.id]),this.outOfDate.add(e.id);break;case"ACTIVATE_SHEET":const s=this.getters.getChartsIdBySheet(e.sheetIdTo);this.evaluateUsedSheets(s);break;case"DELETE_SHEET":for(let e of Object.keys(this.chartRuntime))this.getters.getChartDefinition(e)||delete this.chartRuntime[e]}}getChartRuntime(e){if(this.outOfDate.has(e)||!(e in this.chartRuntime)){const t=this.getters.getChartDefinition(e);if(void 0===t)return;this.chartRuntime[e]=this.mapDefinitionToRuntime(t),this.outOfDate.delete(e)}return this.chartRuntime[e]}truncateLabel(e){return e?e.length>20?e.substring(0,20)+"…":e:""}getDefaultConfiguration(e,t){const s={};e.labelRange||1!==e.dataSets.length?s.position=e.legendPosition:s.display=!1;const o={type:e.type,options:{legend:s,responsive:!0,maintainAspectRatio:!1,layout:{padding:{left:20,right:20,top:e.title?10:25,bottom:10}},elements:{line:{fill:!1},point:{hitRadius:15}},animation:{duration:0},hover:{animationDuration:10},responsiveAnimationDuration:0,title:{display:!!e.title,fontSize:22,fontStyle:"normal",text:e.title}},data:{labels:t.map(this.truncateLabel),datasets:[]}};return"pie"!==e.type?(o.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2}}],yAxes:[{position:e.verticalAxisPosition,ticks:{beginAtZero:!0}}]},"bar"===e.type&&e.stackedBar&&(o.options.scales.xAxes[0].stacked=!0,o.options.scales.yAxes[0].stacked=!0)):o.options.tooltips={callbacks:{title:function(e,t){return t.datasets[e[0].datasetIndex].label}}},o}getSheetIdsUsedInChart(e){const t=new Set;for(let s of e.dataSets)t.add(s.dataRange.sheetId);return e.labelRange&&t.add(e.labelRange.sheetId),t}evaluateUsedSheets(e){const t=new Set;for(let s of e){const e=this.getters.getChartDefinition(s);(void 0!==e?this.getSheetIdsUsedInChart(e):[]).forEach((e=>{e!==this.getters.getActiveSheetId()&&t.add(e)}))}for(let e of t)this.dispatch("EVALUATE_CELLS",{sheetId:e})}mapDefinitionToRuntime(e){let t=[];if(e.labelRange)e.labelRange.invalidXc||e.labelRange.invalidSheetName||(t=this.getters.getRangeFormattedValues(e.labelRange));else if(1===e.dataSets.length)for(let s=0;s<this.getData(e.dataSets[0],e.sheetId).length;s++)t.push("");else if(e.dataSets[0]){t=Es(0,this.getData(e.dataSets[0],e.sheetId).length).map((e=>e.toString()))}const s=this.getDefaultConfiguration(e,t),o=new Fh,i=[];if("pie"===e.type){const t=Math.max(...e.dataSets.map((t=>this.getData(t,e.sheetId).length)));for(let e=0;e<=t;e++)i.push(o.next())}for(const[t,n]of Object.entries(e.dataSets)){let r;if(n.labelCell){const e=n.labelCell,s=e?this.getters.getCell(e.sheetId,e.zone.left,e.zone.top):void 0;r=s&&e?this.truncateLabel(s.formattedValue):r=`${Cc.Series} ${parseInt(t)+1}`}else r=r=`${Cc.Series} ${parseInt(t)+1}`;const a="pie"!==e.type?o.next():"#FFFFFF",l={label:r,data:n.dataRange?this.getData(n,e.sheetId):[],lineTension:0,borderColor:a,backgroundColor:a};"pie"===e.type&&(l.backgroundColor=i),s.data.datasets.push(l)}return s}getData(e,t){if(e.dataRange){const t=e.labelCell?[Xs(e.labelCell.zone)]:[],s=so([Xs(e.dataRange.zone)],t)[0];if(void 0===s)return[];const o=this.getters.getRangeFromSheetXC(e.dataRange.sheetId,s);return this.getters.getRangeValues(o)}return[]}}$h.getters=["getChartRuntime"],$h.modes=["normal"];class Dh extends yh{constructor(){super(...arguments),this.isStale=!0,this.computedStyles={},this.computedIcons={},this.uuidGenerator=new Hs,this.rulePredicate={CellIsRule:(e,t)=>{if(e&&e.evaluated.type===Fe.error)return!1;const s=t.values.map(Xr);switch(t.operator){case"IsEmpty":return!_s(e)||""===e.evaluated.value.toString().trim();case"IsNotEmpty":return _s(e)&&""!==e.evaluated.value.toString().trim();case"BeginsWith":return!(!e&&""===s[0])&&(_s(e)&&(null==e?void 0:e.evaluated.value.toString().startsWith(s[0].toString())));case"EndsWith":return!(!e&&""===s[0])&&(_s(e)&&e.evaluated.value.toString().endsWith(s[0].toString()));case"Between":return _s(e)&&e.evaluated.value>=s[0]&&e.evaluated.value<=s[1];case"NotBetween":return!(_s(e)&&e.evaluated.value>=s[0]&&e.evaluated.value<=s[1]);case"ContainsText":return _s(e)&&e.evaluated.value.toString().indexOf(s[0].toString())>-1;case"NotContains":return!_s(e)||!e.evaluated.value||-1==e.evaluated.value.toString().indexOf(s[0].toString());case"GreaterThan":return _s(e)&&e.evaluated.value>s[0];case"GreaterThanOrEqual":return _s(e)&&e.evaluated.value>=s[0];case"LessThan":return _s(e)&&e.evaluated.value<s[0];case"LessThanOrEqual":return _s(e)&&e.evaluated.value<=s[0];case"NotEqual":return!(!_s(e)&&""===s[0])&&(_s(e)&&e.evaluated.value!==s[0]);case"Equal":return!e&&""===s[0]||_s(e)&&e.evaluated.value===s[0];default:console.warn(a("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}}}handle(e){switch(e.type){case"ACTIVATE_SHEET":const t=e.sheetIdTo;this.computedStyles[t]=this.computedStyles[t]||{},this.computedIcons[t]=this.computedIcons[t]||{},this.isStale=!0;break;case"AUTOFILL_CELL":const s=this.getters.getActiveSheetId(),o=this.getters.getRulesByCell(s,e.originCol,e.originRow);for(const t of o)this.adaptRules(s,t,[is(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.origin,e.target,e.operation);break;case"DUPLICATE_SHEET":case"CREATE_SHEET":case"DELETE_SHEET":case"ADD_CONDITIONAL_FORMAT":case"REMOVE_CONDITIONAL_FORMAT":case"REMOVE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"EVALUATE_CELLS":case"UPDATE_CELL":case"UNDO":case"REDO":case"DELETE_CELL":case"INSERT_CELL":this.isStale=!0}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getConditionalStyle(e,t){var s;const o=this.getters.getActiveSheetId(),i=this.computedStyles[o];return i&&(null===(s=i[e])||void 0===s?void 0:s[t])}getConditionalIcon(e,t){var s;const o=this.getters.getActiveSheetId(),i=this.computedIcons[o];return i&&(null===(s=i[e])||void 0===s?void 0:s[t])}computeStyles(){var e;const t=this.getters.getActiveSheetId();this.computedStyles[t]={},this.computedIcons[t]={};const s=this.computedStyles[t];for(let o of this.getters.getConditionalFormats(t))try{switch(o.rule.type){case"ColorScaleRule":for(let e of o.ranges)this.applyColorScale(e,o.rule);break;case"IconSetRule":for(let e of o.ranges)this.applyIcon(e,o.rule);break;default:for(let i of o.ranges){const n=qs(i);for(let i=n.top;i<=n.bottom;i++)for(let r=n.left;r<=n.right;r++){const n=this.rulePredicate[o.rule.type];let a=this.getters.getCell(t,r,i);n&&n(a,o.rule)&&(s[r]||(s[r]=[]),s[r][i]=Object.assign((null===(e=s[r])||void 0===e?void 0:e[i])||{},o.rule.style))}}}}catch(e){}}parsePoint(e,t,s){switch(t.type){case"value":return this.getters.evaluateFormula(`=${s}(${e})`);case"number":return Number(t.value);case"percentage":const o=this.getters.evaluateFormula(`=min(${e})`);return o+(this.getters.evaluateFormula(`=max(${e})`)-o)*Number(t.value)/100;case"percentile":return this.getters.evaluateFormula(`=PERCENTILE(${e},${Number(t.value)/100})`);case"formula":const i=t.value&&this.getters.evaluateFormula(t.value);return i instanceof Promise?null:i;default:return null}}applyIcon(e,t){const s=this.parsePoint(e,t.lowerInflectionPoint),o=this.parsePoint(e,t.upperInflectionPoint);if(null===s||null===o||s>o)return;const i=qs(e),n=this.getters.getActiveSheetId(),r=this.computedIcons[n],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=i.top;e<=i.bottom;e++)for(let l=i.left;l<=i.right;l++){const i=this.getters.getCell(n,l,e);if((null==i?void 0:i.evaluated.type)!==Fe.number)continue;const c=this.computeIcon(i.evaluated.value,o,t.upperInflectionPoint.operator,s,t.lowerInflectionPoint.operator,a);r[l]||(r[l]=[]),r[l][e]=c}}computeIcon(e,t,s,o,i,n){return"ge"===s&&e>=t||"gt"===s&&e>t?n[0]:"ge"===i&&e>=o||"gt"===i&&e>o?n[1]:n[2]}applyColorScale(e,t){var s;const o=this.parsePoint(e,t.minimum,"min"),i=t.midpoint?this.parsePoint(e,t.midpoint):null,n=this.parsePoint(e,t.maximum,"max");if(null===o||null===n||o>=n||i&&(o>=i||i>=n))return;const r=qs(e),a=this.getters.getActiveSheetId(),l=this.computedStyles[a],c=[];t.midpoint&&i?(c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,i,t.minimum.color,t.midpoint.color)}),c.push({minValue:i,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(i,n,t.midpoint.color,t.maximum.color)})):c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,n,t.minimum.color,t.maximum.color)});for(let e=r.top;e<=r.bottom;e++)for(let t=r.left;t<=r.right;t++){const r=this.getters.getCell(a,t,e);if((null==r?void 0:r.evaluated.type)===Fe.number){const a=ms(r.evaluated.value,o,n);let h;h=2===c.length&&i?a<=i?this.colorCell(a,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(a,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(a,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),l[t]||(l[t]=[]),l[t][e]=(null===(s=l[t])||void 0===s?void 0:s[e])||{},l[t][e].fillColor="#"+Xt(h)}}}computeColorDiffUnits(e,t,s,o){const i=t-e;return[((s>>16)%256-(o>>16)%256)/i,((s>>8)%256-(o>>8)%256)/i,(s%256-o%256)/i]}colorCell(e,t,s,o){const[i,n,r]=o;return Math.round((s>>16)%256-i*(e-t))<<16|Math.round((s>>8)%256-n*(e-t))<<8|Math.round(s%256-r*(e-t))}adaptRules(e,t,s,o){if(0===s.length&&0===o.length)return;const i=this.getters.getConditionalFormats(e),n=i.findIndex((e=>e.id===t.id));let r=[];n>-1&&(r=i[n].ranges),r=r.concat(s);const a=so(r,o);0!==a.length?this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:t.id,rule:t.rule,stopIfTrue:t.stopIfTrue},target:a.map(qs),sheetId:e}):this.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:t.id,sheetId:e})}pasteCf(e,t,s){const o=is(t.col,t.row);for(let i of this.getters.getConditionalFormats(e.sheetId))for(let n of i.ranges)if(to(e.col,e.row,qs(n))){const n=i,r=[];if("CUT"===s&&r.push(is(e.col,e.row)),e.sheetId===t.sheetId)this.adaptRules(e.sheetId,n,[o],r);else{this.adaptRules(e.sheetId,n,[],r);const s=this.getCFToCopyTo(t.sheetId,n);this.adaptRules(t.sheetId,s,[o],[])}}}getCFToCopyTo(e,t){const s=this.getters.getConditionalFormats(e).find((e=>e.stopIfTrue===t.stopIfTrue&&Fs(e.rule,t.rule)));return s||{...t,id:this.uuidGenerator.uuidv4(),ranges:[]}}}Dh.getters=["getConditionalStyle","getConditionalIcon"],Dh.modes=["normal"];var Ph;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(Ph||(Ph={}));class Uh extends yh{constructor(){super(...arguments),this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1},this.replaceOptions={modifyFormulas:!1},this.toSearch=""}handle(e){switch(e.type){case"UPDATE_SEARCH":this.updateSearch(e.toSearch,e.searchOptions);break;case"CLEAR_SEARCH":case"UNDO":case"REDO":case"REMOVE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":this.clearSearch();break;case"SELECT_SEARCH_PREVIOUS_MATCH":this.selectNextCell(Ph.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(Ph.next);break;case"REPLACE_SEARCH":this.replace(e.replaceWith,e.replaceOptions);break;case"REPLACE_ALL_SEARCH":this.replaceAll(e.replaceWith,e.replaceOptions);break;case"ACTIVATE_SHEET":case"REFRESH_SEARCH":this.refreshSearch()}}getSearchMatches(){return this.searchMatches}getCurrentSelectedMatchIndex(){return this.selectedMatchIndex}updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null),this.toSearch=e,this.updateRegex(),this.refreshSearch()}refreshSearch(){const e=this.findMatches();this.searchMatches=e,this.selectNextCell(Ph.current)}updateRegex(){let e=ps(this.toSearch);const t=this.searchOptions.matchCase?"":"i";this.searchOptions.exactMatch&&(e=`^${e}$`),this.currentSearchRegex=RegExp(e,t)}findMatches(){const e=this.getters.getActiveSheetId(),t=this.getters.getCells(e),s=[];if(this.toSearch)for(const e of Object.values(t))if(e&&this.currentSearchRegex&&this.currentSearchRegex.test(this.searchOptions.searchFormulas&&e.isFormula()?e.content:String(e.evaluated.value))){const t=this.getters.getCellPosition(e.id),o={col:t.col,row:t.row,selected:!1};s.push(o)}return s.sort(this.sortByRowThenColumn)}sortByRowThenColumn(e,t){return e.row===t.row?e.col-t.col:e.row>t.row?1:-1}selectNextCell(e){const t=this.searchMatches;if(!t.length)return void(this.selectedMatchIndex=null);let s;s=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,s=(s%t.length+t.length)%t.length,null!==this.selectedMatchIndex&&this.selectedMatchIndex===s||(this.selectedMatchIndex=s,this.dispatch("SELECT_CELL",{col:t[s].col,row:t[s].row}));for(let e=0;e<this.searchMatches.length;e++)this.searchMatches[e].selected=e===this.selectedMatchIndex}clearSearch(){this.toSearch="",this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1},this.replaceOptions={modifyFormulas:!1}}replace(e,t){if(this.replaceOptions=t,null===this.selectedMatchIndex||!this.currentSearchRegex)return;const s=this.searchMatches[this.selectedMatchIndex],o=this.getters.getActiveSheetId(),i=this.getters.getCell(o,s.col,s.row),n=this.toReplace(i,o);if(i&&n){const t=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),o=n.toString().replace(t,e);this.dispatch("UPDATE_CELL",{sheetId:this.getters.getActiveSheetId(),col:s.col,row:s.row,content:o}),this.searchMatches.splice(this.selectedMatchIndex,1),this.selectNextCell(Ph.current)}else this.selectNextCell(Ph.next)}replaceAll(e,t){const s=this.searchMatches.length;for(let o=0;o<s;o++)this.replace(e,t)}toReplace(e,t){if(e){if(this.searchOptions.searchFormulas&&e.isFormula())return e.content;if(this.replaceOptions.modifyFormulas||!e.isFormula())return e.evaluated.value.toString()}return null}drawGrid(e){const{ctx:t,viewport:s}=e,o=this.getters.getActiveSheetId();for(const e of this.searchMatches){const i=this.getters.getMerge(o,e.col,e.row),n=i?i.left:e.col,r=i?i.right:e.col,a=i?i.top:e.row,l=i?i.bottom:e.row,[c,h,d,u]=this.getters.getRect({top:a,left:n,right:r,bottom:l},s);d>0&&u>0&&(t.fillStyle="#8B008B33",t.fillRect(c,h,d,u),e.selected&&(t.strokeStyle="#8B008B",t.strokeRect(c,h,d,u)))}}}Uh.layers=[3],Uh.getters=["getSearchMatches","getCurrentSelectedMatchIndex"];class Vh extends yh{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,s){const o=this.searchNumberFormat(e,t);if(void 0!==o){const i=this.changeDecimalFormat(o,s);this.dispatch("SET_FORMATTING",{sheetId:e,target:t,format:i})}}searchNumberFormat(e,t){var s;for(let o of t)for(let t=o.top;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++){const o=this.getters.getCell(e,i,t);if((null==o?void 0:o.evaluated.type)===Fe.number&&!(null===(s=o.format)||void 0===s?void 0:s.match(_)))return o.format||this.setDefaultNumberFormat(o.evaluated.value)}}setDefaultNumberFormat(e){const t=e.toString().split(".");return 1===t.length?"0":"0."+Array(t[1].length+1).join("0")}changeDecimalFormat(e,t){const s=Math.sign(t),o=e.split(";");let i=[];for(let e of o){const t=e.indexOf("."),o=e.toUpperCase().indexOf("E");let n;const r=o>-1?e.slice(0,o):e,a=t>-1?r.slice(t).match(/0/g).length:0,l=r.lastIndexOf("0");l>-1?s>0?n=a<re?e.slice(0,l+1)+(0===a?".0":"0")+e.slice(l+1):e:a>0?(n=e.slice(0,l)+e.slice(l+1),1===a&&(n=n.slice(0,t)+n.slice(t+1))):n=e:n=e,i.push(n)}return i.join(";")}}Vh.modes=["normal"];class Bh extends yh{getHighlights(){return this.prepareHighlights(this.getters.getComposerHighlights().concat(this.getters.getSelectionInputHighlights()))}prepareHighlights(e){if(0===e.length)return[];const t=this.getters.getActiveSheetId(),s=[];for(let[o,i]of e){const{xc:e,sheetName:n}=ts(o),r=n?this.getters.getSheetIdByName(n):t;if(r){let o=qs(e);const{height:n,width:a}=io(o);o=n*a==1?this.getters.expandZone(t,qs(e)):o,s.push({zone:o,color:i,sheet:r})}}return s.filter((e=>e.zone.top>=0&&e.zone.left>=0&&e.zone.bottom<this.getters.getSheet(e.sheet).rows.length&&e.zone.right<this.getters.getSheet(e.sheet).cols.length))}drawGrid(e){const{ctx:t,viewport:s,thinLineWidth:o}=e,i=this.getters.getActiveSheetId(),n=3*o;t.lineWidth=n;for(let e of this.getHighlights().filter(((e,t)=>this.getHighlights().findIndex((t=>Js(t.zone,e.zone)&&t.sheet===i))===t))){const[o,i,r,a]=this.getters.getRect(e.zone,s);r>0&&a>0&&(t.strokeStyle=e.color,t.strokeRect(o+n/2,i+n/2,r-n,a-n),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(o+n,i+n,r-2*n,a-2*n))}}}function Hh(e,t){let s=0,o=e.length-1;for(;s<=o;){const i=Math.floor((s+o)/2),n=e[i];if(t<n.start)o=i-1;else if(t>n.end)s=i+1;else{if(!n.isHidden)return i;s+=1}}return-1}Bh.modes=["normal"],Bh.layers=[1],Bh.getters=["getHighlights"];class zh extends yh{constructor(){super(...arguments),this.boxes=[]}getColIndex(e,t,s){if(e<v)return-1;const o=(s||this.getters.getActiveSheet()).cols;return Hh(o,e-v+o[t].start+1)}getRowIndex(e,t,s){if(e<m)return-1;const o=(s||this.getters.getActiveSheet()).rows;return Hh(o,e-m+o[t].start+1)}getRect(e,t){const{left:s,top:o,right:i,bottom:n}=e,{offsetX:r,offsetY:a}=this.getShiftedViewport(t),{cols:l,rows:c}=this.getters.getActiveSheet(),h=Math.max(l[s].start-r,v),d=l[i].end-r-h,u=Math.max(c[o].start-a,m);return[h,u,d,c[n].end-a-u]}isVisibleInViewport(e,t,s){const{right:o,left:i,top:n,bottom:r}=s;return t<=r&&t>=n&&e>=i&&e<=o}getEdgeScrollCol(e){let t=!1,s=0,o=0;const{width:i}=this.getters.getViewportDimensionWithHeaders(),{width:n}=this.getters.getMaxViewportSize(this.getters.getActiveSheet()),{left:r,offsetX:a}=this.getters.getActiveSnappedViewport();return e<v&&r>0?(t=!0,s=-1,o=ls(v-e)):e>i&&a<n-i&&(t=!0,s=1,o=ls(e-i)),{canEdgeScroll:t,direction:s,delay:o}}getEdgeScrollRow(e){let t=!1,s=0,o=0;const{height:i}=this.getters.getViewportDimensionWithHeaders(),{height:n}=this.getters.getMaxViewportSize(this.getters.getActiveSheet()),{top:r,offsetY:a}=this.getters.getActiveSnappedViewport();return e<m&&r>0?(t=!0,s=-1,o=ls(m-e)):e>i&&a<n-i&&(t=!0,s=1,o=ls(e-i)),{canEdgeScroll:t,direction:s,delay:o}}drawGrid(e,t){switch(t){case 0:this.boxes=this.getGridBoxes(e),this.drawBackground(e),this.drawCellBackground(e),this.drawBorders(e),this.drawTexts(e),this.drawIcon(e);break;case 7:this.drawHeaders(e)}}drawBackground(e){const{ctx:t,thinLineWidth:s,viewport:o}=e,{width:i,height:n}=this.getters.getViewportDimensionWithHeaders(),{cols:r,rows:a,id:l}=this.getters.getActiveSheet();t.fillStyle="white",t.fillRect(0,0,i,n);const{right:c,left:h,top:d,bottom:u,offsetX:p,offsetY:g}=this.getShiftedViewport(o);if(!this.getters.getGridLinesVisibility(l))return;t.lineWidth=2*s,t.strokeStyle="#E2E3E3",t.beginPath();const f=Math.min(n,a[u].end-g);for(let e=h;e<=c;e++){if(r[e].isHidden)continue;const s=r[e].end-p;t.moveTo(s,0),t.lineTo(s,f)}const m=Math.min(i,r[c].end-p);for(let e=d;e<=u;e++){if(a[e].isHidden)continue;const s=a[e].end-g;t.moveTo(0,s),t.lineTo(m,s)}t.stroke()}drawCellBackground(e){const{ctx:t,thinLineWidth:s}=e;t.lineWidth=.3*s;const o=.1*s;t.strokeStyle="#111";const i=this.getters.getGridLinesVisibility(this.getters.getActiveSheetId());for(let e of this.boxes){let s=e.style;(s.fillColor&&"#ffffff"!==s.fillColor||e.isMerge)&&(t.fillStyle=s.fillColor||"#ffffff",t.fillRect(e.x,e.y,e.width,e.height),i&&t.strokeRect(e.x+o,e.y+o,e.width-2*o,e.height-2*o)),e.error&&(t.fillStyle="red",t.beginPath(),t.moveTo(e.x+e.width-5,e.y),t.lineTo(e.x+e.width,e.y),t.lineTo(e.x+e.width,e.y+5),t.fill())}}drawBorders(e){const{ctx:t,thinLineWidth:s}=e;for(let e of this.boxes){let t=e.border;if(t){const{x:s,y:i,width:n,height:r}=e;t.left&&o(t.left,s,i,s,i+r),t.top&&o(t.top,s,i,s+n,i),t.right&&o(t.right,s+n,i,s+n,i+r),t.bottom&&o(t.bottom,s,i+r,s+n,i+r)}}function o([e,o],i,n,r,a){t.strokeStyle=o,t.lineWidth=("thin"===e?2:3)*s,t.beginPath(),t.moveTo(i,n),t.lineTo(r,a),t.stroke()}}drawTexts(e){const{ctx:t,thinLineWidth:s}=e;let o;t.textBaseline="middle";for(let e of this.boxes)if(e.content){const i=e.style||{},n=e.content.align||"left",r=i.italic?"italic ":"",a=i.bold?"bold":T,l=i.fontSize||R,c=hs[l],h=`${r}${a} ${c}px ${L}`;let d;h!==o&&(o=h,t.font=h),t.fillStyle=i.textColor||"#000";let u=e.y+e.height/2+1;d="left"===n?e.x+(e.image?e.image.size+2*w:4):"right"===n?e.x+e.width-4:e.x+e.width/2,t.textAlign=n,e.clipRect&&(t.save(),t.beginPath(),t.rect(...e.clipRect),t.clip()),t.fillText(e.content.text,Math.round(d),Math.round(u)),(i.strikethrough||i.underline)&&("right"===n?d-=e.content.width:"center"===n&&(d-=e.content.width/2),i.strikethrough&&t.fillRect(d,u,e.content.width,2.6*s),i.underline&&(u=e.y+e.height/2+1+c/2,t.fillRect(d,u,e.content.width,1.3*s))),e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const s=e.image.image,o=e.image.size,i=(e.height-o)/2;e.image.clipIcon&&(t.save(),t.beginPath(),t.rect(...e.image.clipIcon),t.clip()),t.drawImage(s,e.x+w,e.y+i,o,o),e.image.clipIcon&&t.restore()}}drawHeaders(e){const{ctx:t,thinLineWidth:s,viewport:o}=e,{right:i,left:n,top:r,bottom:a,offsetX:l,offsetY:p}=this.getShiftedViewport(o),{width:g,height:f}=this.getters.getViewportDimensionWithHeaders(),E=this.getters.getSelectedZones(),{cols:b,rows:S}=this.getters.getActiveSheet(),C=this.getters.getActiveCols(),y=this.getters.getActiveRows();t.fillStyle=c,t.font=`400 11px ${L}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=s,t.strokeStyle="#333",t.fillRect(0,0,g,m),t.fillRect(0,0,v,f),t.fillStyle=h;for(let e of E){const s=Math.max(v,b[e.left].start-l),o=Math.max(v,b[e.right].end-l),i=Math.max(m,S[e.top].start-p),n=Math.max(m,S[e.bottom].end-p);t.fillStyle=C.has(e.left)?d:h,t.fillRect(s,0,o-s,m),t.fillStyle=y.has(e.top)?d:h,t.fillRect(0,i,v,n-i)}t.beginPath(),t.moveTo(v,0),t.lineTo(v,f),t.moveTo(0,m),t.lineTo(g,m),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(let e=n;e<=i;e++){const s=b[e];s.isHidden||(t.fillStyle=C.has(e)?"#fff":u,t.fillText(s.name,(s.start+s.end)/2-l,13),t.moveTo(s.end-l,0),t.lineTo(s.end-l,m))}for(let e=r;e<=a;e++){const s=S[e];s.isHidden||(t.fillStyle=y.has(e)?"#fff":u,t.fillText(s.name,24,(s.start+s.end)/2-p),t.moveTo(0,s.end-p),t.lineTo(v,s.end-p))}t.stroke()}hasContent(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.getCell(s,e,t);return o&&!o.isEmpty()||this.getters.isInMerge(s,e,t)}getShiftedViewport(e){return{...e,offsetX:e.offsetX-v,offsetY:e.offsetY-m}}findNextEmptyCol(e,t,s){let o=e;for(;o<t&&!this.hasContent(o+1,s);)o++;return o}findPreviousEmptyCol(e,t,s){let o=e;for(;o>t&&!this.hasContent(o-1,s);)o--;return o}computeCellAlignment(e,t){if(e.isFormula()&&this.getters.shouldShowFormulas())return"left";const{align:s}=this.getters.getCellStyle(e);return t&&e.evaluated.type===Fe.number?"center"!==s?"left":s:s||e.defaultAlign}createBoxFromPosition(e,t,s,o,i,n){const{right:r,left:a,offsetX:l,offsetY:c}=this.getShiftedViewport(o),h=this.getters.getCol(e,t),d=this.getters.getRow(e,s),u=this.getters.getCell(e,t,s),p=this.getters.shouldShowFormulas(),g={x:h.start-l,y:d.start-c,width:i,height:n,border:this.getters.getCellBorder(e,t,s)||void 0,style:{...this.getters.getCellStyle(u),...this.getters.getConditionalStyle(t,s)}};if(!u)return g;const f=this.getters.getConditionalIcon(t,s),m=g.style.fontSize||R,v=hs[m],E=f?2*w+v:0;f&&(g.image={type:"icon",size:v,clipIcon:[g.x,g.y,Math.min(E,i),n],image:Yl[f].img});const b=this.getters.getCellText(u,p),S=this.getters.getTextWidth(u),C=E+S,y=this.computeCellAlignment(u,C>i);g.content={text:b,width:S,align:y},u.evaluated.type===Fe.error&&(g.error=u.evaluated.error);const I=C>i||hs[m]>n;if(f)g.clipRect=[g.x+E,g.y,Math.max(0,i-E),n];else if(I){let o,u;switch(this.getters.isInMerge(e,t,s)?(o=this.getters.getMerge(e,t,s).right,u=t):(o=this.findNextEmptyCol(t,r,s),u=this.findPreviousEmptyCol(t,a,s)),y){case"left":{const t=this.getters.getCol(e,o).end-h.start;(t<S||v>d.size)&&(g.clipRect=[h.start-l,d.start-c,t,n]);break}case"right":{const t=this.getters.getCol(e,u),s=h.end+i-h.size-t.start;(s<S||v>d.size)&&(g.clipRect=[t.start-l,d.start-c,s,n]);break}case"center":{const s=this.getters.getCol(e,u),i=this.getters.getCol(e,o).end-s.start;(i<S||u===t||o===t||v>d.size)&&(g.clipRect=[s.start-l,d.start-c,i,n]);break}}}return g}getGridBoxes(e){const t=[],{viewport:s}=e,{right:o,left:i,top:n,bottom:r}=this.getShiftedViewport(s),a=this.getters.getActiveSheetId();for(let e=n;e<=r;e++){const n=this.getters.getRow(a,e);if(!n.isHidden)for(let r=i;r<=o;r++){const o=this.getters.getCol(a,r);o.isHidden||(this.getters.isInMerge(a,r,e)||t.push(this.createBoxFromPosition(a,r,e,s,o.size,n.size)))}}for(const e of this.getters.getMerges(a))if(!this.getters.isMergeHidden(a,e)&&eo(e,s)){const o=this.getters.getCol(a,e.right).end-this.getters.getCol(a,e.left).start,i=this.getters.getRow(a,e.bottom).end-this.getters.getRow(a,e.top).start,n=this.createBoxFromPosition(a,e.left,e.top,s,o,i),r=this.getters.getCellBorder(a,e.right,e.bottom);n.border={...n.border,bottom:r?r.bottom:void 0,right:r?r.right:void 0},n.isMerge=!0,t.push(n)}return t}}zh.layers=[0,7],zh.getters=["getColIndex","getRowIndex","getRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow"],zh.modes=["normal"];const Zh=new Hs;class Gh extends yh{constructor(){super(...arguments),this.inputs={},this.activeSheets={},this.inputHasSingleRange={},this.focusedInputId=null,this.focusedRange=null,this.willAddNewRange=!1}allowDispatch(e){switch(e.type){case"FOCUS_RANGE":const t=this.getIndex(e.id,e.rangeId);if(this.focusedInputId===e.id&&this.focusedRange===t)return 24;break;case"ADD_EMPTY_RANGE":if(this.inputHasSingleRange[e.id]&&1===this.inputs[e.id].length)return 25}return 0}handle(e){switch(e.type){case"ENABLE_NEW_SELECTION_INPUT":this.initInput(e.id,e.initialRanges||[],e.hasSingleRange);break;case"DISABLE_SELECTION_INPUT":this.focusedInputId===e.id&&this.unfocus(),delete this.inputs[e.id],delete this.activeSheets[e.id],delete this.inputHasSingleRange[e.id];break;case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"FOCUS_RANGE":this.focus(e.id,this.getIndex(e.id,e.rangeId));break;case"CHANGE_RANGE":{const t=this.getIndex(e.id,e.rangeId);if(null!==t){const s=e.id;this.focusedInputId===s&&this.focusedRange===t||this.dispatch("FOCUS_RANGE",{id:s,rangeId:this.inputs[s][t].id});const o=e.value.split(",").map((e=>e.trim()));this.setRange(s,t,o)}break}case"ADD_EMPTY_RANGE":this.insertNewRange(e.id,this.inputs[e.id].length,[""]),this.focusLast(e.id);break;case"REMOVE_RANGE":const t=this.getIndex(e.id,e.rangeId);null!==t&&this.removeRange(e.id,t);break;case"SELECT_CELL":case"SET_SELECTION":if(!this.focusedInputId)break;const s=this.getSelectionInputValue(this.focusedInputId),o=(this.inputHasSingleRange[this.focusedInputId]?[this.getters.getSelectedZone()]:this.getters.getSelectedZones()).map(Xs).filter((e=>!s.includes(e))),i=this.activeSheets[this.focusedInputId],n=this.getters.getActiveSheetId(),r=this.getters.getSheetName(n);this.add(o.map((e=>n===i?e:`${fs(r)}!${e}`)));break;case"PREPARE_SELECTION_EXPANSION":{const[e,t]=[this.focusedInputId,this.focusedRange];null===e||null===t||this.inputHasSingleRange[e]||(this.willAddNewRange=""!==this.inputs[e][t].xc.trim());break}}}getSelectionInput(e){return this.inputs[e]?this.inputs[e].map(((t,s)=>Object.assign({},t,{color:this.focusedInputId===e&&null!==this.focusedRange&&this.isRangeValid(t.xc)?t.color:null,isFocused:this.focusedInputId===e&&this.focusedRange===s}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:s}=ts(e);return null!==t.match(es)&&(!s||void 0!==this.getters.getSheetIdByName(s))}getSelectionInputValue(e){return this.cleanInputs(this.inputs[e].map((e=>e.xc?e.xc:"")))}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].map((e=>this.inputToHighlights(this.focusedInputId,e))).flat():[]}initInput(e,t,s=!1){this.inputs[e]=[],this.insertNewRange(e,0,t),this.activeSheets[e]=this.getters.getActiveSheetId(),this.inputHasSingleRange[e]=s,0===this.inputs[e].length&&this.dispatch("ADD_EMPTY_RANGE",{id:e})}focus(e,t){this.focusedInputId=e,this.focusedRange=t}focusLast(e){this.focus(e,this.inputs[e].length-1)}unfocus(){this.focusedInputId=null,this.focusedRange=null}add(e){if(null===this.focusedInputId||null===this.focusedRange||this.getters.isSelectingForComposer()||0===e.length)return;if(this.getters.getSelectionMode()===Lh.expanding&&this.willAddNewRange){const t=this.focusedInputId;this.insertNewRange(t,this.inputs[t].length,e),this.focusLast(this.focusedInputId),this.willAddNewRange=!1}else this.setRange(this.focusedInputId,this.focusedRange,e)}setContent(e,t,s){this.inputs[e][t]={...this.inputs[e][t],id:Zh.uuidv4(),xc:s}}insertNewRange(e,t,s){this.inputs[e].splice(t,0,...s.map(((t,s)=>({xc:t,id:(this.inputs[e].length+s+1).toString(),color:Kt()}))))}setRange(e,t,s){const[,...o]=s;this.setContent(e,t,s[0]),this.insertNewRange(e,t+1,o),o.length&&this.focus(e,t+o.length)}removeRange(e,t){this.inputs[e].splice(t,1),this.focusedInputId===e&&null!==this.focusedRange&&this.focusLast(e)}inputToHighlights(e,{xc:t,color:s}){const o=this.cleanInputs([t]).filter((e=>this.isRangeValid(e))).filter((t=>this.shouldBeHighlighted(this.activeSheets[e],t)));if(0===o.length)return[];const[i,...n]=o,r=[[i,s||Kt()]];for(const e of n)r.push([e,Kt()]);return r}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:s}=ts(t),o=this.getters.getSheetIdByName(s),i=this.getters.getActiveSheet().id;return this.isRangeValid(t)&&(o===i||void 0===o&&i===e)}getIndex(e,t){const s=this.inputs[e].findIndex((e=>e.id===t));return s>=0?s:null}}Gh.modes=["normal"],Gh.layers=[1],Gh.getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];class Wh{constructor(){this.bus=new o.core.EventBus}on(e,t,s){this.bus.on(e,t,s)}trigger(e,t){this.bus.trigger(e,t)}off(e,t){this.bus.off(e,t)}clear(){this.bus.clear()}}function qh(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?function(e,t,s){const o="left"===t?"right":"bottom";let i=e[t],n=e[o];for(let r of s.sort(((e,t)=>t-e)))e[t]>r&&(i--,n--),e[t]<=r&&e[o]>=r&&n--;if(!(i>n))return{...e,[t]:i,[o]:n}}(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?function(e,t,s,o,i){const n="left"===t?"columns":"rows",r="before"===o?s-1:s,a="left"===t?"right":"bottom",l="before"===o?e[a]>r:e[a]>=r;return e[t]<=r&&l?ao(e,n,"RESIZE",i):r<e[t]?ao(e,n,"MOVE",i):{...e}}(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}function jh(e,t){const s=e.definition;let o,i;return s.labelRange&&(o=qh(qs(s.labelRange),t)),s.dataSets&&(i=s.dataSets.map(qs).map((e=>qh(e,t))).filter(_s).map(Xs)),{...e,definition:{...s,dataSets:i,labelRange:o?Xs(o):void 0}}}yl.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],jh),yl.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],jh),yl.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),yl.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){var s;if(e.name===t.name)return{...e,name:(null===(s=e.name)||void 0===s?void 0:s.match(/\d+/))?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),yl.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const s=[];for(const o of e.target)for(const e of t.target)eo(o,e)||s.push({...o});if(s.length)return{...e,target:s};return}));const Xh=[{match:function(e){return"sheetId"in e},fn:function(e,t){const s="DELETE_SHEET"===t.type&&t.sheetId;if(e.sheetId===s)return"IGNORE_COMMAND";if("CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId)return e;return"SKIP_TRANSFORMATION"}},{match:function(e){return"target"in e},fn:function(e,t){const s=[];for(const o of e.target){const e=qh(o,t);e&&s.push(e)}if(!s.length)return"IGNORE_COMMAND";return{...e,target:s}}},{match:function(e){return"col"in e&&"row"in e},fn:function(e,t){if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const s="COL"===t.dimension?"col":"row";let o=e[s];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(o))return"IGNORE_COMMAND";for(let t of e)o>=t&&o--}"ADD_COLUMNS_ROWS"===t.type&&(o>t.base||o===t.base&&"before"===t.position)&&(o+=t.quantity);return{...e,[s]:o}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const s of t.target){if(!(e.col===s.left&&e.row===s.top)&&to(e.col,e.row,s))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e},fn:function(e,t){if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const s="ADD_COLUMNS_ROWS"===e.type,o=s?"base":"elements";let i=s?[e[o]]:e[o];if("REMOVE_COLUMNS_ROWS"===t.type&&(i=i.map((e=>{if(t.elements.includes(e))return;const s=t.elements.sort(((e,t)=>t-e));for(let t of s)e>t&&e--;return e})).filter(_s)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;i=i.map((s=>s>e?s+t.quantity:s))}if(i.length){let t=i;return s&&(t=i[0]),{...e,[o]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}}];function Yh(e,t){const s=yl.getTransformation(e.type,t.type);return s?s(e,t):function(e,t){for(const{match:s,fn:o}of Xh)if(s(e)){const s=o(e,t);if("SKIP_TRANSFORMATION"===s)continue;if("IGNORE_COMMAND"===s)return;return s}return e}(e,t)}function Kh(e,t){let s=[...e];for(const e of t)s=s.map((t=>Yh(t,e))).filter(_s);return s}class Qh{constructor(e,t,s,o){this._commands=[],this._changes=[],this.id=e,this.clientId=t,this._commands=[...s],this._changes=o?[...o]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class Jh extends Error{}class ed extends Wh{constructor(e,t,s=N){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=s,this.clients={},this.clientId="local",this.pendingMessages=[],this.waitingAck=!1,this.waitingUndoRedoAck=!1,this.isReplayingInitialRevisions=!1,this.processedRevisions=new Set,this.uuidGenerator=new Hs,this.debouncedMove=o.utils.debounce(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t){if(!e.length||!t.length||!this.canApplyOptimisticUpdate())return;const s=new Qh(this.uuidGenerator.uuidv4(),this.clientId,e,t);this.revisions.append(s.id,s),this.trigger("new-local-state-update",{id:s.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:s.id,clientId:s.clientId,commands:s.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))}loadInitialMessages(e){this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1}leave(){delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}snapshot(e){const t=this.uuidGenerator.uuidv4();this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){const e=this.clients[this.clientId];if(!e)throw new Jh("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(_s))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}_move(e){var t;if(!this.clients[this.clientId])return;const s=null===(t=this.clients[this.clientId])||void 0===t?void 0:t.position;if((null==s?void 0:s.col)===e.col&&s.row===e.row&&s.sheetId===e.sheetId)return;const o=s?"CLIENT_MOVED":"CLIENT_JOINED",i=this.getClient();this.clients[this.clientId]={...i,position:e},this.transportService.sendMessage({type:o,version:1,client:{...i,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:s}=e,o=new Qh(e.nextRevisionId,t,s);if(o.clientId!==this.clientId){this.revisions.insert(o.id,o,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:Kh(s,t)})}break;case"SNAPSHOT_CREATED":{const t=new Qh(e.nextRevisionId,"server",[]);this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger("snapshot");break}}this.acknowledge(e),this.trigger("collaborative-event-received")}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;const t=this.clients[this.clientId];if(t){const{position:e}=t;e&&this.transportService.sendMessage({type:"CLIENT_MOVED",version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),this.waitingAck||(this.waitingAck=!0,this.sendPendingMessage())}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if("REMOTE_REVISION"===e.type){const t=this.revisions.get(e.nextRevisionId);if(0===t.commands.length){this.revisions.drop(t.id);const e=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.nextRevisionId));return this.trigger("pending-revisions-dropped",{revisionIds:e}),this.waitingAck=!1,this.waitingUndoRedoAck=!1,void(this.pendingMessages=[])}e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw new Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.\n ${JSON.stringify(e)}`);this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(this.waitingUndoRedoAck=!1),e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":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.sendPendingMessage()}}isAlreadyProcessed(e){switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter((({type:e})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const td=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];class sd extends yh{constructor(){super(...arguments),this.availableColors=new Set(td),this.colors={}}isPositionValid(e){const t=this.getters.getSheet(e.sheetId);return e.row<t.rows.length&&e.col<t.cols.length}chooseNewColor(){0===this.availableColors.size&&(this.availableColors=new Set(td));const e=(t=[...this.availableColors.values()])[Math.floor(Math.random()*t.length)];var t;return this.availableColors.delete(e),e}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof Jh)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const s of this.getters.getConnectedClients())if(s.id!==this.getters.getClient().id&&s.position&&s.position.sheetId===e&&this.isPositionValid(s.position)){const e=s.position;this.colors[s.id]||(this.colors[s.id]=this.chooseNewColor());const o=this.colors[s.id];t.push({...s,position:e,color:o})}return t}drawGrid(e){const{viewport:t,ctx:s,thinLineWidth:o}=e,i=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:n,col:r}=e.position,a=this.getters.expandZone(i,{top:n,bottom:n,left:r,right:r}),[l,c,h,d]=this.getters.getRect(a,t);if(h<=0||d<=0)continue;const u=e.color,p=`${u}10`;s.fillStyle=p,s.lineWidth=4*o,s.strokeStyle=u,s.globalCompositeOperation="multiply",s.fillRect(l,c,h,d),s.globalCompositeOperation="source-over",s.strokeRect(l,c,h,d),s.font=`bold ${R+1}px ${L}`}}}sd.getters=["getClientsToDisplay"],sd.layers=[5],sd.modes=["normal"];class od extends yh{allowDispatch(e){if("SORT_CELLS"===e.type){if(!to(e.col,e.row,e.zone))throw new Error(a("The anchor must be part of the provided zone"));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return 0}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection)}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;for(let s=t.top;s<=t.bottom;s++)for(let o=t.left;o<=t.right;o++)if(!this.getters.isInMerge(e,o,s))return 48;return 0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const s=this.getters.getMerges(e).filter((e=>eo(e,t))),o=io(s[0]);let[i,n]=[o.width,o.height];return s.every((e=>{let[t,s]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&s===n}))?0:48}expand(e,t){const{left:s,right:o,top:i,bottom:n}=this.getters.expandZone(e.id,t);return{left:Math.max(0,s),right:Math.min(e.cols.length-1,o),top:Math.max(0,i),bottom:Math.min(e.rows.length-1,n)}}checkExpandedValues(e,t){const s=this.expand(e,t),o=e.id;let i,n=[];if(this.getters.doesIntersectMerge(o,s)){const{left:e,right:t,top:r,bottom:a}=s;for(let s=e;s<=t;s++)for(let e=r;e<=a;e++){const[t,r]=this.getters.getMainCell(o,s,e);i=this.getters.getCell(o,t,r),n.push((null==i?void 0:i.formattedValue)||"")}}else n=this.getters.getCellsInZone(o,s).map((e=>(null==e?void 0:e.formattedValue)||""));return n.some((e=>""!==e))}getContiguousZone(e,t){let s,{top:o,bottom:i,left:n,right:r}=t;const a=this.getters.getSheet(e);let l=!1;for(;!l;)l=!0,o>0&&(s=this.checkExpandedValues(a,{left:n-1,right:r+1,top:o-1,bottom:o-1}),s&&(l=!1,o--)),n>0&&(s=this.checkExpandedValues(a,{left:n-1,right:n-1,top:o-1,bottom:i+1}),s&&(l=!1,n--)),r<a.cols.length-1&&(s=this.checkExpandedValues(a,{left:r+1,right:r+1,top:o-1,bottom:i+1}),s&&(l=!1,r++)),i<a.rows.length-1&&(s=this.checkExpandedValues(a,{left:n-1,right:r+1,top:i+1,bottom:i+1}),s&&(l=!1,i++));return{left:n,right:r,top:o,bottom:i}}hasHeader(e){if(1===e[0].length)return!1;let t=e.map((e=>e.map((e=>(null==e?void 0:e.evaluated.type)||Fe.empty))));return t[0][0]===Fe.empty&&(t=t.slice(1)),!t.some((e=>e[0]===Fe.empty))&&!!t.some((e=>e[1]!==Fe.empty&&e[0]!==e[1]))}sortZone(e,t,s,o){const[i,n]=this.mainCellsSteps(e,s);let r=this.getters.getMainCell(e,t.col,t.row)[0],a=Object.assign({},s),l=this.mainCells(e,s);this.hasHeader(l)&&(a.top+=n),l=this.mainCells(e,a);const c=function(e,t){const s=e.map(Pa),o=s.filter((e=>e.type===Fe.empty)),i=s.filter((e=>e.type!==Fe.empty)),n="descending"===t?-1:1;return i.sort(((e,t)=>{let s=Da.indexOf(e.type)-Da.indexOf(t.type);return 0===s&&(s=e.type===Fe.text||e.type===Fe.error?e.value.localeCompare(t.value):e.value-t.value),n*s})).concat(o)}(l[r-a.left],o),h=c.map((e=>e.index)),[d,u]=[l.length,l[0].length];for(let t=0;t<d;t++)for(let s=0;s<u;s++){let o=l[t][h[s]],r=a.left+t*i,c=a.top+s*n,d={sheetId:e,col:r,row:c,content:"",value:""};if(o){let t=o.content;if(o.isFormula()){const s=c-this.getters.getCellPosition(o.id).row,i=this.getters.createAdaptedRanges(o.dependencies,0,s,e);t=this.getters.buildFormulaContent(e,o,i)}d.style=o.style,d.content=t,d.format=o.format,d.value=o.evaluated.value}this.dispatch("UPDATE_CELL",d)}}mainCellsSteps(e,t){const s=this.getters.getMerge(e,t.left,t.top);return[s?s.right-s.left+1:1,s?s.bottom-s.top+1:1]}mainCells(e,t){const[s,o]=this.mainCellsSteps(e,t),i=[],n=Es(t.left,t.right+1,s),r=Es(t.top,t.bottom+1,o);for(const t of n){const s=[];i.push(s);for(const o of r)s.push(this.getters.getCell(e,t,o))}return i}}od.getters=["getContiguousZone"];class id extends yh{constructor(){super(...arguments),this.showFormulas=!1}handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}id.modes=["normal"],id.getters=["shouldShowFormulas"];class nd extends yh{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}allowDispatch(e){switch(e.type){case"AUTORESIZE_ROWS":case"AUTORESIZE_COLUMNS":try{this.getters.getSheet(e.sheetId);break}catch(e){return 23}}return 0}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){const s=this.getColMaxWidth(e.sheetId,t);0!==s&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:s+6,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":for(let t of e.rows){const s=this.getRowMaxHeight(e.sheetId,t);0!==s&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"ROW",size:s+6,sheetId:e.sheetId})}}}getCellWidth(e){let t=this.getTextWidth(e);const s=this.getters.getCellPosition(e.id);return this.getters.getConditionalIcon(s.col,s.row)&&(t+=function(e,t){const s=t.fontSize||R;return hs[s]+2*w}(this.ctx,this.getters.getCellStyle(e))),t}getTextWidth(e){const t=this.getters.getCellText(e,this.getters.shouldShowFormulas());return vs(this.ctx,t,this.getters.getCellStyle(e))}getCellHeight(e){const t=this.getters.getCellStyle(e).fontSize||R;return hs[t]}getCellText(e,t=!1){return t&&(e.isFormula()||e.evaluated.type===Fe.error)?e.content:e.formattedValue}getColMaxWidth(e,t){const s=this.getters.getColCells(e,t).map((e=>this.getCellWidth(e)));return Math.max(0,...s)}getRowMaxHeight(e,t){const s=this.getters.getSheet(e),o=Object.values(s.rows[t].cells).filter(_s).map((e=>this.getters.getCellById(e))).map((e=>this.getCellHeight(e)));return Math.max(0,...o)}}nd.getters=["getCellWidth","getCellHeight","getTextWidth","getCellText"];class rd extends yh{constructor(){super(...arguments),this.viewports={},this.snappedViewports={},this.updateSnap=!1,this.viewportWidth=1e3,this.viewportHeight=1e3}allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.checkOffsetValidity(e.offsetX,e.offsetY);case"RESIZE_VIEWPORT":return e.width<0||e.height<0?54:0;default:return 0}}handle(e){switch(e.type){case"UNDO":case"REDO":this.cleanViewports(),this.resetViewports();break;case"RESIZE_VIEWPORT":this.cleanViewports(),this.resizeViewport(e.height,e.width);break;case"SET_VIEWPORT_OFFSET":this.setViewportOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const t=this.getActiveTopRow(),s=this.clipOffsetY(t.start+this.viewportHeight);this.shiftVertically(s);break;case"SHIFT_VIEWPORT_UP":{const e=this.getActiveTopRow(),t=this.clipOffsetY(e.end-this.viewportHeight);this.shiftVertically(t);break}case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":"COL"===e.dimension?this.adjustViewportOffsetX(e.sheetId,this.getViewport(e.sheetId)):this.adjustViewportOffsetY(e.sheetId,this.getViewport(e.sheetId));break;case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":"COL"===e.dimension?this.adjustViewportZoneX(e.sheetId,this.getViewport(e.sheetId)):this.adjustViewportZoneY(e.sheetId,this.getViewport(e.sheetId));break;case"ACTIVATE_SHEET":this.refreshViewport(e.sheetIdTo);break;case"SELECT_CELL":case"MOVE_POSITION":this.refreshViewport(this.getters.getActiveSheetId())}}finalize(){this.updateSnap&&(this.snapViewportToCell(this.getters.getActiveSheetId()),this.updateSnap=!1)}getViewportDimensionWithHeaders(){return{width:this.viewportWidth+v,height:this.viewportHeight+m}}getActiveViewport(){const e=this.getters.getActiveSheetId();return this.getViewport(e)}getActiveSnappedViewport(){const e=this.getters.getActiveSheetId();return this.getSnappedViewport(e)}getMaxViewportSize(e){const t=Gs(e,"cols"),s=Gs(e,"rows"),o=e.cols.find((e=>e.end>t.end-this.viewportWidth))||e.cols[e.cols.length-1],i=e.rows.find((e=>e.end>s.end-this.viewportHeight))||e.rows[e.rows.length-1];return{width:t.end+Math.max(b,Math.min(o.size,this.viewportWidth-t.size)),height:s.end+Math.max(S+5,Math.min(i.size,this.viewportHeight-s.size))}}getMaximumViewportOffset(e){const{width:t,height:s}=this.getters.getMaxViewportSize(e);return{maxOffsetX:Math.max(0,t-this.viewportWidth+1),maxOffsetY:Math.max(0,s-this.viewportHeight+1)}}checkOffsetValidity(e,t){const s=this.getters.getActiveSheet(),{maxOffsetX:o,maxOffsetY:i}=this.getMaximumViewportOffset(s);return e<0||t<0||t>i||e>o?53:0}getSnappedViewport(e){return this.snapViewportToCell(e),this.snappedViewports[e]}getViewport(e){return this.viewports[e]?this.viewports[e]:this.generateViewportState(e)}cleanViewports(){const e=this.getters.getVisibleSheets();for(let t of Object.keys(this.viewports))e.includes(t)||delete this.viewports[t]}resetViewports(){for(let[e,t]of Object.entries(this.viewports))this.adjustViewportOffsetX(e,t),this.adjustViewportOffsetY(e,t),this.adjustViewportsPosition(e)}adjustViewportOffsetX(e,t){const{offsetX:s}=t,{width:o}=this.getMaxViewportSize(this.getters.getSheet(e));if(this.viewportWidth+s>o){const e=this.viewportWidth+s-o;t.offsetX=Math.max(0,s-e)}this.adjustViewportZoneX(e,t)}adjustViewportOffsetY(e,t){const{offsetY:s}=t,{height:o}=this.getMaxViewportSize(this.getters.getSheet(e));if(this.viewportHeight+s>o){const e=this.viewportHeight+s-o;t.offsetY=Math.max(0,s-e)}this.adjustViewportZoneY(e,t)}resizeViewport(e,t){this.viewportHeight=e,this.viewportWidth=t,this.recomputeViewports()}recomputeViewports(){for(let e of Object.keys(this.viewports))this.adjustViewportOffsetX(e,this.viewports[e]),this.adjustViewportOffsetY(e,this.viewports[e])}setViewportOffset(e,t){const s=this.getters.getActiveSheetId();this.getActiveViewport(),this.viewports[s].offsetX=e,this.viewports[s].offsetY=t,this.adjustViewportZone(s,this.viewports[s])}clipOffsetY(e){const{height:t}=this.getters.getMaxViewportSize(this.getters.getActiveSheet()),s=t-this.viewportHeight;return e=Math.min(e,s),e=Math.max(e,0)}generateViewportState(e){return this.viewports[e]={left:0,right:0,top:0,bottom:0,offsetX:0,offsetY:0},this.viewports[e]}refreshViewport(e){const t=this.getViewport(e);this.adjustViewportZone(e,t),this.adjustViewportsPosition(e)}adjustViewportZone(e,t){this.adjustViewportZoneX(e,t),this.adjustViewportZoneY(e,t)}adjustViewportZoneX(e,t){const s=this.getters.getSheet(e),o=s.cols;t.left=this.getters.getColIndex(t.offsetX+v,0,s);const i=this.viewportWidth+t.offsetX;t.right=o.length-1;for(let e=t.left;e<o.length;e++)if(i<o[e].end){t.right=e;break}this.updateSnap=!0}adjustViewportZoneY(e,t){const s=this.getters.getSheet(e),o=s.rows;t.top=this.getters.getRowIndex(t.offsetY+m,0,s);const i=this.viewportHeight+t.offsetY;t.bottom=o.length-1;for(let e=t.top;e<o.length;e++)if(i<o[e].end){t.bottom=e;break}this.updateSnap=!0}adjustViewportsPosition(e,t){const s=this.getters.getSheet(e),{cols:o,rows:i}=s,n=this.getSnappedViewport(e);t=t||this.getters.getSheetPosition(e);const[r,a]=zs(s,...this.getters.getMainCell(e,t[0],t[1]));for(;o[r].end>n.offsetX+this.viewportWidth&&n.offsetX<o[r].start;)n.offsetX=o[n.left].end,this.adjustViewportZoneX(e,n);for(;r<n.left;){const t=o.slice(0,n.left).reverse().findIndex((e=>!e.isHidden));n.offsetX=o[n.left-1-t].start,this.adjustViewportZoneX(e,n)}for(;i[a].end>n.offsetY+this.viewportHeight&&n.offsetY<i[a].start;)n.offsetY=i[n.top].end,this.adjustViewportZoneY(e,n);for(;a<n.top;){const t=i.slice(0,n.top).reverse().findIndex((e=>!e.isHidden));n.offsetY=i[n.top-1-t].start,this.adjustViewportZoneY(e,n)}const{top:l,left:c}=this.viewports[e];l===n.top&&c===n.left||(this.viewports[e]=n),this.updateSnap=!1}snapViewportToCell(e){const{cols:t,rows:s}=this.getters.getSheet(e),o=this.getViewport(e),i=Object.assign({},o);this.adjustViewportOffsetX(e,i),this.adjustViewportOffsetY(e,i),i.offsetX=t[i.left].start,i.offsetY=s[i.top].start,this.adjustViewportZone(e,i),this.snappedViewports[e]=i}shiftVertically(e){const{top:t,offsetX:s}=this.getActiveSnappedViewport();this.setViewportOffset(s,e);const{anchor:o}=this.getters.getSelection(),i=this.getActiveSnappedViewport().top-t;this.dispatch("SELECT_CELL",{col:o[0],row:o[1]+i})}getActiveTopRow(){const{top:e}=this.getActiveSnappedViewport(),t=this.getters.getActiveSheet();return this.getters.getRow(t.id,e)}}rd.getters=["getActiveViewport","getActiveSnappedViewport","getViewportDimensionWithHeaders","getMaxViewportSize","getMaximumViewportOffset"],rd.modes=["normal"];const ad=(new Me).add("sheet",La).add("cell",Sa).add("merge",xa).add("borders",Ea).add("conditional formatting",wa).add("figures",Ia).add("chart",Ca),ld=(new Me).add("selection",Mh).add("ui_sheet",nd).add("ui_options",id).add("evaluation",Nh).add("evaluation_cf",Dh).add("evaluation_chart",$h).add("clipboard",Th).add("edition",_h).add("highlight",Bh).add("selectionInput",Gh).add("viewport",rd).add("grid renderer",zh).add("autofill",Ih).add("find_and_replace",Uh).add("sort",od).add("automatic_sum",xh).add("format",Vh).add("selection_multiuser",sd);class cd{constructor(){this.listeners=[]}sendMessage(e){for(const{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter((t=>t.id!==e))}}class hd extends o.core.EventBus{constructor(){super(...arguments),this.registry=new Me}add(e,t){this.registry.add(e,t);const s=o.utils.debounce((()=>this.trigger("data-loaded",{id:e})),0);return t.on("data-loaded",this,(()=>s())),t.loadMetadata(),this}get(e){return this.registry.get(e)}getAll(){return this.registry.getAll()}remove(e){this.get(e).off("data-loaded",this),this.registry.remove(e)}async waitForReady(){const e=[];for(const t of this.getAll())e.push(t.get());return Promise.all(e)}}class dd extends o.core.EventBus{async loadMetadata(){this.metadataPromise||(this.metadataPromise=this._fetchMetadata().then((e=>(this.metadata=e,e)))),await this.metadataPromise}async get(e){return e&&e.forceFetch&&(this.data=void 0,this.dataPromise=void 0),await this.loadMetadata(),this.dataPromise||(this.dataPromise=this._fetch(e).then((e=>(this.data=e,this.lastUpdate=Date.now(),this.trigger("data-loaded"),e)))),this.dataPromise}getSync(){return this.data}getMetadataSync(){return this.metadata}getLastUpdate(){return this.lastUpdate}}function ud(e){return Oa.get(e.type)(e)}function pd(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class gd{constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){var e;return null===(e=this.operations[this.operations.length-1])||void 0===e?void 0:e.id}getFirstOperationAmong(e,t){for(const s of this.operations){if(s.id===e)return e;if(s.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const s=this.buildTransformation.with(e.data),{before:o,operation:i,after:n}=this.locateOperation(t);this.operations=[...o,i,e,...n.map((e=>e.transformed(s)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new gd(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:s}=this.locateOperation(e);this.operations=t.concat([s])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class fd{constructor(e,t){this.id=e,this.data=t}transformed(e){return new md(this.id,ks((()=>e(this.data))))}}class md{constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new md(this.id,this.lazyData.map(e))}}class vd{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new vd(function*(e,t){for(const s of e)if(yield s,s.operation.id===t)return}(this.operations,e))}stopBefore(e){return new vd(function*(e,t){for(const s of e){if(s.operation.id===t)return;yield s}}(this.operations,e))}startAfter(e){return new vd(function*(e,t){let s=!0;for(const o of e)s||(yield o),o.operation.id===t&&(s=!1)}(this.operations,e))}}class Ed{constructor(e,t){this.buildTransformation=e,this.branchingOperationIds=new Map,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new vd(Ss(this._execution(e),this._execution(e)))}revertedExecution(e){return new vd(Ss(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){var s;const o=e.getLastOperationId()||(null===(s=this.previousBranch(e))||void 0===s?void 0:s.getLastOperationId());e.append(t),o&&this.insertPrevious(e,t,o)}insertOperationAfter(e,t,s){e.insert(t,s),this.updateNextWith(e,t,s),this.insertPrevious(e,t,s)}undo(e,t){const s=this.buildTransformation.without(t.data),o=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const i=e.fork(t.id);o&&this.branchingOperationIds.set(i,o),this.insertBranchAfter(e,i),this.transform(i,s)}redo(e){const t=this.nextBranch(e);if(!t)return;const s=this.nextBranch(t);this.removeBranchFromTree(t);const o=this.branchingOperationIds.get(t);o?this.branchingOperationIds.set(e,o):this.branchingOperationIds.delete(e),s&&this.rebaseUp(s)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const s of this.revertedExecution(e))if(s.operation.id===t)return s;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:s}=this.findPreviousBranchingOperation(e);if(!t||!s)return;const o=this.buildTransformation.without(s.data),i=t.fork(s.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(o);const n=this.nextBranch(i);n&&this.rebaseUp(n)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const s=this.branches.findIndex((t=>t===e));this.branches.splice(s+1,0,t)}updateNextWith(e,t,s){const o=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(o&&i)if(e.getFirstOperationAmong(s,o)===o){const n=this.addToNextBranch(e,i,o,t,s);this.updateNextWith(i,n,s)}else{const e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,s,o,i){let n=o;return i===s?(n=this.getTransformedOperation(e,s,o),t.prepend(n)):t.contains(i)?(n=this.getTransformedOperation(e,s,o),t.insert(n,i)):t.append(o),n}getTransformedOperation(e,t,s){const o=e.getOperation(t),i=this.buildTransformation.without(o.data);return s.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const s=this.nextBranch(e);s&&this.transform(s,t)}insertPrevious(e,t,s){const{previousBranch:o,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!o||!i)return;const n=this.buildTransformation.with(i.data),r=e.fork(s);r.transform(n),o.cutAfter(s),o.appendBranch(r);const a=t.transformed(n);this.insertPrevious(o,a,s)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const s=this.branchingOperationIds.get(t);return s?{previousBranch:t,branchingOperation:t.getOperation(s)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let s=!!t;const o=e.getOperations();for(let i=o.length-1;i>=0;i--){const n=o[i];n.id===t&&(s=!1),s||(yield{operation:n,branch:e,isCancelled:!this.shouldExecute(e,n)})}const i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class bd{constructor(e,t,s,o,i){this.applyOperation=t,this.revertOperation=s,this.buildEmpty=o,this.buildTransformation=i,this.HEAD_BRANCH=new gd(this.buildTransformation),this.tree=new Ed(i,this.HEAD_BRANCH);const n=new fd(e,o(e));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){const s=new fd(e,t),o=this.tree.getLastBranch();this.tree.insertOperationLast(o,s),this.HEAD_BRANCH=o,this.HEAD_OPERATION=s}insert(e,t,s){const o=new fd(e,t);this.revertTo(s),this.tree.insertOperationAfter(this.HEAD_BRANCH,o,s),this.fastForward()}undo(e,t,s){const{branch:o,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(o,i),this.fastForward(),this.insert(t,this.buildEmpty(t),s)}redo(e,t,s){const{branch:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(o),this.fastForward(),this.insert(t,this.buildEmpty(t),s)}drop(e){this.revertBefore(e),this.tree.drop(e)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:s,isCancelled:o}of e)o||this.revertOperation(s.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:s,isCancelled:o}of e)o||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=s}}function Sd(e,t,s){return new bd(e,(e=>{const o=e.commands.slice(),{changes:i}=t((()=>{for(const e of o)s(e)}));e.setChanges(i)}),(e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){Cd(t.changes[e],"before")}}([e])),(e=>new Qh(e,"empty",[],[])),{with:e=>t=>new Qh(t.id,t.clientId,Kh(t.commands,e.commands)),without:e=>t=>new Qh(t.id,t.clientId,Kh(t.commands,e.commands.map(ud).flat()))})}function Cd(e,t){let s=e.root,o=e.path[e.path.length-1];for(let t=0;t<e.path.slice(0,-1).length;t++){const o=e.path[t];if(void 0===s[o]){const i=e.path[t+1];s[o]=pd(i)}s=s[o]}void 0===e[t]?delete s[o]:s[o]=e[t]}class yd extends o.core.EventBus{constructor(e,t){super(),this.dispatch=e,this.session=t,this.undoStack=[],this.redoStack=[],this.session.on("new-local-state-update",this,this.onNewLocalStateUpdate),this.session.on("revision-undone",this,(({commands:e})=>this.selectiveUndo(e))),this.session.on("revision-redone",this,(({commands:e})=>this.selectiveRedo(e))),this.session.on("pending-revisions-dropped",this,(({revisionIds:e})=>this.drop(e))),this.session.on("snapshot",this,(()=>{this.undoStack=[],this.redoStack=[]}))}allowDispatch(e){switch(e.type){case"REQUEST_UNDO":if(!this.canUndo())return 6;break;case"REQUEST_REDO":if(!this.canRedo())return 7}return 0}beforeHandle(e){}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();t&&("UNDO"===e?(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}drop(e){this.undoStack=this.undoStack.filter((t=>!e.includes(t))),this.redoStack=[]}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}selectiveUndo(e){this.dispatch("UNDO",{commands:e})}selectiveRedo(e){this.dispatch("REDO",{commands:e})}}class wd{constructor(e){this.providers=[],this.getters=e}allowDispatch(e){return 0}beforeHandle(e){}handle(e){switch(e.type){case"REMOVE_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",s="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";e.elements.sort(((e,t)=>t-e));const i=bs(e.elements);this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};let r=n,a="NONE";for(let e of i){const i=Math.min(...e),l=Math.max(...e);if(n.zone[t]<=i&&i<=n.zone[s]){const e=Math.min(n.zone[s],l)-i+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e)}else if(n.zone[t]>=i&&n.zone[s]<=l)a="REMOVE",r=this.buildInvalidRange(O);else if(n.zone[t]<=l&&n.zone[s]>=l){const e=l-n.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e),r=this.createAdaptedRange(r,o,"MOVE",-(n.zone[t]-i))}else i<n.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,o,a,-(l-i+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",s="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((i=>{if(i.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(i.zone[t]<=e.base&&e.base<i.zone[s])return{changeType:"RESIZE",range:this.createAdaptedRange(i,o,"RESIZE",e.quantity)};if(e.base<i.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(i,o,"MOVE",e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[s])return{changeType:"RESIZE",range:this.createAdaptedRange(i,o,"RESIZE",e.quantity)};if(e.base<=i.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(i,o,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>t.sheetId!==e.sheetId?{changeType:"NONE"}:{changeType:"REMOVE",range:t={...this.buildInvalidRange(O),invalidSheetName:this.getters.getSheetName(e.sheetId)}}),e.sheetId);break;case"RENAME_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.name&&t.invalidSheetName===e.name){const s={...t,zone:{...t.zone}};return s.invalidSheetName=void 0,s.sheetId=e.sheetId,{changeType:"CHANGE",range:s}}return{changeType:"NONE"}}))}}finalize(){}verifyRangeRemoved(e){return t=>{const s=e(t);return"NONE"===s.changeType||js(s.range.zone)?s:{range:s.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,s,o){return{...e,zone:ao(e.zone,t,s,o)}}executeOnAllRanges(e,t){const s=this.verifyRangeRemoved(e);for(const e of this.providers)e(s,t)}addRangeProvider(e){this.providers.push(e)}orderZone(e,t){if(e.right<e.left){let s=e.right;e.right=e.left,e.left=s;let o=t[1].colFixed;t[1].colFixed=t[0].colFixed,t[0].colFixed=o}if(e.bottom<e.top){let s=e.bottom;e.bottom=e.top,e.top=s;let o=t[1].rowFixed;t[1].rowFixed=t[0].rowFixed,t[0].rowFixed=o}}createAdaptedRanges(e,t,s,o){return e.map((e=>js(e.zone)?(e={...e,sheetId:e.prefixSheet?e.sheetId:o,zone:{left:e.zone.left+(e.parts[0].colFixed?0:t),right:e.zone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.zone.top+(e.parts[0].rowFixed?0:s),bottom:e.zone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:s)}},this.orderZone(e.zone,e.parts),e):e))}getRangeFromSheetXC(e,t){let s,o,i,n=t,r=!1;if(!es.test(t))return this.buildInvalidRange(t);t.includes("!")&&(({xc:n,sheetName:s}=ts(t)),s?(o=this.getters.getSheetIdByName(s),r=!0,o||(i=s)):i=s);const a=Ws(n);let l=n.split(":").map((e=>({colFixed:e.startsWith("$"),rowFixed:e.includes("$",1)})));return this.orderZone(a,l),{sheetId:o||e,zone:a,parts:l,invalidSheetName:i,prefixSheet:r}}getRangeString(e,t){if(!e)return O;if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return O;if(e.zone.left<0||e.zone.top<0)return O;let s=e.sheetId!==t||e.invalidSheetName||e.prefixSheet,o="";if(s&&(o=e.invalidSheetName?e.invalidSheetName:fs(this.getters.getSheetName(e.sheetId))),s&&!o)return O;let i=Array(9);return i[0]=e.parts&&e.parts[0].colFixed?"$":"",i[1]=ss(e.zone.left),i[2]=e.parts&&e.parts[0].rowFixed?"$":"",i[3]=String(e.zone.top+1),e.parts&&2===e.parts.length&&(e.zone.top!==e.zone.bottom||e.zone.left!==e.zone.right||e.parts[0].rowFixed||e.parts[0].colFixed||e.parts[1].rowFixed||e.parts[1].colFixed)&&(i[4]=":",i[5]=e.parts[1].colFixed?"$":"",i[6]=ss(e.zone.right),i[7]=e.parts[1].rowFixed?"$":"",i[8]=String(e.zone.bottom+1)),`${s?o+"!":""}${i.join("")}`}buildInvalidRange(e){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:e}}}wd.getters=["getRangeString","getRangeFromSheetXC","createAdaptedRanges"];class Id{constructor(){this.changes=[],this.commands=[]}recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop(),[s,...o]=e;let i=s,n=o[o.length-1];for(let e=0;e<=o.length-2;e++){const t=o[e];if(void 0===i[t]){const s=o[e+1];i[t]=pd(s)}i=i[t]}i[n]!==t&&(this.changes.push({root:s,path:o,before:i[n],after:t}),void 0===t?delete i[n]:i[n]=t)}}const xd={General:0,0:1,"0.00":2,"#,#00":3,"#,##0.00":4,"0%":9,"0.00%":10,"0.00E+00":11,"# ?/?":12,"# ??/??":13,"mm-dd-yy":14,"d-mm-yy":15,"mm-yy":16,"mmm-yy":17,"h:mm AM/PM":18,"h:mm:ss AM/PM":19,"h:mm":20,"h:mm:ss":21,"m/d/yy h:mm":22,"#,##0 ;(#,##0)":37,"#,##0 ;[Red](#,##0)":38,"#,##0.00;(#,##0.00)":39,"#,##0.00;[Red](#,##0.00)":40,"mm:ss":45,"[h]:mm:ss":46,"mmss.0":47,"##0.0E+0":48,"@":49,"hh:mm:ss a":19},Td={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},Rd={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"},Ld="http://schemas.openxmlformats.org/drawingml/2006/main",Md="http://schemas.openxmlformats.org/drawingml/2006/chart",Ad={workbook:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",sheet:"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+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"},_d="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Od=.75,Nd=.1425,kd=164,Fd={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}]},$d=["ACOT","ACOTH","AGGREGATE","ARABIC","BASE","BETA.DIST","BETA.INV","BINOM.DIST","BINOM.DIST.RANGE","BINOM.INV","BITAND","BITLSHIFT","BITOR","BITRSHIFT","BITXOR","CEILING.MATH","CEILING.PRECISE","CHISQ.DIST","CHISQ.DIST.RT","CHISQ.INV","CHISQ.INV.RT","CHISQ.TEST","COMBINA","CONCAT","CONFIDENCE.NORM","CONFIDENCE.T","COT","COTH","COVARIANCE.P","COVARIANCE.S","CSC","CSCH","DAYS","DECIMAL","ERF.PRECISE","ERFC.PRECISE","EXPON.DIST","F.DIST","F.DIST.RT","F.INV","F.INV.RT","F.TEST","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","HYPGEOM.DIST","IFNA","IFS","IMCOSH","IMCOT","IMCSC","IMCSCH","IMSEC","IMSECH","IMSINH","IMTAN","ISFORMULA","ISOWEEKNUM","LOGNORM.DIST","LOGNORM.INV","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","QUARTILE.EXC","QUARTILE.INC","QUERYSTRING","RANK.AVG","RANK.EQ","RRI","SEC","SECH","SHEET","SHEETS","SKEW.P","STDEV.P","STDEV.S","SWITCH","T.DIST","T.DIST.2T","T.DIST.RT","T.INV","T.INV.2T","T.TEST","TEXTJOIN","UNICHAR","UNICODE","VAR.P","VAR.S","WEBSERVICE","WEIBULL.DIST","XOR","Z.TEST"];function Dd(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function Pd(e){return Math.round(Od*e*window.devicePixelRatio*100)/100}function Ud(e){return Math.round(Nd*e*100)/100}function Vd(e,t){let s={};e.style&&(s=t.styles[e.style]);const o=e.format?t.formats[e.format]:void 0;let i={};e.border&&(i=t.borders[e.border]);const n={font:{size:(null==s?void 0:s.fontSize)||R,color:(null==s?void 0:s.textColor)?s.textColor:"000000",family:2,name:"Arial"},fill:(null==s?void 0:s.fillColor)?{fgColor:s.fillColor}:{reservedAttribute:"none"},numFmt:o,border:i||{},verticalAlignment:"center",horizontalAlignment:null==s?void 0:s.align};return n.font.strike=!!(null==s?void 0:s.strikethrough)||void 0,n.font.underline=!!(null==s?void 0:s.underline)||void 0,n.font.bold=!!(null==s?void 0:s.bold)||void 0,n.font.italic=!!(null==s?void 0:s.italic)||void 0,n}function Bd(e,t){const{id:s}=zd(t.font,e.fonts),{id:o}=zd(t.fill,e.fills),{id:i}=zd(t.border,e.borders),n=function(e,t){if(!e)return 0;let s=xd[e];if(!s){const{id:o}=zd(e,t);s=o+kd}return s}(t.numFmt,e.numFmts),r={fontId:s,fillId:o,borderId:i,numFmtId:n,verticalAlignment:t.verticalAlignment,horizontalAlignment:t.horizontalAlignment},{id:a}=zd(r,e.styles);return a}function Hd(e,t,s){let o,i=e.find((e=>e.path===t));return i?(o=`rId${(i.rels.length+1).toString()}`,i.rels.push({...s,id:o})):(o="rId1",e.push({path:t,rels:[{...s,id:o}]})),o}function zd(e,t){for(let[s,o]of Object.entries(t))if(JSON.stringify(o)===JSON.stringify(e))return{id:parseInt(s,10),list:t};let s=t.findIndex((t=>JSON.stringify(t)===JSON.stringify(e)));return-1===s&&(t.push(e),s=t.length-1),{id:s,list:t}}const Zd=[];function Gd(e){const t=Zd.findIndex((t=>t===e));return-1===t?(Zd.push(e),Zd.length):t+1}function Wd(e){return Math.round(914400*e/96)}class qd{constructor(e){this.xmlString=e}toString(){return this.xmlString}}function jd(e,t,s){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:s}}function Xd(e){return String(e).replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"")}function Yd(e){return new qd(e.map((([e,t])=>`${e}="${Xd(t)}"`)).join(" "))}function Kd(e){const t=(new DOMParser).parseFromString(e.toString(),"text/xml"),s=t.querySelector("parsererror");if(s){const t=s.innerHTML,o=parseInt(t.split(":")[0],10),i=e.toString().trim().split("\n"),n=i.slice(Math.max(o-3,0),Math.min(o+2,i.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${n}`)}return t}function Qd(e,t){return eu`
1048
+ `;class bh extends t.Component{constructor(){super(...arguments),this.getters=this.env.getters,this.state=t.useState(this.initialState())}get hasSearchResult(){return null!==this.env.getters.getCurrentSelectedMatchIndex()}setup(){ph((()=>this.focusInput())),gh((()=>this.env.dispatch("CLEAR_SEARCH")))}onInput(e){this.state.toSearch=e.target.value,this.debouncedUpdateSearch()}onKeydownSearch(e){"Enter"===e.key&&(e.preventDefault(),this.onSelectNextCell())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),this.replace())}onFocusSidePanel(){this.state.searchOptions.searchFormulas=this.getters.shouldShowFormulas(),this.state.replaceOptions.modifyFormulas=this.state.searchOptions.searchFormulas?this.state.searchOptions.searchFormulas:this.state.replaceOptions.modifyFormulas,this.env.dispatch("REFRESH_SEARCH")}searchFormulas(){this.env.dispatch("SET_FORMULA_VISIBILITY",{show:this.state.searchOptions.searchFormulas}),this.state.replaceOptions.modifyFormulas=this.state.searchOptions.searchFormulas,this.updateSearch()}onSelectPreviousCell(){this.env.dispatch("SELECT_SEARCH_PREVIOUS_MATCH")}onSelectNextCell(){this.env.dispatch("SELECT_SEARCH_NEXT_MATCH")}updateSearch(){this.env.dispatch("UPDATE_SEARCH",{toSearch:this.state.toSearch,searchOptions:this.state.searchOptions})}debouncedUpdateSearch(){clearTimeout(this.inDebounce),this.inDebounce=setTimeout((()=>this.updateSearch.call(this)),400)}replace(){this.env.dispatch("REPLACE_SEARCH",{replaceWith:this.state.replaceWith,replaceOptions:this.state.replaceOptions})}replaceAll(){this.env.dispatch("REPLACE_ALL_SEARCH",{replaceWith:this.state.replaceWith,replaceOptions:this.state.replaceOptions})}focusInput(){const e=this.el.querySelector("input");e&&e.focus()}initialState(){return{toSearch:"",replaceWith:"",searchOptions:{matchCase:!1,exactMatch:!1,searchFormulas:!1},replaceOptions:{modifyFormulas:!1}}}}bh.template=vh,bh.style=Eh;const Sh=new Ae;Sh.add("ConditionalFormatting",{title:a("Conditional formatting"),Body:uh}),Sh.add("ChartPanel",{title:a("Chart"),Body:zc}),Sh.add("FindAndReplace",{title:a("Find and Replace"),Body:bh});const Ch=new Ae;class yh extends ma{constructor(e,t,s,o){super(t,s,o),this.getters=e,this.ui=o}drawGrid(e,t){}}yh.layers=[];class wh{constructor(e,t,s){this.index=0,this.cells=e,this.getters=t,this.direction=s}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:s,tooltip:o}=Ma.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:s,tooltip:o,origin:{col:e.data.col,row:e.data.row}}}}class Ih extends yh{constructor(){super(...arguments),this.lastCellSelected={}}allowDispatch(e){switch(e.type){case"AUTOFILL_SELECT":const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:ms(e.col,0,this.getters.getSheet(t).cols.length),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:ms(e.row,0,this.getters.getSheet(t).rows.length),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:30;case"AUTOFILL_AUTO":const s=this.getters.getSelectedZone();return s.top===s.bottom?0:1}return 0}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;case"AUTOFILL_CELL":this.autoFillMerge(e.originCol,e.originRow,e.col,e.row);const t=this.getters.getActiveSheetId();this.dispatch("UPDATE_CELL",{sheetId:t,col:e.col,row:e.row,style:e.style||null,content:e.content||"",format:e.format||""}),this.dispatch("SET_BORDER",{sheetId:t,col:e.col,row:e.row,border:e.border})}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),s=this.autofillZone;switch(this.direction){case 1:for(let o=t.left;o<=t.right;o++){const i=[];for(let e=t.top;e<=t.bottom;e++)i.push(ns(o,e));const n=this.createGenerator(i);for(let t=s.top;t<=s.bottom;t++)this.computeNewCell(n,o,t,e)}break;case 0:for(let o=t.left;o<=t.right;o++){const i=[];for(let e=t.bottom;e>=t.top;e--)i.push(ns(o,e));const n=this.createGenerator(i);for(let t=s.bottom;t>=s.top;t--)this.computeNewCell(n,o,t,e)}break;case 2:for(let o=t.top;o<=t.bottom;o++){const i=[];for(let e=t.right;e>=t.left;e--)i.push(ns(e,o));const n=this.createGenerator(i);for(let t=s.right;t>=s.left;t--)this.computeNewCell(n,t,o,e)}break;case 3:for(let o=t.top;o<=t.bottom;o++){const i=[];for(let e=t.left;e<=t.right;e++)i.push(ns(e,o));const n=this.createGenerator(i);for(let t=s.left;t<=s.right;t++)this.computeNewCell(n,t,o,e)}}if(e){const e=Qs(this.getters.getSelectedZone(),this.autofillZone);this.autofillZone=void 0,this.lastCellSelected={},this.direction=void 0,this.tooltip=void 0,this.dispatch("SET_SELECTION",{zones:[e],anchor:[e.left,e.top],anchorZone:e})}}select(e,t){const s=this.getters.getSelectedZone();if(to(e,t,s))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case 0:this.saveZone(t,s.top-1,s.left,s.right);break;case 1:this.saveZone(s.bottom+1,t,s.left,s.right);break;case 2:this.saveZone(s.top,s.bottom,e,s.left-1);break;case 3:this.saveZone(s.top,s.bottom,s.right+1,e)}this.autofill(!1)}}autofillAuto(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let s=e.left,o=e.bottom;if(s>0){let e=this.getters.getCell(t,s-1,o);for(;e&&!e.isEmpty();)o+=1,e=this.getters.getCell(t,s-1,o)}if(o===e.bottom&&(s=e.right,s<=this.getters.getActiveSheet().cols.length)){let e=this.getters.getCell(t,s+1,o);for(;e&&!e.isEmpty();)o+=1,e=this.getters.getCell(t,s+1,o)}o!==e.bottom&&(this.select(e.left,o-1),this.autofill(!0))}computeNewCell(e,t,s,o){const{cellData:i,tooltip:n,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=i;this.tooltip=n,o&&this.dispatch("AUTOFILL_CELL",{originCol:r.col,originRow:r.row,col:t,row:s,content:a,style:l,border:c,format:h})}getRule(e,t){const s=Aa.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((s=>s.condition(e,t)));return s&&s.generateRule(e,t)}createGenerator(e){const t=[],s=[],o=this.getters.getActiveSheetId();for(let t of e){const[e,i]=is(t),n=this.getters.getCell(o,e,i);s.push({col:e,row:i,cell:n,sheetId:o})}const i=s.map((e=>e.cell));for(let e of s){let s={type:"COPY_MODIFIER"};if(e&&e.cell){s=this.getRule(e.cell,i)||s}const{sheetId:o,col:n,row:r}=e,a=this.getters.getCellBorder(o,n,r)||void 0;t.push({data:{...e,border:a},rule:s})}return new wh(t,this.getters,this.direction)}saveZone(e,t,s,o){this.autofillZone={top:e,bottom:t,left:s,right:o}}getDirection(e,t){const s=this.getters.getSelectedZone(),o={up:{number:s.top-t,value:0},down:{number:t-s.bottom,value:1},left:{number:s.left-e,value:2},right:{number:e-s.right,value:3}};if(1===Object.values(o).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(o).find((e=>e.number>0?1:0)).value;const i=o.up.number>0?"up":"down",n=o.left.number>0?"left":"right";return Math.abs(o[i].number)>=Math.abs(o[n].number)?o[i].value:o[n].value}autoFillMerge(e,t,s,o){const i=this.getters.getActiveSheet();if(this.getters.isInMerge(i.id,s,o)&&!this.getters.isInMerge(i.id,e,t)){const e=this.getters.getMerge(i.id,s,o);e&&this.dispatch("REMOVE_MERGE",{sheetId:i.id,target:[e]})}const n=this.getters.getMerge(i.id,e,t);(null==n?void 0:n.topLeft.col)===e&&(null==n?void 0:n.topLeft.row)===t&&this.dispatch("ADD_MERGE",{sheetId:i.id,target:[{top:o,bottom:o+n.bottom-n.top,left:s,right:s+n.right-n.left}]})}drawGrid(e){if(!this.autofillZone)return;const{viewport:t,ctx:s,thinLineWidth:o}=e,[i,n,r,a]=this.getters.getRect(this.autofillZone,t);r>0&&a>0&&(s.strokeStyle="black",s.lineWidth=o,s.setLineDash([3]),s.strokeRect(i,n,r,a),s.setLineDash([]))}}Ih.layers=[6],Ih.getters=["getAutofillTooltip"],Ih.modes=["normal"];class xh extends yh{handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:s}=this.getters.getSelection();for(const o of t){const t=this.getAutomaticSums(e,o,s);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,s){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,s):this.sumData(e,t)}sumData(e,t){const s=this.dimensionsToSum(e,t),o=this.sumDimensions(e,t,s).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return s.has("ROW")&&s.has("COL")&&o.push(this.sumTotal(t)),o}sumAdjacentData(e,t,s){const[o,i]=to(s[0],s[1],t)?s:[t.left,t.top],n=this.findAdjacentData(e,o,i);return n?this.getters.isSingleCellOrMerge(e,t)||no(Qs(n,t))?[{position:[o,i],zone:n}]:this.sumDimensions(e,Qs(n,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,s){const o=this.getters.getSheet(e),i=this.findSuitableZoneToSum(o,...this.getters.getMainCell(e,t,s));if(i)return this.getters.expandZone(e,i)}findSuitableZoneToSum(e,t,s){const o=this.getters.getCell(e.id,t,s-1),i=this.getters.getCell(e.id,t-1,s);if(this.isNumber(i)&&!this.isNumber(o))return this.findHorizontalZone(e,t,s);const n=this.findVerticalZone(e,t,s);if(this.isZoneValid(n))return n;const r=this.findHorizontalZone(e,t,s);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,s){const o={top:0,bottom:s-1,left:t,right:t},i=this.reduceZoneStart(e,o,o.bottom);return{...o,top:i}}findHorizontalZone(e,t,s){const o={top:s,bottom:s,left:0,right:t-1},i=this.reduceZoneStart(e,o,o.right);return{...o,left:i}}reduceZoneStart(e,t,s){const o=this.getters.getCellsInZone(e.id,t),i=Es(s,-1,-1),n=i.filter((e=>{var t;return o[e]&&!(null===(t=o[e])||void 0===t?void 0:t.isAutoSummable)})),r=Math.max(...n),a=bs(i.filter((e=>this.isNumber(o[e]))))[0]||[];return Math.max(...a)<r?1/0:Math.min(...a)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){var t;return(null==e?void 0:e.evaluated.type)===$e.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(_))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){const s=new Set;return no(t)?(s.add(1===io(t).width?"COL":"ROW"),s):(this.lastColIsEmpty(e,t)&&s.add("ROW"),this.lastRowIsEmpty(e,t)&&s.add("COL"),0===s.size&&s.add("COL"),s)}sumDimensions(e,t,s){return[...s.has("COL")?this.sumColumns(t,e):[],...s.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:s}=e;return{position:[s,t],zone:{...e,top:t,right:s-1}}}sumColumns(e,t){const s=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,s.bottom-1)},ro(s).map((t=>({position:t,zone:{...e,right:t[0],left:t[0]}})))}sumRows(e,t){const s=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,s.right-1)},ro(s).map((t=>({position:t,zone:{...e,top:t[1],bottom:t[1]}})))}dispatchCellUpdates(e,t){for(const s of t){const[t,o]=s.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:`=SUM(${this.getters.zoneToXC(e,s.zone)})`})}}nextEmptyRow(e,t){let s=t.bottom+1;const{left:o,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:s,top:s,left:o,right:i});)s++;return{...t,top:s,bottom:s}}nextEmptyCol(e,t){let s=t.right+1;const{top:o,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:s,right:s,top:o,bottom:i});)s++;return{...t,left:s,right:s}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}xh.getters=["getAutomaticSums"],xh.modes=["normal","headless"];class Th extends yh{constructor(){super(...arguments),this.status="invisible",this._isPaintingFormat=!1}allowDispatch(e){switch(e.type){case"PASTE":return this.isPasteAllowed(this.state,e.target,!!e.force);case"INSERT_CELL":{const{cut:t,paste:s}=this.getInsertCellsTargets(e.zone,e.shiftDimension),o=this.getClipboardState(t,"CUT");return this.isPasteAllowed(o,s,!1)}case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),o=this.getClipboardState(t,"CUT");return this.isPasteAllowed(o,s,!1)}}return 0}handle(e){var t,s;switch(e.type){case"COPY":case"CUT":this.state=this.getClipboardState(e.target,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const o=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1;const i=this.state.cells.length,n=this.state.cells[0].length;this.paste(this.state,e.target,o),this.selectPastedZone(n,i,e.target),this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!js(t[0])){for(const[t,s]of ro(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:s,sheetId:this.getters.getActiveSheetId()});break}const o=this.getClipboardState(t,"CUT");this.paste(o,s);break}case"INSERT_CELL":{const{cut:t,paste:s}=this.getInsertCellsTargets(e.zone,e.shiftDimension),o=this.getClipboardState(t,"CUT");this.paste(o,s);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(t=this.state)||void 0===t?void 0:t.operation))return;this.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.state=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(s=this.state)||void 0===s?void 0:s.operation))return;for(let t of e.elements){if(this.isColRowDirtyingClipboard(t,e.dimension)){this.state=void 0;break}}this.status="invisible";break;case"PASTE_FROM_OS_CLIPBOARD":this.pasteFromClipboard(e.target,e.text);break;case"ACTIVATE_PAINT_FORMAT":this.state=this.getClipboardState(e.target,"COPY"),this._isPaintingFormat=!0,this.status="visible";break;default:Ve(e)&&(this.status="invisible")}}getClipboardContent(){return this.state&&this.state.cells.length&&this.state.cells.map((e=>e.map((e=>e.cell?this.getters.getCellText(e.cell,this.getters.shouldShowFormulas()):"")).join("\t"))).join("\n")||"\t"}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const s=this.getters.getActiveSheet();let o;return o="COL"===t?{...e,left:e.right+1,right:s.cols.length-1}:{...e,top:e.bottom+1,bottom:s.rows.length-1},{cut:[o],paste:[e]}}getInsertCellsTargets(e,t){const s=this.getters.getActiveSheet();let o,i;return"COL"===t?(o={...e,right:s.cols.length-1},i={...e,left:e.right+1,right:e.right+1}):(o={...e,bottom:s.rows.length-1},i={...e,top:e.bottom+1,bottom:s.rows.length-1}),{cut:[o],paste:[i]}}removeMergeIfTopLeft(e){const{sheetId:t,col:s,row:o}=e,[i,n]=this.getters.getMainCell(t,s,o);if(n===o&&i===s){const e=this.getters.getMerge(t,s,o);e&&this.dispatch("REMOVE_MERGE",{sheetId:t,target:[e]})}}pasteMergeIfExist(e,t){let{sheetId:s,col:o,row:i}=e;const[n,r]=this.getters.getMainCell(s,o,i);if(n===o&&r===i){const e=this.getters.getMerge(s,o,i);if(!e)return;({sheetId:s,col:o,row:i}=t),this.dispatch("ADD_MERGE",{sheetId:s,force:!0,target:[{left:o,top:i,right:o+e.right-e.left,bottom:i+e.bottom-e.top}]})}}getPasteZones(e,t){if(!t.length||!t[0].length)return e;const s=[],o=t.length,i=t[0].length,n=e[e.length-1],r=n.left,a=n.top,l=Math.max(1,Math.floor((n.right+1-r)/i)),c=Math.max(1,Math.floor((n.bottom+1-a)/o));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)s.push({left:r,top:a,right:r-1+e*i,bottom:a-1+t*o});return s}getClipboardState(e,t){const s=new Set(e.map((e=>e.left))),o=new Set(e.map((e=>e.right))),i=new Set(e.map((e=>e.top))),n=new Set(e.map((e=>e.bottom))),r=1===i.size&&1===n.size||1===s.size&&1===o.size?function(e){return e.reduce(((e,t)=>{const s=e.length;for(let o=0;o<s;o++)if(eo(e[o],t))return e[o]=Qs(e[o],t),e;return e[s]=t,e}),[])}(e):[e[e.length-1]],a=r.map((e=>ro(e))).flat(),l=[...new Set(a.map((e=>e[0])))].sort(((e,t)=>e-t)),c=[...new Set(a.map((e=>e[1])))].sort(((e,t)=>e-t)),h=[],d=[],u=this.getters.getActiveSheetId();for(let e of c){let t=[];for(let s of l){t.push({cell:this.getters.getCell(u,s,e),border:this.getters.getCellBorder(u,s,e)||void 0,position:{col:s,row:e,sheetId:u}});const o=this.getters.getMerge(u,s,e);o&&o.top===e&&o.left===s&&d.push(o)}h.push(t)}return{cells:h,operation:t,sheetId:u,zones:r,merges:d}}pasteFromClipboard(e,t){this.status="invisible";const s=t.replace(/\r/g,"").split("\n").map((e=>e.split("\t"))),{left:o,top:i}=e[0],n=Math.max.apply(Math,s.map((e=>e.length))),r=s.length,a=this.getters.getActiveSheet();this.addMissingDimensions(a,n,r,o,i);for(let e=0;e<s.length;e++)for(let t=0;t<s[e].length;t++)this.dispatch("UPDATE_CELL",{row:i+e,col:o+t,content:s[e][t],sheetId:a.id});const l={left:o,top:i,right:o+n-1,bottom:i+r-1};this.dispatch("SET_SELECTION",{anchor:[o,i],zones:[l],anchorZone:l})}isPasteAllowed(e,t,s){const o=this.getters.getActiveSheetId();if(!e)return 20;if(t.length>1&&(e.cells.length>1||e.cells[0].length>1))return 19;if(!s)for(let s of this.getPasteZones(t,e.cells))if(this.getters.doesIntersectMerge(o,s))return 2;return 0}paste(e,t,s){if("CUT"===e.operation&&this.clearClippedZones(e),t.length>1)for(const o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++)this.pasteZone(e,t,i,s);else{const o=e.cells.length,i=e.cells[0].length,n=t[0],r=Math.max(1,Math.floor((n.right+1-n.left)/i)),a=Math.max(1,Math.floor((n.bottom+1-n.top)/o));for(let t=0;t<r;t++)for(let r=0;r<a;r++)this.pasteZone(e,n.left+t*i,n.top+r*o,s)}"CUT"===e.operation&&(this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:e.merges}),this.state=void 0)}selectPastedZone(e,t,s){const o=s[0],i=o.left,n=o.top,r=Math.max(1,Math.floor((o.right+1-o.left)/e)),a=Math.max(1,Math.floor((o.bottom+1-o.top)/t));if(t>1||e>1){const s={left:i,top:n,right:i+r*e-1,bottom:n+a*t-1},[o,l]=this.getters.getSelection().anchor,c=ms(o,i,i+r*e-1),h=ms(l,n,n+a*t-1);this.dispatch("SET_SELECTION",{anchor:[c,h],zones:[s],anchorZone:s})}}clearClippedZones(e){for(const t of e.cells)for(const e of t)e.cell&&this.dispatch("CLEAR_CELL",e.position);this.dispatch("CLEAR_FORMATTING",{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,s,o){const i=e.cells.length,n=e.cells[0].length,r="onlyValue"!==o&&this.state&&this.state===e,a=this.getters.getActiveSheet();this.addMissingDimensions(a,n,i,t,s);for(let l=0;l<i;l++){const i=e.cells[l];for(let c=0;c<n;c++){const n=i[c],h={col:t+c,row:s+l,sheetId:a.id};this.removeMergeIfTopLeft(h),this.pasteMergeIfExist(n.position,h),this.pasteCell(n,h,e.operation,e.zones,o),r&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:n.position,target:h,operation:e.operation})}}}addMissingDimensions(e,t,s,o,i){const{cols:n,rows:r,id:a}=e,l=s+i-r.length;l>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:r.length-1,sheetId:a,quantity:l,position:"after"});const c=t+o-n.length;c>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:n.length-1,sheetId:a,quantity:c,position:"after"})}pasteCell(e,t,s,o,i){const{sheetId:n,col:r,row:a}=t,l=this.getters.getCell(n,r,a);if("onlyValue"!==i&&this.dispatch("SET_BORDER",{sheetId:n,col:r,row:a,border:e.border}),e.cell){if("onlyFormat"===i)return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.cell.format});if("onlyValue"===i){const s=jr(e.cell.evaluated.value);return void this.dispatch("UPDATE_CELL",{...t,content:s})}let l=e.cell.content;if(e.cell.isFormula()){const t=r-e.position.col,i=a-e.position.row;l=this.getUpdatedContent(n,e.cell,t,i,o,s)}this.dispatch("UPDATE_CELL",{...t,content:l,style:e.cell.style||null,format:e.cell.format})}else l&&("onlyValue"===i?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===i?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,s,o,i,n){if("CUT"===n){const n=[];for(const r of t.dependencies)this.isZoneOverlapClippedZone(i,r.zone)?n.push(...this.getters.createAdaptedRanges([r],s,o,e)):n.push(r);return this.getters.buildFormulaContent(e,t,n)}const r=this.getters.createAdaptedRanges(t.dependencies,s,o,e);return this.getters.buildFormulaContent(e,t,r)}isZoneOverlapClippedZone(e,t){return e.some((e=>eo(t,e)))}isColRowDirtyingClipboard(e,t){if(!this.state||!this.state.zones)return!1;for(let s of this.state.zones){if("COL"===t&&e<=s.right)return!0;if("ROW"===t&&e<=s.bottom)return!0}return!1}drawGrid(e){const{viewport:t,ctx:s,thinLineWidth:o}=e;if("visible"===this.status&&this.state&&this.state.zones&&this.state.zones.length&&this.state.sheetId===this.getters.getActiveSheetId()){s.setLineDash([8,5]),s.strokeStyle=p,s.lineWidth=3.3*o;for(const e of this.state.zones){const[o,i,n,r]=this.getters.getRect(e,t);n>0&&r>0&&s.strokeRect(o,i,n,r)}}}}Th.layers=[2],Th.getters=["getClipboardContent","isPaintingFormat"],Th.modes=["normal"];const Rh=[{name:a("Sum"),types:[$e.number],compute:e=>Ht.compute([e])},{name:a("Avg"),types:[$e.number],compute:e=>fo.compute([e])},{name:a("Min"),types:[$e.number],compute:e=>Oo.compute([e])},{name:a("Max"),types:[$e.number],compute:e=>Lo.compute([e])},{name:a("Count"),types:[$e.number,$e.text,$e.boolean,$e.error],compute:e=>wo.compute([e])},{name:a("Count Numbers"),types:[$e.number,$e.text,$e.boolean,$e.error],compute:e=>yo.compute([e])}];var Lh;!function(e){e[e.idle=0]="idle",e[e.selecting=1]="selecting",e[e.readyToExpand=2]="readyToExpand",e[e.expanding=3]="expanding"}(Lh||(Lh={}));class Mh extends yh{constructor(e,t,s,o){super(e,t,s,o),this.selection={zones:[{top:0,left:0,bottom:0,right:0}],anchor:[0,0],anchorZone:{top:0,left:0,bottom:0,right:0}},this.selectedFigureId=null,this.activeCol=0,this.activeRow=0,this.mode=Lh.idle,this.sheetsData={},this.activeSheet=null,this.moveClient=o.moveClient}allowDispatch(e){switch(e.type){case"SET_SELECTION":if(-1===e.zones.findIndex((t=>Js(t,e.anchorZone))))return 16;break;case"ALTER_SELECTION":if(e.delta){const{left:t,right:s,top:o,bottom:i}=this.getSelectedZone(),n=this.getters.getActiveSheet(),r=Zs(n,"cols",Es(t,s+1)),a=Zs(n,"rows",Es(o,i+1));if(0!==e.delta[0]&&void 0===a||0!==e.delta[1]&&void 0===r)return 17}break;case"MOVE_POSITION":{const{cols:t,rows:s}=this.getters.getActiveSheet();if(0!==e.deltaX&&s[this.activeRow].isHidden||0!==e.deltaY&&t[this.activeCol].isHidden)return 17;const{col:o,row:i}=this.getNextAvailablePosition(e.deltaX,e.deltaY);if(i<0||i>s.length-1||o<0||o>t.length-1)return 17;break}case"SELECT_COLUMN":{const{index:t}=e;if(t<0||t>=this.getters.getActiveSheet().cols.length)return 17;break}case"SELECT_ROW":{const{index:t}=e;if(t<0||t>=this.getters.getActiveSheet().rows.length)return 17;break}case"ACTIVATE_SHEET":try{this.getters.getSheet(e.sheetIdTo);break}catch(e){return 23}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return 0}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":case"CREATE_FIGURE":case"CREATE_CHART":case"UPDATE_FIGURE":case"EVALUATE_CELLS":case"DISABLE_SELECTION_INPUT":case"ENABLE_NEW_SELECTION_INPUT":case"RESIZE_VIEWPORT":break;case"DELETE_FIGURE":this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;default:this.selectedFigureId=null}switch(e.type){case"START":const t=zs(this.getters.getSheets()[0],0,0);this.activeCol=t[0],this.activeRow=t[1],this.dispatch("ACTIVATE_SHEET",{sheetIdTo:this.getters.getSheets()[0].id,sheetIdFrom:this.getters.getSheets()[0].id}),this.selectCell(...t);break;case"ACTIVATE_SHEET":this.setActiveSheet(e.sheetIdTo),this.sheetsData[e.sheetIdFrom]={selection:JSON.parse(JSON.stringify(this.selection)),activeCol:this.activeCol,activeRow:this.activeRow},e.sheetIdTo in this.sheetsData?Object.assign(this,this.sheetsData[e.sheetIdTo]):this.selectCell(...zs(this.getters.getSheet(e.sheetIdTo),0,0));break;case"SET_SELECTION":this.setSelection(e.anchor,e.zones,e.anchorZone,e.strict);break;case"START_SELECTION":this.mode=Lh.selecting;break;case"PREPARE_SELECTION_EXPANSION":this.mode=Lh.readyToExpand;break;case"START_SELECTION_EXPANSION":this.mode=Lh.expanding;break;case"STOP_SELECTION":this.mode=Lh.idle;break;case"MOVE_POSITION":this.movePosition(e.deltaX,e.deltaY);break;case"SELECT_CELL":this.selectCell(e.col,e.row);break;case"SELECT_COLUMN":this.selectColumn(e.index,e.createRange||!1,e.updateRange||!1);break;case"SELECT_ROW":this.selectRow(e.index,e.createRange||!1,e.updateRange||!1);break;case"SELECT_ALL":this.selectAll();break;case"ALTER_SELECTION":e.delta&&this.moveSelection(e.delta[0],e.delta[1]),e.cell&&this.addCellToSelection(...e.cell);break;case"UNDO":case"REDO":case"DELETE_SHEET":if(!this.getters.tryGetSheet(this.getActiveSheetId())){const e=this.getters.getVisibleSheets();this.activeSheet=this.getters.getSheet(e[0]),this.selectCell(0,0)}this.ensureSelectionValidity();break;case"REMOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&("COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e));break;case"ADD_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onAddElements(e);break;case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"UPDATE_CHART":case"SELECT_FIGURE":this.selectedFigureId=e.id;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left")}}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveCell(){const e=this.getters.getActiveSheetId(),[t,s]=this.getters.getMainCell(e,this.activeCol,this.activeRow);return this.getters.getCell(e,t,s)}getActiveCols(){const e=new Set;for(let t of this.selection.zones)if(0===t.top&&t.bottom===this.getters.getActiveSheet().rows.length-1)for(let s=t.left;s<=t.right;s++)e.add(s);return e}getActiveRows(){const e=new Set;for(let t of this.selection.zones)if(0===t.left&&t.right===this.getters.getActiveSheet().cols.length-1)for(let s=t.top;s<=t.bottom;s++)e.add(s);return e}getCurrentStyle(){const e=this.getters.getActiveCell();return e?this.getters.getCellStyle(e):{}}getSelectedZones(){return this.selection.zones}getSelectedZone(){return this.selection.anchorZone}getSelection(){return this.selection}getSelectedFigureId(){return this.selectedFigureId}getPosition(){return[this.activeCol,this.activeRow]}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getPosition();{const t=this.sheetsData[e];return t?[t.activeCol,t.activeRow]:zs(this.getters.getSheet(e),0,0)}}getStatisticFnResults(){const e=new Set(this.selection.zones.map((e=>this.getters.getCellsInZone(this.getters.getActiveSheetId(),e))).flat().filter((e=>void 0!==e)));let t=new Set,s=[];for(let o of e)t.add(o.evaluated.type),s.push(o.evaluated.value);let o={};for(let e of Rh){let i;e.types.some((e=>t.has(e)))&&(i=e.compute(s)),o[e.name]=i}return o}getSelectionMode(){return this.mode}isSelected(e){return!!this.getters.getSelectedZones().find((t=>Js(t,e)))}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],s=this.getters.getFigures(e),{offsetX:o,offsetY:i}=this.getters.getActiveSnappedViewport(),{width:n,height:r}=this.getters.getViewportDimensionWithHeaders();for(let e of s)e.x>=o+n||e.x+e.width<=o||e.y>=i+r||e.y+e.height<=i||t.push(e);return t}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let s=[];const o="COL"===e?"left":"top",i="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[i]-e[o]+1},((t,s)=>e[o]+s));s=s.concat(t)}return[...new Set(s)].sort()}selectColumn(e,t,s){const o=this.getters.getActiveSheet().rows.length-1;let i={left:e,right:e,top:0,bottom:o};const n=this.selection.zones;let r,a;const l=this.getters.getActiveSheet().rows.findIndex((e=>!e.isHidden));if(s){const[e,t]=this.selection.anchor;i=Qs(i,{left:e,right:e,top:l,bottom:o}),r=this.updateSelectionZones(i),a=[e,t]}else r=t?n.concat(i):[i],a=[e,l];this.dispatch("SET_SELECTION",{zones:r,anchor:a,strict:!0,anchorZone:i})}selectRow(e,t,s){const o=this.getters.getActiveSheet().cols.length-1;let i={top:e,bottom:e,left:0,right:o};const n=this.selection.zones;let r,a;const l=this.getters.getActiveSheet().cols.findIndex((e=>!e.isHidden));if(s){const[e,t]=this.selection.anchor;i=Qs(i,{left:l,right:o,top:t,bottom:t}),r=this.updateSelectionZones(i),a=[e,t]}else r=t?n.concat(i):[i],a=[l,e];this.dispatch("SET_SELECTION",{zones:r,anchor:a,strict:!0,anchorZone:i})}selectAll(){const e={left:0,top:0,bottom:this.getters.getActiveSheet().rows.length-1,right:this.getters.getActiveSheet().cols.length-1};this.dispatch("SET_SELECTION",{zones:[e],anchor:[0,0],anchorZone:e})}selectCell(e,t){const s=this.getters.getActiveSheet();this.moveClient({sheetId:s.id,col:e,row:t});const o=this.getters.expandZone(s.id,{left:e,right:e,top:t,bottom:t});let i;i=this.mode===Lh.expanding?lo([...this.selection.zones,o]):[o],this.selection=this.clipSelection(s.id,{anchor:[e,t],zones:i,anchorZone:o}),this.activeCol=this.selection.anchor[0],this.activeRow=this.selection.anchor[1]}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}getNextAvailablePosition(e,t){return{col:this.getNextAvailableCol(e,this.activeCol,this.activeRow),row:this.getNextAvailableRow(t,this.activeCol,this.activeRow)}}getNextAvailableCol(e,t,s){const{cols:o,id:i}=this.getActiveSheet(),n={col:t,row:s};return this.getNextAvailableHeader(e,o,t,n,(e=>this.getters.isInSameMerge(i,t,s,e,s)))}getNextAvailableRow(e,t,s){const{rows:o,id:i}=this.getActiveSheet(),n={col:t,row:s};return this.getNextAvailableHeader(e,o,s,n,(e=>this.getters.isInSameMerge(i,t,s,t,e)))}getNextAvailableHeader(e,t,s,o,i){var n,r,a;const l=this.getters.getActiveSheetId(),{col:c,row:h}=o;if(0===e)return s;let d=s+e;if(this.getters.isInMerge(l,c,h)){for(;i(d);)d+=e;for(;null===(n=t[d])||void 0===n?void 0:n.isHidden;)d+=e}else if(null===(r=t[d])||void 0===r?void 0:r.isHidden)for(;null===(a=t[d])||void 0===a?void 0:a.isHidden;)d+=e;return d<0||d>t.length-1?t[s].isHidden?this.getNextAvailableHeader(-e,t,s,o,i):s:d}movePosition(e,t){const{col:s,row:o}=this.getNextAvailablePosition(e,t);this.selectCell(s,o)}setSelection(e,t,s,o=!1){this.selectCell(...e);const i=this.getters.getActiveSheetId();let n;t=lo(t),n=o?{zones:t,anchorZone:s,anchor:e}:{anchor:e,zones:t.map((e=>this.getters.expandZone(i,e))),anchorZone:this.getters.expandZone(i,s)},this.selection=this.clipSelection(i,n)}getReferencePosition(){const e=this.getters.getActiveSheet(),t=this.selection,{left:s,right:o,top:i,bottom:n}=t.anchorZone,[r,a]=t.anchor;return{col:e.cols[r].isHidden&&Zs(e,"cols",Es(s,o+1))||r,row:e.rows[a].isHidden&&Zs(e,"rows",Es(i,n+1))||a}}moveSelection(e,t){const s=this.selection;let o=[];const[i,n]=s.anchor,{left:r,right:a,top:l,bottom:c}=s.anchorZone;let h=s.anchorZone;const d=this.getters.getActiveSheet(),u=e=>{const{left:t,right:s,top:o,bottom:i}=this.getters.expandZone(d.id,e);return{left:Math.max(0,t),right:Math.min(d.cols.length-1,s),top:Math.max(0,o),bottom:Math.min(d.rows.length-1,i)}},{col:p,row:g}=this.getReferencePosition();let f=0;for(;null!==h;){if(f++,e<0){const t=this.getNextAvailableCol(e,a-(f-1),g);h=p<=a-f?u({top:l,left:r,bottom:c,right:t}):null}if(e>0){const t=this.getNextAvailableCol(e,r+(f-1),g);h=r+f<=p?u({top:l,left:t,bottom:c,right:a}):null}if(t<0){const e=this.getNextAvailableRow(t,p,c-(f-1));h=g<=c-f?u({top:l,left:r,bottom:e,right:a}):null}if(t>0){const e=this.getNextAvailableRow(t,p,l+(f-1));h=l+f<=g?u({top:e,left:r,bottom:c,right:a}):null}if(h=h?co(h):h,h&&!Js(h,s.anchorZone))return o=this.updateSelectionZones(h),void this.dispatch("SET_SELECTION",{zones:o,anchor:[i,n],anchorZone:h})}h=u(Qs({top:n,bottom:n,left:i,right:i},co({top:this.getNextAvailableRow(t,p,l),left:this.getNextAvailableCol(e,r,g),bottom:this.getNextAvailableRow(t,p,c),right:this.getNextAvailableCol(e,a,g)}))),Js(h,s.anchorZone)||(o=this.updateSelectionZones(h),this.dispatch("SET_SELECTION",{zones:o,anchor:[i,n],anchorZone:h}))}addCellToSelection(e,t){const s=this.selection,[o,i]=s.anchor,n={left:Math.min(o,e),top:Math.min(i,t),right:Math.max(o,e),bottom:Math.max(i,t)},r=this.updateSelectionZones(n);this.dispatch("SET_SELECTION",{zones:r,anchor:[o,i],anchorZone:n})}ensureSelectionValidity(){const{anchor:e,zones:t,anchorZone:s}=this.clipSelection(this.getActiveSheetId(),this.selection);this.setSelection(e,t,s);const o=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of o)delete this.sheetsData[e];for(const e in this.sheetsData){const{anchor:t,zones:s,anchorZone:o}=this.clipSelection(e,this.sheetsData[e].selection);this.sheetsData[e]={selection:{anchor:t,zones:s,anchorZone:o},activeCol:t[0],activeRow:t[1]}}}clipSelection(e,t){const s=this.getters.getSheet(e),o=s.cols.length-1,i=s.rows.length-1,n=t.zones.map((e=>({left:ms(e.left,0,o),right:ms(e.right,0,o),top:ms(e.top,0,i),bottom:ms(e.bottom,0,i)})));return{anchor:[ms(t.anchor[0],0,o),ms(t.anchor[1],0,i)],zones:n,anchorZone:{left:ms(t.anchorZone.left,0,o),right:ms(t.anchorZone.right,0,o),top:ms(t.anchorZone.top,0,i),bottom:ms(t.anchorZone.bottom,0,i)}}}onColumnsRemoved(e){const t=Ks(this.getSelectedZone(),"left",e.elements);this.setSelection([t.left,t.top],[t],t,!0),this.ensureSelectionValidity()}onRowsRemoved(e){const t=Ks(this.getSelectedZone(),"top",e.elements);this.setSelection([t.left,t.top],[t],t,!0),this.ensureSelectionValidity()}onAddElements(e){const t=Ys(this.getSelectedZone(),"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.setSelection([t.left,t.top],[t],t,!0)}updateSelectionZones(e){let t=[...this.selection.zones];const s=this.selection.anchorZone,o=t.findIndex((e=>Js(e,s)));return o>=0&&(t[o]=e),t}activateNextSheet(e){const t=this.getters.getSheets().map((e=>e.id)),s=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[s]})}onMoveElements(e){const t=e.elements.length;this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:"before"});const s="COL"===e.dimension,o=e.elements[0],i=e.elements[t-1],n=e.base<o,r=n&&s?t:0,a=n&&!s?t:0,l=this.getters.getSheet(e.sheetId);this.dispatch("CUT",{target:[{left:s?o+r:0,right:s?i+r:l.cols.length-1,top:s?0:o+a,bottom:s?l.rows.length-1:i+a}]}),this.dispatch("PASTE",{target:[{left:s?e.base:0,right:s?e.base+t-1:l.cols.length-1,top:s?0:e.base,bottom:s?l.rows.length-1:e.base+t-1}]});const c=n?e.elements.map((e=>e+t)):e.elements;let h=e.base;for(const t of c){const s="COL"===e.dimension?this.getters.getCol(e.sheetId,t).size:this.getters.getRow(e.sheetId,t).size;this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:s,elements:[h]}),h+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:c})}isMoveElementAllowed(e){const t="COL"===e.dimension,s=e.elements[0],o=e.elements[e.elements.length-1],i=e.sheetId,n=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;return n(i,s-1,s)||n(i,o,o+1)||n(i,e.base-1,e.base)?2:0}drawGrid(e){if("inactive"!==this.getters.getEditionMode())return;const{viewport:t,ctx:s,thinLineWidth:o}=e,i=this.getSelectedZones();s.fillStyle="#f3f7fe";const n=1===i.length&&i[0].left===i[0].right&&i[0].top===i[0].bottom;s.fillStyle=n?"#f3f7fe":"#e9f0ff",s.strokeStyle=p,s.lineWidth=1.5*o,s.globalCompositeOperation="multiply";for(const e of i){const[o,i,n,r]=this.getters.getRect(e,t);s.fillRect(o,i,n,r),s.strokeRect(o,i,n,r)}s.globalCompositeOperation="source-over";const r=this.getters.getActiveSheetId(),[a,l]=this.getPosition();let c;s.strokeStyle=p,s.lineWidth=3*o,c=this.getters.isInMerge(r,a,l)?this.getters.getMerge(r,a,l):{top:l,bottom:l,left:a,right:a};const[h,d,u,g]=this.getters.getRect(c,t);u>0&&g>0&&s.strokeRect(h,d,u,g)}}Mh.layers=[5],Mh.modes=["normal"],Mh.getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getStatisticFnResults","getSelectedFigureId","getVisibleFigures","getSelection","getPosition","getSheetPosition","getSelectionMode","isSelected","getElementsFromSelection"];const Ah=a("The cell you are trying to edit has been deleted.");class _h extends yh{constructor(){super(...arguments),this.col=0,this.row=0,this.mode="inactive",this.sheet="",this.currentContent="",this.currentTokens=[],this.selectionStart=0,this.selectionEnd=0,this.selectionInitialStart=0,this.multiSelectionInitialStart=0,this.initialContent="",this.previousRef="",this.previousRange=void 0,this.colorIndexByRange={}}allowDispatch(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":return this.validateSelection(this.currentContent.length,e.start,e.end);case"SET_CURRENT_CONTENT":return e.selection?this.validateSelection(e.content.length,e.selection.start,e.selection.end):0;case"START_EDITION":if(e.selection){const t=this.getters.getActiveCell(),s=e.text||(null==t?void 0:t.composerContent)||"";return this.validateSelection(s.length,e.selection.start,e.selection.end)}return 0;default:return 0}}handle(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":this.selectionStart=e.start,this.selectionEnd=e.end;break;case"STOP_COMPOSER_RANGE_SELECTION":this.isSelectingForComposer()&&(this.mode="editing");break;case"START_EDITION":this.startEdition(e.text,e.selection);break;case"STOP_EDITION":e.cancel?(this.cancelEdition(),this.resetContent()):this.stopEdition();break;case"SET_CURRENT_CONTENT":this.setContent(e.content,e.selection,!0);break;case"REPLACE_COMPOSER_CURSOR_SELECTION":this.replaceSelection(e.text);break;case"SELECT_FIGURE":this.cancelEdition(),this.resetContent();break;case"SELECT_CELL":case"SET_SELECTION":case"MOVE_POSITION":switch(this.mode){case"editing":this.dispatch("STOP_EDITION");break;case"waitingForRangeSelection":this.insertSelectedRange();break;case"rangeSelected":switch(e.type){case"MOVE_POSITION":this.replaceAllSelectedRanges();break;case"SELECT_CELL":this.getters.getSelectionMode()===Lh.expanding?this.insertSelectedRange():this.replaceAllSelectedRanges();break;case"SET_SELECTION":e.strict?this.getters.getSelectionMode()===Lh.expanding?this.insertSelectedRange():this.replaceAllSelectedRanges():this.replaceSelectedRange()}}break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"START_CHANGE_HIGHLIGHT":this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((t=>{let s=t.value;const{xc:o,sheetName:i}=ss(s),n=i||this.getters.getSheetName(this.sheet),r=this.getters.getActiveSheetId();return Js(this.getters.expandZone(r,qs(o)),e.zone)&&this.getters.getSheetName(r)===n}));this.previousRef=t.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=t.start;break;case"CHANGE_HIGHLIGHT":const s=this.getZoneReference(e.zone,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(s),this.previousRef=s,this.selectionStart=this.currentContent.length,this.selectionEnd=this.currentContent.length;break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheet)||"inactive"===this.mode||(this.cancelEdition(),this.resetContent(),this.ui.notifyUI({type:"NOTIFICATION",text:Ah}))}}getEditionMode(){return this.mode}getCurrentContent(){if("inactive"===this.mode){const e=this.getters.getActiveCell();return(null==e?void 0:e.composerContent)||""}return this.currentContent}getEditionSheet(){return this.sheet}getComposerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}isSelectingForComposer(){return"waitingForRangeSelection"===this.mode||"rangeSelected"===this.mode||"resettingPosition"===this.mode}getCurrentTokens(){return this.currentTokens}getTokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find((s=>s.start<=e&&s.end>=t))}validateSelection(e,t,s){return t>=0&&t<=e&&s>=0&&s<=e?0:31}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"NOTIFICATION",text:Ah});const{top:t,left:s}=Ks({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",e.elements);this.col=s,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"NOTIFICATION",text:Ah});const{top:t,left:s}=Ks({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",e.elements);this.col=s,this.row=t}onAddElements(e){const{top:t,left:s}=Ys({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=s,this.row=t}startComposerRangeSelection(){this.mode="resettingPosition",this.sheet===this.getters.getActiveSheetId()&&this.dispatch("SELECT_CELL",{col:this.col,row:this.row}),this.mode="waitingForRangeSelection",this.multiSelectionInitialStart=this.selectionStart}startEdition(e,t){const s=this.getters.getActiveCell();this.initialContent=(null==s?void 0:s.composerContent)||"",this.mode="editing";const[o,i]=this.getters.getPosition();this.col=o,this.row=i,this.sheet=this.getters.getActiveSheetId(),this.setContent(e||this.initialContent,t),this.colorIndexByRange={}}stopEdition(){if("inactive"!==this.mode){this.cancelEdition();const e=this.getters.getActiveSheetId(),t=this.getters.getSheets().find((e=>e.id===this.sheet)).id,[s,o]=this.getters.getMainCell(t,this.col,this.row);let i=this.currentContent;if(!(this.initialContent!==i))return;if(i){const t=this.getters.getCell(e,s,o);if(i.startsWith("=")){const e=this.currentTokens.filter((e=>"LEFT_PAREN"===e.type)).length,t=this.currentTokens.filter((e=>"RIGHT_PAREN"===e.type)).length,s=e-t;s>0&&(i+=new Array(s).fill(")").join(""))}else(null==t?void 0:t.isLink())&&(i=Ts(i,t.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheet,col:s,row:o,content:i})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheet,content:"",col:s,row:o});e!==this.sheet&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheet}),this.setContent("")}}cancelEdition(){this.mode="inactive"}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,s){e=e.replace(/[\r\n]/g,"");const o=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(o||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?Wr(e):[],this.currentTokens.length>100&&s&&this.ui.notifyUI({type:"NOTIFICATION",text:a("This formula has over 100 parts. It can't be processed properly, consider splitting it into multiple cells")})),this.canStartComposerRangeSelection()&&this.startComposerRangeSelection()}insertSelectedRange(){const e=Math.min(this.selectionStart,this.selectionEnd),t=this.getZoneReference(this.getters.getSelectedZone());if("waitingForRangeSelection"===this.mode)return this.insertText(t,e),this.selectionInitialStart=e,void(this.mode="rangeSelected");this.insertText(","+t,e),this.selectionInitialStart=e+1}replaceSelectedRange(){const{end:e}=this.getters.getComposerSelection();this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:this.selectionInitialStart,end:e}),this.replaceSelection(this.getZoneReference(this.getters.getSelectedZone()))}replaceAllSelectedRanges(){const{end:e}=this.getters.getComposerSelection();this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:this.multiSelectionInitialStart,end:e}),this.replaceSelection(this.getZoneReference(this.getters.getSelectedZone())),this.selectionInitialStart=this.multiSelectionInitialStart}getZoneReference(e,t=[{colFixed:!1,rowFixed:!1}]){const s=this.getters.getActiveSheetId();let o=this.getters.zoneToXC(s,e,t);if(this.getters.getEditionSheet()!==this.getters.getActiveSheetId()){o=`${fs(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${o}`}return o}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),s=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,s)}replaceText(e,t,s){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(s,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const s=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),o=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:s,selection:{start:o,end:o}})}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=[],t={};for(let s of this.currentTokens.filter((e=>"REFERENCE"===e.type))){let o=s.value;const{xc:i,sheetName:n}=ss(o);if(ts.test(i)){const s=(n?`${n}!`:`${this.getters.getSheetName(this.getters.getEditionSheet())}!`)+i.replace(/\$/g,"");e.push(s);const o=this.colorIndexByRange[s];void 0!==o&&(t[s]=o)}}this.colorIndexByRange=t;let s=Object.values(t),o=0;return e.map((e=>{if(void 0===this.colorIndexByRange[e]){for(;s.includes(o);)o++;s.push(o),this.colorIndexByRange[e]=o}return[e,Xt[this.colorIndexByRange[e]%Xt.length]]}))}canStartComposerRangeSelection(){if("editing"!==this.mode&&this.selectionStart===this.selectionEnd)return!1;if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(e){const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let s=t,o=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(o.type);){if("SPACE"!==o.type||s<1)return!1;s--,o=this.currentTokens[s]}for(s=t+1,o=this.currentTokens[s];o&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(o.type);){if("SPACE"!==o.type)return!1;s++,o=this.currentTokens[s]}s++,o=this.currentTokens[s]}return!0}return!1}}_h.getters=["getEditionMode","isSelectingForComposer","getCurrentContent","getEditionSheet","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights"],_h.modes=["normal"];const Oh=hr.mapping;class Nh extends yh{constructor(e,t,s,o){super(e,t,s,o),this.isUpToDate=new Set,this.evalContext=o.evalContext,o.dataSources.on("data-loaded",this,(()=>{this.dispatch("EVALUATE_CELLS",{sheetId:this.getters.getActiveSheetId()})}))}handle(e){switch(De.has(e.type)&&this.isUpToDate.clear(),e.type){case"UPDATE_CELL":"content"in e&&this.isUpToDate.clear();break;case"ACTIVATE_SHEET":this.evaluate(e.sheetIdTo),this.isUpToDate.add(e.sheetIdTo);break;case"EVALUATE_CELLS":this.evaluate(e.sheetId),this.isUpToDate.add(e.sheetId);break;case"EVALUATE_ALL_SHEETS":this.evaluateAllSheets()}}finalize(){const e=this.getters.getActiveSheetId();this.isUpToDate.has(e)||(this.evaluate(e),this.isUpToDate.add(e))}evaluateFormula(e,t=this.getters.getActiveSheetId()){const s=Gr(e),o=this.getFormulaParameters((()=>{})),i=[];for(let e of s.dependencies)i.push(this.getters.getRangeFromSheetXC(t,e));return s.execute(i,t,...o)}getRangeFormattedValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getCellsInZone(t.id,e.zone).map((e=>(null==e?void 0:e.formattedValue)||""))}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getCellsInZone(t.id,e.zone).map((e=>null==e?void 0:e.evaluated.value))}evaluate(e){const t=this.getters.getCells(e),s=this.getFormulaParameters(i),o={};for(let s of Object.values(t))i(s,e);function i(e,t){if(!e.isFormula())return;const i=e.id;if(i in o)null===o[i]&&e.assignError("#CYCLE",a("Circular reference"));else{o[i]=null;try{if(s[2].__originCellXC=()=>{const e=s[2].getters.getCellPosition(i);return ns(e.col,e.row)},e.assignValue(e.compiledFormula.execute(e.dependencies,t,...s)),Array.isArray(e.evaluated.value))throw new Error(a("This formula depends on invalid values"))}catch(t){!function(e,t){if(e instanceof Error||(e=new Error(e)),"#CYCLE"!==t.evaluated.value){t.assignValue("#ERROR");const o=s[2].__lastFnCalled||"";t.assignError("#ERROR",e.message.replace("[[FUNCTION_NAME]]",o))}}(t,e)}o[i]=!0}}}getFormulaParameters(e){const t=Object.assign(Object.create(Oh),this.evalContext,{getters:this.getters}),s=this.getters;function o(t,s){if(e(t,s),t.evaluated.type===$e.error)throw new Error(a("This formula depends on invalid values"));return t.evaluated.value}function i(e){const i=e.sheetId;if(!js(e.zone))throw new Error(a("Invalid reference"));const n={top:0,bottom:s.getNumberRows(i)-1,left:0,right:s.getNumberCols(i)-1},r=[],l=function(e,t){if(eo(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)}}(e.zone,n);if(!l)return r.push([]),r;for(let s=l.left;s<=l.right;s++){const i=[];for(let n=l.top;n<=l.bottom;n++){const r=t.getters.getCell(e.sheetId,s,n);i.push(r?o(r,e.sheetId):void 0)}r.push(i)}return r}return[function(e,i,n,r,l,c){const h=i[e];if(r)return t.getters.getRangeString(h,n);if(!js(h.zone))throw new Error(a("Invalid reference"));if(h.zone.bottom!==h.zone.top||h.zone.left!==h.zone.right)throw new Error(c?a("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",l.toString(),c.toString()):a("Function %s expects its parameters to be single values or single cell references, not ranges.",l.toString()));if(h.invalidSheetName)throw new Error(a("Invalid sheet name: %s",h.invalidSheetName));return function(e){let t;if(!s.tryGetSheet(e.sheetId))throw new Error(a("Invalid sheet name"));return t=s.getCell(e.sheetId,e.zone.left,e.zone.top),!t||t.isEmpty()?null:o(t,e.sheetId)}(h)},function(e,t,s){return i(t[e])},t]}evaluateAllSheets(){for(const e of this.getters.getVisibleSheets())this.evaluate(e),this.isUpToDate.add(e)}}Nh.getters=["evaluateFormula","getRangeFormattedValues","getRangeValues"],Nh.modes=["normal"];const kh=["rgb(31,119,180)","rgb(255,127,14)","rgb(174,199,232)","rgb(255,187,120)","rgb(44,160,44)","rgb(152,223,138)","rgb(214,39,40)","rgb(255,152,150)","rgb(148,103,189)","rgb(197,176,213)","rgb(140,86,75)","rgb(196,156,148)","rgb(227,119,194)","rgb(247,182,210)","rgb(127,127,127)","rgb(199,199,199)","rgb(188,189,34)","rgb(219,219,141)","rgb(23,190,207)","rgb(158,218,229)"];class Fh{constructor(){this.graphColorIndex=0}next(){return kh[this.graphColorIndex++%kh.length]}}class $h extends yh{constructor(){super(...arguments),this.chartRuntime={},this.outOfDate=new Set}handle(e){if(De.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&"content"in e)for(let e of Object.keys(this.chartRuntime))this.outOfDate.add(e);switch(e.type){case"UPDATE_CHART":case"CREATE_CHART":const t=this.getters.getChartDefinition(e.id);this.chartRuntime[e.id]=this.mapDefinitionToRuntime(t);break;case"DELETE_FIGURE":delete this.chartRuntime[e.id];break;case"REFRESH_CHART":this.evaluateUsedSheets([e.id]),this.outOfDate.add(e.id);break;case"ACTIVATE_SHEET":const s=this.getters.getChartsIdBySheet(e.sheetIdTo);this.evaluateUsedSheets(s);break;case"DELETE_SHEET":for(let e of Object.keys(this.chartRuntime))this.getters.getChartDefinition(e)||delete this.chartRuntime[e]}}getChartRuntime(e){if(this.outOfDate.has(e)||!(e in this.chartRuntime)){const t=this.getters.getChartDefinition(e);if(void 0===t)return;this.chartRuntime[e]=this.mapDefinitionToRuntime(t),this.outOfDate.delete(e)}return this.chartRuntime[e]}truncateLabel(e){return e?e.length>20?e.substring(0,20)+"…":e:""}getDefaultConfiguration(e,t){const s={};e.labelRange||1!==e.dataSets.length?s.position=e.legendPosition:s.display=!1;const o={type:e.type,options:{legend:s,responsive:!0,maintainAspectRatio:!1,layout:{padding:{left:20,right:20,top:e.title?10:25,bottom:10}},elements:{line:{fill:!1},point:{hitRadius:15}},animation:{duration:0},hover:{animationDuration:10},responsiveAnimationDuration:0,title:{display:!!e.title,fontSize:22,fontStyle:"normal",text:e.title}},data:{labels:t.map(this.truncateLabel),datasets:[]}};return"pie"!==e.type?(o.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2}}],yAxes:[{position:e.verticalAxisPosition,ticks:{beginAtZero:!0}}]},"bar"===e.type&&e.stackedBar&&(o.options.scales.xAxes[0].stacked=!0,o.options.scales.yAxes[0].stacked=!0)):o.options.tooltips={callbacks:{title:function(e,t){return t.datasets[e[0].datasetIndex].label}}},o}getSheetIdsUsedInChart(e){const t=new Set;for(let s of e.dataSets)t.add(s.dataRange.sheetId);return e.labelRange&&t.add(e.labelRange.sheetId),t}evaluateUsedSheets(e){const t=new Set;for(let s of e){const e=this.getters.getChartDefinition(s);(void 0!==e?this.getSheetIdsUsedInChart(e):[]).forEach((e=>{e!==this.getters.getActiveSheetId()&&t.add(e)}))}for(let e of t)this.dispatch("EVALUATE_CELLS",{sheetId:e})}mapDefinitionToRuntime(e){let t=[];if(e.labelRange)e.labelRange.invalidXc||e.labelRange.invalidSheetName||(t=this.getters.getRangeFormattedValues(e.labelRange));else if(1===e.dataSets.length)for(let s=0;s<this.getData(e.dataSets[0],e.sheetId).length;s++)t.push("");else if(e.dataSets[0]){t=Es(0,this.getData(e.dataSets[0],e.sheetId).length).map((e=>e.toString()))}const s=this.getDefaultConfiguration(e,t),o=new Fh,i=[];if("pie"===e.type){const t=Math.max(...e.dataSets.map((t=>this.getData(t,e.sheetId).length)));for(let e=0;e<=t;e++)i.push(o.next())}for(const[t,n]of Object.entries(e.dataSets)){let r;if(n.labelCell){const e=n.labelCell,s=e?this.getters.getCell(e.sheetId,e.zone.left,e.zone.top):void 0;r=s&&e?this.truncateLabel(s.formattedValue):r=`${Cc.Series} ${parseInt(t)+1}`}else r=r=`${Cc.Series} ${parseInt(t)+1}`;const a="pie"!==e.type?o.next():"#FFFFFF",l={label:r,data:n.dataRange?this.getData(n,e.sheetId):[],lineTension:0,borderColor:a,backgroundColor:a};"pie"===e.type&&(l.backgroundColor=i),s.data.datasets.push(l)}return s}getData(e,t){if(e.dataRange){const t=e.labelCell?[Xs(e.labelCell.zone)]:[],s=so([Xs(e.dataRange.zone)],t)[0];if(void 0===s)return[];const o=this.getters.getRangeFromSheetXC(e.dataRange.sheetId,s);return this.getters.getRangeValues(o)}return[]}}$h.getters=["getChartRuntime"],$h.modes=["normal"];class Dh extends yh{constructor(){super(...arguments),this.isStale=!0,this.computedStyles={},this.computedIcons={},this.uuidGenerator=new Hs,this.rulePredicate={CellIsRule:(e,t)=>{if(e&&e.evaluated.type===$e.error)return!1;const s=t.values.map(Xr);switch(t.operator){case"IsEmpty":return!_s(e)||""===e.evaluated.value.toString().trim();case"IsNotEmpty":return _s(e)&&""!==e.evaluated.value.toString().trim();case"BeginsWith":return!(!e&&""===s[0])&&(_s(e)&&(null==e?void 0:e.evaluated.value.toString().startsWith(s[0].toString())));case"EndsWith":return!(!e&&""===s[0])&&(_s(e)&&e.evaluated.value.toString().endsWith(s[0].toString()));case"Between":return _s(e)&&e.evaluated.value>=s[0]&&e.evaluated.value<=s[1];case"NotBetween":return!(_s(e)&&e.evaluated.value>=s[0]&&e.evaluated.value<=s[1]);case"ContainsText":return _s(e)&&e.evaluated.value.toString().indexOf(s[0].toString())>-1;case"NotContains":return!_s(e)||!e.evaluated.value||-1==e.evaluated.value.toString().indexOf(s[0].toString());case"GreaterThan":return _s(e)&&e.evaluated.value>s[0];case"GreaterThanOrEqual":return _s(e)&&e.evaluated.value>=s[0];case"LessThan":return _s(e)&&e.evaluated.value<s[0];case"LessThanOrEqual":return _s(e)&&e.evaluated.value<=s[0];case"NotEqual":return!(!_s(e)&&""===s[0])&&(_s(e)&&e.evaluated.value!==s[0]);case"Equal":return!e&&""===s[0]||_s(e)&&e.evaluated.value===s[0];default:console.warn(a("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}}}handle(e){switch(e.type){case"ACTIVATE_SHEET":const t=e.sheetIdTo;this.computedStyles[t]=this.computedStyles[t]||{},this.computedIcons[t]=this.computedIcons[t]||{},this.isStale=!0;break;case"AUTOFILL_CELL":const s=this.getters.getActiveSheetId(),o=this.getters.getRulesByCell(s,e.originCol,e.originRow);for(const t of o)this.adaptRules(s,t,[ns(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.origin,e.target,e.operation);break;case"DUPLICATE_SHEET":case"CREATE_SHEET":case"DELETE_SHEET":case"ADD_CONDITIONAL_FORMAT":case"REMOVE_CONDITIONAL_FORMAT":case"REMOVE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"EVALUATE_CELLS":case"UPDATE_CELL":case"UNDO":case"REDO":case"DELETE_CELL":case"INSERT_CELL":this.isStale=!0}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getConditionalStyle(e,t){var s;const o=this.getters.getActiveSheetId(),i=this.computedStyles[o];return i&&(null===(s=i[e])||void 0===s?void 0:s[t])}getConditionalIcon(e,t){var s;const o=this.getters.getActiveSheetId(),i=this.computedIcons[o];return i&&(null===(s=i[e])||void 0===s?void 0:s[t])}computeStyles(){var e;const t=this.getters.getActiveSheetId();this.computedStyles[t]={},this.computedIcons[t]={};const s=this.computedStyles[t];for(let o of this.getters.getConditionalFormats(t))try{switch(o.rule.type){case"ColorScaleRule":for(let e of o.ranges)this.applyColorScale(e,o.rule);break;case"IconSetRule":for(let e of o.ranges)this.applyIcon(e,o.rule);break;default:for(let i of o.ranges){const n=qs(i);for(let i=n.top;i<=n.bottom;i++)for(let r=n.left;r<=n.right;r++){const n=this.rulePredicate[o.rule.type];let a=this.getters.getCell(t,r,i);n&&n(a,o.rule)&&(s[r]||(s[r]=[]),s[r][i]=Object.assign((null===(e=s[r])||void 0===e?void 0:e[i])||{},o.rule.style))}}}}catch(e){}}parsePoint(e,t,s){switch(t.type){case"value":return this.getters.evaluateFormula(`=${s}(${e})`);case"number":return Number(t.value);case"percentage":const o=this.getters.evaluateFormula(`=min(${e})`);return o+(this.getters.evaluateFormula(`=max(${e})`)-o)*Number(t.value)/100;case"percentile":return this.getters.evaluateFormula(`=PERCENTILE(${e},${Number(t.value)/100})`);case"formula":const i=t.value&&this.getters.evaluateFormula(t.value);return i instanceof Promise?null:i;default:return null}}applyIcon(e,t){const s=this.parsePoint(e,t.lowerInflectionPoint),o=this.parsePoint(e,t.upperInflectionPoint);if(null===s||null===o||s>o)return;const i=qs(e),n=this.getters.getActiveSheetId(),r=this.computedIcons[n],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=i.top;e<=i.bottom;e++)for(let l=i.left;l<=i.right;l++){const i=this.getters.getCell(n,l,e);if((null==i?void 0:i.evaluated.type)!==$e.number)continue;const c=this.computeIcon(i.evaluated.value,o,t.upperInflectionPoint.operator,s,t.lowerInflectionPoint.operator,a);r[l]||(r[l]=[]),r[l][e]=c}}computeIcon(e,t,s,o,i,n){return"ge"===s&&e>=t||"gt"===s&&e>t?n[0]:"ge"===i&&e>=o||"gt"===i&&e>o?n[1]:n[2]}applyColorScale(e,t){var s;const o=this.parsePoint(e,t.minimum,"min"),i=t.midpoint?this.parsePoint(e,t.midpoint):null,n=this.parsePoint(e,t.maximum,"max");if(null===o||null===n||o>=n||i&&(o>=i||i>=n))return;const r=qs(e),a=this.getters.getActiveSheetId(),l=this.computedStyles[a],c=[];t.midpoint&&i?(c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,i,t.minimum.color,t.midpoint.color)}),c.push({minValue:i,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(i,n,t.midpoint.color,t.maximum.color)})):c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,n,t.minimum.color,t.maximum.color)});for(let e=r.top;e<=r.bottom;e++)for(let t=r.left;t<=r.right;t++){const r=this.getters.getCell(a,t,e);if((null==r?void 0:r.evaluated.type)===$e.number){const a=ms(r.evaluated.value,o,n);let h;h=2===c.length&&i?a<=i?this.colorCell(a,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(a,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(a,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),l[t]||(l[t]=[]),l[t][e]=(null===(s=l[t])||void 0===s?void 0:s[e])||{},l[t][e].fillColor="#"+Yt(h)}}}computeColorDiffUnits(e,t,s,o){const i=t-e;return[((s>>16)%256-(o>>16)%256)/i,((s>>8)%256-(o>>8)%256)/i,(s%256-o%256)/i]}colorCell(e,t,s,o){const[i,n,r]=o;return Math.round((s>>16)%256-i*(e-t))<<16|Math.round((s>>8)%256-n*(e-t))<<8|Math.round(s%256-r*(e-t))}adaptRules(e,t,s,o){if(0===s.length&&0===o.length)return;const i=this.getters.getConditionalFormats(e),n=i.findIndex((e=>e.id===t.id));let r=[];n>-1&&(r=i[n].ranges),r=r.concat(s);const a=so(r,o);0!==a.length?this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:t.id,rule:t.rule,stopIfTrue:t.stopIfTrue},target:a.map(qs),sheetId:e}):this.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:t.id,sheetId:e})}pasteCf(e,t,s){const o=ns(t.col,t.row);for(let i of this.getters.getConditionalFormats(e.sheetId))for(let n of i.ranges)if(to(e.col,e.row,qs(n))){const n=i,r=[];if("CUT"===s&&r.push(ns(e.col,e.row)),e.sheetId===t.sheetId)this.adaptRules(e.sheetId,n,[o],r);else{this.adaptRules(e.sheetId,n,[],r);const s=this.getCFToCopyTo(t.sheetId,n);this.adaptRules(t.sheetId,s,[o],[])}}}getCFToCopyTo(e,t){const s=this.getters.getConditionalFormats(e).find((e=>e.stopIfTrue===t.stopIfTrue&&Fs(e.rule,t.rule)));return s||{...t,id:this.uuidGenerator.uuidv4(),ranges:[]}}}Dh.getters=["getConditionalStyle","getConditionalIcon"],Dh.modes=["normal"];var Ph;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(Ph||(Ph={}));class Uh extends yh{constructor(){super(...arguments),this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1},this.replaceOptions={modifyFormulas:!1},this.toSearch=""}handle(e){switch(e.type){case"UPDATE_SEARCH":this.updateSearch(e.toSearch,e.searchOptions);break;case"CLEAR_SEARCH":case"UNDO":case"REDO":case"REMOVE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":this.clearSearch();break;case"SELECT_SEARCH_PREVIOUS_MATCH":this.selectNextCell(Ph.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(Ph.next);break;case"REPLACE_SEARCH":this.replace(e.replaceWith,e.replaceOptions);break;case"REPLACE_ALL_SEARCH":this.replaceAll(e.replaceWith,e.replaceOptions);break;case"ACTIVATE_SHEET":case"REFRESH_SEARCH":this.refreshSearch()}}getSearchMatches(){return this.searchMatches}getCurrentSelectedMatchIndex(){return this.selectedMatchIndex}updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null),this.toSearch=e,this.updateRegex(),this.refreshSearch()}refreshSearch(){const e=this.findMatches();this.searchMatches=e,this.selectNextCell(Ph.current)}updateRegex(){let e=ps(this.toSearch);const t=this.searchOptions.matchCase?"":"i";this.searchOptions.exactMatch&&(e=`^${e}$`),this.currentSearchRegex=RegExp(e,t)}findMatches(){const e=this.getters.getActiveSheetId(),t=this.getters.getCells(e),s=[];if(this.toSearch)for(const e of Object.values(t))if(e&&this.currentSearchRegex&&this.currentSearchRegex.test(this.searchOptions.searchFormulas&&e.isFormula()?e.content:String(e.evaluated.value))){const t=this.getters.getCellPosition(e.id),o={col:t.col,row:t.row,selected:!1};s.push(o)}return s.sort(this.sortByRowThenColumn)}sortByRowThenColumn(e,t){return e.row===t.row?e.col-t.col:e.row>t.row?1:-1}selectNextCell(e){const t=this.searchMatches;if(!t.length)return void(this.selectedMatchIndex=null);let s;s=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,s=(s%t.length+t.length)%t.length,null!==this.selectedMatchIndex&&this.selectedMatchIndex===s||(this.selectedMatchIndex=s,this.dispatch("SELECT_CELL",{col:t[s].col,row:t[s].row}));for(let e=0;e<this.searchMatches.length;e++)this.searchMatches[e].selected=e===this.selectedMatchIndex}clearSearch(){this.toSearch="",this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1},this.replaceOptions={modifyFormulas:!1}}replace(e,t){if(this.replaceOptions=t,null===this.selectedMatchIndex||!this.currentSearchRegex)return;const s=this.searchMatches[this.selectedMatchIndex],o=this.getters.getActiveSheetId(),i=this.getters.getCell(o,s.col,s.row),n=this.toReplace(i,o);if(i&&n){const t=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),o=n.toString().replace(t,e);this.dispatch("UPDATE_CELL",{sheetId:this.getters.getActiveSheetId(),col:s.col,row:s.row,content:o}),this.searchMatches.splice(this.selectedMatchIndex,1),this.selectNextCell(Ph.current)}else this.selectNextCell(Ph.next)}replaceAll(e,t){const s=this.searchMatches.length;for(let o=0;o<s;o++)this.replace(e,t)}toReplace(e,t){if(e){if(this.searchOptions.searchFormulas&&e.isFormula())return e.content;if(this.replaceOptions.modifyFormulas||!e.isFormula())return e.evaluated.value.toString()}return null}drawGrid(e){const{ctx:t,viewport:s}=e,o=this.getters.getActiveSheetId();for(const e of this.searchMatches){const i=this.getters.getMerge(o,e.col,e.row),n=i?i.left:e.col,r=i?i.right:e.col,a=i?i.top:e.row,l=i?i.bottom:e.row,[c,h,d,u]=this.getters.getRect({top:a,left:n,right:r,bottom:l},s);d>0&&u>0&&(t.fillStyle="#8B008B33",t.fillRect(c,h,d,u),e.selected&&(t.strokeStyle="#8B008B",t.strokeRect(c,h,d,u)))}}}Uh.layers=[3],Uh.getters=["getSearchMatches","getCurrentSelectedMatchIndex"];class Vh extends yh{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,s){const o=this.searchNumberFormat(e,t);if(void 0!==o){const i=this.changeDecimalFormat(o,s);this.dispatch("SET_FORMATTING",{sheetId:e,target:t,format:i})}}searchNumberFormat(e,t){var s;for(let o of t)for(let t=o.top;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++){const o=this.getters.getCell(e,i,t);if((null==o?void 0:o.evaluated.type)===$e.number&&!(null===(s=o.format)||void 0===s?void 0:s.match(_)))return o.format||this.setDefaultNumberFormat(o.evaluated.value)}}setDefaultNumberFormat(e){const t=e.toString().split(".");return 1===t.length?"0":"0."+Array(t[1].length+1).join("0")}changeDecimalFormat(e,t){const s=Math.sign(t),o=e.split(";");let i=[];for(let e of o){const t=e.indexOf("."),o=e.toUpperCase().indexOf("E");let n;const r=o>-1?e.slice(0,o):e,a=t>-1?r.slice(t).match(/0/g).length:0,l=r.lastIndexOf("0");l>-1?s>0?n=a<ae?e.slice(0,l+1)+(0===a?".0":"0")+e.slice(l+1):e:a>0?(n=e.slice(0,l)+e.slice(l+1),1===a&&(n=n.slice(0,t)+n.slice(t+1))):n=e:n=e,i.push(n)}return i.join(";")}}Vh.modes=["normal"];class Bh extends yh{getHighlights(){return this.prepareHighlights(this.getters.getComposerHighlights().concat(this.getters.getSelectionInputHighlights()))}prepareHighlights(e){if(0===e.length)return[];const t=this.getters.getActiveSheetId(),s=[];for(let[o,i]of e){const{xc:e,sheetName:n}=ss(o),r=n?this.getters.getSheetIdByName(n):t;if(r){let o=qs(e);const{height:n,width:a}=io(o);o=n*a==1?this.getters.expandZone(t,qs(e)):o,s.push({zone:o,color:i,sheet:r})}}return s.filter((e=>e.zone.top>=0&&e.zone.left>=0&&e.zone.bottom<this.getters.getSheet(e.sheet).rows.length&&e.zone.right<this.getters.getSheet(e.sheet).cols.length))}drawGrid(e){const{ctx:t,viewport:s,thinLineWidth:o}=e,i=this.getters.getActiveSheetId(),n=3*o;t.lineWidth=n;for(let e of this.getHighlights().filter(((e,t)=>this.getHighlights().findIndex((t=>Js(t.zone,e.zone)&&t.sheet===i))===t))){const[o,i,r,a]=this.getters.getRect(e.zone,s);r>0&&a>0&&(t.strokeStyle=e.color,t.strokeRect(o+n/2,i+n/2,r-n,a-n),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(o+n,i+n,r-2*n,a-2*n))}}}function Hh(e,t){let s=0,o=e.length-1;for(;s<=o;){const i=Math.floor((s+o)/2),n=e[i];if(t<n.start)o=i-1;else if(t>n.end)s=i+1;else{if(!n.isHidden)return i;s+=1}}return-1}Bh.modes=["normal"],Bh.layers=[1],Bh.getters=["getHighlights"];class zh extends yh{constructor(){super(...arguments),this.boxes=[]}getColIndex(e,t,s){if(e<v)return-1;const o=(s||this.getters.getActiveSheet()).cols;return Hh(o,e-v+o[t].start+1)}getRowIndex(e,t,s){if(e<m)return-1;const o=(s||this.getters.getActiveSheet()).rows;return Hh(o,e-m+o[t].start+1)}getRect(e,t){const{left:s,top:o,right:i,bottom:n}=e,{offsetX:r,offsetY:a}=this.getShiftedViewport(t),{cols:l,rows:c}=this.getters.getActiveSheet(),h=Math.max(l[s].start-r,v),d=l[i].end-r-h,u=Math.max(c[o].start-a,m);return[h,u,d,c[n].end-a-u]}isVisibleInViewport(e,t,s){const{right:o,left:i,top:n,bottom:r}=s;return t<=r&&t>=n&&e>=i&&e<=o}getEdgeScrollCol(e){let t=!1,s=0,o=0;const{width:i}=this.getters.getViewportDimensionWithHeaders(),{width:n}=this.getters.getMaxViewportSize(this.getters.getActiveSheet()),{left:r,offsetX:a}=this.getters.getActiveSnappedViewport();return e<v&&r>0?(t=!0,s=-1,o=cs(v-e)):e>i&&a<n-i&&(t=!0,s=1,o=cs(e-i)),{canEdgeScroll:t,direction:s,delay:o}}getEdgeScrollRow(e){let t=!1,s=0,o=0;const{height:i}=this.getters.getViewportDimensionWithHeaders(),{height:n}=this.getters.getMaxViewportSize(this.getters.getActiveSheet()),{top:r,offsetY:a}=this.getters.getActiveSnappedViewport();return e<m&&r>0?(t=!0,s=-1,o=cs(m-e)):e>i&&a<n-i&&(t=!0,s=1,o=cs(e-i)),{canEdgeScroll:t,direction:s,delay:o}}drawGrid(e,t){switch(t){case 0:this.boxes=this.getGridBoxes(e),this.drawBackground(e),this.drawCellBackground(e),this.drawBorders(e),this.drawTexts(e),this.drawIcon(e);break;case 7:this.drawHeaders(e)}}drawBackground(e){const{ctx:t,thinLineWidth:s,viewport:o}=e,{width:i,height:n}=this.getters.getViewportDimensionWithHeaders(),{cols:r,rows:a,id:l}=this.getters.getActiveSheet();t.fillStyle="white",t.fillRect(0,0,i,n);const{right:c,left:h,top:d,bottom:u,offsetX:p,offsetY:g}=this.getShiftedViewport(o);if(!this.getters.getGridLinesVisibility(l))return;t.lineWidth=2*s,t.strokeStyle="#E2E3E3",t.beginPath();const f=Math.min(n,a[u].end-g);for(let e=h;e<=c;e++){if(r[e].isHidden)continue;const s=r[e].end-p;t.moveTo(s,0),t.lineTo(s,f)}const m=Math.min(i,r[c].end-p);for(let e=d;e<=u;e++){if(a[e].isHidden)continue;const s=a[e].end-g;t.moveTo(0,s),t.lineTo(m,s)}t.stroke()}drawCellBackground(e){const{ctx:t,thinLineWidth:s}=e;t.lineWidth=.3*s;const o=.1*s;t.strokeStyle="#111";const i=this.getters.getGridLinesVisibility(this.getters.getActiveSheetId());for(let e of this.boxes){let s=e.style;(s.fillColor&&"#ffffff"!==s.fillColor||e.isMerge)&&(t.fillStyle=s.fillColor||"#ffffff",t.fillRect(e.x,e.y,e.width,e.height),i&&t.strokeRect(e.x+o,e.y+o,e.width-2*o,e.height-2*o)),e.error&&(t.fillStyle="red",t.beginPath(),t.moveTo(e.x+e.width-5,e.y),t.lineTo(e.x+e.width,e.y),t.lineTo(e.x+e.width,e.y+5),t.fill())}}drawBorders(e){const{ctx:t,thinLineWidth:s}=e;for(let e of this.boxes){let t=e.border;if(t){const{x:s,y:i,width:n,height:r}=e;t.left&&o(t.left,s,i,s,i+r),t.top&&o(t.top,s,i,s+n,i),t.right&&o(t.right,s+n,i,s+n,i+r),t.bottom&&o(t.bottom,s,i+r,s+n,i+r)}}function o([e,o],i,n,r,a){t.strokeStyle=o,t.lineWidth=("thin"===e?2:3)*s,t.beginPath(),t.moveTo(i,n),t.lineTo(r,a),t.stroke()}}drawTexts(e){const{ctx:t,thinLineWidth:s}=e;let o;t.textBaseline="middle";for(let e of this.boxes)if(e.content){const i=e.style||{},n=e.content.align||"left",r=i.italic?"italic ":"",a=i.bold?"bold":T,l=i.fontSize||R,c=ds[l],h=`${r}${a} ${c}px ${L}`;let d;h!==o&&(o=h,t.font=h),t.fillStyle=i.textColor||"#000";let u=e.y+e.height/2+1;d="left"===n?e.x+(e.image?e.image.size+2*w:4):"right"===n?e.x+e.width-4:e.x+e.width/2,t.textAlign=n,e.clipRect&&(t.save(),t.beginPath(),t.rect(...e.clipRect),t.clip()),t.fillText(e.content.text,Math.round(d),Math.round(u)),(i.strikethrough||i.underline)&&("right"===n?d-=e.content.width:"center"===n&&(d-=e.content.width/2),i.strikethrough&&t.fillRect(d,u,e.content.width,2.6*s),i.underline&&(u=e.y+e.height/2+1+c/2,t.fillRect(d,u,e.content.width,1.3*s))),e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const s=e.image.image,o=e.image.size,i=(e.height-o)/2;e.image.clipIcon&&(t.save(),t.beginPath(),t.rect(...e.image.clipIcon),t.clip()),t.drawImage(s,e.x+w,e.y+i,o,o),e.image.clipIcon&&t.restore()}}drawHeaders(e){const{ctx:t,thinLineWidth:s,viewport:o}=e,{right:i,left:n,top:r,bottom:a,offsetX:l,offsetY:p}=this.getShiftedViewport(o),{width:g,height:f}=this.getters.getViewportDimensionWithHeaders(),E=this.getters.getSelectedZones(),{cols:b,rows:S}=this.getters.getActiveSheet(),C=this.getters.getActiveCols(),y=this.getters.getActiveRows();t.fillStyle=c,t.font=`400 11px ${L}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=s,t.strokeStyle="#333",t.fillRect(0,0,g,m),t.fillRect(0,0,v,f),t.fillStyle=h;for(let e of E){const s=Math.max(v,b[e.left].start-l),o=Math.max(v,b[e.right].end-l),i=Math.max(m,S[e.top].start-p),n=Math.max(m,S[e.bottom].end-p);t.fillStyle=C.has(e.left)?d:h,t.fillRect(s,0,o-s,m),t.fillStyle=y.has(e.top)?d:h,t.fillRect(0,i,v,n-i)}t.beginPath(),t.moveTo(v,0),t.lineTo(v,f),t.moveTo(0,m),t.lineTo(g,m),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(let e=n;e<=i;e++){const s=b[e];s.isHidden||(t.fillStyle=C.has(e)?"#fff":u,t.fillText(s.name,(s.start+s.end)/2-l,13),t.moveTo(s.end-l,0),t.lineTo(s.end-l,m))}for(let e=r;e<=a;e++){const s=S[e];s.isHidden||(t.fillStyle=y.has(e)?"#fff":u,t.fillText(s.name,24,(s.start+s.end)/2-p),t.moveTo(0,s.end-p),t.lineTo(v,s.end-p))}t.stroke()}hasContent(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.getCell(s,e,t);return o&&!o.isEmpty()||this.getters.isInMerge(s,e,t)}getShiftedViewport(e){return{...e,offsetX:e.offsetX-v,offsetY:e.offsetY-m}}findNextEmptyCol(e,t,s){let o=e;for(;o<t&&!this.hasContent(o+1,s);)o++;return o}findPreviousEmptyCol(e,t,s){let o=e;for(;o>t&&!this.hasContent(o-1,s);)o--;return o}computeCellAlignment(e,t){if(e.isFormula()&&this.getters.shouldShowFormulas())return"left";const{align:s}=this.getters.getCellStyle(e);return t&&e.evaluated.type===$e.number?"center"!==s?"left":s:s||e.defaultAlign}createBoxFromPosition(e,t,s,o,i,n){const{right:r,left:a,offsetX:l,offsetY:c}=this.getShiftedViewport(o),h=this.getters.getCol(e,t),d=this.getters.getRow(e,s),u=this.getters.getCell(e,t,s),p=this.getters.shouldShowFormulas(),g={x:h.start-l,y:d.start-c,width:i,height:n,border:this.getters.getCellBorder(e,t,s)||void 0,style:{...this.getters.getCellStyle(u),...this.getters.getConditionalStyle(t,s)}};if(!u)return g;const f=this.getters.getConditionalIcon(t,s),m=g.style.fontSize||R,v=ds[m],E=f?2*w+v:0;f&&(g.image={type:"icon",size:v,clipIcon:[g.x,g.y,Math.min(E,i),n],image:Yl[f].img});const b=this.getters.getCellText(u,p),S=this.getters.getTextWidth(u),C=E+S,y=this.computeCellAlignment(u,C>i);g.content={text:b,width:S,align:y},u.evaluated.type===$e.error&&(g.error=u.evaluated.error);const I=C>i||ds[m]>n;if(f)g.clipRect=[g.x+E,g.y,Math.max(0,i-E),n];else if(I){let o,u;switch(this.getters.isInMerge(e,t,s)?(o=this.getters.getMerge(e,t,s).right,u=t):(o=this.findNextEmptyCol(t,r,s),u=this.findPreviousEmptyCol(t,a,s)),y){case"left":{const t=this.getters.getCol(e,o).end-h.start;(t<S||v>d.size)&&(g.clipRect=[h.start-l,d.start-c,t,n]);break}case"right":{const t=this.getters.getCol(e,u),s=h.end+i-h.size-t.start;(s<S||v>d.size)&&(g.clipRect=[t.start-l,d.start-c,s,n]);break}case"center":{const s=this.getters.getCol(e,u),i=this.getters.getCol(e,o).end-s.start;(i<S||u===t||o===t||v>d.size)&&(g.clipRect=[s.start-l,d.start-c,i,n]);break}}}return g}getGridBoxes(e){const t=[],{viewport:s}=e,{right:o,left:i,top:n,bottom:r}=this.getShiftedViewport(s),a=this.getters.getActiveSheetId();for(let e=n;e<=r;e++){const n=this.getters.getRow(a,e);if(!n.isHidden)for(let r=i;r<=o;r++){const o=this.getters.getCol(a,r);o.isHidden||(this.getters.isInMerge(a,r,e)||t.push(this.createBoxFromPosition(a,r,e,s,o.size,n.size)))}}for(const e of this.getters.getMerges(a))if(!this.getters.isMergeHidden(a,e)&&eo(e,s)){const o=this.getters.getCol(a,e.right).end-this.getters.getCol(a,e.left).start,i=this.getters.getRow(a,e.bottom).end-this.getters.getRow(a,e.top).start,n=this.createBoxFromPosition(a,e.left,e.top,s,o,i),r=this.getters.getCellBorder(a,e.right,e.bottom);n.border={...n.border,bottom:r?r.bottom:void 0,right:r?r.right:void 0},n.isMerge=!0,t.push(n)}return t}}zh.layers=[0,7],zh.getters=["getColIndex","getRowIndex","getRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow"],zh.modes=["normal"];const Zh=new Hs;class Gh extends yh{constructor(){super(...arguments),this.inputs={},this.activeSheets={},this.inputHasSingleRange={},this.focusedInputId=null,this.focusedRange=null,this.willAddNewRange=!1}allowDispatch(e){switch(e.type){case"FOCUS_RANGE":const t=this.getIndex(e.id,e.rangeId);if(this.focusedInputId===e.id&&this.focusedRange===t)return 24;break;case"ADD_EMPTY_RANGE":if(this.inputHasSingleRange[e.id]&&1===this.inputs[e.id].length)return 25}return 0}handle(e){switch(e.type){case"ENABLE_NEW_SELECTION_INPUT":this.initInput(e.id,e.initialRanges||[],e.hasSingleRange);break;case"DISABLE_SELECTION_INPUT":this.focusedInputId===e.id&&this.unfocus(),delete this.inputs[e.id],delete this.activeSheets[e.id],delete this.inputHasSingleRange[e.id];break;case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"FOCUS_RANGE":this.focus(e.id,this.getIndex(e.id,e.rangeId));break;case"CHANGE_RANGE":{const t=this.getIndex(e.id,e.rangeId);if(null!==t){const s=e.id;this.focusedInputId===s&&this.focusedRange===t||this.dispatch("FOCUS_RANGE",{id:s,rangeId:this.inputs[s][t].id});const o=e.value.split(",").map((e=>e.trim()));this.setRange(s,t,o)}break}case"ADD_EMPTY_RANGE":this.insertNewRange(e.id,this.inputs[e.id].length,[""]),this.focusLast(e.id);break;case"REMOVE_RANGE":const t=this.getIndex(e.id,e.rangeId);null!==t&&this.removeRange(e.id,t);break;case"SELECT_CELL":case"SET_SELECTION":if(!this.focusedInputId)break;const s=this.getSelectionInputValue(this.focusedInputId),o=(this.inputHasSingleRange[this.focusedInputId]?[this.getters.getSelectedZone()]:this.getters.getSelectedZones()).map(Xs).filter((e=>!s.includes(e))),i=this.activeSheets[this.focusedInputId],n=this.getters.getActiveSheetId(),r=this.getters.getSheetName(n);this.add(o.map((e=>n===i?e:`${fs(r)}!${e}`)));break;case"PREPARE_SELECTION_EXPANSION":{const[e,t]=[this.focusedInputId,this.focusedRange];null===e||null===t||this.inputHasSingleRange[e]||(this.willAddNewRange=""!==this.inputs[e][t].xc.trim());break}}}getSelectionInput(e){return this.inputs[e]?this.inputs[e].map(((t,s)=>Object.assign({},t,{color:this.focusedInputId===e&&null!==this.focusedRange&&this.isRangeValid(t.xc)?t.color:null,isFocused:this.focusedInputId===e&&this.focusedRange===s}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:s}=ss(e);return null!==t.match(ts)&&(!s||void 0!==this.getters.getSheetIdByName(s))}getSelectionInputValue(e){return this.cleanInputs(this.inputs[e].map((e=>e.xc?e.xc:"")))}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].map((e=>this.inputToHighlights(this.focusedInputId,e))).flat():[]}initInput(e,t,s=!1){this.inputs[e]=[],this.insertNewRange(e,0,t),this.activeSheets[e]=this.getters.getActiveSheetId(),this.inputHasSingleRange[e]=s,0===this.inputs[e].length&&this.dispatch("ADD_EMPTY_RANGE",{id:e})}focus(e,t){this.focusedInputId=e,this.focusedRange=t}focusLast(e){this.focus(e,this.inputs[e].length-1)}unfocus(){this.focusedInputId=null,this.focusedRange=null}add(e){if(null===this.focusedInputId||null===this.focusedRange||this.getters.isSelectingForComposer()||0===e.length)return;if(this.getters.getSelectionMode()===Lh.expanding&&this.willAddNewRange){const t=this.focusedInputId;this.insertNewRange(t,this.inputs[t].length,e),this.focusLast(this.focusedInputId),this.willAddNewRange=!1}else this.setRange(this.focusedInputId,this.focusedRange,e)}setContent(e,t,s){this.inputs[e][t]={...this.inputs[e][t],id:Zh.uuidv4(),xc:s}}insertNewRange(e,t,s){this.inputs[e].splice(t,0,...s.map(((t,s)=>({xc:t,id:(this.inputs[e].length+s+1).toString(),color:Qt()}))))}setRange(e,t,s){const[,...o]=s;this.setContent(e,t,s[0]),this.insertNewRange(e,t+1,o),o.length&&this.focus(e,t+o.length)}removeRange(e,t){this.inputs[e].splice(t,1),this.focusedInputId===e&&null!==this.focusedRange&&this.focusLast(e)}inputToHighlights(e,{xc:t,color:s}){const o=this.cleanInputs([t]).filter((e=>this.isRangeValid(e))).filter((t=>this.shouldBeHighlighted(this.activeSheets[e],t)));if(0===o.length)return[];const[i,...n]=o,r=[[i,s||Qt()]];for(const e of n)r.push([e,Qt()]);return r}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:s}=ss(t),o=this.getters.getSheetIdByName(s),i=this.getters.getActiveSheet().id;return this.isRangeValid(t)&&(o===i||void 0===o&&i===e)}getIndex(e,t){const s=this.inputs[e].findIndex((e=>e.id===t));return s>=0?s:null}}Gh.modes=["normal"],Gh.layers=[1],Gh.getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];class Wh{constructor(){this.bus=new o.core.EventBus}on(e,t,s){this.bus.on(e,t,s)}trigger(e,t){this.bus.trigger(e,t)}off(e,t){this.bus.off(e,t)}clear(){this.bus.clear()}}function qh(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?function(e,t,s){const o="left"===t?"right":"bottom";let i=e[t],n=e[o];for(let r of s.sort(((e,t)=>t-e)))e[t]>r&&(i--,n--),e[t]<=r&&e[o]>=r&&n--;if(!(i>n))return{...e,[t]:i,[o]:n}}(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?function(e,t,s,o,i){const n="left"===t?"columns":"rows",r="before"===o?s-1:s,a="left"===t?"right":"bottom",l="before"===o?e[a]>r:e[a]>=r;return e[t]<=r&&l?ao(e,n,"RESIZE",i):r<e[t]?ao(e,n,"MOVE",i):{...e}}(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}function jh(e,t){const s=e.definition;let o,i;return s.labelRange&&(o=qh(qs(s.labelRange),t)),s.dataSets&&(i=s.dataSets.map(qs).map((e=>qh(e,t))).filter(_s).map(Xs)),{...e,definition:{...s,dataSets:i,labelRange:o?Xs(o):void 0}}}yl.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],jh),yl.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],jh),yl.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),yl.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){var s;if(e.name===t.name)return{...e,name:(null===(s=e.name)||void 0===s?void 0:s.match(/\d+/))?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),yl.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const s=[];for(const o of e.target)for(const e of t.target)eo(o,e)||s.push({...o});if(s.length)return{...e,target:s};return}));const Xh=[{match:function(e){return"sheetId"in e},fn:function(e,t){const s="DELETE_SHEET"===t.type&&t.sheetId;if(e.sheetId===s)return"IGNORE_COMMAND";if("CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId)return e;return"SKIP_TRANSFORMATION"}},{match:function(e){return"target"in e},fn:function(e,t){const s=[];for(const o of e.target){const e=qh(o,t);e&&s.push(e)}if(!s.length)return"IGNORE_COMMAND";return{...e,target:s}}},{match:function(e){return"col"in e&&"row"in e},fn:function(e,t){if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const s="COL"===t.dimension?"col":"row";let o=e[s];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(o))return"IGNORE_COMMAND";for(let t of e)o>=t&&o--}"ADD_COLUMNS_ROWS"===t.type&&(o>t.base||o===t.base&&"before"===t.position)&&(o+=t.quantity);return{...e,[s]:o}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const s of t.target){if(!(e.col===s.left&&e.row===s.top)&&to(e.col,e.row,s))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e},fn:function(e,t){if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const s="ADD_COLUMNS_ROWS"===e.type,o=s?"base":"elements";let i=s?[e[o]]:e[o];if("REMOVE_COLUMNS_ROWS"===t.type&&(i=i.map((e=>{if(t.elements.includes(e))return;const s=t.elements.sort(((e,t)=>t-e));for(let t of s)e>t&&e--;return e})).filter(_s)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;i=i.map((s=>s>e?s+t.quantity:s))}if(i.length){let t=i;return s&&(t=i[0]),{...e,[o]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}}];function Yh(e,t){const s=yl.getTransformation(e.type,t.type);return s?s(e,t):function(e,t){for(const{match:s,fn:o}of Xh)if(s(e)){const s=o(e,t);if("SKIP_TRANSFORMATION"===s)continue;if("IGNORE_COMMAND"===s)return;return s}return e}(e,t)}function Kh(e,t){let s=[...e];for(const e of t)s=s.map((t=>Yh(t,e))).filter(_s);return s}class Qh{constructor(e,t,s,o){this._commands=[],this._changes=[],this.id=e,this.clientId=t,this._commands=[...s],this._changes=o?[...o]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class Jh extends Error{}class ed extends Wh{constructor(e,t,s=N){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=s,this.clients={},this.clientId="local",this.pendingMessages=[],this.waitingAck=!1,this.waitingUndoRedoAck=!1,this.isReplayingInitialRevisions=!1,this.processedRevisions=new Set,this.uuidGenerator=new Hs,this.debouncedMove=o.utils.debounce(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t){if(!e.length||!t.length||!this.canApplyOptimisticUpdate())return;const s=new Qh(this.uuidGenerator.uuidv4(),this.clientId,e,t);this.revisions.append(s.id,s),this.trigger("new-local-state-update",{id:s.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:s.id,clientId:s.clientId,commands:s.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))}loadInitialMessages(e){this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1}leave(){delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}snapshot(e){const t=this.uuidGenerator.uuidv4();this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){const e=this.clients[this.clientId];if(!e)throw new Jh("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(_s))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}_move(e){var t;if(!this.clients[this.clientId])return;const s=null===(t=this.clients[this.clientId])||void 0===t?void 0:t.position;if((null==s?void 0:s.col)===e.col&&s.row===e.row&&s.sheetId===e.sheetId)return;const o=s?"CLIENT_MOVED":"CLIENT_JOINED",i=this.getClient();this.clients[this.clientId]={...i,position:e},this.transportService.sendMessage({type:o,version:1,client:{...i,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:s}=e,o=new Qh(e.nextRevisionId,t,s);if(o.clientId!==this.clientId){this.revisions.insert(o.id,o,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:Kh(s,t)})}break;case"SNAPSHOT_CREATED":{const t=new Qh(e.nextRevisionId,"server",[]);this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger("snapshot");break}}this.acknowledge(e),this.trigger("collaborative-event-received")}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;const t=this.clients[this.clientId];if(t){const{position:e}=t;e&&this.transportService.sendMessage({type:"CLIENT_MOVED",version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),this.waitingAck||(this.waitingAck=!0,this.sendPendingMessage())}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if("REMOTE_REVISION"===e.type){const t=this.revisions.get(e.nextRevisionId);if(0===t.commands.length){this.revisions.drop(t.id);const e=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.nextRevisionId));return this.trigger("pending-revisions-dropped",{revisionIds:e}),this.waitingAck=!1,this.waitingUndoRedoAck=!1,void(this.pendingMessages=[])}e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw new Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.\n ${JSON.stringify(e)}`);this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(this.waitingUndoRedoAck=!1),e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":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.sendPendingMessage()}}isAlreadyProcessed(e){switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter((({type:e})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const td=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];class sd extends yh{constructor(){super(...arguments),this.availableColors=new Set(td),this.colors={}}isPositionValid(e){const t=this.getters.getSheet(e.sheetId);return e.row<t.rows.length&&e.col<t.cols.length}chooseNewColor(){0===this.availableColors.size&&(this.availableColors=new Set(td));const e=(t=[...this.availableColors.values()])[Math.floor(Math.random()*t.length)];var t;return this.availableColors.delete(e),e}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof Jh)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const s of this.getters.getConnectedClients())if(s.id!==this.getters.getClient().id&&s.position&&s.position.sheetId===e&&this.isPositionValid(s.position)){const e=s.position;this.colors[s.id]||(this.colors[s.id]=this.chooseNewColor());const o=this.colors[s.id];t.push({...s,position:e,color:o})}return t}drawGrid(e){const{viewport:t,ctx:s,thinLineWidth:o}=e,i=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:n,col:r}=e.position,a=this.getters.expandZone(i,{top:n,bottom:n,left:r,right:r}),[l,c,h,d]=this.getters.getRect(a,t);if(h<=0||d<=0)continue;const u=e.color,p=`${u}10`;s.fillStyle=p,s.lineWidth=4*o,s.strokeStyle=u,s.globalCompositeOperation="multiply",s.fillRect(l,c,h,d),s.globalCompositeOperation="source-over",s.strokeRect(l,c,h,d),s.font=`bold ${R+1}px ${L}`}}}sd.getters=["getClientsToDisplay"],sd.layers=[5],sd.modes=["normal"];class od extends yh{allowDispatch(e){if("SORT_CELLS"===e.type){if(!to(e.col,e.row,e.zone))throw new Error(a("The anchor must be part of the provided zone"));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return 0}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection)}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;for(let s=t.top;s<=t.bottom;s++)for(let o=t.left;o<=t.right;o++)if(!this.getters.isInMerge(e,o,s))return 48;return 0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const s=this.getters.getMerges(e).filter((e=>eo(e,t))),o=io(s[0]);let[i,n]=[o.width,o.height];return s.every((e=>{let[t,s]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&s===n}))?0:48}expand(e,t){const{left:s,right:o,top:i,bottom:n}=this.getters.expandZone(e.id,t);return{left:Math.max(0,s),right:Math.min(e.cols.length-1,o),top:Math.max(0,i),bottom:Math.min(e.rows.length-1,n)}}checkExpandedValues(e,t){const s=this.expand(e,t),o=e.id;let i,n=[];if(this.getters.doesIntersectMerge(o,s)){const{left:e,right:t,top:r,bottom:a}=s;for(let s=e;s<=t;s++)for(let e=r;e<=a;e++){const[t,r]=this.getters.getMainCell(o,s,e);i=this.getters.getCell(o,t,r),n.push((null==i?void 0:i.formattedValue)||"")}}else n=this.getters.getCellsInZone(o,s).map((e=>(null==e?void 0:e.formattedValue)||""));return n.some((e=>""!==e))}getContiguousZone(e,t){let s,{top:o,bottom:i,left:n,right:r}=t;const a=this.getters.getSheet(e);let l=!1;for(;!l;)l=!0,o>0&&(s=this.checkExpandedValues(a,{left:n-1,right:r+1,top:o-1,bottom:o-1}),s&&(l=!1,o--)),n>0&&(s=this.checkExpandedValues(a,{left:n-1,right:n-1,top:o-1,bottom:i+1}),s&&(l=!1,n--)),r<a.cols.length-1&&(s=this.checkExpandedValues(a,{left:r+1,right:r+1,top:o-1,bottom:i+1}),s&&(l=!1,r++)),i<a.rows.length-1&&(s=this.checkExpandedValues(a,{left:n-1,right:r+1,top:i+1,bottom:i+1}),s&&(l=!1,i++));return{left:n,right:r,top:o,bottom:i}}hasHeader(e){if(1===e[0].length)return!1;let t=e.map((e=>e.map((e=>(null==e?void 0:e.evaluated.type)||$e.empty))));return t[0][0]===$e.empty&&(t=t.slice(1)),!t.some((e=>e[0]===$e.empty))&&!!t.some((e=>e[1]!==$e.empty&&e[0]!==e[1]))}sortZone(e,t,s,o){const[i,n]=this.mainCellsSteps(e,s);let r=this.getters.getMainCell(e,t.col,t.row)[0],a=Object.assign({},s),l=this.mainCells(e,s);this.hasHeader(l)&&(a.top+=n),l=this.mainCells(e,a);const c=function(e,t){const s=e.map(Pa),o=s.filter((e=>e.type===$e.empty)),i=s.filter((e=>e.type!==$e.empty)),n="descending"===t?-1:1;return i.sort(((e,t)=>{let s=Da.indexOf(e.type)-Da.indexOf(t.type);return 0===s&&(s=e.type===$e.text||e.type===$e.error?e.value.localeCompare(t.value):e.value-t.value),n*s})).concat(o)}(l[r-a.left],o),h=c.map((e=>e.index)),[d,u]=[l.length,l[0].length];for(let t=0;t<d;t++)for(let s=0;s<u;s++){let o=l[t][h[s]],r=a.left+t*i,c=a.top+s*n,d={sheetId:e,col:r,row:c,content:"",value:""};if(o){let t=o.content;if(o.isFormula()){const s=c-this.getters.getCellPosition(o.id).row,i=this.getters.createAdaptedRanges(o.dependencies,0,s,e);t=this.getters.buildFormulaContent(e,o,i)}d.style=o.style,d.content=t,d.format=o.format,d.value=o.evaluated.value}this.dispatch("UPDATE_CELL",d)}}mainCellsSteps(e,t){const s=this.getters.getMerge(e,t.left,t.top);return[s?s.right-s.left+1:1,s?s.bottom-s.top+1:1]}mainCells(e,t){const[s,o]=this.mainCellsSteps(e,t),i=[],n=Es(t.left,t.right+1,s),r=Es(t.top,t.bottom+1,o);for(const t of n){const s=[];i.push(s);for(const o of r)s.push(this.getters.getCell(e,t,o))}return i}}od.getters=["getContiguousZone"];class id extends yh{constructor(){super(...arguments),this.showFormulas=!1}handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}id.modes=["normal"],id.getters=["shouldShowFormulas"];class nd extends yh{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}allowDispatch(e){switch(e.type){case"AUTORESIZE_ROWS":case"AUTORESIZE_COLUMNS":try{this.getters.getSheet(e.sheetId);break}catch(e){return 23}}return 0}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){const s=this.getColMaxWidth(e.sheetId,t);0!==s&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:s+6,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":for(let t of e.rows){const s=this.getRowMaxHeight(e.sheetId,t);0!==s&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"ROW",size:s+6,sheetId:e.sheetId})}}}getCellWidth(e){let t=this.getTextWidth(e);const s=this.getters.getCellPosition(e.id);return this.getters.getConditionalIcon(s.col,s.row)&&(t+=function(e,t){const s=t.fontSize||R;return ds[s]+2*w}(this.ctx,this.getters.getCellStyle(e))),t}getTextWidth(e){const t=this.getters.getCellText(e,this.getters.shouldShowFormulas());return vs(this.ctx,t,this.getters.getCellStyle(e))}getCellHeight(e){const t=this.getters.getCellStyle(e).fontSize||R;return ds[t]}getCellText(e,t=!1){return t&&(e.isFormula()||e.evaluated.type===$e.error)?e.content:e.formattedValue}getColMaxWidth(e,t){const s=this.getters.getColCells(e,t).map((e=>this.getCellWidth(e)));return Math.max(0,...s)}getRowMaxHeight(e,t){const s=this.getters.getSheet(e),o=Object.values(s.rows[t].cells).filter(_s).map((e=>this.getters.getCellById(e))).map((e=>this.getCellHeight(e)));return Math.max(0,...o)}}nd.getters=["getCellWidth","getCellHeight","getTextWidth","getCellText"];class rd extends yh{constructor(){super(...arguments),this.viewports={},this.snappedViewports={},this.updateSnap=!1,this.viewportWidth=1e3,this.viewportHeight=1e3}allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.checkOffsetValidity(e.offsetX,e.offsetY);case"RESIZE_VIEWPORT":return e.width<0||e.height<0?54:0;default:return 0}}handle(e){switch(e.type){case"UNDO":case"REDO":this.cleanViewports(),this.resetViewports();break;case"RESIZE_VIEWPORT":this.cleanViewports(),this.resizeViewport(e.height,e.width);break;case"SET_VIEWPORT_OFFSET":this.setViewportOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const t=this.getActiveTopRow(),s=this.clipOffsetY(t.start+this.viewportHeight);this.shiftVertically(s);break;case"SHIFT_VIEWPORT_UP":{const e=this.getActiveTopRow(),t=this.clipOffsetY(e.end-this.viewportHeight);this.shiftVertically(t);break}case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":"COL"===e.dimension?this.adjustViewportOffsetX(e.sheetId,this.getViewport(e.sheetId)):this.adjustViewportOffsetY(e.sheetId,this.getViewport(e.sheetId));break;case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":"COL"===e.dimension?this.adjustViewportZoneX(e.sheetId,this.getViewport(e.sheetId)):this.adjustViewportZoneY(e.sheetId,this.getViewport(e.sheetId));break;case"ACTIVATE_SHEET":this.refreshViewport(e.sheetIdTo);break;case"SELECT_CELL":case"MOVE_POSITION":this.refreshViewport(this.getters.getActiveSheetId())}}finalize(){this.updateSnap&&(this.snapViewportToCell(this.getters.getActiveSheetId()),this.updateSnap=!1)}getViewportDimensionWithHeaders(){return{width:this.viewportWidth+v,height:this.viewportHeight+m}}getActiveViewport(){const e=this.getters.getActiveSheetId();return this.getViewport(e)}getActiveSnappedViewport(){const e=this.getters.getActiveSheetId();return this.getSnappedViewport(e)}getMaxViewportSize(e){const t=Gs(e,"cols"),s=Gs(e,"rows"),o=e.cols.find((e=>e.end>t.end-this.viewportWidth))||e.cols[e.cols.length-1],i=e.rows.find((e=>e.end>s.end-this.viewportHeight))||e.rows[e.rows.length-1];return{width:t.end+Math.max(b,Math.min(o.size,this.viewportWidth-t.size)),height:s.end+Math.max(S+5,Math.min(i.size,this.viewportHeight-s.size))}}getMaximumViewportOffset(e){const{width:t,height:s}=this.getters.getMaxViewportSize(e);return{maxOffsetX:Math.max(0,t-this.viewportWidth+1),maxOffsetY:Math.max(0,s-this.viewportHeight+1)}}checkOffsetValidity(e,t){const s=this.getters.getActiveSheet(),{maxOffsetX:o,maxOffsetY:i}=this.getMaximumViewportOffset(s);return e<0||t<0||t>i||e>o?53:0}getSnappedViewport(e){return this.snapViewportToCell(e),this.snappedViewports[e]}getViewport(e){return this.viewports[e]?this.viewports[e]:this.generateViewportState(e)}cleanViewports(){const e=this.getters.getVisibleSheets();for(let t of Object.keys(this.viewports))e.includes(t)||delete this.viewports[t]}resetViewports(){for(let[e,t]of Object.entries(this.viewports))this.adjustViewportOffsetX(e,t),this.adjustViewportOffsetY(e,t),this.adjustViewportsPosition(e)}adjustViewportOffsetX(e,t){const{offsetX:s}=t,{width:o}=this.getMaxViewportSize(this.getters.getSheet(e));if(this.viewportWidth+s>o){const e=this.viewportWidth+s-o;t.offsetX=Math.max(0,s-e)}this.adjustViewportZoneX(e,t)}adjustViewportOffsetY(e,t){const{offsetY:s}=t,{height:o}=this.getMaxViewportSize(this.getters.getSheet(e));if(this.viewportHeight+s>o){const e=this.viewportHeight+s-o;t.offsetY=Math.max(0,s-e)}this.adjustViewportZoneY(e,t)}resizeViewport(e,t){this.viewportHeight=e,this.viewportWidth=t,this.recomputeViewports()}recomputeViewports(){for(let e of Object.keys(this.viewports))this.adjustViewportOffsetX(e,this.viewports[e]),this.adjustViewportOffsetY(e,this.viewports[e])}setViewportOffset(e,t){const s=this.getters.getActiveSheetId();this.getActiveViewport(),this.viewports[s].offsetX=e,this.viewports[s].offsetY=t,this.adjustViewportZone(s,this.viewports[s])}clipOffsetY(e){const{height:t}=this.getters.getMaxViewportSize(this.getters.getActiveSheet()),s=t-this.viewportHeight;return e=Math.min(e,s),e=Math.max(e,0)}generateViewportState(e){return this.viewports[e]={left:0,right:0,top:0,bottom:0,offsetX:0,offsetY:0},this.viewports[e]}refreshViewport(e){const t=this.getViewport(e);this.adjustViewportZone(e,t),this.adjustViewportsPosition(e)}adjustViewportZone(e,t){this.adjustViewportZoneX(e,t),this.adjustViewportZoneY(e,t)}adjustViewportZoneX(e,t){const s=this.getters.getSheet(e),o=s.cols;t.left=this.getters.getColIndex(t.offsetX+v,0,s);const i=this.viewportWidth+t.offsetX;t.right=o.length-1;for(let e=t.left;e<o.length;e++)if(i<o[e].end){t.right=e;break}this.updateSnap=!0}adjustViewportZoneY(e,t){const s=this.getters.getSheet(e),o=s.rows;t.top=this.getters.getRowIndex(t.offsetY+m,0,s);const i=this.viewportHeight+t.offsetY;t.bottom=o.length-1;for(let e=t.top;e<o.length;e++)if(i<o[e].end){t.bottom=e;break}this.updateSnap=!0}adjustViewportsPosition(e,t){const s=this.getters.getSheet(e),{cols:o,rows:i}=s,n=this.getSnappedViewport(e);t=t||this.getters.getSheetPosition(e);const[r,a]=zs(s,...this.getters.getMainCell(e,t[0],t[1]));for(;o[r].end>n.offsetX+this.viewportWidth&&n.offsetX<o[r].start;)n.offsetX=o[n.left].end,this.adjustViewportZoneX(e,n);for(;r<n.left;){const t=o.slice(0,n.left).reverse().findIndex((e=>!e.isHidden));n.offsetX=o[n.left-1-t].start,this.adjustViewportZoneX(e,n)}for(;i[a].end>n.offsetY+this.viewportHeight&&n.offsetY<i[a].start;)n.offsetY=i[n.top].end,this.adjustViewportZoneY(e,n);for(;a<n.top;){const t=i.slice(0,n.top).reverse().findIndex((e=>!e.isHidden));n.offsetY=i[n.top-1-t].start,this.adjustViewportZoneY(e,n)}const{top:l,left:c}=this.viewports[e];l===n.top&&c===n.left||(this.viewports[e]=n),this.updateSnap=!1}snapViewportToCell(e){const{cols:t,rows:s}=this.getters.getSheet(e),o=this.getViewport(e),i=Object.assign({},o);this.adjustViewportOffsetX(e,i),this.adjustViewportOffsetY(e,i),i.offsetX=t[i.left].start,i.offsetY=s[i.top].start,this.adjustViewportZone(e,i),this.snappedViewports[e]=i}shiftVertically(e){const{top:t,offsetX:s}=this.getActiveSnappedViewport();this.setViewportOffset(s,e);const{anchor:o}=this.getters.getSelection(),i=this.getActiveSnappedViewport().top-t;this.dispatch("SELECT_CELL",{col:o[0],row:o[1]+i})}getActiveTopRow(){const{top:e}=this.getActiveSnappedViewport(),t=this.getters.getActiveSheet();return this.getters.getRow(t.id,e)}}rd.getters=["getActiveViewport","getActiveSnappedViewport","getViewportDimensionWithHeaders","getMaxViewportSize","getMaximumViewportOffset"],rd.modes=["normal"];const ad=(new Ae).add("sheet",La).add("cell",Sa).add("merge",xa).add("borders",Ea).add("conditional formatting",wa).add("figures",Ia).add("chart",Ca),ld=(new Ae).add("selection",Mh).add("ui_sheet",nd).add("ui_options",id).add("evaluation",Nh).add("evaluation_cf",Dh).add("evaluation_chart",$h).add("clipboard",Th).add("edition",_h).add("highlight",Bh).add("selectionInput",Gh).add("viewport",rd).add("grid renderer",zh).add("autofill",Ih).add("find_and_replace",Uh).add("sort",od).add("automatic_sum",xh).add("format",Vh).add("selection_multiuser",sd);class cd{constructor(){this.listeners=[]}sendMessage(e){for(const{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter((t=>t.id!==e))}}class hd extends o.core.EventBus{constructor(){super(...arguments),this.registry=new Ae}add(e,t){this.registry.add(e,t);const s=o.utils.debounce((()=>this.trigger("data-loaded",{id:e})),0);return t.on("data-loaded",this,(()=>s())),t.loadMetadata(),this}get(e){return this.registry.get(e)}getAll(){return this.registry.getAll()}remove(e){this.get(e).off("data-loaded",this),this.registry.remove(e)}async waitForReady(){const e=[];for(const t of this.getAll())e.push(t.get());return Promise.all(e)}}class dd extends o.core.EventBus{async loadMetadata(){this.metadataPromise||(this.metadataPromise=this._fetchMetadata().then((e=>(this.metadata=e,e)))),await this.metadataPromise}async get(e){return e&&e.forceFetch&&(this.data=void 0,this.dataPromise=void 0),await this.loadMetadata(),this.dataPromise||(this.dataPromise=this._fetch(e).then((e=>(this.data=e,this.lastUpdate=Date.now(),this.trigger("data-loaded"),e)))),this.dataPromise}getSync(){return this.data}getMetadataSync(){return this.metadata}getLastUpdate(){return this.lastUpdate}}function ud(e){return Oa.get(e.type)(e)}function pd(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class gd{constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){var e;return null===(e=this.operations[this.operations.length-1])||void 0===e?void 0:e.id}getFirstOperationAmong(e,t){for(const s of this.operations){if(s.id===e)return e;if(s.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const s=this.buildTransformation.with(e.data),{before:o,operation:i,after:n}=this.locateOperation(t);this.operations=[...o,i,e,...n.map((e=>e.transformed(s)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new gd(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:s}=this.locateOperation(e);this.operations=t.concat([s])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class fd{constructor(e,t){this.id=e,this.data=t}transformed(e){return new md(this.id,ks((()=>e(this.data))))}}class md{constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new md(this.id,this.lazyData.map(e))}}class vd{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new vd(function*(e,t){for(const s of e)if(yield s,s.operation.id===t)return}(this.operations,e))}stopBefore(e){return new vd(function*(e,t){for(const s of e){if(s.operation.id===t)return;yield s}}(this.operations,e))}startAfter(e){return new vd(function*(e,t){let s=!0;for(const o of e)s||(yield o),o.operation.id===t&&(s=!1)}(this.operations,e))}}class Ed{constructor(e,t){this.buildTransformation=e,this.branchingOperationIds=new Map,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new vd(Ss(this._execution(e),this._execution(e)))}revertedExecution(e){return new vd(Ss(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){var s;const o=e.getLastOperationId()||(null===(s=this.previousBranch(e))||void 0===s?void 0:s.getLastOperationId());e.append(t),o&&this.insertPrevious(e,t,o)}insertOperationAfter(e,t,s){e.insert(t,s),this.updateNextWith(e,t,s),this.insertPrevious(e,t,s)}undo(e,t){const s=this.buildTransformation.without(t.data),o=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const i=e.fork(t.id);o&&this.branchingOperationIds.set(i,o),this.insertBranchAfter(e,i),this.transform(i,s)}redo(e){const t=this.nextBranch(e);if(!t)return;const s=this.nextBranch(t);this.removeBranchFromTree(t);const o=this.branchingOperationIds.get(t);o?this.branchingOperationIds.set(e,o):this.branchingOperationIds.delete(e),s&&this.rebaseUp(s)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const s of this.revertedExecution(e))if(s.operation.id===t)return s;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:s}=this.findPreviousBranchingOperation(e);if(!t||!s)return;const o=this.buildTransformation.without(s.data),i=t.fork(s.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(o);const n=this.nextBranch(i);n&&this.rebaseUp(n)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const s=this.branches.findIndex((t=>t===e));this.branches.splice(s+1,0,t)}updateNextWith(e,t,s){const o=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(o&&i)if(e.getFirstOperationAmong(s,o)===o){const n=this.addToNextBranch(e,i,o,t,s);this.updateNextWith(i,n,s)}else{const e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,s,o,i){let n=o;return i===s?(n=this.getTransformedOperation(e,s,o),t.prepend(n)):t.contains(i)?(n=this.getTransformedOperation(e,s,o),t.insert(n,i)):t.append(o),n}getTransformedOperation(e,t,s){const o=e.getOperation(t),i=this.buildTransformation.without(o.data);return s.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const s=this.nextBranch(e);s&&this.transform(s,t)}insertPrevious(e,t,s){const{previousBranch:o,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!o||!i)return;const n=this.buildTransformation.with(i.data),r=e.fork(s);r.transform(n),o.cutAfter(s),o.appendBranch(r);const a=t.transformed(n);this.insertPrevious(o,a,s)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const s=this.branchingOperationIds.get(t);return s?{previousBranch:t,branchingOperation:t.getOperation(s)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let s=!!t;const o=e.getOperations();for(let i=o.length-1;i>=0;i--){const n=o[i];n.id===t&&(s=!1),s||(yield{operation:n,branch:e,isCancelled:!this.shouldExecute(e,n)})}const i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class bd{constructor(e,t,s,o,i){this.applyOperation=t,this.revertOperation=s,this.buildEmpty=o,this.buildTransformation=i,this.HEAD_BRANCH=new gd(this.buildTransformation),this.tree=new Ed(i,this.HEAD_BRANCH);const n=new fd(e,o(e));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){const s=new fd(e,t),o=this.tree.getLastBranch();this.tree.insertOperationLast(o,s),this.HEAD_BRANCH=o,this.HEAD_OPERATION=s}insert(e,t,s){const o=new fd(e,t);this.revertTo(s),this.tree.insertOperationAfter(this.HEAD_BRANCH,o,s),this.fastForward()}undo(e,t,s){const{branch:o,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(o,i),this.fastForward(),this.insert(t,this.buildEmpty(t),s)}redo(e,t,s){const{branch:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(o),this.fastForward(),this.insert(t,this.buildEmpty(t),s)}drop(e){this.revertBefore(e),this.tree.drop(e)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:s,isCancelled:o}of e)o||this.revertOperation(s.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:s,isCancelled:o}of e)o||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=s}}function Sd(e,t,s){return new bd(e,(e=>{const o=e.commands.slice(),{changes:i}=t((()=>{for(const e of o)s(e)}));e.setChanges(i)}),(e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){Cd(t.changes[e],"before")}}([e])),(e=>new Qh(e,"empty",[],[])),{with:e=>t=>new Qh(t.id,t.clientId,Kh(t.commands,e.commands)),without:e=>t=>new Qh(t.id,t.clientId,Kh(t.commands,e.commands.map(ud).flat()))})}function Cd(e,t){let s=e.path[0];const o=e.path[e.path.length-1];for(let t=1;t<e.path.slice(0,-1).length;t++){const o=e.path[t];if(void 0===s[o]){const i=e.path[t+1];s[o]=pd(i)}s=s[o]}void 0===e[t]?delete s[o]:s[o]=e[t]}class yd extends o.core.EventBus{constructor(e,t){super(),this.dispatch=e,this.session=t,this.undoStack=[],this.redoStack=[],this.session.on("new-local-state-update",this,this.onNewLocalStateUpdate),this.session.on("revision-undone",this,(({commands:e})=>this.selectiveUndo(e))),this.session.on("revision-redone",this,(({commands:e})=>this.selectiveRedo(e))),this.session.on("pending-revisions-dropped",this,(({revisionIds:e})=>this.drop(e))),this.session.on("snapshot",this,(()=>{this.undoStack=[],this.redoStack=[]}))}allowDispatch(e){switch(e.type){case"REQUEST_UNDO":if(!this.canUndo())return 6;break;case"REQUEST_REDO":if(!this.canRedo())return 7}return 0}beforeHandle(e){}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();t&&("UNDO"===e?(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}drop(e){this.undoStack=this.undoStack.filter((t=>!e.includes(t))),this.redoStack=[]}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}selectiveUndo(e){this.dispatch("UNDO",{commands:e})}selectiveRedo(e){this.dispatch("REDO",{commands:e})}}class wd{constructor(e){this.providers=[],this.getters=e}allowDispatch(e){return 0}beforeHandle(e){}handle(e){switch(e.type){case"REMOVE_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",s="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";e.elements.sort(((e,t)=>t-e));const i=bs(e.elements);this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};let r=n,a="NONE";for(let e of i){const i=Math.min(...e),l=Math.max(...e);if(n.zone[t]<=i&&i<=n.zone[s]){const e=Math.min(n.zone[s],l)-i+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e)}else if(n.zone[t]>=i&&n.zone[s]<=l)a="REMOVE",r=this.buildInvalidRange(O);else if(n.zone[t]<=l&&n.zone[s]>=l){const e=l-n.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e),r=this.createAdaptedRange(r,o,"MOVE",-(n.zone[t]-i))}else i<n.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,o,a,-(l-i+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",s="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((i=>{if(i.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(i.zone[t]<=e.base&&e.base<i.zone[s])return{changeType:"RESIZE",range:this.createAdaptedRange(i,o,"RESIZE",e.quantity)};if(e.base<i.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(i,o,"MOVE",e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[s])return{changeType:"RESIZE",range:this.createAdaptedRange(i,o,"RESIZE",e.quantity)};if(e.base<=i.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(i,o,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>t.sheetId!==e.sheetId?{changeType:"NONE"}:{changeType:"REMOVE",range:t={...this.buildInvalidRange(O),invalidSheetName:this.getters.getSheetName(e.sheetId)}}),e.sheetId);break;case"RENAME_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.name&&t.invalidSheetName===e.name){const s={...t,zone:{...t.zone}};return s.invalidSheetName=void 0,s.sheetId=e.sheetId,{changeType:"CHANGE",range:s}}return{changeType:"NONE"}}))}}finalize(){}verifyRangeRemoved(e){return t=>{const s=e(t);return"NONE"===s.changeType||js(s.range.zone)?s:{range:s.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,s,o){return{...e,zone:ao(e.zone,t,s,o)}}executeOnAllRanges(e,t){const s=this.verifyRangeRemoved(e);for(const e of this.providers)e(s,t)}addRangeProvider(e){this.providers.push(e)}orderZone(e,t){if(e.right<e.left){let s=e.right;e.right=e.left,e.left=s;let o=t[1].colFixed;t[1].colFixed=t[0].colFixed,t[0].colFixed=o}if(e.bottom<e.top){let s=e.bottom;e.bottom=e.top,e.top=s;let o=t[1].rowFixed;t[1].rowFixed=t[0].rowFixed,t[0].rowFixed=o}}createAdaptedRanges(e,t,s,o){return e.map((e=>js(e.zone)?(e={...e,sheetId:e.prefixSheet?e.sheetId:o,zone:{left:e.zone.left+(e.parts[0].colFixed?0:t),right:e.zone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.zone.top+(e.parts[0].rowFixed?0:s),bottom:e.zone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:s)}},this.orderZone(e.zone,e.parts),e):e))}getRangeFromSheetXC(e,t){let s,o,i,n=t,r=!1;if(!ts.test(t))return this.buildInvalidRange(t);t.includes("!")&&(({xc:n,sheetName:s}=ss(t)),s?(o=this.getters.getSheetIdByName(s),r=!0,o||(i=s)):i=s);const a=Ws(n);let l=n.split(":").map((e=>({colFixed:e.startsWith("$"),rowFixed:e.includes("$",1)})));return this.orderZone(a,l),{sheetId:o||e,zone:a,parts:l,invalidSheetName:i,prefixSheet:r}}getRangeString(e,t){if(!e)return O;if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return O;if(e.zone.left<0||e.zone.top<0)return O;let s=e.sheetId!==t||e.invalidSheetName||e.prefixSheet,o="";if(s&&(o=e.invalidSheetName?e.invalidSheetName:fs(this.getters.getSheetName(e.sheetId))),s&&!o)return O;let i=Array(9);return i[0]=e.parts&&e.parts[0].colFixed?"$":"",i[1]=os(e.zone.left),i[2]=e.parts&&e.parts[0].rowFixed?"$":"",i[3]=String(e.zone.top+1),e.parts&&2===e.parts.length&&(e.zone.top!==e.zone.bottom||e.zone.left!==e.zone.right||e.parts[0].rowFixed||e.parts[0].colFixed||e.parts[1].rowFixed||e.parts[1].colFixed)&&(i[4]=":",i[5]=e.parts[1].colFixed?"$":"",i[6]=os(e.zone.right),i[7]=e.parts[1].rowFixed?"$":"",i[8]=String(e.zone.bottom+1)),`${s?o+"!":""}${i.join("")}`}buildInvalidRange(e){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:e}}}wd.getters=["getRangeString","getRangeFromSheetXC","createAdaptedRanges"];class Id{constructor(){this.changes=[],this.commands=[]}recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop();let s=e[0],o=e[e.length-1];const i=e.length-2;for(let t=1;t<=i;t++){const o=e[t];if(void 0===s[o]){const i=e[t+1];s[o]=pd(i)}s=s[o]}s[o]!==t&&(this.changes.push({path:e,before:s[o],after:t}),void 0===t?delete s[o]:s[o]=t)}}const xd={General:0,0:1,"0.00":2,"#,#00":3,"#,##0.00":4,"0%":9,"0.00%":10,"0.00E+00":11,"# ?/?":12,"# ??/??":13,"mm-dd-yy":14,"d-mm-yy":15,"mm-yy":16,"mmm-yy":17,"h:mm AM/PM":18,"h:mm:ss AM/PM":19,"h:mm":20,"h:mm:ss":21,"m/d/yy h:mm":22,"#,##0 ;(#,##0)":37,"#,##0 ;[Red](#,##0)":38,"#,##0.00;(#,##0.00)":39,"#,##0.00;[Red](#,##0.00)":40,"mm:ss":45,"[h]:mm:ss":46,"mmss.0":47,"##0.0E+0":48,"@":49,"hh:mm:ss a":19},Td={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},Rd={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"},Ld="http://schemas.openxmlformats.org/drawingml/2006/main",Md="http://schemas.openxmlformats.org/drawingml/2006/chart",Ad={workbook:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",sheet:"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+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"},_d="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Od=.75,Nd=.1425,kd=164,Fd={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}]},$d=["ACOT","ACOTH","AGGREGATE","ARABIC","BASE","BETA.DIST","BETA.INV","BINOM.DIST","BINOM.DIST.RANGE","BINOM.INV","BITAND","BITLSHIFT","BITOR","BITRSHIFT","BITXOR","CEILING.MATH","CEILING.PRECISE","CHISQ.DIST","CHISQ.DIST.RT","CHISQ.INV","CHISQ.INV.RT","CHISQ.TEST","COMBINA","CONCAT","CONFIDENCE.NORM","CONFIDENCE.T","COT","COTH","COVARIANCE.P","COVARIANCE.S","CSC","CSCH","DAYS","DECIMAL","ERF.PRECISE","ERFC.PRECISE","EXPON.DIST","F.DIST","F.DIST.RT","F.INV","F.INV.RT","F.TEST","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","HYPGEOM.DIST","IFNA","IFS","IMCOSH","IMCOT","IMCSC","IMCSCH","IMSEC","IMSECH","IMSINH","IMTAN","ISFORMULA","ISOWEEKNUM","LOGNORM.DIST","LOGNORM.INV","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","QUARTILE.EXC","QUARTILE.INC","QUERYSTRING","RANK.AVG","RANK.EQ","RRI","SEC","SECH","SHEET","SHEETS","SKEW.P","STDEV.P","STDEV.S","SWITCH","T.DIST","T.DIST.2T","T.DIST.RT","T.INV","T.INV.2T","T.TEST","TEXTJOIN","UNICHAR","UNICODE","VAR.P","VAR.S","WEBSERVICE","WEIBULL.DIST","XOR","Z.TEST"];function Dd(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function Pd(e){return Math.round(Od*e*window.devicePixelRatio*100)/100}function Ud(e){return Math.round(Nd*e*100)/100}function Vd(e,t){let s={};e.style&&(s=t.styles[e.style]);const o=e.format?t.formats[e.format]:void 0;let i={};e.border&&(i=t.borders[e.border]);const n={font:{size:(null==s?void 0:s.fontSize)||R,color:(null==s?void 0:s.textColor)?s.textColor:"000000",family:2,name:"Arial"},fill:(null==s?void 0:s.fillColor)?{fgColor:s.fillColor}:{reservedAttribute:"none"},numFmt:o,border:i||{},verticalAlignment:"center",horizontalAlignment:null==s?void 0:s.align};return n.font.strike=!!(null==s?void 0:s.strikethrough)||void 0,n.font.underline=!!(null==s?void 0:s.underline)||void 0,n.font.bold=!!(null==s?void 0:s.bold)||void 0,n.font.italic=!!(null==s?void 0:s.italic)||void 0,n}function Bd(e,t){const{id:s}=zd(t.font,e.fonts),{id:o}=zd(t.fill,e.fills),{id:i}=zd(t.border,e.borders),n=function(e,t){if(!e)return 0;let s=xd[e];if(!s){const{id:o}=zd(e,t);s=o+kd}return s}(t.numFmt,e.numFmts),r={fontId:s,fillId:o,borderId:i,numFmtId:n,verticalAlignment:t.verticalAlignment,horizontalAlignment:t.horizontalAlignment},{id:a}=zd(r,e.styles);return a}function Hd(e,t,s){let o,i=e.find((e=>e.path===t));return i?(o=`rId${(i.rels.length+1).toString()}`,i.rels.push({...s,id:o})):(o="rId1",e.push({path:t,rels:[{...s,id:o}]})),o}function zd(e,t){for(let[s,o]of Object.entries(t))if(JSON.stringify(o)===JSON.stringify(e))return{id:parseInt(s,10),list:t};let s=t.findIndex((t=>JSON.stringify(t)===JSON.stringify(e)));return-1===s&&(t.push(e),s=t.length-1),{id:s,list:t}}const Zd=[];function Gd(e){const t=Zd.findIndex((t=>t===e));return-1===t?(Zd.push(e),Zd.length):t+1}function Wd(e){return Math.round(914400*e/96)}class qd{constructor(e){this.xmlString=e}toString(){return this.xmlString}}function jd(e,t,s){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:s}}function Xd(e){return String(e).replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"")}function Yd(e){return new qd(e.map((([e,t])=>`${e}="${Xd(t)}"`)).join(" "))}function Kd(e){const t=(new DOMParser).parseFromString(e.toString(),"text/xml"),s=t.querySelector("parsererror");if(s){const t=s.innerHTML,o=parseInt(t.split(":")[0],10),i=e.toString().trim().split("\n"),n=i.slice(Math.max(o-3,0),Math.min(o+2,i.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${n}`)}return t}function Qd(e,t){return eu`
1049
1049
  <Override ContentType="${t}" PartName="${e}" />
1050
- `}function Jd(e){return new qd(e.join("\n"))}function eu(e,...t){let s=[e[0]];for(let o=0;o<t.length;o++){const i=t[o]instanceof qd?t[o]:Xd(t[o]);s.push(i+e[o+1])}return new qd(s.join(""))}const tu=17781237,su=88853993;function ou(e){const t=[["xmlns:r",_d],["xmlns:a",Ld],["xmlns:c",Md]],s=iu({backgroundColor:Qt(e.data.backgroundColor),line:{color:"000000"}});let o=eu``;e.data.title&&(o=eu`
1050
+ `}function Jd(e){return new qd(e.join("\n"))}function eu(e,...t){let s=[e[0]];for(let o=0;o<t.length;o++){const i=t[o]instanceof qd?t[o]:Xd(t[o]);s.push(i+e[o+1])}return new qd(s.join(""))}const tu=17781237,su=88853993;function ou(e){const t=[["xmlns:r",_d],["xmlns:a",Ld],["xmlns:c",Md]],s=iu({backgroundColor:Jt(e.data.backgroundColor),line:{color:"000000"}});let o=eu``;e.data.title&&(o=eu`
1051
1051
  <c:title>
1052
1052
  ${ru(e.data.title)}
1053
1053
  <c:overlay val="0" />
1054
1054
  </c:title>
1055
- `);let i=eu``;switch(e.data.type){case"bar":i=function(e){const t=new Fh,s=[];for(const[o,i]of Object.entries(e.dataSets)){const n=Qt(t.next()),r=iu({backgroundColor:n,line:{color:n}});s.push(eu`
1055
+ `);let i=eu``;switch(e.data.type){case"bar":i=function(e){const t=new Fh,s=[];for(const[o,i]of Object.entries(e.dataSets)){const n=Jt(t.next()),r=iu({backgroundColor:n,line:{color:n}});s.push(eu`
1056
1056
  <c:ser>
1057
1057
  <c:idx val="${o}"/>
1058
1058
  <c:order val="${o}"/>
@@ -1077,7 +1077,7 @@
1077
1077
  </c:barChart>
1078
1078
  ${cu("b","c:catAx",tu,su)}
1079
1079
  ${cu(o,"c:valAx",su,tu)}
1080
- `}(e.data);break;case"line":i=function(e){const t=new Fh,s=[];for(const[o,i]of Object.entries(e.dataSets)){const n=iu({line:{width:2.5,style:"solid",color:Qt(t.next())}});s.push(eu`
1080
+ `}(e.data);break;case"line":i=function(e){const t=new Fh,s=[];for(const[o,i]of Object.entries(e.dataSets)){const n=iu({line:{width:2.5,style:"solid",color:Jt(t.next())}});s.push(eu`
1081
1081
  <c:ser>
1082
1082
  <c:idx val="${o}"/>
1083
1083
  <c:order val="${o}"/>
@@ -1103,7 +1103,7 @@
1103
1103
  </c:lineChart>
1104
1104
  ${cu("b","c:catAx",tu,su)}
1105
1105
  ${cu(o,"c:valAx",su,tu)}
1106
- `}(e.data);break;case"pie":i=function(e,{holeSize:t}={holeSize:50}){const s=new Fh,o=Math.max(...e.dataSets.map((e=>{const t=qs(e.range),{height:s,width:o}=io(t);return s*o}))),i=Es(0,o).map((()=>Qt(s.next()))),n=[];for(const[t,s]of Object.entries(e.dataSets).reverse()){const o=qs(s.range),{height:r,width:a}=io(o),l=[];for(const e of Es(0,r*a)){const t=iu({backgroundColor:i[e],line:{color:"FFFFFF",width:1.5}});l.push(eu`
1106
+ `}(e.data);break;case"pie":i=function(e,{holeSize:t}={holeSize:50}){const s=new Fh,o=Math.max(...e.dataSets.map((e=>{const t=qs(e.range),{height:s,width:o}=io(t);return s*o}))),i=Es(0,o).map((()=>Jt(s.next()))),n=[];for(const[t,s]of Object.entries(e.dataSets).reverse()){const o=qs(s.range),{height:r,width:a}=io(o),l=[];for(const e of Es(0,r*a)){const t=iu({backgroundColor:i[e],line:{color:"FFFFFF",width:1.5}});l.push(eu`
1107
1107
  <c:dPt>
1108
1108
  <c:idx val="${e}"/>
1109
1109
  ${t}
@@ -1139,7 +1139,7 @@
1139
1139
  <!-- how the chart element is placed on the chart -->
1140
1140
  <c:layout />
1141
1141
  ${i}
1142
- ${iu({backgroundColor:Qt(e.data.backgroundColor)})}
1142
+ ${iu({backgroundColor:Jt(e.data.backgroundColor)})}
1143
1143
  </c:plotArea>
1144
1144
  ${function(e){return eu`
1145
1145
  <c:legend>
@@ -1243,13 +1243,13 @@
1243
1243
  ${n}
1244
1244
  </f>
1245
1245
  ${s}
1246
- `,{attrs:o,node:i}}{const t=e.value,s=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n"}}(t);return o.push(["t",s]),i=eu`<v>${t}</v>`,{attrs:o,node:i}}}function pu(e,t){let s=e;const o=[];if(["TRUE","FALSE"].includes(s.trim()))s="TRUE"===s?"1":"0",o.push(["t","b"]);else if(!ee(s)){const{id:i}=zd(e,t);s=i.toString(),o.push(["t","s"])}return{attrs:o,node:eu`<v>${s}</v>`}}function gu(e){let t;"="===e[0]&&(e=e.slice(1));try{t=Nr(e)}catch(t){return e}return t=Fr(t,"STRING",fu),t=Fr(t,"FUNCALL",(e=>(e=function(e){const t=e.value.toUpperCase(),s=e.args,o=Fd[t];if(o){const i=hr.content[t].args.filter((e=>!e.optional)),n=i.length-e.args.length;if(n)for(let t=e.args.length;t<i.length;t++){const e=o[t-n];s.push({type:e.type,value:e.value})}}return{...e,args:s}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:$d.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})),e))),t?$r(t):e}function fu(e){const t=e.value.replace(new RegExp('"',"g"),""),s=W(t);if(s){let o=[];return(t.match(z)||t.match(Z))&&o.push("yyyy-mm-dd"),t.match(G)&&o.push("hh:mm:ss"),{...e,value:X({value:s.value,format:o.join(" ")})}}return{...e,value:e.value.replace(/\\"/g,'""')}}function mu(e,t){const s=[];for(const o of t)switch(o.rule.type){case"CellIsRule":s.push(vu(o,o.rule,e));break;case"ColorScaleRule":s.push(Eu(o,o.rule));break;case"IconSetRule":s.push(bu(o,o.rule));break;default:console.warn(`Conditional formatting ${o.rule.type} not implemented`)}return s}function vu(e,t,s){const o=Su(e),i=Dd(t.operator);o.push(...function(e){const t=Dd(e.operator);switch(e.operator){case"ContainsText":case"NotContains":case"BeginsWith":case"EndsWith":return[["type",t],["text",e.values[0]]];case"IsEmpty":case"IsNotEmpty":return[["type",t]];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":case"Between":case"NotBetween":return[["type","cellIs"]]}}(t),["operator",i]);const n=function(e,t){const s=e[0].split(":")[0],o=t.values;switch(t.operator){case"ContainsText":return[`NOT(ISERROR(SEARCH("${o[0]}",${s})))`];case"NotContains":return[`ISERROR(SEARCH("${o[0]}",${s}))`];case"BeginsWith":return[`LEFT(${s},LEN("${o[0]}"))="${o[0]}"`];case"EndsWith":return[`RIGHT(${s},LEN("${o[0]}"))="${o[0]}"`];case"IsEmpty":return[`LEN(TRIM(${s}))=0`];case"IsNotEmpty":return[`LEN(TRIM(${s}))>0`];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":return[o[0]];case"Between":case"NotBetween":return[o[0],o[1]]}}(e.ranges,t).map((e=>eu`<formula>${e}</formula>`)),r={font:{color:t.style.textColor,bold:t.style.bold,italic:t.style.italic,strike:t.style.strikethrough,underline:t.style.underline}};t.style.fillColor&&(r.fill={fgColor:t.style.fillColor});const{id:a}=zd(r,s);return o.push(["dxfId",a]),eu`
1246
+ `,{attrs:o,node:i}}{const t=e.value,s=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n"}}(t);return o.push(["t",s]),i=eu`<v>${t}</v>`,{attrs:o,node:i}}}function pu(e,t){let s=e;const o=[];if(["TRUE","FALSE"].includes(s.trim()))s="TRUE"===s?"1":"0",o.push(["t","b"]);else if(!te(s)){const{id:i}=zd(e,t);s=i.toString(),o.push(["t","s"])}return{attrs:o,node:eu`<v>${s}</v>`}}function gu(e){let t;"="===e[0]&&(e=e.slice(1));try{t=Nr(e)}catch(t){return e}return t=Fr(t,"STRING",fu),t=Fr(t,"FUNCALL",(e=>(e=function(e){const t=e.value.toUpperCase(),s=e.args,o=Fd[t];if(o){const i=hr.content[t].args.filter((e=>!e.optional)),n=i.length-e.args.length;if(n)for(let t=e.args.length;t<i.length;t++){const e=o[t-n];s.push({type:e.type,value:e.value})}}return{...e,args:s}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:$d.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})),e))),t?$r(t):e}function fu(e){const t=e.value.replace(new RegExp('"',"g"),""),s=q(t);if(s){let o=[];return(t.match(Z)||t.match(G))&&o.push("yyyy-mm-dd"),t.match(W)&&o.push("hh:mm:ss"),{...e,value:Y({value:s.value,format:o.join(" ")})}}return{...e,value:e.value.replace(/\\"/g,'""')}}function mu(e,t){const s=[];for(const o of t)switch(o.rule.type){case"CellIsRule":s.push(vu(o,o.rule,e));break;case"ColorScaleRule":s.push(Eu(o,o.rule));break;case"IconSetRule":s.push(bu(o,o.rule));break;default:console.warn(`Conditional formatting ${o.rule.type} not implemented`)}return s}function vu(e,t,s){const o=Su(e),i=Dd(t.operator);o.push(...function(e){const t=Dd(e.operator);switch(e.operator){case"ContainsText":case"NotContains":case"BeginsWith":case"EndsWith":return[["type",t],["text",e.values[0]]];case"IsEmpty":case"IsNotEmpty":return[["type",t]];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":case"Between":case"NotBetween":return[["type","cellIs"]]}}(t),["operator",i]);const n=function(e,t){const s=e[0].split(":")[0],o=t.values;switch(t.operator){case"ContainsText":return[`NOT(ISERROR(SEARCH("${o[0]}",${s})))`];case"NotContains":return[`ISERROR(SEARCH("${o[0]}",${s}))`];case"BeginsWith":return[`LEFT(${s},LEN("${o[0]}"))="${o[0]}"`];case"EndsWith":return[`RIGHT(${s},LEN("${o[0]}"))="${o[0]}"`];case"IsEmpty":return[`LEN(TRIM(${s}))=0`];case"IsNotEmpty":return[`LEN(TRIM(${s}))>0`];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":return[o[0]];case"Between":case"NotBetween":return[o[0],o[1]]}}(e.ranges,t).map((e=>eu`<formula>${e}</formula>`)),r={font:{color:t.style.textColor,bold:t.style.bold,italic:t.style.italic,strike:t.style.strikethrough,underline:t.style.underline}};t.style.fillColor&&(r.fill={fgColor:t.style.fillColor});const{id:a}=zd(r,s);return o.push(["dxfId",a]),eu`
1247
1247
  <conditionalFormatting sqref="${e.ranges.join(" ")}">
1248
1248
  <cfRule ${Yd(o)}>
1249
1249
  ${Jd(n)}
1250
1250
  </cfRule>
1251
1251
  </conditionalFormatting>
1252
- `}function Eu(e,t){const s=Su(e);s.push(["type","colorScale"]);const o=[];for(const i of e.ranges){const e=[],n=[];let r=!0;for(let s of["minimum","midpoint","maximum"]){const o=t[s];o&&("formula"!==o.type?(e.push(yu(o,s)),n.push([["rgb",Xt(o.color)]])):r=!1)}if(!r){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const a=e.map((e=>eu`<cfvo ${Yd(e)}/>`)),l=n.map((e=>eu`<color ${Yd(e)}/>`));o.push(eu`
1252
+ `}function Eu(e,t){const s=Su(e);s.push(["type","colorScale"]);const o=[];for(const i of e.ranges){const e=[],n=[];let r=!0;for(let s of["minimum","midpoint","maximum"]){const o=t[s];o&&("formula"!==o.type?(e.push(yu(o,s)),n.push([["rgb",Yt(o.color)]])):r=!1)}if(!r){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const a=e.map((e=>eu`<cfvo ${Yd(e)}/>`)),l=n.map((e=>eu`<color ${Yd(e)}/>`));o.push(eu`
1253
1253
  <conditionalFormatting sqref="${i}">
1254
1254
  <cfRule ${Yd(s)}>
1255
1255
  <colorScale>
@@ -1308,16 +1308,16 @@
1308
1308
  ${e.underline?eu`<u />`:""}
1309
1309
  ${e.strike?eu`<strike />`:""}
1310
1310
  ${e.size?eu`<sz val="${e.size}" />`:""}
1311
- ${e.color?eu`<color rgb="${Qt(e.color)}" />`:""}
1311
+ ${e.color?eu`<color rgb="${Jt(e.color)}" />`:""}
1312
1312
  ${e.name?eu`<name val="${e.name}" />`:""}
1313
1313
  </font>
1314
- `}function Ru(e){return e?Yd([["style",e[0]],["color",Qt(e[1])]]):eu``}function Lu(e){if(!Object.values(e).length)return eu``;const t=[];for(let[s,o]of Object.entries(e)){const e=[["min",parseInt(s)+1],["max",parseInt(s)+1],["width",Ud(o.size||b)],["customWidth",1],["hidden",o.isHidden?1:0]];t.push(eu`
1314
+ `}function Ru(e){return e?Yd([["style",e[0]],["color",Jt(e[1])]]):eu``}function Lu(e){if(!Object.values(e).length)return eu``;const t=[];for(let[s,o]of Object.entries(e)){const e=[["min",parseInt(s)+1],["max",parseInt(s)+1],["width",Ud(o.size||b)],["customWidth",1],["hidden",o.isHidden?1:0]];t.push(eu`
1315
1315
  <col ${Yd(e)}/>
1316
1316
  `)}return eu`
1317
1317
  <cols>
1318
1318
  ${Jd(t)}
1319
1319
  </cols>
1320
- `}function Mu(e,t,s){const o=[];for(let i=0;i<s.rowNumber;i++){const n=[["r",i+1]],r=s.rows[i]||{};n.push(["ht",Pd(r.size||S)],["customHeight",1],["hidden",r.isHidden?1:0]);const a=[];for(let o=0;o<s.colNumber;o++){const n=is(o,i),r=s.cells[n];if(r){const s=[["r",n]],o=Bd(e,Vd(r,t));s.push(["s",o]);let i=[],l=eu``;if(r.isFormula)({attrs:i,node:l}=uu(r));else if(r.content&&xs(r.content)){const{label:t}=Rs(r.content);({attrs:i,node:l}=pu(t,e.sharedStrings))}else r.content&&""!==r.content&&({attrs:i,node:l}=pu(r.content,e.sharedStrings));s.push(...i),a.push(eu`
1320
+ `}function Mu(e,t,s){const o=[];for(let i=0;i<s.rowNumber;i++){const n=[["r",i+1]],r=s.rows[i]||{};n.push(["ht",Pd(r.size||S)],["customHeight",1],["hidden",r.isHidden?1:0]);const a=[];for(let o=0;o<s.colNumber;o++){const n=ns(o,i),r=s.cells[n];if(r){const s=[["r",n]],o=Bd(e,Vd(r,t));s.push(["s",o]);let i=[],l=eu``;if(r.isFormula)({attrs:i,node:l}=uu(r));else if(r.content&&xs(r.content)){const{label:t}=Rs(r.content);({attrs:i,node:l}=pu(t,e.sharedStrings))}else r.content&&""!==r.content&&({attrs:i,node:l}=pu(r.content,e.sharedStrings));s.push(...i),a.push(eu`
1321
1321
  <c ${Yd(s)}>
1322
1322
  ${l}
1323
1323
  </c>
@@ -1380,7 +1380,7 @@
1380
1380
  `):t.push(eu`
1381
1381
  <fill>
1382
1382
  <patternFill patternType="solid">
1383
- <fgColor rgb="${Qt(s.fgColor)}" />
1383
+ <fgColor rgb="${Jt(s.fgColor)}" />
1384
1384
  <bgColor indexed="64" />
1385
1385
  </patternFill>
1386
1386
  </fill>
@@ -1414,7 +1414,7 @@
1414
1414
  ${function(e){const t=[];for(const s of e){let e=eu``;s.font&&(e=Tu(s.font));let o=eu``;s.fill&&(o=eu`
1415
1415
  <fill>
1416
1416
  <patternFill>
1417
- <bgColor rgb="${Qt(s.fill.fgColor)}" />
1417
+ <bgColor rgb="${Jt(s.fill.fgColor)}" />
1418
1418
  </patternFill>
1419
1419
  </fill>
1420
1420
  `),t.push(eu`
@@ -1448,7 +1448,7 @@
1448
1448
  <Relationships xmlns="${Rd.Relationships}">
1449
1449
  <Relationship ${Yd(e)} />
1450
1450
  </Relationships>
1451
- `;return jd(Kd(t),"_rels/.rels")}()),{name:"my_spreadsheet.xlsx",files:t}}var Nu;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(Nu||(Nu={}));class ku extends o.core.EventBus{constructor(e={},t={},s=[],o=new Hs){super(),this.corePlugins=[],this.uiPlugins=[],this.dataSources=new hd,this.isReplayingCommand=!1,this.renderers=[],this.status=0,this.dispatch=(e,t)=>{const s={type:e,...t};let o=this.status;if(this.config.isReadonly&&(i=s,!De.has(i.type)))return new Ve(52);var i;if(!this.session.canApplyOptimisticUpdate())return new Ve(49);switch(o){case 0:const t=this.checkDispatchAllowed(s);if(!t.isSuccessful)return t;this.status=1;const{changes:o,commands:i}=this.state.recordChanges((()=>{Ue(s)&&this.state.addCommand(s),this.dispatchToHandlers(this.handlers,s),this.finalize()}));this.session.save(i,o),this.status=0,"headless"!==this.config.mode&&this.trigger("update");break;case 1:if(Ue(s)){const e=this.checkDispatchAllowed(s);if(!e.isSuccessful)return e;this.state.addCommand(s),this.dispatchToHandlers(this.handlers,s)}else this.dispatchToHandlers(this.handlers,s);break;case 3:throw new Error(a("Cannot dispatch commands in the finalize state"));case 2:if(Ue(s))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,s)}return Ve.Success},this.dispatchFromCorePlugin=(e,t)=>{const s={type:e,...t},o=this.status;this.status=2;const i=this.isReplayingCommand?[this.range,...this.corePlugins]:this.handlers;return this.dispatchToHandlers(i,s),this.status=o,Ve.Success},Os.model=this,s=ua(e,s);const i=ha(e);this.state=new Id,this.uuidGenerator=o,this.config=this.setupConfig(t),this.session=this.setupSession(i.revisionId),this.config.moveClient=this.session.move.bind(this.session),this.history=new yd(this.dispatchFromCorePlugin,this.session),this.getters={isReadonly:()=>this.config.isReadonly,canUndo:this.history.canUndo.bind(this.history),canRedo:this.history.canRedo.bind(this.history),getClient:this.session.getClient.bind(this.session),getConnectedClients:this.session.getConnectedClients.bind(this.session),isFullySynchronized:this.session.isFullySynchronized.bind(this.session)},this.range=new wd(this.getters),this.getters.getRangeString=this.range.getRangeString.bind(this.range),this.getters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.getters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.uuidGenerator.setIsFastStrategy(!0);for(let e of ad.getAll())this.setupCorePlugin(e,i);for(let e of ld.getAll())this.setupUiPlugin(e);this.uuidGenerator.setIsFastStrategy(!1),this.dispatch("START"),this.setupSessionEvents(),this.session.loadInitialMessages(s),this.joinSession(t.client),t.snapshotRequested&&this.session.snapshot(this.exportData())}get handlers(){return[this.range,...this.corePlugins,...this.uiPlugins,this.history]}joinSession(e){this.session.join(e)}leaveSession(){this.session.leave()}destroy(){delete Os.model}setupUiPlugin(e){if(e.modes.includes(this.config.mode)){const t=new e(this.getters,this.state,this.dispatch,this.config);for(let s of e.getters){if(!(s in t))throw new Error(`Invalid getter name: ${s} for plugin ${t.constructor}`);this.getters[s]=t[s].bind(t)}this.uiPlugins.push(t);const s=e.layers.map((e=>[t,e]));this.renderers.push(...s),this.renderers.sort(((e,t)=>e[1]-t[1]))}}setupCorePlugin(e,t){if(e.modes.includes(this.config.mode)){const s=new e(this.getters,this.state,this.range,this.dispatchFromCorePlugin,this.config,this.uuidGenerator);for(let t of e.getters){if(!(t in s))throw new Error(`Invalid getter name: ${t} for plugin ${s.constructor}`);this.getters[t]=s[t].bind(s)}s.import(t),this.corePlugins.push(s)}}onRemoteRevisionReceived({commands:e}){for(let t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.uiPlugins,t),this.status=e}this.finalize()}setupSession(e){return new ed(Sd(e,this.state.recordChanges.bind(this.state),(e=>{this.checkDispatchAllowed(e).isSuccessful&&(this.isReplayingCommand=!0,this.dispatchToHandlers([this.range,...this.corePlugins],e),this.isReplayingCommand=!1)})),this.config.transportService,e)}setupSessionEvents(){this.session.on("remote-revision-received",this,this.onRemoteRevisionReceived),this.session.on("revision-redone",this,this.finalize),this.session.on("revision-undone",this,this.finalize),this.session.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.session.on("collaborative-event-received",this,(()=>{this.trigger("update")}))}setupConfig(e){const t=e.client||{id:this.uuidGenerator.uuidv4(),name:a("Anonymous").toString()},s=e.transportService||new cd;return{mode:e.mode||"normal",evalContext:e.evalContext||{},transportService:s,client:t,moveClient:()=>{},isHeadless:"headless"===e.mode||!1,isReadonly:e.isReadonly||!1,snapshotRequested:!1,dataSources:this.dataSources,notifyUI:e=>this.trigger("notify-ui",e)}}checkDispatchAllowed(e){const t=this.handlers.map((t=>t.allowDispatch(e)));return new Ve(t.flat())}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0}dispatchToHandlers(e,t){for(const s of e)s.beforeHandle(t);for(const s of e)s.handle(t)}drawGrid(e){e.viewport=this.getters.getActiveSnappedViewport();for(let[t,s]of this.renderers)e.ctx.save(),t.drawGrid(e,s),e.ctx.restore()}exportData(){let e=fa();for(let t of this.handlers)t instanceof va&&t.export(e);return e.revisionId=this.session.getRevisionId()||N,e=JSON.parse(JSON.stringify(e)),e}updateReadOnly(e){e&&this.dispatch("STOP_EDITION",{cancel:!0}),this.config.isReadonly=e||!1}waitForIdle(){return this.dataSources.waitForReady()}async exportXLSX(){await this.waitForIdle(),this.dispatch("EVALUATE_ALL_SHEETS");let e={...fa(),sheets:[(t=ca,s="Sheet1",{...ga(t,s),charts:[]})]};var t,s;for(let t of this.handlers)t instanceof va&&t.exportForExcel(e);return e=JSON.parse(JSON.stringify(e)),Ou(e)}}const{useComponent:Fu,useState:$u,onPatched:Du,onMounted:Pu}=t.hooks;function Uu(e){const t=$u({x:0,y:0}),s=Fu(),o=function(){const e=$u({x:0,y:0});let t=document.querySelector(".o-spreadsheet");function s(){if(t||(t=document.querySelector(".o-spreadsheet")),t){const{top:s,left:o}=t.getBoundingClientRect();e.x=o,e.y=s}}return Pu(s),Du(s),e}();function i(){const i=(null==e?void 0:e.el)||s.el,{top:n,left:r}=i.getBoundingClientRect(),a=r-o.x,l=n-o.y;a===t.x&&l===t.y||(t.x=a,t.y=l)}return Pu(i),Du(i),t}const{Portal:Vu}=t.misc,{xml:Bu}=t.tags,Hu=Bu`
1451
+ `;return jd(Kd(t),"_rels/.rels")}()),{name:"my_spreadsheet.xlsx",files:t}}var Nu;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(Nu||(Nu={}));class ku extends o.core.EventBus{constructor(e={},t={},s=[],o=new Hs){super(),this.corePlugins=[],this.uiPlugins=[],this.dataSources=new hd,this.isReplayingCommand=!1,this.renderers=[],this.status=0,this.dispatch=(e,t)=>{const s={type:e,...t};let o=this.status;if(this.config.isReadonly&&(i=s,!Pe.has(i.type)))return new Be(52);var i;if(!this.session.canApplyOptimisticUpdate())return new Be(49);switch(o){case 0:const t=this.checkDispatchAllowed(s);if(!t.isSuccessful)return t;this.status=1;const{changes:o,commands:i}=this.state.recordChanges((()=>{Ve(s)&&this.state.addCommand(s),this.dispatchToHandlers(this.handlers,s),this.finalize()}));this.session.save(i,o),this.status=0,"headless"!==this.config.mode&&this.trigger("update");break;case 1:if(Ve(s)){const e=this.checkDispatchAllowed(s);if(!e.isSuccessful)return e;this.state.addCommand(s),this.dispatchToHandlers(this.handlers,s)}else this.dispatchToHandlers(this.handlers,s);break;case 3:throw new Error(a("Cannot dispatch commands in the finalize state"));case 2:if(Ve(s))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,s)}return Be.Success},this.dispatchFromCorePlugin=(e,t)=>{const s={type:e,...t},o=this.status;this.status=2;const i=this.isReplayingCommand?[this.range,...this.corePlugins]:this.handlers;return this.dispatchToHandlers(i,s),this.status=o,Be.Success},Os.model=this,s=ua(e,s);const i=ha(e);this.state=new Id,this.uuidGenerator=o,this.config=this.setupConfig(t),this.session=this.setupSession(i.revisionId),this.config.moveClient=this.session.move.bind(this.session),this.history=new yd(this.dispatchFromCorePlugin,this.session),this.getters={isReadonly:()=>this.config.isReadonly,canUndo:this.history.canUndo.bind(this.history),canRedo:this.history.canRedo.bind(this.history),getClient:this.session.getClient.bind(this.session),getConnectedClients:this.session.getConnectedClients.bind(this.session),isFullySynchronized:this.session.isFullySynchronized.bind(this.session)},this.range=new wd(this.getters),this.getters.getRangeString=this.range.getRangeString.bind(this.range),this.getters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.getters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.uuidGenerator.setIsFastStrategy(!0);for(let e of ad.getAll())this.setupCorePlugin(e,i);for(let e of ld.getAll())this.setupUiPlugin(e);this.uuidGenerator.setIsFastStrategy(!1),this.dispatch("START"),this.setupSessionEvents(),this.session.loadInitialMessages(s),this.joinSession(t.client),t.snapshotRequested&&this.session.snapshot(this.exportData())}get handlers(){return[this.range,...this.corePlugins,...this.uiPlugins,this.history]}joinSession(e){this.session.join(e)}leaveSession(){this.session.leave()}destroy(){delete Os.model}setupUiPlugin(e){if(e.modes.includes(this.config.mode)){const t=new e(this.getters,this.state,this.dispatch,this.config);for(let s of e.getters){if(!(s in t))throw new Error(`Invalid getter name: ${s} for plugin ${t.constructor}`);this.getters[s]=t[s].bind(t)}this.uiPlugins.push(t);const s=e.layers.map((e=>[t,e]));this.renderers.push(...s),this.renderers.sort(((e,t)=>e[1]-t[1]))}}setupCorePlugin(e,t){if(e.modes.includes(this.config.mode)){const s=new e(this.getters,this.state,this.range,this.dispatchFromCorePlugin,this.config,this.uuidGenerator);for(let t of e.getters){if(!(t in s))throw new Error(`Invalid getter name: ${t} for plugin ${s.constructor}`);this.getters[t]=s[t].bind(s)}s.import(t),this.corePlugins.push(s)}}onRemoteRevisionReceived({commands:e}){for(let t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.uiPlugins,t),this.status=e}this.finalize()}setupSession(e){return new ed(Sd(e,this.state.recordChanges.bind(this.state),(e=>{this.checkDispatchAllowed(e).isSuccessful&&(this.isReplayingCommand=!0,this.dispatchToHandlers([this.range,...this.corePlugins],e),this.isReplayingCommand=!1)})),this.config.transportService,e)}setupSessionEvents(){this.session.on("remote-revision-received",this,this.onRemoteRevisionReceived),this.session.on("revision-redone",this,this.finalize),this.session.on("revision-undone",this,this.finalize),this.session.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.session.on("collaborative-event-received",this,(()=>{this.trigger("update")}))}setupConfig(e){const t=e.client||{id:this.uuidGenerator.uuidv4(),name:a("Anonymous").toString()},s=e.transportService||new cd;return{mode:e.mode||"normal",evalContext:e.evalContext||{},transportService:s,client:t,moveClient:()=>{},isHeadless:"headless"===e.mode||!1,isReadonly:e.isReadonly||!1,snapshotRequested:!1,dataSources:this.dataSources,notifyUI:e=>this.trigger("notify-ui",e)}}checkDispatchAllowed(e){const t=this.handlers.map((t=>t.allowDispatch(e)));return t.some((e=>0!==e))?new Be(t.flat()):Be.Success}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0}dispatchToHandlers(e,t){for(const s of e)s.beforeHandle(t);for(const s of e)s.handle(t)}drawGrid(e){e.viewport=this.getters.getActiveSnappedViewport();for(let[t,s]of this.renderers)e.ctx.save(),t.drawGrid(e,s),e.ctx.restore()}exportData(){let e=fa();for(let t of this.handlers)t instanceof va&&t.export(e);return e.revisionId=this.session.getRevisionId()||N,e=JSON.parse(JSON.stringify(e)),e}updateReadOnly(e){e&&this.dispatch("STOP_EDITION",{cancel:!0}),this.config.isReadonly=e||!1}waitForIdle(){return this.dataSources.waitForReady()}async exportXLSX(){await this.waitForIdle(),this.dispatch("EVALUATE_ALL_SHEETS");let e={...fa(),sheets:[(t=ca,s="Sheet1",{...ga(t,s),charts:[]})]};var t,s;for(let t of this.handlers)t instanceof va&&t.exportForExcel(e);return e=JSON.parse(JSON.stringify(e)),Ou(e)}}const{useComponent:Fu,useState:$u,onPatched:Du,onMounted:Pu}=t.hooks;function Uu(e){const t=$u({x:0,y:0}),s=Fu(),o=function(){const e=$u({x:0,y:0});let t=document.querySelector(".o-spreadsheet");function s(){if(t||(t=document.querySelector(".o-spreadsheet")),t){const{top:s,left:o}=t.getBoundingClientRect();e.x=o,e.y=s}}return Pu(s),Du(s),e}();function i(){const i=(null==e?void 0:e.el)||s.el,{top:n,left:r}=i.getBoundingClientRect(),a=r-o.x,l=n-o.y;a===t.x&&l===t.y||(t.x=a,t.y=l)}return Pu(i),Du(i),t}const{Portal:Vu}=t.misc,{xml:Bu}=t.tags,Hu=Bu`
1452
1452
  <Portal target="'.o-spreadsheet'">
1453
1453
  <div class="o-popover" t-att-style="style">
1454
1454
  <t t-slot="default"/>
@@ -1659,7 +1659,7 @@
1659
1659
  opacity: 0;
1660
1660
  }
1661
1661
  }
1662
- `;class np extends t.Component{constructor(){super(...arguments),this.position=Uu(),this.getters=this.env.getters,this.menuState=ep({isOpen:!1,position:null,menuItems:[]}),this.selectedStatisticFn=""}setup(){tp((()=>this.focusSheet())),sp((()=>this.focusSheet()))}focusSheet(){const e=this.el.querySelector(`[data-id="${this.getters.getActiveSheetId()}"]`);e&&e.scrollIntoView&&e.scrollIntoView()}addSheet(){const e=this.env.getters.getActiveSheetId(),t=this.env.getters.getVisibleSheets().findIndex((t=>t===e))+1,s=this.env.uuidGenerator.uuidv4(),o=this.getters.getNextSheetName(this.env._t("Sheet"));this.env.dispatch("CREATE_SHEET",{sheetId:s,position:t,name:o}),this.env.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:s})}listSheets(e){const t=new $a,s=this.getters.getActiveSheetId();let o=0;for(let e of this.getters.getSheets())t.add(e.id,{name:e.name,sequence:o,isReadonlyAllowed:!0,action:t=>t.dispatch("ACTIVATE_SHEET",{sheetIdFrom:s,sheetIdTo:e.id})}),o++;const i=e.currentTarget,{left:n}=i.getBoundingClientRect();this.openContextMenu(n,t)}activateSheet(e){this.env.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:e})}onDblClick(e){bl(this.env,e)}openContextMenu(e,t){this.menuState.isOpen=!0,this.menuState.menuItems=t.getAll().filter((e=>e.isVisible(this.env))),this.menuState.position={x:e,y:this.position.y}}onIconClick(e,t){if(this.getters.getActiveSheetId()!==e&&this.activateSheet(e),this.menuState.isOpen)this.menuState.isOpen=!1;else{const e=t.currentTarget.parentElement,{left:s}=e.getBoundingClientRect();this.openContextMenu(s,Sl)}}onContextMenu(e,t){this.getters.getActiveSheetId()!==e&&this.activateSheet(e);const s=t.currentTarget,{left:o}=s.getBoundingClientRect();this.openContextMenu(o,Sl)}getSelectedStatistic(){const e=this.getters.getStatisticFnResults();if(!Object.values(e).every((e=>void 0===e)))return""===this.selectedStatisticFn&&(this.selectedStatisticFn=Object.keys(e)[0]),this.getComposedFnName(this.selectedStatisticFn,e[this.selectedStatisticFn])}listSelectionStatistics(e){const t=new $a;let s=0;for(let[e,o]of Object.entries(this.getters.getStatisticFnResults()))t.add(e,{name:this.getComposedFnName(e,o),sequence:s,isReadonlyAllowed:!0,action:()=>{this.selectedStatisticFn=e}}),s++;const o=e.currentTarget,{left:i,width:n}=o.getBoundingClientRect();this.openContextMenu(i+n,t)}getComposedFnName(e,t){return e+": "+(void 0!==t?ie(t):"__")}}function rp(e,t){const s=i=>{t(i),window.removeEventListener("mouseup",s),window.removeEventListener("dragstart",o),window.removeEventListener("mousemove",e),window.removeEventListener("wheel",e)};function o(e){e.preventDefault()}window.addEventListener("mouseup",s),window.addEventListener("dragstart",o),window.addEventListener("mousemove",e),window.addEventListener("wheel",e)}function ap(e,t,s,o){const i=e.getBoundingClientRect();let n,r=null;const a=e=>{if(n=e,r)return;const o=n.clientX-i.left,l=n.clientY-i.top,c=t.getters.getEdgeScrollCol(o),h=t.getters.getEdgeScrollRow(l),{top:d,left:u,bottom:p,right:g}=t.getters.getActiveSnappedViewport();let f,m;if(f=c.canEdgeScroll?c.direction>0?g:u-1:t.getters.getColIndex(o,u),m=h.canEdgeScroll?h.direction>0?p:d-1:t.getters.getRowIndex(l,d),s(f,m),c.canEdgeScroll){const{left:e,offsetY:s}=t.getters.getActiveSnappedViewport(),{cols:o}=t.getters.getActiveSheet(),i=o[e+c.direction].start;t.dispatch("SET_VIEWPORT_OFFSET",{offsetX:i,offsetY:s}),r=setTimeout((()=>{r=null,a(n)}),Math.round(c.delay))}if(h.canEdgeScroll){const{top:e,offsetX:s}=t.getters.getActiveSnappedViewport(),{rows:o}=t.getters.getActiveSheet(),i=o[e+h.direction].start;t.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s,offsetY:i}),r=setTimeout((()=>{r=null,a(n)}),Math.round(h.delay))}};rp(a,(()=>{clearTimeout(r),o()}))}np.template=op,np.style=ip,np.components={Menu:Ku};const{xml:lp,css:cp}=t.tags,{useState:hp}=t.hooks,dp=lp`
1662
+ `;class np extends t.Component{constructor(){super(...arguments),this.position=Uu(),this.getters=this.env.getters,this.menuState=ep({isOpen:!1,position:null,menuItems:[]}),this.selectedStatisticFn=""}setup(){tp((()=>this.focusSheet())),sp((()=>this.focusSheet()))}focusSheet(){const e=this.el.querySelector(`[data-id="${this.getters.getActiveSheetId()}"]`);e&&e.scrollIntoView&&e.scrollIntoView()}addSheet(){const e=this.env.getters.getActiveSheetId(),t=this.env.getters.getVisibleSheets().findIndex((t=>t===e))+1,s=this.env.uuidGenerator.uuidv4(),o=this.getters.getNextSheetName(this.env._t("Sheet"));this.env.dispatch("CREATE_SHEET",{sheetId:s,position:t,name:o}),this.env.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:s})}listSheets(e){const t=new $a,s=this.getters.getActiveSheetId();let o=0;for(let e of this.getters.getSheets())t.add(e.id,{name:e.name,sequence:o,isReadonlyAllowed:!0,action:t=>t.dispatch("ACTIVATE_SHEET",{sheetIdFrom:s,sheetIdTo:e.id})}),o++;const i=e.currentTarget,{left:n}=i.getBoundingClientRect();this.openContextMenu(n,t)}activateSheet(e){this.env.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:e})}onDblClick(e){bl(this.env,e)}openContextMenu(e,t){this.menuState.isOpen=!0,this.menuState.menuItems=t.getAll().filter((e=>e.isVisible(this.env))),this.menuState.position={x:e,y:this.position.y}}onIconClick(e,t){if(this.getters.getActiveSheetId()!==e&&this.activateSheet(e),this.menuState.isOpen)this.menuState.isOpen=!1;else{const e=t.currentTarget.parentElement,{left:s}=e.getBoundingClientRect();this.openContextMenu(s,Sl)}}onContextMenu(e,t){this.getters.getActiveSheetId()!==e&&this.activateSheet(e);const s=t.currentTarget,{left:o}=s.getBoundingClientRect();this.openContextMenu(o,Sl)}getSelectedStatistic(){const e=this.getters.getStatisticFnResults();if(!Object.values(e).every((e=>void 0===e)))return""===this.selectedStatisticFn&&(this.selectedStatisticFn=Object.keys(e)[0]),this.getComposedFnName(this.selectedStatisticFn,e[this.selectedStatisticFn])}listSelectionStatistics(e){const t=new $a;let s=0;for(let[e,o]of Object.entries(this.getters.getStatisticFnResults()))t.add(e,{name:this.getComposedFnName(e,o),sequence:s,isReadonlyAllowed:!0,action:()=>{this.selectedStatisticFn=e}}),s++;const o=e.currentTarget,{left:i,width:n}=o.getBoundingClientRect();this.openContextMenu(i+n,t)}getComposedFnName(e,t){return e+": "+(void 0!==t?ne(t):"__")}}function rp(e,t){const s=i=>{t(i),window.removeEventListener("mouseup",s),window.removeEventListener("dragstart",o),window.removeEventListener("mousemove",e),window.removeEventListener("wheel",e)};function o(e){e.preventDefault()}window.addEventListener("mouseup",s),window.addEventListener("dragstart",o),window.addEventListener("mousemove",e),window.addEventListener("wheel",e)}function ap(e,t,s,o){const i=e.getBoundingClientRect();let n,r=null;const a=e=>{if(n=e,r)return;const o=n.clientX-i.left,l=n.clientY-i.top,c=t.getters.getEdgeScrollCol(o),h=t.getters.getEdgeScrollRow(l),{top:d,left:u,bottom:p,right:g}=t.getters.getActiveSnappedViewport();let f,m;if(f=c.canEdgeScroll?c.direction>0?g:u-1:t.getters.getColIndex(o,u),m=h.canEdgeScroll?h.direction>0?p:d-1:t.getters.getRowIndex(l,d),s(f,m),c.canEdgeScroll){const{left:e,offsetY:s}=t.getters.getActiveSnappedViewport(),{cols:o}=t.getters.getActiveSheet(),i=o[e+c.direction].start;t.dispatch("SET_VIEWPORT_OFFSET",{offsetX:i,offsetY:s}),r=setTimeout((()=>{r=null,a(n)}),Math.round(c.delay))}if(h.canEdgeScroll){const{top:e,offsetX:s}=t.getters.getActiveSnappedViewport(),{rows:o}=t.getters.getActiveSheet(),i=o[e+h.direction].start;t.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s,offsetY:i}),r=setTimeout((()=>{r=null,a(n)}),Math.round(h.delay))}};rp(a,(()=>{clearTimeout(r),o()}))}np.template=op,np.style=ip,np.components={Menu:Ku};const{xml:lp,css:cp}=t.tags,{useState:hp}=t.hooks,dp=lp`
1663
1663
  <div class="o-autofill" t-on-mousedown="onMouseDown" t-att-style="style" t-on-dblclick="onDblClick">
1664
1664
  <div class="o-autofill-handler" t-att-style="styleHandler"/>
1665
1665
  <t t-set="tooltip" t-value="getTooltip()"/>
@@ -1715,7 +1715,7 @@
1715
1715
  opacity: 0;
1716
1716
  pointer-events: none;
1717
1717
  }
1718
- `;class bp extends t.Component{get tagStyle(){const{col:e,row:t,color:s}=this.props,o=this.env.getters.getActiveSnappedViewport(),{height:i}=this.env.getters.getViewportDimensionWithHeaders(),[n,r,,]=this.env.getters.getRect({left:e,top:t,right:e,bottom:t},o);return`bottom: ${i-r+15}px;left: ${n-1}px;border: 1px solid ${s};background-color: ${s};${this.props.active?"opacity:1 !important":""}`}}bp.template=vp,bp.style=Ep;const{onMounted:Sp,onWillUpdateProps:Cp}=t.hooks,{xml:yp,css:wp}=t.tags,Ip=hr.content,xp=new Me;xp.add("functions",(()=>Object.keys(Ip).map((e=>({text:e,description:Ip[e].description})))));const Tp=yp`
1718
+ `;class bp extends t.Component{get tagStyle(){const{col:e,row:t,color:s}=this.props,o=this.env.getters.getActiveSnappedViewport(),{height:i}=this.env.getters.getViewportDimensionWithHeaders(),[n,r,,]=this.env.getters.getRect({left:e,top:t,right:e,bottom:t},o);return`bottom: ${i-r+15}px;left: ${n-1}px;border: 1px solid ${s};background-color: ${s};${this.props.active?"opacity:1 !important":""}`}}bp.template=vp,bp.style=Ep;const{onMounted:Sp,onWillUpdateProps:Cp}=t.hooks,{xml:yp,css:wp}=t.tags,Ip=hr.content,xp=new Ae;xp.add("functions",(()=>Object.keys(Ip).map((e=>({text:e,description:Ip[e].description})))));const Tp=yp`
1719
1719
  <div t-att-class="{'o-autocomplete-dropdown':state.values.length}"
1720
1720
  t-att-style="state.values.length > 0 ? props.borderStyle : null"
1721
1721
  >
@@ -1926,7 +1926,7 @@
1926
1926
  .o-topbar-toolbar .o-composer-container:focus-within {
1927
1927
  border: 1px solid ${p};
1928
1928
  }
1929
- `;class sg extends t.Component{constructor(){super(...arguments),this.composerRef=Bp("o_composer"),this.getters=this.env.getters,this.dispatch=this.env.dispatch,this.composerState=Hp({positionStart:0,positionEnd:0}),this.autoCompleteState=Hp({showProvider:!1,provider:"functions",search:""}),this.functionDescriptionState=Hp({showDescription:!1,functionName:"",functionDescription:{},argToFocus:0}),this.isKeyStillDown=!1,this.compositionActive=!1,this.borderStyle="box-shadow: 0 1px 4px 3px rgba(60, 64, 67, 0.15);",this.shouldProcessInputEvents=!1,this.tokens=[],this.keyMapping={ArrowUp:this.processArrowKeys,ArrowDown:this.processArrowKeys,ArrowLeft:this.processArrowKeys,ArrowRight:this.processArrowKeys,Enter:this.processEnterKey,Escape:this.processEscapeKey,F2:()=>console.warn("Not implemented"),F4:()=>console.warn("Not implemented"),Tab:e=>this.processTabKey(e)},this.contentHelper=new Mp(this.composerRef.el)}get assistantStyle(){if(this.props.delimitation&&this.props.rect){const[e,t,,s]=this.props.rect;let o="";return t>this.props.delimitation.height-(t+s)&&(o+="\n top: -8px;\n transform: translate(0, -100%);\n "),e+300>this.props.delimitation.width&&(o+="right:0px;"),o+="width:300px;"}return"width:300px;"}setup(){zp((()=>{Os.composer=this;const e=this.composerRef.el;this.contentHelper.updateEl(e),this.processContent()})),Gp((()=>{var e,t;delete Os.composer,null===(t=(e=this.props).onComposerUnmounted)||void 0===t||t.call(e)})),Zp((()=>{this.isKeyStillDown||this.processContent()}))}processArrowKeys(e){if(this.getters.isSelectingForComposer())return this.functionDescriptionState.showDescription=!1,void e.preventDefault();("cellFocus"!==this.props.focus||this.autoCompleteState.showProvider)&&(e.stopPropagation(),["ArrowUp","ArrowDown"].includes(e.key)&&this.autoCompleteState.showProvider&&this.autocompleteAPI&&(e.preventDefault(),"ArrowUp"===e.key?this.autocompleteAPI.moveUp():this.autocompleteAPI.moveDown()),this.updateCursorIfNeeded())}processTabKey(e){if(e.preventDefault(),e.stopPropagation(),this.autoCompleteState.showProvider&&this.autocompleteAPI){const e=this.autocompleteAPI.getValueToFill();if(e)return void this.autoComplete(e)}else this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=e.shiftKey?-1:1;this.dispatch("MOVE_POSITION",{deltaX:t,deltaY:0})}processEnterKey(e){if(e.preventDefault(),e.stopPropagation(),this.isKeyStillDown=!1,this.autoCompleteState.showProvider&&this.autocompleteAPI){const e=this.autocompleteAPI.getValueToFill();if(e)return void this.autoComplete(e)}this.dispatch("STOP_EDITION"),this.dispatch("MOVE_POSITION",{deltaX:0,deltaY:e.shiftKey?-1:1})}processEscapeKey(){this.dispatch("STOP_EDITION",{cancel:!0})}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){let t=this.keyMapping[e.key];t?t.call(this,e):(e.stopPropagation(),this.updateCursorIfNeeded())}updateCursorIfNeeded(){if(!this.getters.isSelectingForComposer()){const{start:e,end:t}=this.contentHelper.getCurrentSelection();this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:e,end:t}),this.isKeyStillDown=!0}}onInput(){if("inactive"===this.props.focus||!this.shouldProcessInputEvents)return;this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const e=this.composerRef.el;this.dispatch("SET_CURRENT_CONTENT",{content:e.childNodes.length?e.textContent:"",selection:this.contentHelper.getCurrentSelection()})}onKeyup(e){if(this.isKeyStillDown=!1,"inactive"===this.props.focus||["Control","Shift","Tab","Enter"].includes(e.key))return;if(this.autoCompleteState.showProvider&&["ArrowUp","ArrowDown"].includes(e.key))return;if(this.getters.isSelectingForComposer()&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return;if(e.preventDefault(),e.stopPropagation(),this.autoCompleteState.showProvider=!1,e.ctrlKey&&" "===e.key)return this.autoCompleteState.search="",this.autoCompleteState.showProvider=!0,void this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const{start:t,end:s}=this.getters.getComposerSelection(),{start:o,end:i}=this.contentHelper.getCurrentSelection();o===t&&i===s||this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",this.contentHelper.getCurrentSelection()),this.processTokenAtCursor(),this.processContent()}onMousedown(e){e.button>0||this.contentHelper.removeSelection()}onClick(){if(this.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection();this.dispatch("STOP_COMPOSER_RANGE_SELECTION"),"inactive"===this.props.focus&&this.props.onComposerContentFocused(e),this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",e),this.processTokenAtCursor()}onBlur(){this.isKeyStillDown=!1}onCompleted(e){e&&this.autoComplete(e)}processContent(){if(this.compositionActive)return;this.contentHelper.removeAll(),this.shouldProcessInputEvents=!1,"inactive"!==this.props.focus&&this.contentHelper.selectRange(0,0);const e=this.getContent();if(0!==e.length){this.contentHelper.setText(e);const{start:t,end:s}=this.getters.getComposerSelection();"inactive"!==this.props.focus&&this.contentHelper.selectRange(t,s)}this.shouldProcessInputEvents=!0}getContent(){let e;const t=this.getters.getCurrentContent(),s=t.startsWith("=")&&this.getters.getCurrentTokens().length>0;return e=""===t?[]:s&&"inactive"!==this.getters.getEditionMode()?this.getColoredTokens():[{value:t}],e}getColoredTokens(){const e=this.getters.getCurrentTokens(),t=this.getters.getTokenAtCursor(),s=[],{end:o}=this.getters.getComposerSelection();for(const i of e){switch(i.type){case"OPERATOR":case"NUMBER":case"FUNCTION":case"COMMA":case"STRING":s.push({value:i.value,color:Jp[i.type]||"#000"});break;case"REFERENCE":const{xc:e,sheetName:o}=ts(i.value);s.push({value:i.value,color:this.rangeColor(e,o)||"#000"});break;case"SYMBOL":let n=i.value;["TRUE","FALSE"].includes(n.toUpperCase())?s.push({value:i.value,color:Kp}):s.push({value:i.value,color:"#000"});break;case"LEFT_PAREN":case"RIGHT_PAREN":t&&["LEFT_PAREN","RIGHT_PAREN"].includes(t.type)&&t.parenIndex&&t.parenIndex===i.parenIndex?s.push({value:i.value,color:"pink"}):s.push({value:i.value,color:Jp[i.type]||"#000"});break;default:s.push({value:i.value,color:"#000"})}"waitingForRangeSelection"===this.getters.getEditionMode()&&o===i.end&&(s[s.length-1].class=Qp)}return s}rangeColor(e,t){if("inactive"===this.getters.getEditionMode())return;const s=this.getters.getHighlights(),o=t?this.getters.getSheetIdByName(t):this.getters.getEditionSheet(),i=s.find((t=>{if(t.sheet!==o)return!1;let s=qs(e);const{height:i,width:n}=io(s);return s=i*n==1?this.getters.expandZone(o,qs(e)):s,t.sheet===o&&Js(s,t.zone)}));return i&&i.color?i.color:void 0}processTokenAtCursor(){let e=this.getters.getCurrentContent();if(this.autoCompleteState.showProvider=!1,this.functionDescriptionState.showDescription=!1,e.startsWith("=")){const e=this.getters.getTokenAtCursor();if(e){const{xc:t}=ts(e.value);if("FUNCTION"===e.type||"SYMBOL"===e.type&&!es.test(t))this.autoCompleteState.search=e.value,this.autoCompleteState.showProvider=!0;else if(e.functionContext&&"UNKNOWN"!==e.type){const t=e.functionContext,s=t.parent.toUpperCase(),o=jp[s],i=t.argPosition;this.functionDescriptionState.functionName=s,this.functionDescriptionState.functionDescription=o,this.functionDescriptionState.argToFocus=o.getArgToFocus(i+1)-1,this.functionDescriptionState.showDescription=!0}}}}autoComplete(e){if(e){const t=this.getters.getTokenAtCursor();if(t){let s=t.end,o=t.end;["SYMBOL","FUNCTION"].includes(t.type)&&(s=t.start);const i=this.getters.getCurrentTokens();if(this.autoCompleteState.provider&&i.length){e+="(";const s=i.map((e=>e.start)).indexOf(t.start);if(s+1<i.length){"LEFT_PAREN"===i[s+1].type&&o++}}this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:s,end:o})}this.dispatch("REPLACE_COMPOSER_CURSOR_SELECTION",{text:e})}this.processTokenAtCursor()}}sg.template=eg,sg.style=tg,sg.components={TextValueProvider:Lp,FunctionDescriptionProvider:Vp},sg.defaultProps={inputStyle:"",focus:"inactive"};const{useState:og,onMounted:ig}=t.hooks,{xml:ng,css:rg}=t.tags,ag=ng`
1929
+ `;class sg extends t.Component{constructor(){super(...arguments),this.composerRef=Bp("o_composer"),this.getters=this.env.getters,this.dispatch=this.env.dispatch,this.composerState=Hp({positionStart:0,positionEnd:0}),this.autoCompleteState=Hp({showProvider:!1,provider:"functions",search:""}),this.functionDescriptionState=Hp({showDescription:!1,functionName:"",functionDescription:{},argToFocus:0}),this.isKeyStillDown=!1,this.compositionActive=!1,this.borderStyle="box-shadow: 0 1px 4px 3px rgba(60, 64, 67, 0.15);",this.shouldProcessInputEvents=!1,this.tokens=[],this.keyMapping={ArrowUp:this.processArrowKeys,ArrowDown:this.processArrowKeys,ArrowLeft:this.processArrowKeys,ArrowRight:this.processArrowKeys,Enter:this.processEnterKey,Escape:this.processEscapeKey,F2:()=>console.warn("Not implemented"),F4:()=>console.warn("Not implemented"),Tab:e=>this.processTabKey(e)},this.contentHelper=new Mp(this.composerRef.el)}get assistantStyle(){if(this.props.delimitation&&this.props.rect){const[e,t,,s]=this.props.rect;let o="";return t>this.props.delimitation.height-(t+s)&&(o+="\n top: -8px;\n transform: translate(0, -100%);\n "),e+300>this.props.delimitation.width&&(o+="right:0px;"),o+="width:300px;"}return"width:300px;"}setup(){zp((()=>{Os.composer=this;const e=this.composerRef.el;this.contentHelper.updateEl(e),this.processContent()})),Gp((()=>{var e,t;delete Os.composer,null===(t=(e=this.props).onComposerUnmounted)||void 0===t||t.call(e)})),Zp((()=>{this.isKeyStillDown||this.processContent()}))}processArrowKeys(e){if(this.getters.isSelectingForComposer())return this.functionDescriptionState.showDescription=!1,void e.preventDefault();("cellFocus"!==this.props.focus||this.autoCompleteState.showProvider)&&(e.stopPropagation(),["ArrowUp","ArrowDown"].includes(e.key)&&this.autoCompleteState.showProvider&&this.autocompleteAPI&&(e.preventDefault(),"ArrowUp"===e.key?this.autocompleteAPI.moveUp():this.autocompleteAPI.moveDown()),this.updateCursorIfNeeded())}processTabKey(e){if(e.preventDefault(),e.stopPropagation(),this.autoCompleteState.showProvider&&this.autocompleteAPI){const e=this.autocompleteAPI.getValueToFill();if(e)return void this.autoComplete(e)}else this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=e.shiftKey?-1:1;this.dispatch("MOVE_POSITION",{deltaX:t,deltaY:0})}processEnterKey(e){if(e.preventDefault(),e.stopPropagation(),this.isKeyStillDown=!1,this.autoCompleteState.showProvider&&this.autocompleteAPI){const e=this.autocompleteAPI.getValueToFill();if(e)return void this.autoComplete(e)}this.dispatch("STOP_EDITION"),this.dispatch("MOVE_POSITION",{deltaX:0,deltaY:e.shiftKey?-1:1})}processEscapeKey(){this.dispatch("STOP_EDITION",{cancel:!0})}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){let t=this.keyMapping[e.key];t?t.call(this,e):(e.stopPropagation(),this.updateCursorIfNeeded())}updateCursorIfNeeded(){if(!this.getters.isSelectingForComposer()){const{start:e,end:t}=this.contentHelper.getCurrentSelection();this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:e,end:t}),this.isKeyStillDown=!0}}onInput(){if("inactive"===this.props.focus||!this.shouldProcessInputEvents)return;this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const e=this.composerRef.el;this.dispatch("SET_CURRENT_CONTENT",{content:e.childNodes.length?e.textContent:"",selection:this.contentHelper.getCurrentSelection()})}onKeyup(e){if(this.isKeyStillDown=!1,"inactive"===this.props.focus||["Control","Shift","Tab","Enter"].includes(e.key))return;if(this.autoCompleteState.showProvider&&["ArrowUp","ArrowDown"].includes(e.key))return;if(this.getters.isSelectingForComposer()&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return;if(e.preventDefault(),e.stopPropagation(),this.autoCompleteState.showProvider=!1,e.ctrlKey&&" "===e.key)return this.autoCompleteState.search="",this.autoCompleteState.showProvider=!0,void this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const{start:t,end:s}=this.getters.getComposerSelection(),{start:o,end:i}=this.contentHelper.getCurrentSelection();o===t&&i===s||this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",this.contentHelper.getCurrentSelection()),this.processTokenAtCursor(),this.processContent()}onMousedown(e){e.button>0||this.contentHelper.removeSelection()}onClick(){if(this.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection();this.dispatch("STOP_COMPOSER_RANGE_SELECTION"),"inactive"===this.props.focus&&this.props.onComposerContentFocused(e),this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",e),this.processTokenAtCursor()}onBlur(){this.isKeyStillDown=!1}onCompleted(e){e&&this.autoComplete(e)}processContent(){if(this.compositionActive)return;this.contentHelper.removeAll(),this.shouldProcessInputEvents=!1,"inactive"!==this.props.focus&&this.contentHelper.selectRange(0,0);const e=this.getContent();if(0!==e.length){this.contentHelper.setText(e);const{start:t,end:s}=this.getters.getComposerSelection();"inactive"!==this.props.focus&&this.contentHelper.selectRange(t,s)}this.shouldProcessInputEvents=!0}getContent(){let e;const t=this.getters.getCurrentContent(),s=t.startsWith("=")&&this.getters.getCurrentTokens().length>0;return e=""===t?[]:s&&"inactive"!==this.getters.getEditionMode()?this.getColoredTokens():[{value:t}],e}getColoredTokens(){const e=this.getters.getCurrentTokens(),t=this.getters.getTokenAtCursor(),s=[],{end:o}=this.getters.getComposerSelection();for(const i of e){switch(i.type){case"OPERATOR":case"NUMBER":case"FUNCTION":case"COMMA":case"STRING":s.push({value:i.value,color:Jp[i.type]||"#000"});break;case"REFERENCE":const{xc:e,sheetName:o}=ss(i.value);s.push({value:i.value,color:this.rangeColor(e,o)||"#000"});break;case"SYMBOL":let n=i.value;["TRUE","FALSE"].includes(n.toUpperCase())?s.push({value:i.value,color:Kp}):s.push({value:i.value,color:"#000"});break;case"LEFT_PAREN":case"RIGHT_PAREN":t&&["LEFT_PAREN","RIGHT_PAREN"].includes(t.type)&&t.parenIndex&&t.parenIndex===i.parenIndex?s.push({value:i.value,color:"pink"}):s.push({value:i.value,color:Jp[i.type]||"#000"});break;default:s.push({value:i.value,color:"#000"})}"waitingForRangeSelection"===this.getters.getEditionMode()&&o===i.end&&(s[s.length-1].class=Qp)}return s}rangeColor(e,t){if("inactive"===this.getters.getEditionMode())return;const s=this.getters.getHighlights(),o=t?this.getters.getSheetIdByName(t):this.getters.getEditionSheet(),i=s.find((t=>{if(t.sheet!==o)return!1;let s=qs(e);const{height:i,width:n}=io(s);return s=i*n==1?this.getters.expandZone(o,qs(e)):s,t.sheet===o&&Js(s,t.zone)}));return i&&i.color?i.color:void 0}processTokenAtCursor(){let e=this.getters.getCurrentContent();if(this.autoCompleteState.showProvider=!1,this.functionDescriptionState.showDescription=!1,e.startsWith("=")){const e=this.getters.getTokenAtCursor();if(e){const{xc:t}=ss(e.value);if("FUNCTION"===e.type||"SYMBOL"===e.type&&!ts.test(t))this.autoCompleteState.search=e.value,this.autoCompleteState.showProvider=!0;else if(e.functionContext&&"UNKNOWN"!==e.type){const t=e.functionContext,s=t.parent.toUpperCase(),o=jp[s],i=t.argPosition;this.functionDescriptionState.functionName=s,this.functionDescriptionState.functionDescription=o,this.functionDescriptionState.argToFocus=o.getArgToFocus(i+1)-1,this.functionDescriptionState.showDescription=!0}}}}autoComplete(e){if(e){const t=this.getters.getTokenAtCursor();if(t){let s=t.end,o=t.end;["SYMBOL","FUNCTION"].includes(t.type)&&(s=t.start);const i=this.getters.getCurrentTokens();if(this.autoCompleteState.provider&&i.length){e+="(";const s=i.map((e=>e.start)).indexOf(t.start);if(s+1<i.length){"LEFT_PAREN"===i[s+1].type&&o++}}this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:s,end:o})}this.dispatch("REPLACE_COMPOSER_CURSOR_SELECTION",{text:e})}this.processTokenAtCursor()}}sg.template=eg,sg.style=tg,sg.components={TextValueProvider:Lp,FunctionDescriptionProvider:Vp},sg.defaultProps={inputStyle:"",focus:"inactive"};const{useState:og,onMounted:ig}=t.hooks,{xml:ng,css:rg}=t.tags,ag=ng`
1930
1930
  <div class="o-grid-composer" t-att-style="containerStyle">
1931
1931
  <Composer
1932
1932
  focus = "props.focus"
@@ -1944,7 +1944,7 @@
1944
1944
  position: absolute;
1945
1945
  border: ${3*.4*window.devicePixelRatio||1}px solid ${p};
1946
1946
  }
1947
- `;class cg extends t.Component{constructor(){super(...arguments),this.getters=this.env.getters,this.composerState=og({rect:null,delimitation:null});const[e,t]=this.getters.getPosition();this.zone=this.getters.expandZone(this.getters.getActiveSheetId(),{left:e,right:e,top:t,bottom:t}),this.rect=this.getters.getRect(this.zone,this.getters.getActiveSnappedViewport())}setup(){ig((()=>{const e=this.el,t=e.parentElement.clientHeight-this.rect[1]-15;e.style.maxHeight=t+"px";const s=e.parentElement.clientWidth-this.rect[0]-14;e.style.maxWidth=s+"px",this.composerState.rect=[this.rect[0],this.rect[1],e.clientWidth,e.clientHeight],this.composerState.delimitation={width:e.parentElement.clientWidth,height:e.parentElement.clientHeight}}))}get containerStyle(){const e=this.getters.getCurrentContent().startsWith("="),t=this.getters.getCurrentStyle(),[s,o,i,n]=this.rect,r=!e&&t.fillColor||"#ffffff",a=!e&&t.textColor||"#000000",l=!e&&t.fontSize||10,c=!e&&t.bold?"bold":500,h=!e&&t.italic?"italic":"normal",d=e?"none":Gc(t);let u="left";if(!e){const e=this.getters.getActiveCell();u=t.align||(null==e?void 0:e.defaultAlign)||"left"}return`\n left: ${s-1}px;\n top: ${o}px;\n min-width: ${i+2}px;\n min-height: ${n+1}px;\n\n background: ${r};\n color: ${a};\n\n font-size: ${hs[l]}px;\n font-weight: ${c};\n font-style: ${h};\n text-decoration: ${d};\n\n text-align: ${u};\n `}get composerStyle(){return`\n line-height: ${S}px;\n max-height: inherit;\n overflow: hidden;\n `}}cg.template=ag,cg.style=lg,cg.components={Composer:sg};const{xml:hg,css:dg}=t.tags,ug=hg`
1947
+ `;class cg extends t.Component{constructor(){super(...arguments),this.getters=this.env.getters,this.composerState=og({rect:null,delimitation:null});const[e,t]=this.getters.getPosition();this.zone=this.getters.expandZone(this.getters.getActiveSheetId(),{left:e,right:e,top:t,bottom:t}),this.rect=this.getters.getRect(this.zone,this.getters.getActiveSnappedViewport())}setup(){ig((()=>{const e=this.el,t=e.parentElement.clientHeight-this.rect[1]-15;e.style.maxHeight=t+"px";const s=e.parentElement.clientWidth-this.rect[0]-14;e.style.maxWidth=s+"px",this.composerState.rect=[this.rect[0],this.rect[1],e.clientWidth,e.clientHeight],this.composerState.delimitation={width:e.parentElement.clientWidth,height:e.parentElement.clientHeight}}))}get containerStyle(){const e=this.getters.getCurrentContent().startsWith("="),t=this.getters.getCurrentStyle(),[s,o,i,n]=this.rect,r=!e&&t.fillColor||"#ffffff",a=!e&&t.textColor||"#000000",l=!e&&t.fontSize||10,c=!e&&t.bold?"bold":500,h=!e&&t.italic?"italic":"normal",d=e?"none":Gc(t);let u="left";if(!e){const e=this.getters.getActiveCell();u=t.align||(null==e?void 0:e.defaultAlign)||"left"}return`\n left: ${s-1}px;\n top: ${o}px;\n min-width: ${i+2}px;\n min-height: ${n+1}px;\n\n background: ${r};\n color: ${a};\n\n font-size: ${ds[l]}px;\n font-weight: ${c};\n font-style: ${h};\n text-decoration: ${d};\n\n text-align: ${u};\n `}get composerStyle(){return`\n line-height: ${S}px;\n max-height: inherit;\n overflow: hidden;\n `}}cg.template=ag,cg.style=lg,cg.components={Composer:sg};const{xml:hg,css:dg}=t.tags,ug=hg`
1948
1948
  <div class="o-error-tooltip">
1949
1949
  <t t-esc="props.text"/>
1950
1950
  </div>
@@ -2228,7 +2228,7 @@
2228
2228
  cursor: pointer;
2229
2229
  color: #000;
2230
2230
  }
2231
- `;class jg extends t.Component{constructor(){super(...arguments),this.getters=this.env.getters}get cell(){const{col:e,row:t}=this.props.cellPosition,s=this.getters.getActiveSheetId(),o=this.getters.getCell(s,e,t);if(null==o?void 0:o.isLink())return o;throw new Error(`LinkDisplay Component can only be used with link cells. ${is(e,t)} is not a link.`)}openLink(){this.cell.action(this.env)}edit(){this.env.openLinkEditor()}unlink(){const e=this.getters.getActiveSheetId(),[t,s]=this.getters.getPosition(),[o,i]=this.getters.getMainCell(e,t,s),n=this.cell.style,r=(null==n?void 0:n.textColor)===A||null==n?void 0:n.textColor;this.env.dispatch("UPDATE_CELL",{col:o,row:i,sheetId:e,content:this.cell.link.label,style:{...n,textColor:r,underline:void 0}})}}jg.template=Wg,jg.components={Menu:Ku},jg.style=qg;const{xml:Xg,css:Yg}=t.tags,{useRef:Kg,onMounted:Qg}=t.hooks,Jg=Xg`
2231
+ `;class jg extends t.Component{constructor(){super(...arguments),this.getters=this.env.getters}get cell(){const{col:e,row:t}=this.props.cellPosition,s=this.getters.getActiveSheetId(),o=this.getters.getCell(s,e,t);if(null==o?void 0:o.isLink())return o;throw new Error(`LinkDisplay Component can only be used with link cells. ${ns(e,t)} is not a link.`)}openLink(){this.cell.action(this.env)}edit(){this.env.openLinkEditor()}unlink(){const e=this.getters.getActiveSheetId(),[t,s]=this.getters.getPosition(),[o,i]=this.getters.getMainCell(e,t,s),n=this.cell.style,r=(null==n?void 0:n.textColor)===A||null==n?void 0:n.textColor;this.env.dispatch("UPDATE_CELL",{col:o,row:i,sheetId:e,content:this.cell.link.label,style:{...n,textColor:r,underline:void 0}})}}jg.template=Wg,jg.components={Menu:Ku},jg.style=qg;const{xml:Xg,css:Yg}=t.tags,{useRef:Kg,onMounted:Qg}=t.hooks,Jg=Xg`
2232
2232
  <div class="o-link-editor" t-on-click.stop="menu.isOpen=false" t-on-keydown.stop="onKeyDown">
2233
2233
  <div class="o-section">
2234
2234
  <div t-esc="env._t('${_c}')" class="o-section-title"/>
@@ -2623,7 +2623,7 @@
2623
2623
  }
2624
2624
  }
2625
2625
  }
2626
- `;class wf extends t.Component{constructor(){super(...arguments),this.menuState=mf({isOpen:!1,position:null,menuItems:[]}),this.vScrollbarRef=pf("vscrollbar"),this.hScrollbarRef=pf("hscrollbar"),this.canvas=pf("canvas"),this.hiddenInput=pf("hiddenInput"),this.getters=this.env.getters,this.dispatch=this.env.dispatch,this.currentSheet=this.getters.getActiveSheetId(),this.clickedCol=0,this.clickedRow=0,this.clipBoardString="",this.hoveredCell=Sf(this.env,(()=>this.getters.getActiveSnappedViewport())),this.keyDownMapping={ENTER:()=>{const e=this.getters.getActiveCell();!e||e.isEmpty()?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},TAB:()=>this.dispatch("MOVE_POSITION",{deltaX:1,deltaY:0}),"SHIFT+TAB":()=>this.dispatch("MOVE_POSITION",{deltaX:-1,deltaY:0}),F2:()=>{const e=this.getters.getActiveCell();!e||e.isEmpty()?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},DELETE:()=>{this.dispatch("DELETE_CONTENT",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones()})},"CTRL+A":()=>this.dispatch("SELECT_ALL"),"CTRL+S":()=>{this.trigger("save-requested")},"CTRL+Z":()=>this.dispatch("REQUEST_UNDO"),"CTRL+Y":()=>this.dispatch("REQUEST_REDO"),"CTRL+B":()=>this.dispatch("SET_FORMATTING",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),style:{bold:!this.getters.getCurrentStyle().bold}}),"CTRL+I":()=>this.dispatch("SET_FORMATTING",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),style:{italic:!this.getters.getCurrentStyle().italic}}),"CTRL+U":()=>this.dispatch("SET_FORMATTING",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),style:{underline:!this.getters.getCurrentStyle().underline}}),"ALT+=":()=>{var e;const t=this.getters.getActiveSheetId(),s=this.getters.getSelectedZone(),o=this.getters.getAutomaticSums(t,s,this.getters.getPosition());if(this.getters.isSingleCellOrMerge(t,s)||this.getters.isEmpty(t,s)&&o.length<=1){const s=(null===(e=o[0])||void 0===e?void 0:e.zone)?this.getters.zoneToXC(t,o[0].zone):"",i=`=SUM(${s})`;this.props.onGridComposerCellFocused(i,{start:5,end:5+s.length})}else this.dispatch("SUM_SELECTION")},"CTRL+HOME":()=>{const e=this.getters.getActiveSheet(),[t,s]=zs(e,0,0);this.dispatch("SELECT_CELL",{col:t,row:s})},"CTRL+END":()=>{const e=this.getters.getActiveSheet(),t=Zs(e,"cols",Es(0,e.cols.length).reverse()),s=Zs(e,"rows",Es(0,e.rows.length).reverse());this.dispatch("SELECT_CELL",{col:t,row:s})},"SHIFT+ ":()=>{const{cols:e}=this.getters.getActiveSheet(),t={...this.getters.getSelectedZone(),left:0,right:e.length-1};this.dispatch("SET_SELECTION",{anchor:this.getters.getPosition(),zones:[t],anchorZone:t})},"CTRL+ ":()=>{const{rows:e}=this.getters.getActiveSheet(),t={...this.getters.getSelectedZone(),top:0,bottom:e.length-1};this.dispatch("SET_SELECTION",{anchor:this.getters.getPosition(),zones:[t],anchorZone:t})},"CTRL+SHIFT+ ":()=>{this.dispatch("SELECT_ALL")},"SHIFT+PAGEDOWN":()=>{this.dispatch("ACTIVATE_NEXT_SHEET")},"SHIFT+PAGEUP":()=>{this.dispatch("ACTIVATE_PREVIOUS_SHEET")},PAGEDOWN:()=>this.dispatch("SHIFT_VIEWPORT_DOWN"),PAGEUP:()=>this.dispatch("SHIFT_VIEWPORT_UP")},this.vScrollbar=new hf(this.vScrollbarRef.el,"vertical"),this.hScrollbar=new hf(this.hScrollbarRef.el,"horizontal")}setup(){Ef(document.body,"cut",this.copy.bind(this,!0)),Ef(document.body,"copy",this.copy.bind(this,!1)),Ef(document.body,"paste",this.paste),function(e,t){const s=pf("canvas");let o=null,i=null;function n(e){1===e.touches.length&&(o=e.touches[0].clientX,i=e.touches[0].clientY)}function r(){o=null,i=null}function a(s){if(1!==s.touches.length)return;t()&&(s.preventDefault(),s.stopPropagation());const n=s.touches[0].clientX,r=s.touches[0].clientY;e(o-n,i-r),o=n,i=r}gf((()=>{s.el.addEventListener("touchstart",n),s.el.addEventListener("touchend",r),s.el.addEventListener("touchmove",a)})),ff((()=>{s.el.removeEventListener("touchstart",n),s.el.removeEventListener("touchend",r),s.el.removeEventListener("touchmove",a)}))}(this.moveCanvas.bind(this),(()=>this.vScrollbar.scroll>0)),gf((()=>this.initGrid())),vf((()=>{this.drawGrid(),this.resizeGrid()})),this.props.exposeFocus((()=>this.focus()))}initGrid(){this.vScrollbar.el=this.vScrollbarRef.el,this.hScrollbar.el=this.hScrollbarRef.el,this.focus(),this.resizeGrid(),this.drawGrid()}get errorTooltip(){const{col:e,row:t}=this.hoveredCell;if(void 0===e||void 0===t)return{isOpen:!1};const s=this.getters.getActiveSheetId(),[o,i]=this.getters.getMainCell(s,e,t),n=this.getters.getCell(s,o,i);if(n&&n.evaluated.type===Fe.error){const s=this.getters.getActiveSnappedViewport(),[o,i,r]=this.getters.getRect({left:e,top:t,right:e,bottom:t},s);return{isOpen:!0,position:{x:o+r,y:i+E},text:n.evaluated.error,cellWidth:r}}return{isOpen:!1}}get activeCellPosition(){const[e,t]=this.getters.getMainCell(this.getters.getActiveSheetId(),...this.getters.getPosition());return{col:e,row:t}}get shouldDisplayLink(){const e=this.getters.getActiveSheetId(),{col:t,row:s}=this.activeCellPosition,o=this.getters.getActiveSnappedViewport(),i=this.getters.getCell(e,t,s);return this.getters.isVisibleInViewport(t,s,o)&&!!i&&i.isLink()&&!this.menuState.isOpen&&!this.props.linkEditorIsOpen&&!this.props.sidePanelIsOpen}get popoverPosition(){const[e,t]=this.getters.getBottomLeftCell(this.getters.getActiveSheetId(),...this.getters.getPosition()),s=this.getters.getActiveSnappedViewport(),[o,i,n,r]=this.getters.getRect({left:e,top:t,right:e,bottom:t},s);return{position:{x:o,y:i+r+E},cellWidth:n,cellHeight:r}}focus(){this.getters.isSelectingForComposer()||this.getters.getSelectedFigureId()||this.hiddenInput.el.focus()}resizeGrid(){const e=this.el.clientHeight-C,t=this.el.clientWidth-C,{height:s,width:o}=this.getters.getViewportDimensionWithHeaders();e==s&&t===o||this.dispatch("RESIZE_VIEWPORT",{height:e-m,width:t-v})}onScroll(){const{offsetX:e,offsetY:t}=this.getters.getActiveViewport();if(e!==this.hScrollbar.scroll||t!==this.vScrollbar.scroll){const{maxOffsetX:e,maxOffsetY:t}=this.getters.getMaximumViewportOffset(this.getters.getActiveSheet());this.dispatch("SET_VIEWPORT_OFFSET",{offsetX:Math.min(this.hScrollbar.scroll,e),offsetY:Math.min(this.vScrollbar.scroll,t)})}}checkSheetChanges(){const e=this.getters.getActiveSheetId();e!==this.currentSheet&&(this.focus(),this.currentSheet=e)}getAutofillPosition(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheet(),{offsetX:s,offsetY:o}=this.getters.getActiveSnappedViewport();return{left:t.cols[e.right].end-4+v-s,top:t.rows[e.bottom].end-4+m-o}}drawGrid(){const{offsetX:e,offsetY:t}=this.getters.getActiveViewport();this.hScrollbar.scroll=e,this.vScrollbar.scroll=t,this.checkSheetChanges();const s=this.canvas.el,o=window.devicePixelRatio||1,i=s.getContext("2d",{alpha:!1}),n=.4*o,r={ctx:i,viewport:this.getters.getActiveViewport(),dpr:o,thinLineWidth:n},{width:a,height:l}=this.getters.getViewportDimensionWithHeaders();s.style.width=`${a}px`,s.style.height=`${l}px`,s.width=a*o,s.height=l*o,s.setAttribute("style",`width:${a}px;height:${l}px;`),i.translate(-.5,-.5),i.scale(o,o),this.props.model.drawGrid(r)}moveCanvas(e,t){this.vScrollbar.scroll=this.vScrollbar.scroll+t,this.hScrollbar.scroll=this.hScrollbar.scroll+e,this.dispatch("SET_VIEWPORT_OFFSET",{offsetX:this.hScrollbar.scroll,offsetY:this.vScrollbar.scroll})}getClientPositionKey(e){var t,s,o;return`${e.id}-${null===(t=e.position)||void 0===t?void 0:t.sheetId}-${null===(s=e.position)||void 0===s?void 0:s.col}-${null===(o=e.position)||void 0===o?void 0:o.row}`}onMouseWheel(e){if(e.ctrlKey)return;function t(t){return t*(0===e.deltaMode?1:S)}const s=e.shiftKey?e.deltaY:e.deltaX,o=e.shiftKey?e.deltaX:e.deltaY;this.moveCanvas(t(s),t(o))}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}getCoordinates(e){const t=this.el.getBoundingClientRect();return[e.pageX-t.left,e.pageY-t.top]}getCartesianCoordinates(e){const[t,s]=this.getCoordinates(e),{left:o,top:i}=this.getters.getActiveSnappedViewport();return[this.getters.getColIndex(t,o),this.getters.getRowIndex(s,i)]}onMouseDown(e){if(e.button>0)return;const[t,s]=this.getCartesianCoordinates(e);if(t<0||s<0)return;this.clickedCol=t,this.clickedRow=s;const o=this.getters.getActiveSheetId(),[i,n]=this.getters.getMainCell(o,t,s),r=this.getters.getCell(o,i,n);(null==r?void 0:r.isLink())||this.closeLinkEditor(),this.dispatch(e.ctrlKey?"START_SELECTION_EXPANSION":"START_SELECTION"),e.shiftKey?this.dispatch("ALTER_SELECTION",{cell:[t,s]}):(this.dispatch("SELECT_CELL",{col:t,row:s}),this.checkSheetChanges());let a,l=t,c=s,h=!1,d=null,u=0;const p=this.getters.getActiveSheet(),g=e=>{if(a=e,d)return;const[t,s]=this.getCoordinates(a);h=!1,u=0;const o=this.getters.getEdgeScrollCol(t),i=this.getters.getEdgeScrollRow(s),{left:n,right:r,top:f,bottom:m}=this.getters.getActiveSnappedViewport();let v,E;if(o.canEdgeScroll?v=o.direction>0?r:n-1:(v=this.getters.getColIndex(t,n),v=-1===v?l:v),i.canEdgeScroll?E=i.direction>0?m:f-1:(E=this.getters.getRowIndex(s,f),E=-1===E?c:E),h=o.canEdgeScroll||i.canEdgeScroll,u=Math.min(o.canEdgeScroll?o.delay:ns,i.canEdgeScroll?i.delay:ns),v===l&&E===c||(l=v,c=E,this.dispatch("ALTER_SELECTION",{cell:[v,E]})),h){const e=p.cols[n+o.direction].start,t=p.rows[f+i.direction].start;this.dispatch("SET_VIEWPORT_OFFSET",{offsetX:e,offsetY:t}),d=setTimeout((()=>{d=null,g(a)}),Math.round(u))}};rp(g,(e=>{clearTimeout(d),this.dispatch(e.ctrlKey?"PREPARE_SELECTION_EXPANSION":"STOP_SELECTION"),this.canvas.el.removeEventListener("mousemove",g),this.getters.isPaintingFormat()&&this.dispatch("PASTE",{target:this.getters.getSelectedZones()})}))}onDoubleClick(e){const[t,s]=this.getCartesianCoordinates(e);if(this.clickedCol===t&&this.clickedRow===s){const e=this.getters.getActiveCell();!e||e.isEmpty()?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()}}closeLinkEditor(){this.props.onLinkEditorClosed()}processTabKey(e){e.preventDefault();const t=e.shiftKey?-1:1;this.dispatch("MOVE_POSITION",{deltaX:t,deltaY:0})}processArrows(e){e.preventDefault(),e.stopPropagation(),this.closeLinkEditor();const t={ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1]}[e.key];if(e.shiftKey){const e=this.getters.getSelectedZone();this.dispatch("ALTER_SELECTION",{delta:t});const s=this.getters.getSelectedZone(),o=this.getters.getActiveSnappedViewport(),i=this.getters.getActiveSheet(),[n,r]=function(e,t,s){let o,i;const{left:n,right:r,top:a,bottom:l}=e,{left:c,right:h,top:d,bottom:u}=t;return o=c!=n?c:h!=r?h:s.left,i=d!=a?d:u!=l?u:s.top,[o,i]}(e,s,o),{left:a,right:l,top:c,bottom:h,offsetX:d,offsetY:u}=o,p=n<a||n>l-1?i.cols[a+t[0]].start:d,g=r<c||r>h-1?i.rows[c+t[1]].start:u;p===d&&g===u||this.dispatch("SET_VIEWPORT_OFFSET",{offsetX:p,offsetY:g})}else this.dispatch("MOVE_POSITION",{deltaX:t[0],deltaY:t[1]});this.getters.isPaintingFormat()&&this.dispatch("PASTE",{target:this.getters.getSelectedZones()})}onInput(e){(e.isComposing||"insertFromPaste"!==e.inputType)&&e.data&&(e.preventDefault(),e.stopPropagation(),this.props.onGridComposerCellFocused(e.data))}onKeydown(e){if(e.key.startsWith("Arrow"))return void this.processArrows(e);let t="";e.ctrlKey&&(t+="CTRL+"),e.metaKey&&(t+="CTRL+"),e.altKey&&(t+="ALT+"),e.shiftKey&&(t+="SHIFT+"),t+=e.key.toUpperCase();let s=this.keyDownMapping[t];return s?(e.preventDefault(),e.stopPropagation(),void s()):void 0}onInputContextMenu(e){e.preventDefault();const t=this.getters.getSelectedZone(),{left:s,top:o}=t;let i="CELL";this.dispatch("STOP_EDITION"),this.getters.getActiveCols().has(s)?i="COL":this.getters.getActiveRows().has(o)&&(i="ROW");const[n,r,a,l]=this.getters.getRect(t,this.getters.getActiveSnappedViewport());this.toggleContextMenu(i,n+a,r+l)}onCanvasContextMenu(e){e.preventDefault();const[t,s]=this.getCartesianCoordinates(e);if(t<0||s<0)return;const o=this.getters.getSelectedZones();let i="CELL";to(t,s,o[o.length-1])?this.getters.getActiveCols().has(t)?i="COL":this.getters.getActiveRows().has(s)&&(i="ROW"):(this.dispatch("STOP_EDITION"),this.dispatch("SELECT_CELL",{col:t,row:s})),this.toggleContextMenu(i,e.offsetX,e.offsetY)}toggleContextMenu(e,t,s){this.closeLinkEditor(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:s+E},this.menuState.menuItems=bf[e].getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}copy(e,t){if(!this.el.contains(document.activeElement))return;if("inactive"!==this.getters.getEditionMode())return;const s=e?"CUT":"COPY",o=this.getters.getSelectedZones();this.dispatch(s,{target:o});const i=this.getters.getClipboardContent();this.clipBoardString=i,t.clipboardData.setData("text/plain",i),t.preventDefault()}paste(e){if(!this.el.contains(document.activeElement))return;const t=e.clipboardData;if(t.types.indexOf("text/plain")>-1){const e=t.getData("text/plain"),s=this.getters.getSelectedZones();this.clipBoardString===e?Ba(this.env,s):this.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:s,text:e})}}closeMenu(){this.menuState.isOpen=!1,this.focus()}}wf.template=Cf,wf.style=yf,wf.components={GridComposer:cg,Overlay:cf,Menu:Ku,Autofill:pp,FiguresContainer:Ag,ClientTag:bp,Highlight:zg,ErrorToolTip:gg,LinkDisplay:jg,LinkEditor:tf,Popover:zu};const{xml:If,css:xf}=t.tags,{useState:Tf,onWillUpdateProps:Rf}=t.hooks,Lf=If`
2626
+ `;class wf extends t.Component{constructor(){super(...arguments),this.menuState=mf({isOpen:!1,position:null,menuItems:[]}),this.vScrollbarRef=pf("vscrollbar"),this.hScrollbarRef=pf("hscrollbar"),this.canvas=pf("canvas"),this.hiddenInput=pf("hiddenInput"),this.getters=this.env.getters,this.dispatch=this.env.dispatch,this.currentSheet=this.getters.getActiveSheetId(),this.clickedCol=0,this.clickedRow=0,this.clipBoardString="",this.hoveredCell=Sf(this.env,(()=>this.getters.getActiveSnappedViewport())),this.keyDownMapping={ENTER:()=>{const e=this.getters.getActiveCell();!e||e.isEmpty()?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},TAB:()=>this.dispatch("MOVE_POSITION",{deltaX:1,deltaY:0}),"SHIFT+TAB":()=>this.dispatch("MOVE_POSITION",{deltaX:-1,deltaY:0}),F2:()=>{const e=this.getters.getActiveCell();!e||e.isEmpty()?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},DELETE:()=>{this.dispatch("DELETE_CONTENT",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones()})},"CTRL+A":()=>this.dispatch("SELECT_ALL"),"CTRL+S":()=>{this.trigger("save-requested")},"CTRL+Z":()=>this.dispatch("REQUEST_UNDO"),"CTRL+Y":()=>this.dispatch("REQUEST_REDO"),"CTRL+B":()=>this.dispatch("SET_FORMATTING",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),style:{bold:!this.getters.getCurrentStyle().bold}}),"CTRL+I":()=>this.dispatch("SET_FORMATTING",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),style:{italic:!this.getters.getCurrentStyle().italic}}),"CTRL+U":()=>this.dispatch("SET_FORMATTING",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),style:{underline:!this.getters.getCurrentStyle().underline}}),"ALT+=":()=>{var e;const t=this.getters.getActiveSheetId(),s=this.getters.getSelectedZone(),o=this.getters.getAutomaticSums(t,s,this.getters.getPosition());if(this.getters.isSingleCellOrMerge(t,s)||this.getters.isEmpty(t,s)&&o.length<=1){const s=(null===(e=o[0])||void 0===e?void 0:e.zone)?this.getters.zoneToXC(t,o[0].zone):"",i=`=SUM(${s})`;this.props.onGridComposerCellFocused(i,{start:5,end:5+s.length})}else this.dispatch("SUM_SELECTION")},"CTRL+HOME":()=>{const e=this.getters.getActiveSheet(),[t,s]=zs(e,0,0);this.dispatch("SELECT_CELL",{col:t,row:s})},"CTRL+END":()=>{const e=this.getters.getActiveSheet(),t=Zs(e,"cols",Es(0,e.cols.length).reverse()),s=Zs(e,"rows",Es(0,e.rows.length).reverse());this.dispatch("SELECT_CELL",{col:t,row:s})},"SHIFT+ ":()=>{const{cols:e}=this.getters.getActiveSheet(),t={...this.getters.getSelectedZone(),left:0,right:e.length-1};this.dispatch("SET_SELECTION",{anchor:this.getters.getPosition(),zones:[t],anchorZone:t})},"CTRL+ ":()=>{const{rows:e}=this.getters.getActiveSheet(),t={...this.getters.getSelectedZone(),top:0,bottom:e.length-1};this.dispatch("SET_SELECTION",{anchor:this.getters.getPosition(),zones:[t],anchorZone:t})},"CTRL+SHIFT+ ":()=>{this.dispatch("SELECT_ALL")},"SHIFT+PAGEDOWN":()=>{this.dispatch("ACTIVATE_NEXT_SHEET")},"SHIFT+PAGEUP":()=>{this.dispatch("ACTIVATE_PREVIOUS_SHEET")},PAGEDOWN:()=>this.dispatch("SHIFT_VIEWPORT_DOWN"),PAGEUP:()=>this.dispatch("SHIFT_VIEWPORT_UP")},this.vScrollbar=new hf(this.vScrollbarRef.el,"vertical"),this.hScrollbar=new hf(this.hScrollbarRef.el,"horizontal")}setup(){Ef(document.body,"cut",this.copy.bind(this,!0)),Ef(document.body,"copy",this.copy.bind(this,!1)),Ef(document.body,"paste",this.paste),function(e,t){const s=pf("canvas");let o=null,i=null;function n(e){1===e.touches.length&&(o=e.touches[0].clientX,i=e.touches[0].clientY)}function r(){o=null,i=null}function a(s){if(1!==s.touches.length)return;t()&&(s.preventDefault(),s.stopPropagation());const n=s.touches[0].clientX,r=s.touches[0].clientY;e(o-n,i-r),o=n,i=r}gf((()=>{s.el.addEventListener("touchstart",n),s.el.addEventListener("touchend",r),s.el.addEventListener("touchmove",a)})),ff((()=>{s.el.removeEventListener("touchstart",n),s.el.removeEventListener("touchend",r),s.el.removeEventListener("touchmove",a)}))}(this.moveCanvas.bind(this),(()=>this.vScrollbar.scroll>0)),gf((()=>this.initGrid())),vf((()=>{this.drawGrid(),this.resizeGrid()})),this.props.exposeFocus((()=>this.focus()))}initGrid(){this.vScrollbar.el=this.vScrollbarRef.el,this.hScrollbar.el=this.hScrollbarRef.el,this.focus(),this.resizeGrid(),this.drawGrid()}get errorTooltip(){const{col:e,row:t}=this.hoveredCell;if(void 0===e||void 0===t)return{isOpen:!1};const s=this.getters.getActiveSheetId(),[o,i]=this.getters.getMainCell(s,e,t),n=this.getters.getCell(s,o,i);if(n&&n.evaluated.type===$e.error){const s=this.getters.getActiveSnappedViewport(),[o,i,r]=this.getters.getRect({left:e,top:t,right:e,bottom:t},s);return{isOpen:!0,position:{x:o+r,y:i+E},text:n.evaluated.error,cellWidth:r}}return{isOpen:!1}}get activeCellPosition(){const[e,t]=this.getters.getMainCell(this.getters.getActiveSheetId(),...this.getters.getPosition());return{col:e,row:t}}get shouldDisplayLink(){const e=this.getters.getActiveSheetId(),{col:t,row:s}=this.activeCellPosition,o=this.getters.getActiveSnappedViewport(),i=this.getters.getCell(e,t,s);return this.getters.isVisibleInViewport(t,s,o)&&!!i&&i.isLink()&&!this.menuState.isOpen&&!this.props.linkEditorIsOpen&&!this.props.sidePanelIsOpen}get popoverPosition(){const[e,t]=this.getters.getBottomLeftCell(this.getters.getActiveSheetId(),...this.getters.getPosition()),s=this.getters.getActiveSnappedViewport(),[o,i,n,r]=this.getters.getRect({left:e,top:t,right:e,bottom:t},s);return{position:{x:o,y:i+r+E},cellWidth:n,cellHeight:r}}focus(){this.getters.isSelectingForComposer()||this.getters.getSelectedFigureId()||this.hiddenInput.el.focus()}resizeGrid(){const e=this.el.clientHeight-C,t=this.el.clientWidth-C,{height:s,width:o}=this.getters.getViewportDimensionWithHeaders();e==s&&t===o||this.dispatch("RESIZE_VIEWPORT",{height:e-m,width:t-v})}onScroll(){const{offsetX:e,offsetY:t}=this.getters.getActiveViewport();if(e!==this.hScrollbar.scroll||t!==this.vScrollbar.scroll){const{maxOffsetX:e,maxOffsetY:t}=this.getters.getMaximumViewportOffset(this.getters.getActiveSheet());this.dispatch("SET_VIEWPORT_OFFSET",{offsetX:Math.min(this.hScrollbar.scroll,e),offsetY:Math.min(this.vScrollbar.scroll,t)})}}checkSheetChanges(){const e=this.getters.getActiveSheetId();e!==this.currentSheet&&(this.focus(),this.currentSheet=e)}getAutofillPosition(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheet(),{offsetX:s,offsetY:o}=this.getters.getActiveSnappedViewport();return{left:t.cols[e.right].end-4+v-s,top:t.rows[e.bottom].end-4+m-o}}drawGrid(){const{offsetX:e,offsetY:t}=this.getters.getActiveViewport();this.hScrollbar.scroll=e,this.vScrollbar.scroll=t,this.checkSheetChanges();const s=this.canvas.el,o=window.devicePixelRatio||1,i=s.getContext("2d",{alpha:!1}),n=.4*o,r={ctx:i,viewport:this.getters.getActiveViewport(),dpr:o,thinLineWidth:n},{width:a,height:l}=this.getters.getViewportDimensionWithHeaders();s.style.width=`${a}px`,s.style.height=`${l}px`,s.width=a*o,s.height=l*o,s.setAttribute("style",`width:${a}px;height:${l}px;`),i.translate(-.5,-.5),i.scale(o,o),this.props.model.drawGrid(r)}moveCanvas(e,t){this.vScrollbar.scroll=this.vScrollbar.scroll+t,this.hScrollbar.scroll=this.hScrollbar.scroll+e,this.dispatch("SET_VIEWPORT_OFFSET",{offsetX:this.hScrollbar.scroll,offsetY:this.vScrollbar.scroll})}getClientPositionKey(e){var t,s,o;return`${e.id}-${null===(t=e.position)||void 0===t?void 0:t.sheetId}-${null===(s=e.position)||void 0===s?void 0:s.col}-${null===(o=e.position)||void 0===o?void 0:o.row}`}onMouseWheel(e){if(e.ctrlKey)return;function t(t){return t*(0===e.deltaMode?1:S)}const s=e.shiftKey?e.deltaY:e.deltaX,o=e.shiftKey?e.deltaX:e.deltaY;this.moveCanvas(t(s),t(o))}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}getCoordinates(e){const t=this.el.getBoundingClientRect();return[e.pageX-t.left,e.pageY-t.top]}getCartesianCoordinates(e){const[t,s]=this.getCoordinates(e),{left:o,top:i}=this.getters.getActiveSnappedViewport();return[this.getters.getColIndex(t,o),this.getters.getRowIndex(s,i)]}onMouseDown(e){if(e.button>0)return;const[t,s]=this.getCartesianCoordinates(e);if(t<0||s<0)return;this.clickedCol=t,this.clickedRow=s;const o=this.getters.getActiveSheetId(),[i,n]=this.getters.getMainCell(o,t,s),r=this.getters.getCell(o,i,n);(null==r?void 0:r.isLink())||this.closeLinkEditor(),this.dispatch(e.ctrlKey?"START_SELECTION_EXPANSION":"START_SELECTION"),e.shiftKey?this.dispatch("ALTER_SELECTION",{cell:[t,s]}):(this.dispatch("SELECT_CELL",{col:t,row:s}),this.checkSheetChanges());let a,l=t,c=s,h=!1,d=null,u=0;const p=this.getters.getActiveSheet(),g=e=>{if(a=e,d)return;const[t,s]=this.getCoordinates(a);h=!1,u=0;const o=this.getters.getEdgeScrollCol(t),i=this.getters.getEdgeScrollRow(s),{left:n,right:r,top:f,bottom:m}=this.getters.getActiveSnappedViewport();let v,E;if(o.canEdgeScroll?v=o.direction>0?r:n-1:(v=this.getters.getColIndex(t,n),v=-1===v?l:v),i.canEdgeScroll?E=i.direction>0?m:f-1:(E=this.getters.getRowIndex(s,f),E=-1===E?c:E),h=o.canEdgeScroll||i.canEdgeScroll,u=Math.min(o.canEdgeScroll?o.delay:rs,i.canEdgeScroll?i.delay:rs),v===l&&E===c||(l=v,c=E,this.dispatch("ALTER_SELECTION",{cell:[v,E]})),h){const e=p.cols[n+o.direction].start,t=p.rows[f+i.direction].start;this.dispatch("SET_VIEWPORT_OFFSET",{offsetX:e,offsetY:t}),d=setTimeout((()=>{d=null,g(a)}),Math.round(u))}};rp(g,(e=>{clearTimeout(d),this.dispatch(e.ctrlKey?"PREPARE_SELECTION_EXPANSION":"STOP_SELECTION"),this.canvas.el.removeEventListener("mousemove",g),this.getters.isPaintingFormat()&&this.dispatch("PASTE",{target:this.getters.getSelectedZones()})}))}onDoubleClick(e){const[t,s]=this.getCartesianCoordinates(e);if(this.clickedCol===t&&this.clickedRow===s){const e=this.getters.getActiveCell();!e||e.isEmpty()?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()}}closeLinkEditor(){this.props.onLinkEditorClosed()}processTabKey(e){e.preventDefault();const t=e.shiftKey?-1:1;this.dispatch("MOVE_POSITION",{deltaX:t,deltaY:0})}processArrows(e){e.preventDefault(),e.stopPropagation(),this.closeLinkEditor();const t={ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1]}[e.key];if(e.shiftKey){const e=this.getters.getSelectedZone();this.dispatch("ALTER_SELECTION",{delta:t});const s=this.getters.getSelectedZone(),o=this.getters.getActiveSnappedViewport(),i=this.getters.getActiveSheet(),[n,r]=function(e,t,s){let o,i;const{left:n,right:r,top:a,bottom:l}=e,{left:c,right:h,top:d,bottom:u}=t;return o=c!=n?c:h!=r?h:s.left,i=d!=a?d:u!=l?u:s.top,[o,i]}(e,s,o),{left:a,right:l,top:c,bottom:h,offsetX:d,offsetY:u}=o,p=n<a||n>l-1?i.cols[a+t[0]].start:d,g=r<c||r>h-1?i.rows[c+t[1]].start:u;p===d&&g===u||this.dispatch("SET_VIEWPORT_OFFSET",{offsetX:p,offsetY:g})}else this.dispatch("MOVE_POSITION",{deltaX:t[0],deltaY:t[1]});this.getters.isPaintingFormat()&&this.dispatch("PASTE",{target:this.getters.getSelectedZones()})}onInput(e){(e.isComposing||"insertFromPaste"!==e.inputType)&&e.data&&(e.preventDefault(),e.stopPropagation(),this.props.onGridComposerCellFocused(e.data))}onKeydown(e){if(e.key.startsWith("Arrow"))return void this.processArrows(e);let t="";e.ctrlKey&&(t+="CTRL+"),e.metaKey&&(t+="CTRL+"),e.altKey&&(t+="ALT+"),e.shiftKey&&(t+="SHIFT+"),t+=e.key.toUpperCase();let s=this.keyDownMapping[t];return s?(e.preventDefault(),e.stopPropagation(),void s()):void 0}onInputContextMenu(e){e.preventDefault();const t=this.getters.getSelectedZone(),{left:s,top:o}=t;let i="CELL";this.dispatch("STOP_EDITION"),this.getters.getActiveCols().has(s)?i="COL":this.getters.getActiveRows().has(o)&&(i="ROW");const[n,r,a,l]=this.getters.getRect(t,this.getters.getActiveSnappedViewport());this.toggleContextMenu(i,n+a,r+l)}onCanvasContextMenu(e){e.preventDefault();const[t,s]=this.getCartesianCoordinates(e);if(t<0||s<0)return;const o=this.getters.getSelectedZones();let i="CELL";to(t,s,o[o.length-1])?this.getters.getActiveCols().has(t)?i="COL":this.getters.getActiveRows().has(s)&&(i="ROW"):(this.dispatch("STOP_EDITION"),this.dispatch("SELECT_CELL",{col:t,row:s})),this.toggleContextMenu(i,e.offsetX,e.offsetY)}toggleContextMenu(e,t,s){this.closeLinkEditor(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:s+E},this.menuState.menuItems=bf[e].getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}copy(e,t){if(!this.el.contains(document.activeElement))return;if("inactive"!==this.getters.getEditionMode())return;const s=e?"CUT":"COPY",o=this.getters.getSelectedZones();this.dispatch(s,{target:o});const i=this.getters.getClipboardContent();this.clipBoardString=i,t.clipboardData.setData("text/plain",i),t.preventDefault()}paste(e){if(!this.el.contains(document.activeElement))return;const t=e.clipboardData;if(t.types.indexOf("text/plain")>-1){const e=t.getData("text/plain"),s=this.getters.getSelectedZones();this.clipBoardString===e?Ba(this.env,s):this.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:s,text:e})}}closeMenu(){this.menuState.isOpen=!1,this.focus()}}wf.template=Cf,wf.style=yf,wf.components={GridComposer:cg,Overlay:cf,Menu:Ku,Autofill:pp,FiguresContainer:Ag,ClientTag:bp,Highlight:zg,ErrorToolTip:gg,LinkDisplay:jg,LinkEditor:tf,Popover:zu};const{xml:If,css:xf}=t.tags,{useState:Tf,onWillUpdateProps:Rf}=t.hooks,Lf=If`
2627
2627
  <div class="o-sidePanel" >
2628
2628
  <div class="o-sidePanelHeader">
2629
2629
  <div class="o-sidePanelTitle" t-esc="getTitle()"/>
@@ -2734,7 +2734,7 @@
2734
2734
  text-align: left;
2735
2735
  }
2736
2736
  }
2737
- `;class Af extends t.Component{constructor(){super(...arguments),this.state=Tf({panel:Sh.get(this.props.component)})}setup(){Rf((e=>this.state.panel=Sh.get(e.component)))}getTitle(){return"function"==typeof this.state.panel.title?this.state.panel.title(this.env):this.state.panel.title}}Af.template=Lf,Af.style=Mf;const{xml:_f,css:Of}=t.tags,{useExternalListener:Nf,onWillUpdateProps:kf,onWillStart:Ff}=t.hooks,$f=[{name:"general",text:"General (no specific format)"},{name:"number",text:"Number (1,000.12)",value:"#,##0.00"},{name:"percent",text:"Percent (10.12%)",value:"0.00%"},{name:"date",text:"Date (9/26/2008)",value:"m/d/yyyy"},{name:"time",text:"Time (10:43:00 PM)",value:"hh:mm:ss a"},{name:"datetime",text:"Date time (9/26/2008 22:43:00)",value:"m/d/yyyy hh:mm:ss"},{name:"duration",text:"Duration (27:51:38)",value:"hhhh:mm:ss"}];class Df extends t.Component{constructor(){super(...arguments),this.formats=$f,this.currentFormat="general",this.fontSizes=cs,this.dispatch=this.env.dispatch,this.getters=this.env.getters,this.style={},this.state=t.useState({menuState:{isOpen:!1,position:null,menuItems:[]},activeTool:""}),this.isSelectingMenu=!1,this.openedEl=null,this.inMerge=!1,this.cannotMerge=!1,this.undoTool=!1,this.redoTool=!1,this.paintFormatTool=!1,this.fillColor="white",this.textColor="black",this.menus=[],this.composerStyle="\n line-height: 34px;\n padding-left: 8px;\n height: 34px;\n background-color: white;\n "}setup(){Nf(window,"click",this.onClick),Ff((()=>this.updateCellState())),kf((()=>this.updateCellState()))}get topbarComponents(){return Ch.getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}onClick(e){this.openedEl&&Zc(this.openedEl,e)||this.closeMenus()}toogleStyle(e){Ga(this.env,{[e]:!this.style[e]})}toogleFormat(e){const t=$f.find((t=>t.name===e)),s=t&&t.value||"";Za(this.env,s)}toggleAlign(e){Ga(this.env,{align:e})}onMenuMouseOver(e,t){this.isSelectingMenu&&this.toggleContextMenu(e,t)}toggleDropdownTool(e,t){const s=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=s?"":e,this.openedEl=s?null:t.target}toggleContextMenu(e,t){this.closeMenus();const s=t.target.offsetLeft,o=t.target.clientHeight+t.target.offsetTop;this.state.menuState.isOpen=!0,this.state.menuState.position={x:s,y:o},this.state.menuState.menuItems=Cl.getChildren(e,this.env).filter((e=>!e.isVisible||e.isVisible(this.env))),this.isSelectingMenu=!0,this.openedEl=t.target}closeMenus(){this.state.activeTool="",this.state.menuState.isOpen=!1,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){this.style=this.getters.getCurrentStyle(),this.fillColor=this.style.fillColor||"white",this.textColor=this.style.textColor||"black";const e=this.getters.getSelectedZones(),{top:t,left:s,right:o,bottom:i}=e[0];if(this.cannotMerge=e.length>1||t===i&&s===o,this.inMerge=!1,!this.cannotMerge){const[t,s]=this.getters.getPosition(),o=this.getters.expandZone(this.getters.getActiveSheetId(),{left:t,right:t,top:s,bottom:s});this.inMerge=Js(e[0],o)}this.undoTool=this.getters.canUndo(),this.redoTool=this.getters.canRedo(),this.paintFormatTool=this.getters.isPaintingFormat();const n=this.getters.getActiveCell();if(n&&n.format){const e=this.formats.find((e=>e.value===n.format));this.currentFormat=e?e.name:""}else this.currentFormat="general";this.menus=Cl.getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}getMenuName(e){return Cl.getName(e,this.env)}toggleMerge(){const e=this.getters.getSelectedZones(),t=[e[e.length-1]],s=this.getters.getActiveSheetId();if(this.inMerge)this.dispatch("REMOVE_MERGE",{sheetId:s,target:t});else{const e=this.dispatch("ADD_MERGE",{sheetId:s,target:t});e.isSuccessful||e.isCancelledBecause(3)&&this.env.askConfirmation(a("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),(()=>{this.dispatch("ADD_MERGE",{sheetId:s,target:t,force:!0})}))}}setColor(e,t){Ga(this.env,{[e]:t})}setBorder(e){this.dispatch("SET_FORMATTING",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),border:e})}setFormat(e){const t=e.target.dataset.format;t&&this.toogleFormat(t)}setDecimal(e){this.dispatch("SET_DECIMAL",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),step:e})}paintFormat(){this.dispatch("ACTIVATE_PAINT_FORMAT",{target:this.getters.getSelectedZones()})}clearFormatting(){this.dispatch("CLEAR_FORMATTING",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones()})}setSize(e){const t=parseFloat(e.target.dataset.size);Ga(this.env,{fontSize:t})}doAction(e){e(this.env),this.closeMenus()}undo(){this.dispatch("REQUEST_UNDO")}redo(){this.dispatch("REQUEST_REDO")}}Df.template=_f`
2737
+ `;class Af extends t.Component{constructor(){super(...arguments),this.state=Tf({panel:Sh.get(this.props.component)})}setup(){Rf((e=>this.state.panel=Sh.get(e.component)))}getTitle(){return"function"==typeof this.state.panel.title?this.state.panel.title(this.env):this.state.panel.title}}Af.template=Lf,Af.style=Mf;const{xml:_f,css:Of}=t.tags,{useExternalListener:Nf,onWillUpdateProps:kf,onWillStart:Ff}=t.hooks,$f=[{name:"general",text:"General (no specific format)"},{name:"number",text:"Number (1,000.12)",value:"#,##0.00"},{name:"percent",text:"Percent (10.12%)",value:"0.00%"},{name:"date",text:"Date (9/26/2008)",value:"m/d/yyyy"},{name:"time",text:"Time (10:43:00 PM)",value:"hh:mm:ss a"},{name:"datetime",text:"Date time (9/26/2008 22:43:00)",value:"m/d/yyyy hh:mm:ss"},{name:"duration",text:"Duration (27:51:38)",value:"hhhh:mm:ss"}];class Df extends t.Component{constructor(){super(...arguments),this.formats=$f,this.currentFormat="general",this.fontSizes=hs,this.dispatch=this.env.dispatch,this.getters=this.env.getters,this.style={},this.state=t.useState({menuState:{isOpen:!1,position:null,menuItems:[]},activeTool:""}),this.isSelectingMenu=!1,this.openedEl=null,this.inMerge=!1,this.cannotMerge=!1,this.undoTool=!1,this.redoTool=!1,this.paintFormatTool=!1,this.fillColor="white",this.textColor="black",this.menus=[],this.composerStyle="\n line-height: 34px;\n padding-left: 8px;\n height: 34px;\n background-color: white;\n "}setup(){Nf(window,"click",this.onClick),Ff((()=>this.updateCellState())),kf((()=>this.updateCellState()))}get topbarComponents(){return Ch.getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}onClick(e){this.openedEl&&Zc(this.openedEl,e)||this.closeMenus()}toogleStyle(e){Ga(this.env,{[e]:!this.style[e]})}toogleFormat(e){const t=$f.find((t=>t.name===e)),s=t&&t.value||"";Za(this.env,s)}toggleAlign(e){Ga(this.env,{align:e})}onMenuMouseOver(e,t){this.isSelectingMenu&&this.toggleContextMenu(e,t)}toggleDropdownTool(e,t){const s=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=s?"":e,this.openedEl=s?null:t.target}toggleContextMenu(e,t){this.closeMenus();const s=t.target.offsetLeft,o=t.target.clientHeight+t.target.offsetTop;this.state.menuState.isOpen=!0,this.state.menuState.position={x:s,y:o},this.state.menuState.menuItems=Cl.getChildren(e,this.env).filter((e=>!e.isVisible||e.isVisible(this.env))),this.isSelectingMenu=!0,this.openedEl=t.target}closeMenus(){this.state.activeTool="",this.state.menuState.isOpen=!1,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){this.style=this.getters.getCurrentStyle(),this.fillColor=this.style.fillColor||"white",this.textColor=this.style.textColor||"black";const e=this.getters.getSelectedZones(),{top:t,left:s,right:o,bottom:i}=e[0];if(this.cannotMerge=e.length>1||t===i&&s===o,this.inMerge=!1,!this.cannotMerge){const[t,s]=this.getters.getPosition(),o=this.getters.expandZone(this.getters.getActiveSheetId(),{left:t,right:t,top:s,bottom:s});this.inMerge=Js(e[0],o)}this.undoTool=this.getters.canUndo(),this.redoTool=this.getters.canRedo(),this.paintFormatTool=this.getters.isPaintingFormat();const n=this.getters.getActiveCell();if(n&&n.format){const e=this.formats.find((e=>e.value===n.format));this.currentFormat=e?e.name:""}else this.currentFormat="general";this.menus=Cl.getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}getMenuName(e){return Cl.getName(e,this.env)}toggleMerge(){const e=this.getters.getSelectedZones(),t=[e[e.length-1]],s=this.getters.getActiveSheetId();if(this.inMerge)this.dispatch("REMOVE_MERGE",{sheetId:s,target:t});else{const e=this.dispatch("ADD_MERGE",{sheetId:s,target:t});e.isSuccessful||e.isCancelledBecause(3)&&this.env.askConfirmation(a("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),(()=>{this.dispatch("ADD_MERGE",{sheetId:s,target:t,force:!0})}))}}setColor(e,t){Ga(this.env,{[e]:t})}setBorder(e){this.dispatch("SET_FORMATTING",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),border:e})}setFormat(e){const t=e.target.dataset.format;t&&this.toogleFormat(t)}setDecimal(e){this.dispatch("SET_DECIMAL",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),step:e})}paintFormat(){this.dispatch("ACTIVATE_PAINT_FORMAT",{target:this.getters.getSelectedZones()})}clearFormatting(){this.dispatch("CLEAR_FORMATTING",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones()})}setSize(e){const t=parseFloat(e.target.dataset.size);Ga(this.env,{fontSize:t})}doAction(e){e(this.env),this.closeMenus()}undo(){this.dispatch("REQUEST_UNDO")}redo(){this.dispatch("REQUEST_REDO")}}Df.template=_f`
2738
2738
  <div class="o-spreadsheet-topbar" t-on-click="props.onClick">
2739
2739
  <div class="o-topbar-top">
2740
2740
  <!-- Menus -->
@@ -3087,4 +3087,4 @@
3087
3087
  height: ${15}px;
3088
3088
  vertical-align: sub;
3089
3089
  }
3090
- `;class qf extends t.Component{constructor(e,s={}){super(e,s),this.model=new ku(this.props.data,{evalContext:{env:this.env},transportService:this.props.transportService,client:this.props.client,isReadonly:this.props.isReadonly,snapshotRequested:this.props.snapshotRequested},this.props.stateUpdateMessages),this.sidePanel=t.useState({isOpen:!1,panelProps:{}}),this.linkEditor=t.useState({isOpen:!1}),this.composer=t.useState({topBarFocus:"inactive",gridFocusMode:"inactive"}),this.keyDownMapping={"CTRL+H":()=>this.toggleSidePanel("FindAndReplace",{}),"CTRL+F":()=>this.toggleSidePanel("FindAndReplace",{})},Uf({openSidePanel:(e,t={})=>this.openSidePanel(e,t),toggleSidePanel:(e,t={})=>this.toggleSidePanel(e,t),dispatch:this.model.dispatch,getters:this.model.getters,uuidGenerator:this.model.uuidGenerator,_t:qf._t,clipboard:navigator.clipboard,export:this.model.exportData.bind(this.model),waitForIdle:this.model.waitForIdle.bind(this.model),exportXLSX:this.model.exportXLSX.bind(this.model),openLinkEditor:()=>this.openLinkEditor()}),this.activateFirstSheet()}setup(){Pf(window,"resize",this.render),Pf(document.body,"keyup",this.onKeyup.bind(this)),Pf(window,"beforeunload",this.leaveCollaborativeSession.bind(this)),Vf((()=>this.initiateModelEvents())),Bf((()=>this.leaveCollaborativeSession())),Hf((e=>this.checkReadonly(e)))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}initiateModelEvents(){this.model.on("update",this,this.render),this.model.on("notify-ui",this,this.onNotifyUI),this.model.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.props.client&&this.model.joinSession(this.props.client)}onNotifyUI(e){if("NOTIFICATION"===e.type)this.env.notifyUser(e.text)}checkReadonly(e){this.props.isReadonly!==e.isReadonly&&this.model.updateReadOnly(e.isReadonly)}leaveCollaborativeSession(){this.model.off("update",this),this.model.leaveSession()}activateFirstSheet(){const e=this.model.getters.getActiveSheetId(),[t]=this.model.getters.getSheets();t.id!==e&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:t.id})}destroy(){this.model.destroy(),super.destroy()}openSidePanel(e,t){this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.isOpen=!1,this.focusGrid()}openLinkEditor(){this.linkEditor.isOpen=!0}closeLinkEditor(){this.linkEditor.isOpen=!1,this.focusGrid()}toggleSidePanel(e,t){this.sidePanel.isOpen&&e===this.sidePanel.component?(this.sidePanel.isOpen=!1,this.focusGrid()):this.openSidePanel(e,t)}focusGrid(){if(!this._focusGrid)throw new Error("_focusGrid should be exposed by the grid component");this._focusGrid()}save(){this.trigger("save-content",{data:this.model.exportData()})}onKeyup(e){"Control"===e.key&&this.model.getters.getSelectionMode()!==Lh.expanding&&this.model.dispatch("STOP_SELECTION")}onKeydown(e){"Control"!==e.key||e.repeat||this.model.dispatch(this.model.getters.getSelectionMode()===Lh.idle?"PREPARE_SELECTION_EXPANSION":"START_SELECTION_EXPANSION");let t="";(e.ctrlKey||e.metaKey)&&(t+="CTRL+"),t+=e.key.toUpperCase();let s=this.keyDownMapping[t];if(s)return e.preventDefault(),e.stopPropagation(),void s()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}||{}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}onGridComposerContentFocused(){this.model.getters.isReadonly()||(this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent({}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}onGridComposerCellFocused(e,t){this.model.getters.isReadonly()||(this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent({content:e,selection:t}||{}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}setComposerContent({content:e,selection:t}){"inactive"===this.model.getters.getEditionMode()?this.model.dispatch("START_EDITION",{text:e,selection:t}):e&&this.model.dispatch("SET_CURRENT_CONTENT",{content:e,selection:t})}}qf.template=Gf,qf.style=Wf,qf.components={TopBar:Df,Grid:wf,BottomBar:np,SidePanel:Af,LinkEditor:tf},qf._t=e=>e;const jf={},Xf={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:m,HEADER_WIDTH:v,TOPBAR_HEIGHT:E,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:b,DEFAULT_CELL_HEIGHT:S,SCROLLBAR_WIDTH:C},Yf={autofillModifiersRegistry:Ma,autofillRulesRegistry:Aa,cellMenuRegistry:fl,colMenuRegistry:ml,linkMenuRegistry:vl,functionRegistry:hr,uiPluginRegistry:ld,corePluginRegistry:ad,rowMenuRegistry:El,sidePanelRegistry:Sh,sheetMenuRegistry:Sl,topbarMenuRegistry:Cl,topbarComponentRegistry:Ch,otRegistry:yl,inverseCommandRegistry:Oa,cellRegistry:qr},Kf={LinkCell:sa},Qf={args:Oe,toBoolean:fe,toNumber:de,toString:pe,toXC:is,toZone:qs,toCartesian:os,numberToLetters:ss,createFullMenuItem:Fa,UuidGenerator:Hs,formatDecimal:ae,computeTextWidth:vs,isMarkdownLink:xs,parseMarkdownLink:Rs,markdownLink:Ts,createEmptyWorkbookData:fa};e.CorePlugin=va,e.DATETIME_FORMAT=_,e.DataSource=dd,e.DispatchResult=Ve,e.Model=ku,e.Registry=Me,e.Revision=Qh,e.SPREADSHEET_DIMENSIONS=Xf,e.Spreadsheet=qf,e.UIPlugin=yh,e.__DEBUG__=Os,e.__info__=jf,e.astToFormula=$r,e.cellTypes=Kf,e.compile=Gr,e.convertAstNodes=Fr,e.coreTypes=Pe,e.functionCache=Zr,e.helpers=Qf,e.invalidateEvaluationCommands=$e,e.parse=Nr,e.readonlyAllowedCommands=De,e.registries=Yf,e.setTranslationMethod=function(e){i=e},Object.defineProperty(e,"__esModule",{value:!0}),jf.version="15.2.12",jf.date="2023-11-16T11:57:04.728Z",jf.hash="d0fd7c1"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
3090
+ `;class qf extends t.Component{constructor(e,s={}){super(e,s),this.model=new ku(this.props.data,{evalContext:{env:this.env},transportService:this.props.transportService,client:this.props.client,isReadonly:this.props.isReadonly,snapshotRequested:this.props.snapshotRequested},this.props.stateUpdateMessages),this.sidePanel=t.useState({isOpen:!1,panelProps:{}}),this.linkEditor=t.useState({isOpen:!1}),this.composer=t.useState({topBarFocus:"inactive",gridFocusMode:"inactive"}),this.keyDownMapping={"CTRL+H":()=>this.toggleSidePanel("FindAndReplace",{}),"CTRL+F":()=>this.toggleSidePanel("FindAndReplace",{})},Uf({openSidePanel:(e,t={})=>this.openSidePanel(e,t),toggleSidePanel:(e,t={})=>this.toggleSidePanel(e,t),dispatch:this.model.dispatch,getters:this.model.getters,uuidGenerator:this.model.uuidGenerator,_t:qf._t,clipboard:navigator.clipboard,export:this.model.exportData.bind(this.model),waitForIdle:this.model.waitForIdle.bind(this.model),exportXLSX:this.model.exportXLSX.bind(this.model),openLinkEditor:()=>this.openLinkEditor()}),this.activateFirstSheet()}setup(){Pf(window,"resize",this.render),Pf(document.body,"keyup",this.onKeyup.bind(this)),Pf(window,"beforeunload",this.leaveCollaborativeSession.bind(this)),Vf((()=>this.initiateModelEvents())),Bf((()=>this.leaveCollaborativeSession())),Hf((e=>this.checkReadonly(e)))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}initiateModelEvents(){this.model.on("update",this,this.render),this.model.on("notify-ui",this,this.onNotifyUI),this.model.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.props.client&&this.model.joinSession(this.props.client)}onNotifyUI(e){if("NOTIFICATION"===e.type)this.env.notifyUser(e.text)}checkReadonly(e){this.props.isReadonly!==e.isReadonly&&this.model.updateReadOnly(e.isReadonly)}leaveCollaborativeSession(){this.model.off("update",this),this.model.leaveSession()}activateFirstSheet(){const e=this.model.getters.getActiveSheetId(),[t]=this.model.getters.getSheets();t.id!==e&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:t.id})}destroy(){this.model.destroy(),super.destroy()}openSidePanel(e,t){this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.isOpen=!1,this.focusGrid()}openLinkEditor(){this.linkEditor.isOpen=!0}closeLinkEditor(){this.linkEditor.isOpen=!1,this.focusGrid()}toggleSidePanel(e,t){this.sidePanel.isOpen&&e===this.sidePanel.component?(this.sidePanel.isOpen=!1,this.focusGrid()):this.openSidePanel(e,t)}focusGrid(){if(!this._focusGrid)throw new Error("_focusGrid should be exposed by the grid component");this._focusGrid()}save(){this.trigger("save-content",{data:this.model.exportData()})}onKeyup(e){"Control"===e.key&&this.model.getters.getSelectionMode()!==Lh.expanding&&this.model.dispatch("STOP_SELECTION")}onKeydown(e){"Control"!==e.key||e.repeat||this.model.dispatch(this.model.getters.getSelectionMode()===Lh.idle?"PREPARE_SELECTION_EXPANSION":"START_SELECTION_EXPANSION");let t="";(e.ctrlKey||e.metaKey)&&(t+="CTRL+"),t+=e.key.toUpperCase();let s=this.keyDownMapping[t];if(s)return e.preventDefault(),e.stopPropagation(),void s()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}||{}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}onGridComposerContentFocused(){this.model.getters.isReadonly()||(this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent({}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}onGridComposerCellFocused(e,t){this.model.getters.isReadonly()||(this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent({content:e,selection:t}||{}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}setComposerContent({content:e,selection:t}){"inactive"===this.model.getters.getEditionMode()?this.model.dispatch("START_EDITION",{text:e,selection:t}):e&&this.model.dispatch("SET_CURRENT_CONTENT",{content:e,selection:t})}}qf.template=Gf,qf.style=Wf,qf.components={TopBar:Df,Grid:wf,BottomBar:np,SidePanel:Af,LinkEditor:tf},qf._t=e=>e;const jf={},Xf={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:m,HEADER_WIDTH:v,TOPBAR_HEIGHT:E,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:b,DEFAULT_CELL_HEIGHT:S,SCROLLBAR_WIDTH:C},Yf={autofillModifiersRegistry:Ma,autofillRulesRegistry:Aa,cellMenuRegistry:fl,colMenuRegistry:ml,linkMenuRegistry:vl,functionRegistry:hr,uiPluginRegistry:ld,corePluginRegistry:ad,rowMenuRegistry:El,sidePanelRegistry:Sh,sheetMenuRegistry:Sl,topbarMenuRegistry:Cl,topbarComponentRegistry:Ch,otRegistry:yl,inverseCommandRegistry:Oa,cellRegistry:qr},Kf={LinkCell:sa},Qf={args:Ne,toBoolean:me,toNumber:ue,toString:ge,toXC:ns,toZone:qs,toCartesian:is,numberToLetters:os,createFullMenuItem:Fa,UuidGenerator:Hs,formatDecimal:le,computeTextWidth:vs,isMarkdownLink:xs,parseMarkdownLink:Rs,markdownLink:Ts,createEmptyWorkbookData:fa};e.CorePlugin=va,e.DATETIME_FORMAT=_,e.DataSource=dd,e.DispatchResult=Be,e.Model=ku,e.Registry=Ae,e.Revision=Qh,e.SPREADSHEET_DIMENSIONS=Xf,e.Spreadsheet=qf,e.UIPlugin=yh,e.__DEBUG__=Os,e.__info__=jf,e.astToFormula=$r,e.cellTypes=Kf,e.compile=Gr,e.convertAstNodes=Fr,e.coreTypes=Ue,e.functionCache=Zr,e.helpers=Qf,e.invalidateEvaluationCommands=De,e.parse=Nr,e.readonlyAllowedCommands=Pe,e.registries=Yf,e.setTranslationMethod=function(e){i=e},Object.defineProperty(e,"__esModule",{value:!0}),jf.version="15.2.14",jf.date="2024-01-12T13:37:05.872Z",jf.hash="6515f7c"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);