@odoo/o-spreadsheet 15.0.3 → 15.0.5

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 i=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var i=s(t);let o=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(o(e),...t)},a=function(e,...t){return{toString:function(){return n(o(e),...t)}}},l="#f5f5f5",c="#F8F9FA",h="#E8EAED",d="#595959",u="#666666",p="#3266ca",g="#FFFFFF",f=26,m=48,v=63,E=96,b=23,S=15,C=14,I=4,y=200,w=1,x="400",T=10,R="'Roboto', arial",L=["thin","#000"],M="#00f",A=/[ymd:]/,_="#REF",O="START_REVISION",N=a("Invalid expression"),k=/'|\*|\?|\/|\\|\[|\]/,F=void 0,$="|",D=2e3,P=(new Date).getFullYear(),U=new Date(1899,11,30),B=new Date(0)-U,V=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,z=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,H=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function Z(e){let t;const s=(e=e.trim()).match(H);if(s){if(t=function(e){if(e=e.trim(),H.test(e)){const t=/AM/i.test(e),s=/PM/i.test(e),i=(t||s?e.substring(0,e.length-2).trim():e).split(/:/),o=i.length>=2,n=3===i.length;let r=Number(i[0]),a=o?Number(i[1]):0,l=n?Number(i[2]):0,c=n?"hh:mm:ss":"hh:mm";if(t||s)c+=" a";else if(!o)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 i;const o=e.match(V),n=e.match(z);if(o||n){let t;if(o?(t=o[0],i=G(t,"mdy")):(t=n[0],i=G(t,"ymd")),null===i)return null;e=e.replace(t,"").trim()}return""!==e||!i&&!t?null:i&&t?{value:i.value+t.value,format:i.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new Date(i.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,i.jsDate.getMonth()+t.jsDate.getMonth()-11,i.jsDate.getDate()+t.jsDate.getDate()-30,i.jsDate.getHours()+t.jsDate.getHours(),i.jsDate.getMinutes()+t.jsDate.getMinutes(),i.jsDate.getSeconds()+t.jsDate.getSeconds())}:i||t}function G(e,t){const s="mdy"===t;if(s||"ymd"===t){const t=e.split(/\/|-|\s/),i=s?0:1,o=s?1:2,n=s?2:0,r=Number(t[i]),a=Number(t[o]),l=2===t[i].length&&r<10||2===t[o].length&&a<10,c=t[n]?function(e){const t=Number(e);switch(e.length){case 1:return D+t;case 2:return D+(D+t>P+10?-100:0)+t;case 3:case 4:return t}return 0}(t[n]):P,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-U;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 W(e){const t=Math.trunc(e);let s=new Date(86400*t*1e3-B),i=e-t;i=i<0?1+i:i;const o=Math.round(24*i),n=Math.round(24*(i-o/24)*60),r=Math.round(24*(i-o/24-n/24/60)*60*60);return s.setHours(o),s.setMinutes(n),s.setSeconds(r),s}function q(e){const t=e.format,s=e.jsDate||W(e.value),i=t.indexOf("h");let o="",n="";return i>0?(o=j(s,t.substring(0,i-1)),n=X(s,t.substring(i))):0===i?n=X(s,t):i<0&&(o=j(s,t)),o+(o&&n?" ":"")+n}function j(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 X(e,t){let s=t.split(/:|\s/);const i=e.getHours(),o="a"===s[s.length-1];let n=i,r="";return o&&(n=0===n?12:n>12?n-12:n,r=i>=12?" PM":" AM",s.pop()),s.map((s=>{switch(s){case"hhhh":return Math.floor((e.getTime()-U)/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 Y=/^-?\d+(\.?\d*(e\d+)?)?(\s*%)?|^-?\.\d+(\s*%)?/,K=/^-?\d+(,\d+)*(\.?\d*(e\d+)?)?(\s*%)?$|^-?\.\d+(\s*%)?$/;function Q(e){return K.test(e.trim())}const J=/,/g;function ee(e){let t=Number(e.replace(J,""));return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}const te=new Intl.NumberFormat("en-US",{useGrouping:!1,maximumFractionDigits:10});function se(e){return Number.isInteger(e)?e.toString():te.format(e)}let ie=[];const oe=20;function ne(e,t,s=""){if(e<0)return"-"+ne(-e,t);const i=t>=oe?oe:t;let o=ie[i];o||(o=new Intl.NumberFormat("en-US",{minimumFractionDigits:i,maximumFractionDigits:i,useGrouping:!1}),ie[i]=o);let n=o.format(e);if(s){let e=n.indexOf(".");n=n.replace(/\d(?=(?:\d{3})+(?:\.|$))/g,((t,i)=>e<0||i<e?`${t}${s}`:t))}return n}function re(e,t){const s=t.split("."),i=1===s.length?0:s[1].match(/0/g).length,o=s[0].includes(",")?",":"",n=t.includes("%");n&&(e*=100);const r=ne(e,i,o);return n?r+"%":r}function ae(e,t){if(!e())throw new Error(t)}const le=e=>a("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function ce(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(Q(e)||""===e)return ee(e);const t=Z(e);if(t)return t.value;throw new Error(le(e));default:return 0}}function he(e){if(""===e)throw new Error(le(e));return ce(e)}function de(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}const ue=e=>a("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function pe(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(ue(e))}return!1;case"number":return!!e;default:return!1}}function ge(e){return W(ce(e))}function fe(e,t,s){for(let i of e)if(Array.isArray(i)){const e=i.length,s=i[0].length;for(let o=0;o<s;o++)for(let s=0;s<e;s++)t(i[s][o])}else s(i)}function me(e,t){fe(e,t,t)}function ve(e,t){fe(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(he(e))}))}function Ee(e,t,s,i){let o=i;for(let i of e)if(Array.isArray(i)){const e=i.length,s=i[0].length;for(let n=0;n<s;n++)for(let s=0;s<e;s++)o=t(o,i[s][n])}else o=s(o,i);return o}function be(e,t,s){return Ee(e,t,t,s)}function Se(e,t,s){return Ee(e,((e,s)=>"number"==typeof s?t(e,s):e),((e,s)=>t(e,he(s))),s)}function Ce(e,t,s){return Ee(e,((e,s)=>null!=s?t(e,"number"==typeof s?s:"boolean"==typeof s?ce(s):0):e),((e,s)=>t(e,ce(s))),s)}function Ie(e,t){return function(e,t,s){for(let i of e)if(Array.isArray(i)){const e=i.length,s=i[0].length;for(let o=0;o<s;o++)for(let s=0;s<e;s++)if(!t(i[s][o]))return}else if(!s(i))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(ue(e));return pe(e)}(e))))}function ye(e,t){let s,i,o=e.substring(0,2);"<="===o||">="===o||"<>"===o?(s=o,i=e.substring(2)):(o=e.substring(0,1),"<"===o||">"===o||"="===o?(s=o,i=e.substring(1)):(s="=",i=e)),Q(i)?i=ce(i):"TRUE"!==i&&"FALSE"!==i||(i=pe(i));const n={operator:s,operand:i};return"string"==typeof i&&(t&&(i+="*"),n.regexp=function(e){let t="",s="";for(let i of e)"?"===i&&"~"!==s?t+=".":"*"===i&&"~"!==s?t+=".*":("*"!==i&&"?"!==i||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(i)&&(t+="\\"),t+=i),s=i;return new RegExp("^"+t+"$","i")}(i)),n}function we(e,t){const{operator:s,operand:i}=t;if(void 0===e||void 0===i)return!1;if("number"==typeof i&&"="===s)return de(e)===de(i);if("<>"===s||"="===s){let o;return o=typeof e==typeof i&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===i),"="===s?o:!o}if(typeof e==typeof i)switch(s){case"<":return e<i;case">":return e>i;case"<=":return e<=i;case">=":return e>=i}return!1}function xe(e,t,s=!1){const i=e.length;if(i%2==1)throw new Error(a("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const o=e[0].length,n=e[0][0].length;let r=[];for(let t=0;t<i-1;t+=2){const i=e[t];if(!Array.isArray(i)||i.length!==o||i[0].length!==n)throw new Error(a("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=de(e[t+1]);r.push(ye(l,s))}for(let s=0;s<o;s++)for(let o=0;o<n;o++){let n=!0;for(let t=0;t<i-1;t+=2){if(n=we(e[t][s][o],r[t/2]),!n)break}n&&t(s,o)}}function Te(e,t){if(void 0===t)return-1;const s=typeof t;let i,o,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===i||i<a||i===a&&o<r)&&(i=a,o=r),l===s&&a>t?h=r-1:c=n+1}return void 0!==o?o:-1}class Re{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 Le=/(.*?)\((.*?)\)(.*)/,Me=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function Ae(e){let t=e.split("\n");const s=[];for(let e of t)e=e.trim(),e&&s.push(_e(e));return s}function _e(e){let t,s=e.match(Le),i=s[1].trim(),o=[],n=!1,r=!1,a=!1;for(let e of s[2].split(",")){const s=e.trim().toUpperCase();let i=Me.find((e=>s===e));i?o.push(i):"RANGE<ANY>"===s?o.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:i,description:s[3].trim(),type:o};return n&&(l.optional=!0),r&&(l.repeating=!0),a&&(l.lazy=!0),void 0!==t&&(l.default=!0,l.defaultValue=t),l}function Oe(e){let t=0,s=0,i=0;for(let o of e.args)t++,o.optional||o.repeating||o.default||s++,o.repeating&&i++;const o=e;return o.minArgRequired=s,o.maxArgPossible=i?1/0:t,o.nbrArgRepeating=i,o.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,i),o}var Ne;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(Ne||(Ne={}));const ke=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),Fe=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"]),$e=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 De(e){return $e.has(e.type)}class Pe{constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new Pe}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var Ue,Be,Ve,ze;e.CommandResult=void 0,(Ue=e.CommandResult||(e.CommandResult={}))[Ue.Success=0]="Success",Ue[Ue.CancelledForUnknownReason=1]="CancelledForUnknownReason",Ue[Ue.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",Ue[Ue.MergeIsDestructive=3]="MergeIsDestructive",Ue[Ue.CellIsMerged=4]="CellIsMerged",Ue[Ue.InvalidTarget=5]="InvalidTarget",Ue[Ue.EmptyUndoStack=6]="EmptyUndoStack",Ue[Ue.EmptyRedoStack=7]="EmptyRedoStack",Ue[Ue.NotEnoughElements=8]="NotEnoughElements",Ue[Ue.NotEnoughSheets=9]="NotEnoughSheets",Ue[Ue.MissingSheetName=10]="MissingSheetName",Ue[Ue.DuplicatedSheetName=11]="DuplicatedSheetName",Ue[Ue.DuplicatedSheetId=12]="DuplicatedSheetId",Ue[Ue.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",Ue[Ue.WrongSheetMove=14]="WrongSheetMove",Ue[Ue.WrongSheetPosition=15]="WrongSheetPosition",Ue[Ue.InvalidAnchorZone=16]="InvalidAnchorZone",Ue[Ue.SelectionOutOfBound=17]="SelectionOutOfBound",Ue[Ue.TargetOutOfSheet=18]="TargetOutOfSheet",Ue[Ue.WrongPasteSelection=19]="WrongPasteSelection",Ue[Ue.EmptyClipboard=20]="EmptyClipboard",Ue[Ue.EmptyRange=21]="EmptyRange",Ue[Ue.InvalidRange=22]="InvalidRange",Ue[Ue.InvalidSheetId=23]="InvalidSheetId",Ue[Ue.InputAlreadyFocused=24]="InputAlreadyFocused",Ue[Ue.MaximumRangesReached=25]="MaximumRangesReached",Ue[Ue.InvalidChartDefinition=26]="InvalidChartDefinition",Ue[Ue.EmptyDataSet=27]="EmptyDataSet",Ue[Ue.InvalidDataSet=28]="InvalidDataSet",Ue[Ue.InvalidLabelRange=29]="InvalidLabelRange",Ue[Ue.InvalidAutofillSelection=30]="InvalidAutofillSelection",Ue[Ue.WrongComposerSelection=31]="WrongComposerSelection",Ue[Ue.MinBiggerThanMax=32]="MinBiggerThanMax",Ue[Ue.LowerBiggerThanUpper=33]="LowerBiggerThanUpper",Ue[Ue.MidBiggerThanMax=34]="MidBiggerThanMax",Ue[Ue.MinBiggerThanMid=35]="MinBiggerThanMid",Ue[Ue.FirstArgMissing=36]="FirstArgMissing",Ue[Ue.SecondArgMissing=37]="SecondArgMissing",Ue[Ue.MinNaN=38]="MinNaN",Ue[Ue.MidNaN=39]="MidNaN",Ue[Ue.MaxNaN=40]="MaxNaN",Ue[Ue.ValueUpperInflectionNaN=41]="ValueUpperInflectionNaN",Ue[Ue.ValueLowerInflectionNaN=42]="ValueLowerInflectionNaN",Ue[Ue.MinInvalidFormula=43]="MinInvalidFormula",Ue[Ue.MidInvalidFormula=44]="MidInvalidFormula",Ue[Ue.MaxInvalidFormula=45]="MaxInvalidFormula",Ue[Ue.ValueUpperInvalidFormula=46]="ValueUpperInvalidFormula",Ue[Ue.ValueLowerInvalidFormula=47]="ValueLowerInvalidFormula",Ue[Ue.InvalidSortZone=48]="InvalidSortZone",Ue[Ue.WaitingSessionConfirmation=49]="WaitingSessionConfirmation",Ue[Ue.MergeOverlap=50]="MergeOverlap",Ue[Ue.TooManyHiddenElements=51]="TooManyHiddenElements",Ue[Ue.Readonly=52]="Readonly",Ue[Ue.InvalidOffset=53]="InvalidOffset",Ue[Ue.InvalidViewportSize=54]="InvalidViewportSize",Ue[Ue.FigureDoesNotExist=55]="FigureDoesNotExist",Ue[Ue.DuplicatedFigureId=56]="DuplicatedFigureId",Ue[Ue.DuplicatedChartId=57]="DuplicatedChartId",Ue[Ue.ChartDoesNotExist=58]="ChartDoesNotExist",function(e){e.FormatFromArgument="FormatFromArgument"}(Be||(Be={})),function(e){e[e.UP=0]="UP",e[e.DOWN=1]="DOWN",e[e.LEFT=2]="LEFT",e[e.RIGHT=3]="RIGHT"}(Ve||(Ve={})),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 He={description:a("Absolute value of a number."),args:Ae(`\n value (number) ${a("The number of which to return the absolute value.")}\n `),returns:["NUMBER"],compute:function(e){return Math.abs(ce(e))},isExported:!0},Ze={description:a("Inverse cosine of a value, in radians."),args:Ae(`\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=ce(e);return ae((()=>Math.abs(t)<=1),a("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},Ge={description:a("Inverse hyperbolic cosine of a number."),args:Ae(`\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=ce(e);return ae((()=>t>=1),a("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},We={description:a("Inverse cotangent of a value."),args:Ae(`\n value (number) ${a("The value for which to calculate the inverse cotangent.")}\n `),returns:["NUMBER"],compute:function(e){const t=ce(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},qe={description:a("Inverse hyperbolic cotangent of a value."),args:Ae(`\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=ce(e);return ae((()=>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},je={description:a("Inverse sine of a value, in radians."),args:Ae(`\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=ce(e);return ae((()=>Math.abs(t)<=1),a("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},Xe={description:a("Inverse hyperbolic sine of a number."),args:Ae(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic sine.")}\n `),returns:["NUMBER"],compute:function(e){return Math.asinh(ce(e))},isExported:!0},Ye={description:a("Inverse tangent of a value, in radians."),args:Ae(`\n value (number) ${a("The value for which to calculate the inverse tangent.")}\n `),returns:["NUMBER"],compute:function(e){return Math.atan(ce(e))},isExported:!0},Ke={description:a("Angle from the X axis to a point (x,y), in radians."),args:Ae(`\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=ce(e),i=ce(t);return ae((()=>0!==s||0!==i),a("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(i,s)},isExported:!0},Qe={description:a("Inverse hyperbolic tangent of a number."),args:Ae(`\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=ce(e);return ae((()=>Math.abs(t)<1),a("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},Je={description:a("Rounds number up to nearest multiple of factor."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=1){const s=ce(e),i=ce(t);return ae((()=>i>=0||s<=0),a("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),s.toString())),i?Math.ceil(s/i)*i:0},isExported:!0},et={description:a("Rounds number up to nearest multiple of factor."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=1,s=0){let i=ce(t);if(0===i)return 0;const o=ce(e);if(i=Math.abs(i),o>=0)return Math.ceil(o/i)*i;return 0===ce(s)?-Math.floor(Math.abs(o)/i)*i:-Math.ceil(Math.abs(o)/i)*i},isExported:!0},tt={description:a("Rounds number up to nearest multiple of factor."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return et.compute(e,t,0)},isExported:!0},st={description:a("Cosine of an angle provided in radians."),args:Ae(`\n angle (number) ${a("The angle to find the cosine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cos(ce(e))},isExported:!0},it={description:a("Hyperbolic cosine of any real number."),args:Ae(`\n value (number) ${a("Any real value to calculate the hyperbolic cosine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cosh(ce(e))},isExported:!0},ot={description:a("Cotangent of an angle provided in radians."),args:Ae(`\n angle (number) ${a("The angle to find the cotangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=ce(e);return ae((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},nt={description:a("Hyperbolic cotangent of any real number."),args:Ae(`\n value (number) ${a("Any real value to calculate the hyperbolic cotangent of.")}\n `),returns:["NUMBER"],compute:function(e){const t=ce(e);return ae((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},rt={description:a("Number of empty values."),args:Ae(`\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 be(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},at={description:a("A conditional count across a range."),args:Ae(`\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 xe(e,((e,s)=>{t+=1})),t},isExported:!0},lt={description:a("Count values depending on multiple criteria."),args:Ae(`\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 xe(e,((e,s)=>{t+=1})),t},isExported:!0};function ct(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const ht={description:a("Counts number of unique values in a range."),args:Ae(`\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 be(e,((e,t)=>ct(t)?e.add(t):e),new Set).size}},dt={description:a("Counts number of unique values in a range, filtered by a set of criteria."),args:Ae(`\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 xe(t,((t,i)=>{const o=e[t][i];ct(o)&&s.add(o)})),s.size}},ut={description:a("Cosecant of an angle provided in radians."),args:Ae(`\n angle (number) ${a("The angle to find the cosecant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=ce(e);return ae((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},pt={description:a("Hyperbolic cosecant of any real number."),args:Ae(`\n value (number) ${a("Any real value to calculate the hyperbolic cosecant of.")}\n `),returns:["NUMBER"],compute:function(e){const t=ce(e);return ae((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},gt={description:a("Converts from another base to decimal."),args:Ae(`\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=ce(t);s=Math.floor(s),ae((()=>2<=s&&s<=36),a("The base (%s) must be between 2 and 36 inclusive.",s.toString()));const i=de(e);if(""===i)return 0;ae((()=>!!i.match(/^-?[a-z0-9]+$/i)),a("The value (%s) must be a valid base %s representation.",i,s.toString()));const o=parseInt(i,s);return ae((()=>!isNaN(o)),a("The value (%s) must be a valid base %s representation.",i,s.toString())),o},isExported:!0},ft={description:a("Converts an angle value in radians to degrees."),args:Ae(`\n angle (number) ${a("The angle to convert from radians to degrees.")}\n `),returns:["NUMBER"],compute:function(e){return 180*ce(e)/Math.PI},isExported:!0},mt={description:a("Euler's number, e (~2.718) raised to a power."),args:Ae(`\n value (number) ${a("The exponent to raise e.")}\n `),returns:["NUMBER"],compute:function(e){return Math.exp(ce(e))},isExported:!0},vt={description:a("Rounds number down to nearest multiple of factor."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=1){const s=ce(e),i=ce(t);return ae((()=>i>=0||s<=0),a("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),s.toString())),i?Math.floor(s/i)*i:0},isExported:!0},Et={description:a("Rounds number down to nearest multiple of factor."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=1,s=0){let i=ce(t);if(0===i)return 0;const o=ce(e);if(i=Math.abs(i),o>=0)return Math.floor(o/i)*i;return 0===ce(s)?-Math.ceil(Math.abs(o)/i)*i:-Math.floor(Math.abs(o)/i)*i},isExported:!0},bt={description:a("Rounds number down to nearest multiple of factor."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=1){return Et.compute(e,t,0)},isExported:!0},St={description:a("Whether the provided value is even."),args:Ae(`\n value (number) ${a("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=he(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},Ct={description:a("Rounds number up to nearest multiple of factor."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=1){return et.compute(e,t,0)},isExported:!0},It={description:a("Whether the provided value is even."),args:Ae(`\n value (number) ${a("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=he(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},yt={description:a("The logarithm of a number, base e (euler's number)."),args:Ae(`\n value (number) ${a("The value for which to calculate the logarithm, base e.")}\n `),returns:["NUMBER"],compute:function(e){const t=ce(e);return ae((()=>t>0),a("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},wt={description:a("Modulo (remainder) operator."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){const s=ce(t);ae((()=>0!==s),a("The divisor must be different from 0."));const i=ce(e)%s;return i>0&&s<0||i<0&&s>0?i+s:i},isExported:!0},xt={description:a("Rounds a number up to the nearest odd integer."),args:Ae(`\n value (number) ${a("The value to round to the next greatest odd number.")}\n `),returns:["NUMBER"],returnFormat:Be.FormatFromArgument,compute:function(e){const t=ce(e);let s=Math.ceil(Math.abs(t));return s=1&s?s:s+1,t<0?-s:s},isExported:!0},Tt={description:a("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},Rt={description:a("A number raised to a power."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){const s=ce(e),i=ce(t);return ae((()=>s>=0||Number.isInteger(i)),a("The exponent (%s) must be an integer when the base is negative.",i.toString())),Math.pow(s,i)},isExported:!0},Lt={description:a("Result of multiplying a series of numbers together."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){let t=0,s=1;for(let i of e)if(Array.isArray(i))for(let e of i)for(let i of e)"number"==typeof i&&(s*=i,t+=1);else null!=i&&(s*=he(i),t+=1);return 0===t?0:s},isExported:!0},Mt={description:a("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},At={description:a("Random integer between two values, inclusive."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){let s=ce(e);Number.isInteger(s)||(s=Math.ceil(s));let i=ce(t);return Number.isInteger(i)||(i=Math.floor(i)),ae((()=>s<=i),a("The high (%s) must be greater than or equal to the low (%s).",i.toString(),s.toString())),s+Math.ceil((i-s+1)*Math.random())-1},isExported:!0},_t={description:a("Rounds a number according to standard rules."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=0){const s=ce(e);let i=ce(t);const o=Math.abs(s);let n;return 0===i?n=Math.round(o):(Number.isInteger(i)||(i=Math.trunc(i)),n=Math.round(o*Math.pow(10,i))/Math.pow(10,i)),s>=0?n:-n},isExported:!0},Ot={description:a("Rounds down a number."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=0){const s=ce(e);let i=ce(t);const o=Math.abs(s);let n;return 0===i?n=Math.floor(o):(Number.isInteger(i)||(i=Math.trunc(i)),n=Math.floor(o*Math.pow(10,i))/Math.pow(10,i)),s>=0?n:-n},isExported:!0},Nt={description:a("Rounds up a number."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=0){const s=ce(e);let i=ce(t);const o=Math.abs(s);let n;return 0===i?n=Math.ceil(o):(Number.isInteger(i)||(i=Math.trunc(i)),n=Math.ceil(o*Math.pow(10,i))/Math.pow(10,i)),s>=0?n:-n},isExported:!0},kt={description:a("Secant of an angle provided in radians."),args:Ae(`\n angle (number) ${a("The angle to find the secant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cos(ce(e))},isExported:!0},Ft={description:a("Hyperbolic secant of any real number."),args:Ae(`\n value (number) ${a("Any real value to calculate the hyperbolic secant of.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cosh(ce(e))},isExported:!0},$t={description:a("Sine of an angle provided in radians."),args:Ae(`\n angle (number) ${a("The angle to find the sine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sin(ce(e))},isExported:!0},Dt={description:a("Hyperbolic sine of any real number."),args:Ae(`\n value (number) ${a("Any real value to calculate the hyperbolic sine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sinh(ce(e))},isExported:!0},Pt={description:a("Positive square root of a positive number."),args:Ae(`\n value (number) ${a("The number for which to calculate the positive square root.")}\n `),returns:["NUMBER"],returnFormat:Be.FormatFromArgument,compute:function(e){const t=ce(e);return ae((()=>t>=0),a("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},Ut={description:a("Sum of a series of numbers and/or cells."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){return Se(e,((e,t)=>e+t),0)},isExported:!0},Bt={description:a("A conditional sum across a range."),args:Ae(`\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 i=0;return xe([e,t],((e,t)=>{const o=s[e][t];"number"==typeof o&&(i+=o)})),i},isExported:!0},Vt={description:a("Sums a range depending on multiple criteria."),args:Ae(`\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 xe(t,((t,i)=>{const o=e[t][i];"number"==typeof o&&(s+=o)})),s},isExported:!0},zt={description:a("Tangent of an angle provided in radians."),args:Ae(`\n angle (number) ${a("The angle to find the tangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tan(ce(e))},isExported:!0},Ht={description:a("Hyperbolic tangent of any real number."),args:Ae(`\n value (number) ${a("Any real value to calculate the hyperbolic tangent of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tanh(ce(e))},isExported:!0},Zt={description:a("Truncates a number."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=0){const s=ce(e);let i=ce(t);return 0===i?Math.trunc(s):(Number.isInteger(i)||(i=Math.trunc(i)),Math.trunc(s*Math.pow(10,i))/Math.pow(10,i))},isExported:!0};var Gt=Object.freeze({__proto__:null,ABS:He,ACOS:Ze,ACOSH:Ge,ACOT:We,ACOTH:qe,ASIN:je,ASINH:Xe,ATAN:Ye,ATAN2:Ke,ATANH:Qe,CEILING:Je,CEILING_MATH:et,CEILING_PRECISE:tt,COS:st,COSH:it,COT:ot,COTH:nt,COUNTBLANK:rt,COUNTIF:at,COUNTIFS:lt,COUNTUNIQUE:ht,COUNTUNIQUEIFS:dt,CSC:ut,CSCH:pt,DECIMAL:gt,DEGREES:ft,EXP:mt,FLOOR:vt,FLOOR_MATH:Et,FLOOR_PRECISE:bt,ISEVEN:St,ISO_CEILING:Ct,ISODD:It,LN:yt,MOD:wt,ODD:xt,PI:Tt,POWER:Rt,PRODUCT:Lt,RAND:Mt,RANDBETWEEN:At,ROUND:_t,ROUNDDOWN:Ot,ROUNDUP:Nt,SEC:kt,SECH:Ft,SIN:$t,SINH:Dt,SQRT:Pt,SUM:Ut,SUMIF:Bt,SUMIFS:Vt,TAN:zt,TANH:Ht,TRUNC:Zt});const Wt=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function qt(e){return e.toString(16).padStart(6,"0")}let jt=0;function Xt(){return jt=++jt%Wt.length,Wt[jt]}function Yt(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 Kt=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),Qt=new RegExp(/^\s*(.*!)?\$?[A-Z]{1,3}\$?[0-9]{1,7}\s*(\s*:\s*\$?[A-Z]{1,3}\$?[0-9]{1,7}\s*)?$/,"i");function Jt(e){const t=e.split("!"),s=t.pop();return{sheetName:t.join("!")||void 0,xc:s}}function es(e){return e<26?String.fromCharCode(65+e):es(Math.floor(e/26)-1)+es(e%26)}function ts(e){e=e.toUpperCase().trim();const[t,s,i]=e.match(Kt);if(t!==e)throw new Error(`Invalid cell description: ${e}`);const o=function(e){let t=0;const s=e.length;for(let i=0;i<s;i++)t+=(e.charCodeAt(i)-65+(i<s-1?1:0))*26**(s-i-1);return t}(s);return[o,parseInt(i,10)-1]}function ss(e,t,s={colFixed:!1,rowFixed:!1}){return(s.colFixed?"$":"")+es(e)+(s.rowFixed?"$":"")+String(t+1)}const is=140,os=20,ns=.035;function rs(e){return os+(is-os)*Math.exp(-ns*(e-1))}const as=[{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}],ls={};for(let e of as)ls[e.pt]=e.px;function cs(e){return JSON.stringify(e,Object.keys(e).sort())}function hs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ds(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]=ds(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 us(e){var t;return(null===(t=e.match(/\w/g))||void 0===t?void 0:t.length)!==e.length&&(e=`'${e}'`),e}function ps(e,t,s){return e<t?t:e>s?s:e}function gs(e,t,s){const i=s.italic?"italic ":"",o=s.bold?"bold":x,n=s.fontSize||T,r=ls[n];return e.font=`${i}${o} ${r}px ${R}`,e.measureText(t).width}function fs(e,t,s=1){if(t<=e&&s>0)return[];if(0===s)throw new Error("range() step must not be zero");const i=Math.ceil(Math.abs((t-e)/s)),o=Array(i);for(let t=0;t<i;t++)o[t]=e+t*s;return o}function ms(e){return e.reduce(((e,t,s,i)=>{if(1===Math.abs(t-i[s-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*vs(e,t){t.next();for(const s of e){const e=t.next();yield{...s,next:e.done?void 0:e.value}}}function Es(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}function bs(e){return null!==Z(e)}const Ss=/^\[([^\[]+)\]\((.+)\)$/,Cs=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function Is(e){return Ss.test(e)}function ys(e,t){return`[${e}](${t})`}function ws(e){const t=e.match(Ss)||[],s=t[1],i=t[2];if(!s||!i)throw new Error(`Could not parse markdown link ${e}.`);return{label:s,url:i}}const xs="o-spreadsheet://";function Ts(e){if(!Is(e))return!1;const{url:t}=ws(e);return t.startsWith(xs)}function Rs(e){if(e.startsWith(xs))return e.substr(xs.length);throw new Error(`${e} is not a valid sheet link`)}function Ls(e){return void 0!==e}const Ms={};function As(e){const t=(e=e.split("!").pop()).replace(/\$/g,"").split(":");let s,i,o,n,r=ts(t[0].trim());if(o=n=r[0],s=i=r[1],2===t.length){let e=ts(t[1].trim());n=e[0],i=e[1]}return{top:s,bottom:i,left:o,right:n}}function _s(e){let{top:t,bottom:s,left:i,right:o}=As(e);return o<i&&([o,i]=[i,o]),s<t&&([s,t]=[t,s]),{top:t,bottom:s,left:i,right:o}}function Os(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 Ns(e){const{top:t,bottom:s,left:i,right:o}=e;return t===s&&i===o?ss(i,t):`${ss(i,t)}:${ss(o,s)}`}function ks(e,t,s,i,o){const n="left"===t?"columns":"rows",r="before"===i?s-1:s,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?Ws(e,n,"RESIZE",o):r<e[t]?Ws(e,n,"MOVE",o):{...e}}function Fs(e,t,s){const i="left"===t?"right":"bottom";let o=e[t],n=e[i];for(let r of s.sort(((e,t)=>t-e)))e[t]>r&&(o--,n--),e[t]<r&&e[i]>=r&&n--;return{...e,[t]:o,[i]:n}}function $s(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 Ds(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function Ps(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function Us(e,t,s){const{left:i,right:o,top:n,bottom:r}=s;return e>=i&&e<=o&&t>=n&&t<=r}function Bs(e,t){const s={};for(let t of e)if(t){const e=_s(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=_s(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 i=[];for(let[e,t]of Object.entries(s))i.push({col:parseInt(e),ranges:Vs(t)});return function(e){const t=e.sort(((e,t)=>e.col-t.col)),s=[];let i=[],o=0;for(let e=0;e<=t.length-1;e++){let n=[];if(o+1===t[e].col)for(let s of t[e].ranges){let o=!1;for(let e of i)s.top==e.top&&s.bottom==e.bottom&&(n.push(e),o=!0);o||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=i.filter((e=>!n.includes(e)));for(let e of r)s.push({top:e.top,bottom:e.bottom,left:e.startCol,right:o});o=t[e].col,i=n}for(let e of i)s.push({top:e.top,bottom:e.bottom,left:e.startCol,right:o});return s}(i).map(Ns)}function Vs(e){const t=new Set,s=new Set;for(let i of e)for(let e=i.top;e<=i.bottom;e++)i.remove?s.add(e):t.add(e);const i=[...t].filter((e=>!s.has(e))).sort(((e,t)=>e-t)),o=[];let n;for(let e of i)n?e===n.bottom+1?n.bottom=e:(o.push({top:n.top,bottom:n.bottom}),n={top:e,bottom:e}):n={top:e,bottom:e};return n&&o.push({top:n.top,bottom:n.bottom}),o}function zs(e,t,s,i,o=1,n=1){var r;const{top:a,bottom:l,left:c,right:h}=e,d=new Array(Math.floor((h-c+1)/o));for(let e=c;e<=h;e+=o){let o=new Array(Math.floor((l-a+1)/n));d[e-c]=o;for(let c=a;c<=l;c+=n){let l=null===(r=t.rows[c])||void 0===r?void 0:r.cells[e];o[(c-a)/n]=l?s(l):i}}return d}function Hs(e){return{height:e.bottom-e.top+1,width:e.right-e.left+1}}function Zs(e){const{width:t,height:s}=Hs(e);return 1===t||1===s}function Gs(e){const t=[],[s,i]=[e.right,e.left].sort(((e,t)=>e-t)),[o,n]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of fs(s,i+1))for(const s of fs(o,n+1))t.push([e,s]);return t}function Ws(e,t,s,i){const o="columns"===t?"right":"bottom",n={...e};return"MOVE"===s&&(n["columns"===t?"left":"top"]+=i),n[o]+=i,n}function qs(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 js(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 Xs(e){const t=[];let s=0;for(let i=0;i<e;i++){const e={start:s,end:s+E,size:E,name:es(i)};t.push(e),s=e.end}return t}function Ys(e){const t=[];let s=0;for(let i=0;i<e;i++){const e={start:s,end:s+b,size:b,name:String(i+1),cells:{}};t.push(e),s=e.end}return t}function Ks(e,t){var s;const i=[];let o=0;for(let n=0;n<t;n++){const t=e[n]&&e[n].size||E,r=(null===(s=e[n])||void 0===s?void 0:s.isHidden)||!1,a={start:o,end:r?o:o+t,size:t,name:es(n)};r&&(a.isHidden=r),i.push(a),o=a.end}return i}function Qs(e,t){var s;const i=[];let o=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:o,end:r?o:o+t,size:t,name:String(n+1),cells:{}};r&&(a.isHidden=r),i.push(a),o=a.end}return i}function Js(e,t=!1){const s={};for(let i in e){const o=e[i];(o.size!==E||t)&&(s[i]={size:o.size}),o.isHidden&&(s[i]=s[i]||{},s[i].isHidden=o.isHidden)}return s}function ei(e,t=!1){const s={};for(let i in e){const o=e[i];(o.size!==b||t)&&(s[i]={size:o.size}),o.isHidden&&(s[i]=s[i]||{},s[i].isHidden=o.isHidden)}return s}class ti{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 si(e,t,s){return[ii(e,"cols",fs(t,e.cols.length)),ii(e,"rows",fs(s,e.rows.length))]}function ii(e,t,s){const i=e[t];return s.find((e=>!i[e].isHidden))}function oi(e,t){let s=e[t].length-1;for(;s>=0&&!0===e[t][s].isHidden;)s--;return e[t][s]}function ni(e,t,s){let i=[],o=[],n=0,r=0;me([e],(e=>{i.push(e),n+=1})),me([t],(e=>{o.push(e),r+=1})),ae((()=>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=i[e],s=o[e];"number"==typeof t&&"number"==typeof s&&(l+=1,c+=t,h+=s)}ae((()=>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=i[e],s=o[e];"number"==typeof t&&"number"==typeof s&&(p+=(t-d)*(s-u))}return p/(l-(s?1:0))}function ri(e,t,s){let i=0,o=0;const n=s?Ce:Se;o=n(e,((e,t)=>(i+=1,e+t)),0),ae((()=>0!==i&&(!t||1!==i)),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const r=o/i;return n(e,((e,t)=>e+Math.pow(t-r,2)),0)/(i-(t?1:0))}function ai(e,t,s){const i=ce(t);ae((()=>s?0<=i&&i<=1:0<i&&i<1),a("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let o,n=[],r=0;me(e,(e=>{"number"==typeof e&&(o=Te(n,e),n.splice(o+1,0,e),r++)})),ae((()=>0!==r),a("[[FUNCTION_NAME]] has no valid input data."));let l=(r+(s?-1:1))*i;if(s||(ae((()=>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 li={description:a("Average magnitude of deviations from mean."),args:Ae(`\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=Se(e,((e,s)=>(t+=1,e+s)),0);ae((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const i=s/t;return Se(e,((e,t)=>e+Math.abs(i-t)),0)/t},isExported:!0},ci={description:a("Numerical average value in a dataset, ignoring text."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){let t=0;const s=Se(e,((e,s)=>(t+=1,e+s)),0);return ae((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/t},isExported:!0},hi=a("[[FUNCTION_NAME]] has mismatched range sizes."),di=a("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),ui={description:a("Weighted average."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){let t,s,i=0,o=0;ae((()=>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)){ae((()=>Array.isArray(s)),hi);let e=t.length,n=t[0].length;ae((()=>e===s.length&&n===s[0].length),hi);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;ae((()=>c===h),a("[[FUNCTION_NAME]] expects number values.")),h&&(ae((()=>l>=0),di),i+=n*l,o+=l)}}else s=ce(s),t=ce(t),ae((()=>s>=0),di),i+=t*s,o+=s;return ae((()=>0!==o),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/o}},pi={description:a("Numerical average value in a dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){let t=0;const s=Ce(e,((e,s)=>(t+=1,e+s)),0);return ae((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/t},isExported:!0},gi={description:a("Average of values depending on criteria."),args:Ae(`\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 i=0,o=0;return xe([e,t],((t,n)=>{const r=(s||e)[t][n];"number"==typeof r&&(i+=1,o+=r)})),ae((()=>0!==i),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/i},isExported:!0},fi={description:a("Average of values depending on multiple criteria."),args:Ae(`\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,i=0;return xe(t,((t,o)=>{const n=e[t][o];"number"==typeof n&&(s+=1,i+=n)})),ae((()=>0!==s),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/s},isExported:!0},mi={description:a("The number of numeric values in dataset."),args:Ae(`\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||Q(s)||Z(s))&&(t+=1);return t},isExported:!0},vi={description:a("The number of values in a dataset."),args:Ae(`\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 be(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},Ei={description:a("The covariance of a dataset."),args:Ae(`\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 ni(e,t,!1)},isExported:!0},bi={description:a("The covariance of a dataset."),args:Ae(`\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 ni(e,t,!1)},isExported:!0},Si={description:a("The sample covariance of a dataset."),args:Ae(`\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 ni(e,t,!0)},isExported:!0},Ci={description:a("Nth largest element from a data set."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){const s=Math.trunc(ce(t));let i,o=[],n=0;me([e],(e=>{"number"==typeof e&&(i=Te(o,e),o.splice(i+1,0,e),n++,n>s&&(o.shift(),n--))}));const r=o.shift();return ae((()=>void 0!==r),a("[[FUNCTION_NAME]] has no valid input data.")),ae((()=>n>=s),a("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s.toString())),r},isExported:!0},Ii={description:a("Maximum value in a numeric dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){const t=Se(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},yi={description:a("Maximum numeric value in a dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){const t=Ce(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},wi={description:a("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:Ae(`\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 xe(t,((t,i)=>{const o=e[t][i];"number"==typeof o&&(s=s<o?o:s)})),s===-1/0?0:s},isExported:!0},xi={description:a("Median value in a numeric dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){let t=[];return ve(e,(e=>{t.push(e)})),ai(t,.5,!0)},isExported:!0},Ti={description:a("Minimum value in a numeric dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){const t=Se(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Ri={description:a("Minimum numeric value in a dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){const t=Ce(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},Li={description:a("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:Ae(`\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 xe(t,((t,i)=>{const o=e[t][i];"number"==typeof o&&(s=s>o?o:s)})),s===1/0?0:s},isExported:!0},Mi={description:a("Value at a given percentile of a dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return _i.compute(e,t)},isExported:!0},Ai={description:a("Value at a given percentile of a dataset exclusive of 0 and 1."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return ai([e],t,!1)},isExported:!0},_i={description:a("Value at a given percentile of a dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return ai([e],t,!0)},isExported:!0},Oi={description:a("Value nearest to a specific quartile of a dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return ki.compute(e,t)},isExported:!0},Ni={description:a("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return ai([e],.25*Math.trunc(ce(t)),!1)},isExported:!0},ki={description:a("Value nearest to a specific quartile of a dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return ai([e],.25*Math.trunc(ce(t)),!0)},isExported:!0},Fi={description:a("Nth smallest element in a data set."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){const s=Math.trunc(ce(t));let i,o=[],n=0;me([e],(e=>{"number"==typeof e&&(i=Te(o,e),o.splice(i+1,0,e),n++,n>s&&(o.pop(),n--))}));const r=o.pop();return ae((()=>void 0!==r),a("[[FUNCTION_NAME]] has no valid input data.")),ae((()=>n>=s),a("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s.toString())),r},isExported:!0},$i={description:a("Standard deviation."),args:Ae(`\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(zi.compute(...e))},isExported:!0},Di={description:a("Standard deviation of entire population."),args:Ae(`\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(Hi.compute(...e))},isExported:!0},Pi={description:a("Standard deviation."),args:Ae(`\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(Zi.compute(...e))},isExported:!0},Ui={description:a("Standard deviation of sample (text as 0)."),args:Ae(`\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(Gi.compute(...e))},isExported:!0},Bi={description:a("Standard deviation of entire population."),args:Ae(`\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(Wi.compute(...e))},isExported:!0},Vi={description:a("Standard deviation of entire population (text as 0)."),args:Ae(`\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(qi.compute(...e))},isExported:!0},zi={description:a("Variance."),args:Ae(`\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 ri(e,!0,!1)},isExported:!0},Hi={description:a("Variance of entire population."),args:Ae(`\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 ri(e,!1,!1)},isExported:!0},Zi={description:a("Variance."),args:Ae(`\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 ri(e,!0,!1)},isExported:!0},Gi={description:a("Variance of sample (text as 0)."),args:Ae(`\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 ri(e,!0,!0)},isExported:!0},Wi={description:a("Variance of entire population."),args:Ae(`\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 ri(e,!1,!1)},isExported:!0},qi={description:a("Variance of entire population (text as 0)."),args:Ae(`\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 ri(e,!1,!0)},isExported:!0};var ji=Object.freeze({__proto__:null,AVEDEV:li,AVERAGE:ci,AVERAGE_WEIGHTED:ui,AVERAGEA:pi,AVERAGEIF:gi,AVERAGEIFS:fi,COUNT:mi,COUNTA:vi,COVAR:Ei,COVARIANCE_P:bi,COVARIANCE_S:Si,LARGE:Ci,MAX:Ii,MAXA:yi,MAXIFS:wi,MEDIAN:xi,MIN:Ti,MINA:Ri,MINIFS:Li,PERCENTILE:Mi,PERCENTILE_EXC:Ai,PERCENTILE_INC:_i,QUARTILE:Oi,QUARTILE_EXC:Ni,QUARTILE_INC:ki,SMALL:Fi,STDEV:$i,STDEV_P:Di,STDEV_S:Pi,STDEVA:Ui,STDEVP:Bi,STDEVPA:Vi,VAR:zi,VAR_P:Hi,VAR_S:Zi,VARA:Gi,VARP:Wi,VARPA:qi});function Xi(e,t,s){var i;const o=new Map,n=e.length;for(let t=n-1;t>=0;t--)o.set(de(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=de(t).toUpperCase();if(r=null!==(i=o.get(e))&&void 0!==i?i:-1,-1===r)throw new Error(a("The field (%s) must be one of %s.",de(t),[...o.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 i=[],n=!0;for(let r=0;r<s.length;r++){const a=de(s[r][0]).toUpperCase(),l=o.get(a),c=s[r][t];if(void 0!==c){if(void 0===l){n=!1;break}i.push([e[l].slice(1,h)]),i.push(c)}}if(n){if(!(i.length>0)){c=new Set(Array(h-1).keys());break}xe(i,((e,t)=>{c.add(t)}),!0)}}const d=e[r];return[...c].map((e=>d[e+1]))}const Yi=Ae(`\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`),Ki={description:a("Average of a set of values from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return ci.compute([i])},isExported:!0},Qi={description:a("Counts values from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return mi.compute([i])},isExported:!0},Ji={description:a("Counts values and text from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return vi.compute([i])},isExported:!0},eo={description:a("Single value from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return ae((()=>1===i.length),a("More than one match found in DGET evaluation.")),i[0]},isExported:!0},to={description:a("Maximum of values from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return Ii.compute([i])},isExported:!0},so={description:a("Minimum of values from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return Ti.compute([i])},isExported:!0},io={description:a("Product of values from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return Lt.compute([i])},isExported:!0},oo={description:a("Standard deviation of population sample from table."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return $i.compute([i])},isExported:!0},no={description:a("Standard deviation of entire population from table."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return Bi.compute([i])},isExported:!0},ro={description:a("Sum of values from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return Ut.compute([i])},isExported:!0},ao={description:a("Variance of population sample from table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return zi.compute([i])},isExported:!0},lo={description:a("Variance of a population from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return Wi.compute([i])},isExported:!0};var co=Object.freeze({__proto__:null,DAVERAGE:Ki,DCOUNT:Qi,DCOUNTA:Ji,DGET:eo,DMAX:to,DMIN:so,DPRODUCT:io,DSTDEV:oo,DSTDEVP:no,DSUM:ro,DVAR:ao,DVARP:lo});const ho=new Date(1899,11,30);function uo(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}const po={description:a("Converts year/month/day into a date."),args:Ae(`\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 i=Math.trunc(ce(e));const o=Math.trunc(ce(t)),n=Math.trunc(ce(s));ae((()=>0<=i&&i<=9999),a("The year (%s) must be between 0 and 9999 inclusive.",i.toString())),i<1900&&(i+=1900);const r=new Date(i,o-1,n).getTime()-ho.getTime();return ae((()=>r>=0),a("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),Math.round(r/864e5)},isExported:!0},go={description:a("Converts a date string to a date value."),args:Ae(`\n date_string (string) ${a("The string representing the date.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e),s=Z(t);return ae((()=>null!==s),a("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(s.value)},isExported:!0},fo={description:a("Day of the month that a specific date falls on."),args:Ae(`\n date (string) ${a("The date from which to extract the day.")}\n `),returns:["NUMBER"],compute:function(e){return ge(e).getDate()},isExported:!0},mo={description:a("Number of days between two dates."),args:Ae(`\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=ge(e),i=ge(t),o=s.getTime()-i.getTime();return Math.round(o/864e5)},isExported:!0},vo={description:a("Date a number of months before/after another date."),args:Ae(`\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=ge(e),i=Math.trunc(ce(t)),o=s.getFullYear(),n=s.getMonth(),r=s.getDate(),a=new Date(o,n+i,r).getTime()-ho.getTime();return Math.round(a/864e5)},isExported:!0},Eo={description:a("Last day of a month before or after a date."),args:Ae(`\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=ge(e),i=Math.trunc(ce(t)),o=s.getFullYear(),n=s.getMonth(),r=new Date(o,n+i+1,0).getTime()-ho.getTime();return Math.round(r/864e5)},isExported:!0},bo={description:a("Hour component of a specific time."),args:Ae(`\n time (date) ${a("The time from which to calculate the hour component.")}\n `),returns:["NUMBER"],compute:function(e){return ge(e).getHours()},isExported:!0},So={description:a("ISO week number of the year."),args:Ae(`\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=ge(e),s=t.getFullYear();let i=1;for(;4!==new Date(s,0,i).getDay();)i+=1;const o=new Date(s,0,i-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=o.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=o;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},Co={description:a("Minute component of a specific time."),args:Ae(`\n time (date) ${a("The time from which to calculate the minute component.")}\n `),returns:["NUMBER"],compute:function(e){return ge(e).getMinutes()},isExported:!0},Io={description:a("Month of the year a specific date falls in"),args:Ae(`\n date (date) ${a("The date from which to extract the month.")}\n `),returns:["NUMBER"],compute:function(e){return ge(e).getMonth()+1},isExported:!0},yo={description:a("Net working days between two provided days."),args:Ae(`\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 xo.compute(e,t,1,s)},isExported:!0};function wo(e){if("string"==typeof e){ae((()=>{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 ae((()=>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 xo={description:a("Net working days between two dates (specifying weekends)."),args:Ae(`\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,i){const o=ge(e),n=ge(t),r=wo(s);let a=new Set;void 0!==i&&me([i],(e=>{const t=ge(e);a.add(t.getTime())}));const l=o.getTime()>n.getTime(),c=new Date((l?o:n).getTime());let h=new Date((l?n:o).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},To={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()-ho.getTime(),s=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/864e5)+s},isExported:!0},Ro={description:a("Minute component of a specific time."),args:Ae(`\n time (date) ${a("The time from which to calculate the second component.")}\n `),returns:["NUMBER"],compute:function(e){return ge(e).getSeconds()},isExported:!0},Lo={description:a("Converts hour/minute/second into a time."),args:Ae(`\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 i=Math.trunc(ce(e)),o=Math.trunc(ce(t)),n=Math.trunc(ce(s));return o+=Math.floor(n/60),n=n%60+(n<0?60:0),i+=Math.floor(o/60),o=o%60+(o<0?60:0),i%=24,ae((()=>i>=0),a("The function [[FUNCTION_NAME]] result cannot be negative")),i/24+o/1440+n/86400},isExported:!0},Mo={description:a("Converts a time string into its serial number representation."),args:Ae(`\n time_string (string) ${a("The string that holds the time representation.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e),s=Z(t);ae((()=>null!==s),a("The time_string (%s) cannot be parsed to date/time.",t));const i=s.value-Math.trunc(s.value);return i<0?1+i:i},isExported:!0},Ao={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()-ho.getTime();return Math.round(t/864e5)},isExported:!0},_o={description:a("Day of the week of the date provided (as number)."),args:Ae(`\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=ge(e),i=Math.round(ce(t)),o=s.getDay();return ae((()=>[1,2,3].includes(i)),a("The type (%s) must be 1, 2 or 3.",i.toString())),1===i?o+1:2===i?0===o?7:o:0===o?6:o-1},isExported:!0},Oo={description:a("Week number of the year."),args:Ae(`\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=ge(e),i=Math.round(ce(t));if(ae((()=>1===i||2===i||11<=i&&i<=17||21===i),a("The type (%s) is out of range.",i.toString())),21===i)return So.compute(e);let o;o=1===i||2===i?i-1:i-10==7?0:i-10;const n=s.getFullYear();let r=1,l=new Date(n,0,r);for(;l.getDay()!==o;)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},No={description:a("Number of working days from start date."),args:Ae(`\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 ko.compute(e,t,1,s)},isExported:!0},ko={description:a("Net working days between two dates (specifying weekends)."),args:Ae(`\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,i){let o=ge(e),n=Math.trunc(ce(t));"string"==typeof s&&ae((()=>"1111111"!==s),a("The weekend (%s) must be different from '1111111'.",s));const r=wo(s);let l=new Set;void 0!==i&&me([i],(e=>{const t=ge(e);l.add(t.getTime())}));let c=new Date(o.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-ho.getTime();return Math.round(p/864e5)},isExported:!0},Fo={description:a("Year specified by a given date."),args:Ae(`\n date (date) ${a("The date from which to extract the year.")}\n `),returns:["NUMBER"],compute:function(e){return ge(e).getFullYear()},isExported:!0},$o={description:a("Exact number of years between two dates."),args:Ae(`\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 i=Math.trunc(ce(e)),o=Math.trunc(ce(t));const n=Math.trunc(ce(s));if(ae((()=>i>=0),a("The start_date (%s) must be positive or null.",i.toString())),ae((()=>o>=0),a("The end_date (%s) must be positive or null.",o.toString())),ae((()=>0<=n&&n<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",n.toString())),i===o)return 0;if(i>o){const e=o;o=i,i=e}const r=ge(i),l=ge(o);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===(uo(p)?29:28)&&(c=30,1===u&&h===(uo(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+=uo(e)?366:365;e=s/t}else t?uo(p)&&(e=366):(uo(p)&&d<2&&(e=366),uo(g)&&(u>1||1===u&&29===h)&&(e=366));f=i/e,m=o/e;break;case 2:f=i/360,m=o/360;break;case 3:f=i/365,m=o/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 Do=Object.freeze({__proto__:null,DATE:po,DATEVALUE:go,DAY:fo,DAYS:mo,EDATE:vo,EOMONTH:Eo,HOUR:bo,ISOWEEKNUM:So,MINUTE:Co,MONTH:Io,NETWORKDAYS:yo,NETWORKDAYS_INTL:xo,NOW:To,SECOND:Ro,TIME:Lo,TIMEVALUE:Mo,TODAY:Ao,WEEKDAY:_o,WEEKNUM:Oo,WORKDAY:No,WORKDAY_INTL:ko,YEAR:Fo,YEARFRAC:$o});function Po(e,t,s,i,o=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<o||Math.abs(l)<o,ae((()=>d<i),a("Function [[FUNCTION_NAME]] didn't find any result")),d++}while(!h);return c}const Uo={description:a("Depreciation via declining balance method."),args:Ae(`\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,i,...o){const n=ce(e),r=ce(t),l=ce(s),c=Math.trunc(ce(i)),h=o.length?Math.trunc(ce(o[0])):12,d=l+(12===h?0:1);ae((()=>n>0),a("The cost (%s) must be strictly positive.",n.toString())),ae((()=>r>=0),a("The salvage (%s) must be positive or null.",r.toString())),ae((()=>l>0),a("The life (%s) must be strictly positive.",l.toString())),ae((()=>c>0),a("The period (%s) must be strictly positive.",c.toString())),ae((()=>1<=h&&h<=12),a("The month (%s) must be between 1 and 12 inclusive.",h.toString())),ae((()=>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}},Bo={description:a("Number of periods for an investment to reach a value."),args:Ae(`\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,i,o,n=0){n=n||0;const r=Math.trunc(ce(e)),l=Math.trunc(ce(t)),c=ce(s),h=ce(i),d=Math.trunc(ce(o)),u=Math.trunc(ce(n));ae((()=>r<l),a("The maturity (%s) must be strictly greater than the settlement (%s).",l.toString(),r.toString())),ae((()=>c>=0),a("The rate (%s) must be positive or null.",c.toString())),ae((()=>h>=0),a("The yield (%s) must be positive or null.",h.toString())),ae((()=>[1,2,4].includes(d)),a("The frequency (%s) must be one of %s",d.toString(),[1,2,4].toString())),ae((()=>0<=u&&u<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",u.toString()));const p=$o.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}},Vo={description:a("Future value of an annuity investment."),args:Ae(`\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,i=0,o=0){i=i||0,o=o||0;const n=ce(e),r=ce(t),a=ce(s),l=ce(i),c=pe(o)?1:0;return n?-l*(1+n)**r-a*(1+n*c)*((1+n)**r-1)/n:-(l+a*r)}},zo={description:a("Internal rate of return given periodic cashflows."),args:Ae(`\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=ce(t);ae((()=>s>-1),a("The rate_guess (%s) must be strictly greater than -1.",s.toString()));let i=!1,o=!1,n=[];ve([e],(e=>{e>0&&(i=!0),e<0&&(o=!0),n.push(e)})),ae((()=>i&&o),a("The cashflow_amounts must include negative and positive values."));const r=n.shift();return Po((function(e){return function(e,t,s){const i=s.length;let o=0;return s.reduce(((t,s)=>(o++,t+s*e**(i-o))),t*e**i)}(e,r,n)}),(function(e){return function(e,t,s){const i=s.length;let o=0;return s.reduce(((t,s)=>(o++,t+s*(i-o)*e**(i-o-1))),t*i*e**(i-1))}(e,r,n)}),s+1,20,1e-5)-1}},Ho={description:a("Modified Macaulay duration."),args:Ae(`\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,i,o,n=0){return Bo.compute(e,t,s,i,o,n)/(1+ce(i)/Math.trunc(ce(o)))}};const Zo={description:a("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:Ae(`\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=ce(e);return ae((()=>-1!==s),a("The discount (%s) must be different from -1.",s.toString())),function(e,t,s){let i=0;return Se(s,((t,s)=>(i++,t+s/(1+e)**i)),t)}(s,0,t)}},Go={description:a("Computes the number of periods needed for an investment to reach a value."),args:Ae(`\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 i=ce(e),o=ce(t),n=ce(s);return ae((()=>i>0),a("The rate (%s) must be strictly positive.",i.toString())),ae((()=>o>0),a("The present_value (%s) must be strictly positive.",o.toString())),ae((()=>n>0),a("The future_value (%s) must be strictly positive.",n.toString())),(Math.log(n)-Math.log(o))/Math.log(1+i)}},Wo={description:a("Present value of an annuity investment."),args:Ae(`\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,i=0,o=0){i=i||0,o=o||0;const n=ce(e),r=ce(t),a=ce(s),l=ce(i),c=pe(o)?1:0;return n?-(a*(1+n*c)*((1+n)**r-1)/n+l)/(1+n)**r:-(l+a*r)}},qo={description:a("Price of a security paying periodic interest."),args:Ae(`\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,i,o,n,r=0){r=r||0;const l=Math.trunc(ce(e)),c=Math.trunc(ce(t)),h=ce(s),d=ce(i),u=ce(o),p=Math.trunc(ce(n)),g=Math.trunc(ce(r));ae((()=>c>l),a("The maturity (%s) must be strictly greater than the settlement (%s).",c.toString(),l.toString())),ae((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ae((()=>d>=0),a("The yield (%s) must be positive or null.",d.toString())),ae((()=>u>0),a("The redemption (%s) must be strictly positive.",u.toString())),ae((()=>[1,2,4].includes(p)),a("The frequency (%s) must be one of %s.",p.toString(),[1,2,4].toString())),ae((()=>0<=g&&g<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",g.toString()));const f=$o.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)}},jo={description:a("Annual yield of a security paying periodic interest."),args:Ae(`\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,i,o,n,r=0){r=r||0;const l=Math.trunc(ce(e)),c=Math.trunc(ce(t)),h=ce(s),d=ce(i),u=ce(o),p=Math.trunc(ce(n)),g=Math.trunc(ce(r));ae((()=>c>l),a("The maturity (%s) must be strictly greater than the settlement (%s).",c.toString(),l.toString())),ae((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ae((()=>d>0),a("The price (%s) must be strictly positive.",d.toString())),ae((()=>u>0),a("The redemption (%s) must be strictly positive.",u.toString())),ae((()=>[1,2,4].includes(p)),a("The frequency (%s) must be one of %s.",p.toString(),[1,2,4].toString())),ae((()=>0<=g&&g<=4),a("The day_count_convention (%s) must between 0 and 4 inclusive.",g.toString()));const f=$o.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=Po((function(e){return function(e,t,s,i,o,n){let r=n-(e+o*(1-t))*i**(s-1+t);for(let e=1;e<=s;e++)r+=o*i**(e-1);return r}(d,v,m,e,E,u)}),(function(e){return function(e,t,s,i,o){let n=-(e+o*(1-t))*(s-1+t)*i**(s-2+t);for(let e=1;e<=s;e++)n+=o*(e-1)*i**(e-2);return n}(d,v,m,e,E)}),1+(h+1)/p,100,1e-5);return(b-1)*p}},Xo={description:a("Annual yield of a security paying interest at maturity."),args:Ae(`\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,i,o,n=0){n=n||0;const r=Math.trunc(ce(e)),l=Math.trunc(ce(t)),c=Math.trunc(ce(s)),h=ce(i),d=ce(o),u=Math.trunc(ce(n));ae((()=>r>=c),a("The settlement (%s) must be greater than or equal to the issue (%s).",r.toString(),c.toString())),ae((()=>l>r),a("The maturity (%s) must be strictly greater than the settlement (%s).",l.toString(),r.toString())),ae((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ae((()=>d>0),a("The price (%s) must be strictly positive.",d.toString())),ae((()=>0<=u&&u<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",u.toString()));const p=$o.compute(c,l,u),g=$o.compute(c,r,u),f=$o.compute(r,l,u);return(100*(1+h*p)/(d+100*h*g)-1)/f}};var Yo=Object.freeze({__proto__:null,DB:Uo,DURATION:Bo,FV:Vo,IRR:zo,MDURATION:Ho,NPV:Zo,PDURATION:Go,PV:Wo,PRICE:qo,YIELD:jo,YIELDMAT:Xo});const Ko={description:a("Whether a value is an error."),args:Ae(`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},Qo={description:a("Whether a value is `true` or `false`."),args:Ae(`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},Jo={description:a("Whether a value is non-textual."),args:Ae(`value (any) ${a("The value to be checked.")}`),returns:["BOOLEAN"],compute:function(e){return"string"!=typeof e},isExported:!0},en={description:a("Whether a value is a number."),args:Ae(`value (any) ${a("The value to be verified as a number.")}`),returns:["BOOLEAN"],compute:function(e){return"number"==typeof e},isExported:!0},tn={description:a("Whether a value is text."),args:Ae(`value (any) ${a("The value to be verified as text.")}`),returns:["BOOLEAN"],compute:function(e){return"string"==typeof e},isExported:!0};var sn=Object.freeze({__proto__:null,ISERROR:Ko,ISLOGICAL:Qo,ISNONTEXT:Jo,ISNUMBER:en,ISTEXT:tn});const on={description:a("Logical `and` operator."),args:Ae(`\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))),ae((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0},nn={description:a("Returns value depending on logical expression."),args:Ae(`\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 i=pe(e)?t():s();return null==i?"":i},isExported:!0},rn={description:a("Value if it is not an error, otherwise 2nd argument."),args:Ae(`\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},an={description:a("Returns a value depending on multiple logical expressions."),args:Ae(`\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){ae((()=>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(pe(e[t]()))return e[t+1]();throw new Error(a("No match."))},isExported:!0},ln={description:a("Returns opposite of provided logical value."),args:Ae(`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!pe(e)},isExported:!0},cn={description:a("Logical `or` operator."),args:Ae(`\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))),ae((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0},hn={description:a("Logical `xor` operator."),args:Ae(`\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))),ae((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0};var dn=Object.freeze({__proto__:null,AND:on,IF:nn,IFERROR:rn,IFS:an,NOT:ln,OR:cn,XOR:hn});function un(e,t){for(let s=0;s<e.length;s++)if(e[s]===t)return s;return-1}const pn={description:a("Column number of a specified cell."),args:Ae(`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)),ae((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return _s(e).left+1},isExported:!0},gn={description:a("Number of columns in a specified array or range."),args:Ae(`range (meta) ${a("The range whose column count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=_s(e);return t.right-t.left+1},isExported:!0},fn={description:a("Horizontal lookup"),args:Ae(`\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,i=true){const o=Math.trunc(ce(s));ae((()=>1<=o&&o<=t[0].length),a("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const n=pe(i),r=t.map((e=>e[0]));let l;return l=n?Te(r,e):un(r,e),ae((()=>l>-1),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",de(e))),t[l][o-1]},isExported:!0},mn={description:a("Look up a value."),args:Ae(`\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 i=t.length,o=t[0].length;const n=o>=i,r=Te(n?t[0]:t.map((e=>e[0])),e);return ae((()=>r>=0),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",de(e))),void 0===s?n?t[i-1][r]:t[r][o-1]:(i=s.length,o=s[0].length,ae((()=>1===i||1===o),a("The result_range must be a single row or a single column.")),i>1?(ae((()=>r<=i-1),a("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(r+1).toString())),s[r][0]):(ae((()=>r<=o-1),a("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(r+1).toString())),s[0][r]))},isExported:!0},vn={description:a("Position of item in range that matches value."),args:Ae(`\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 i=ce(s);const o=t.length,n=t[0].length;ae((()=>1===o||1===n),a("The range must be a single row or a single column."));let r=-1;const l=t.flat();switch(i=Math.sign(i),i){case 1:r=Te(l,e);break;case 0:r=un(l,e);break;case-1:r=function(e,t){const s=typeof t;let i,o,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===i||i>a||i===a&&o>r)&&(i=a,o=r),l===s&&a<=t?h=r-1:c=n+1}return void 0!==o?o:-1}(l,e)}return ae((()=>r>=0),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",de(e))),r+1},isExported:!0},En={description:a("Row number of a specified cell."),args:Ae(`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)),ae((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return _s(e).top+1},isExported:!0},bn={description:a("Number of rows in a specified array or range."),args:Ae(`range (meta) ${a("The range whose row count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=_s(e);return t.bottom-t.top+1},isExported:!0},Sn={description:a("Vertical lookup."),args:Ae(`\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,i=true){const o=Math.trunc(ce(s));ae((()=>1<=o&&o<=t.length),a("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const n=pe(i),r=t[0];let l;return l=n?Te(r,e):un(r,e),ae((()=>l>-1),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",de(e))),t[o-1][l]},isExported:!0};var Cn=Object.freeze({__proto__:null,COLUMN:pn,COLUMNS:gn,HLOOKUP:fn,LOOKUP:mn,MATCH:vn,ROW:En,ROWS:bn,VLOOKUP:Sn});const In={description:a("Sum of two numbers."),args:Ae(`\n value1 (number) ${a("The first addend.")}\n value2 (number) ${a("The second addend.")}\n `),returns:["NUMBER"],returnFormat:Be.FormatFromArgument,compute:function(e,t){return ce(e)+ce(t)}},yn={description:a("Concatenation of two values."),args:Ae(`\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 de(e)+de(t)},isExported:!0},wn={description:a("One number divided by another."),args:Ae(`\n dividend (number) ${a("The number to be divided.")}\n divisor (number) ${a("The number to divide by.")}\n `),returns:["NUMBER"],returnFormat:Be.FormatFromArgument,compute:function(e,t){const s=ce(t);return ae((()=>0!==s),a("The divisor must be different from zero.")),ce(e)/s}};function xn(e){return null==e}const Tn={number:0,string:"",boolean:!1},Rn={description:a("Equal."),args:Ae(`\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=xn(e)?Tn[typeof t]:e,t=xn(t)?Tn[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function Ln(e,t,s){e=xn(e)?Tn[typeof t]:e,t=xn(t)?Tn[typeof e]:t,"number"!=typeof e&&(e=de(e).toUpperCase()),"number"!=typeof t&&(t=de(t).toUpperCase());const i=typeof e,o=typeof t;return"string"===i&&"number"===o||("string"!==o||"number"!==i)&&s(e,t)}const Mn={description:a("Strictly greater than."),args:Ae(`\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 Ln(e,t,((e,t)=>e>t))}},An={description:a("Greater than or equal to."),args:Ae(`\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 Ln(e,t,((e,t)=>e>=t))}},_n={description:a("Less than."),args:Ae(`\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!An.compute(e,t)}},On={description:a("Less than or equal to."),args:Ae(`\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!Mn.compute(e,t)}},Nn={description:a("Difference of two numbers."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return ce(e)-ce(t)}},kn={description:a("Product of two numbers"),args:Ae(`\n factor1 (number) ${a("The first multiplicand.")}\n factor2 (number) ${a("The second multiplicand.")}\n `),returns:["NUMBER"],returnFormat:Be.FormatFromArgument,compute:function(e,t){return ce(e)*ce(t)}},Fn={description:a("Not equal."),args:Ae(`\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!Rn.compute(e,t)}},$n={description:a("A number raised to a power."),args:Ae(`\n base (number) ${a("The number to raise to the exponent power.")}\n exponent (number) ${a("The exponent to raise base to.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return Rt.compute(e,t)}},Dn={description:a("A number with the sign reversed."),args:Ae(`\n value (number) ${a("The number to have its sign reversed. Equivalently, the number to multiply by -1.")}\n `),returnFormat:Be.FormatFromArgument,returns:["NUMBER"],compute:function(e){return-ce(e)}},Pn={description:a("Value interpreted as a percentage."),args:Ae(`\n percentage (number) ${a("The value to interpret as a percentage.")}\n `),returns:["NUMBER"],compute:function(e){return ce(e)/100}},Un={description:a("A specified number, unchanged."),args:Ae(`\n value (any) ${a("The number to return.")}\n `),returnFormat:Be.FormatFromArgument,returns:["ANY"],compute:function(e){return e}};var Bn=Object.freeze({__proto__:null,ADD:In,CONCAT:yn,DIVIDE:wn,EQ:Rn,GT:Mn,GTE:An,LT:_n,LTE:On,MINUS:Nn,MULTIPLY:kn,NE:Fn,POW:$n,UMINUS:Dn,UNARY_PERCENT:Pn,UPLUS:Un});const Vn={description:a("Gets character associated with number."),args:Ae(`\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(ce(e));return ae((()=>t>=1),a("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},zn={description:a("Appends strings to one another."),args:Ae(`\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 be(e,((e,t)=>e+de(t)),"")},isExported:!0},Hn={description:a("Tests whether two strings are identical."),args:Ae(`\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 de(e)===de(t)},isExported:!0},Zn={description:a("First position of string found in text, case-sensitive."),args:Ae(`\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 i=de(e),o=de(t),n=ce(s);ae((()=>""!==o),a("The text_to_search must be non-empty.")),ae((()=>n>=1),a("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const r=o.indexOf(i,n-1);return ae((()=>r>=0),a("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i.toString(),o)),r+1},isExported:!0},Gn={description:a("Concatenates elements of arrays with delimiter."),args:Ae(`\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=de(e);return be(t,((e,t)=>(e?e+s:"")+de(t)),"")}},Wn={description:a("Substring from beginning of specified string."),args:Ae(`\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?ce(t[0]):1;return ae((()=>s>=0),a("The number_of_characters (%s) must be positive or null.",s.toString())),de(e).substring(0,s)},isExported:!0},qn={description:a("Length of a string."),args:Ae(`\n text (string) ${a("The string whose length will be returned.")}\n `),returns:["NUMBER"],compute:function(e){return de(e).length},isExported:!0},jn={description:a("Converts a specified string to lowercase."),args:Ae(`\n text (string) ${a("The string to convert to lowercase.")}\n `),returns:["STRING"],compute:function(e){return de(e).toLowerCase()},isExported:!0},Xn={description:a("Replaces part of a text string with different text."),args:Ae(`\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,i){const o=ce(t);ae((()=>o>=1),a("The position (%s) must be greater than or equal to 1.",o.toString()));const n=de(e),r=ce(s),l=de(i);return n.substring(0,o-1)+l+n.substring(o-1+r)},isExported:!0},Yn={description:a("A substring from the end of a specified string."),args:Ae(`\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?ce(t[0]):1;ae((()=>s>=0),a("The number_of_characters (%s) must be positive or null.",s.toString()));const i=de(e),o=i.length;return i.substring(o-s,o)},isExported:!0},Kn={description:a("First position of string found in text, ignoring case."),args:Ae(`\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 i=de(e).toLowerCase(),o=de(t).toLowerCase(),n=ce(s);ae((()=>""!==o),a("The text_to_search must be non-empty.")),ae((()=>n>=1),a("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const r=o.indexOf(i,n-1);return ae((()=>r>=0),a("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i,o)),r+1},isExported:!0},Qn={description:a("Replaces existing text with new text in a string."),args:Ae(`\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,i){const o=ce(i);ae((()=>o>=0),a("The occurrenceNumber (%s) must be positive or null.",o.toString()));const n=de(e),r=de(t);if(""===r)return n;const l=de(s),c=new RegExp(hs(r),"g");if(0===o)return n.replace(c,l);let h=0;return n.replace(c,(e=>++h===o?l:e))},isExported:!0},Jn={description:a("Combines text from multiple strings and/or arrays."),args:Ae(`\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 i=de(e),o=pe(t);let n=0;return be(s,((e,t)=>o&&""===de(t)?e:(n++?e+i:"")+de(t)),"")},isExported:!0},er={description:a("Removes space characters."),args:Ae(`\n text (string) ${a("The text or reference to a cell containing text to be trimmed.")}\n `),returns:["STRING"],compute:function(e){return de(e).trim()},isExported:!0},tr={description:a("Converts a specified string to uppercase."),args:Ae(`\n text (string) ${a("The string to convert to uppercase.")}\n `),returns:["STRING"],compute:function(e){return de(e).toUpperCase()},isExported:!0};const sr={database:co,date:Do,financial:Yo,info:sn,lookup:Cn,logical:dn,math:Gt,operators:Bn,statistical:ji,text:Object.freeze({__proto__:null,CHAR:Vn,CONCATENATE:zn,EXACT:Hn,FIND:Zn,JOIN:Gn,LEFT:Wn,LEN:qn,LOWER:jn,REPLACE:Xn,RIGHT:Yn,SEARCH:Kn,SUBSTITUTE:Qn,TEXTJOIN:Jn,TRIM:er,UPPER:tr})};const ir=new class extends Re{constructor(){super(...arguments),this.mapping={}}add(e,t){e=e.toUpperCase().replace("_",".");const s=Oe(t);return function(e){let t=!1,s=!1,i=!1;for(let o of e){if(o.type.includes("META")&&o.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&&!o.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||i,n=!(o.optional||o.repeating||o.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=o.repeating,s=o.optional,i=o.default}}(s.args),this.mapping[e]=s.compute,super.add(e,s),this}};for(let e in sr){const t=sr[e];for(let s in t){const i=t[s];i.category=e,ir.add(s,{isExported:!1,...i})}}const or=/^[S|N]?\d+/,nr=ir.content,rr="+,-,*,/,:,=,<>,>=,>,<=,<,%,^,&".split(",");function ar(e){const t=e.split(""),s=[];for(;t.length;){let e=br(t)||dr(t)||pr(t)||fr(t)||cr(t)||lr(t)||Sr(t)||gr(t)||vr(t);e||(e={type:"UNKNOWN",value:t.shift()}),s.push(e)}return s}function lr(e){if(e[0]===$){e.shift();const t=e.join("").match(or);if(!t)return null;e.splice(0,t[0].length),e[0]===$&&e.shift();const s=t[0];switch(s[0]){case"S":return{type:"NORMALIZED_STRING",value:s.substring(1)};case"N":return{type:"NORMALIZED_NUMBER",value:s.substring(1)};default:return{type:"REFERENCE",value:s}}}return null}function cr(e){return"?"===e[0]?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const hr={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function dr(e){if(e[0]in hr){const t=e.shift();return{type:hr[t],value:t}}return null}function ur(e,t){for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;return!0}function pr(e){for(let t of rr)if(ur(e,t))return e.splice(0,t.length),{type:"OPERATOR",value:t};return null}function gr(e){const t=e.join("").match(Y);return t?(e.splice(0,t[0].length),{type:"NUMBER",value:t[0]}):null}function fr(e){if('"'===e[0]){const t=e.shift(),s=[t];for(;e[0]&&(e[0]!==t||"\\"===s[s.length-1]);)s.push(e.shift());return'"'===e[0]&&s.push(e.shift()),{type:"STRING",value:s.join("")}}return null}const mr=/\w|\.|!|\$/;function vr(e){const t=[];if("'"===e[0]){let s=e.shift();for(t.push(s);e[0];)if(s=e.shift(),t.push(s),"'"===s){if(!e[0]||"'"!==e[0])break;s=e.shift(),t.push(s)}if("'"!==s)return{type:"UNKNOWN",value:t.join("")}}for(;e[0]&&e[0].match(mr);)t.push(e.shift());if(t.length){const e=t.join("");return{type:e.toUpperCase()in nr?"FUNCTION":"SYMBOL",value:e}}return null}const Er=/\s/;function br(e){let t=0;for(;e[0]&&e[0].match(Er);)t++,e.shift();return t?{type:"SPACE",value:" ".repeat(t)}:null}function Sr(e){return ur(e,_)?(e.splice(0,_.length),{type:"INVALID_REFERENCE",value:_}):null}const Cr=["-","+"],Ir=["*","+","&"],yr={"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10},wr=6;function xr(e){switch(e.type){case"NUMBER":case"SYMBOL":return 0;case"COMMA":return 3;case"LEFT_PAREN":case"RIGHT_PAREN":return 5;case"OPERATOR":return yr[e.value]||15}throw new Error(a("Unknown token: %s",e.value))}function Tr(e,t,s){if("OPERATOR"===t.type){const i=Rr(s,xr(t));return{type:"BIN_OPERATION",value:t.value,left:e,right:i}}throw new Error(N)}function Rr(e,t){const s=e.shift();if(!s)throw new Error(N);let i=function(e,t){var s;switch(e.type){case"DEBUGGER":const i=Rr(t,1e3);return i.debug=!0,i;case"NUMBER":return{type:"NUMBER",value:ee(e.value)};case"NORMALIZED_NUMBER":return{type:"NORMALIZED_NUMBER",value:parseInt(e.value,10)};case"STRING":return{type:"STRING",value:e.value};case"NORMALIZED_STRING":return{type:"NORMALIZED_STRING",value:parseInt(e.value,10)};case"FUNCTION":if("LEFT_PAREN"!==t.shift().type)throw new Error(a("Wrong function call"));{const i=[];if(t[0]&&"RIGHT_PAREN"!==t[0].type)for("COMMA"===t[0].type?i.push({type:"UNKNOWN",value:""}):i.push(Rr(t,wr));"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)){i.push({type:"UNKNOWN",value:""});break}"COMMA"===(null==e?void 0:e.type)?i.push({type:"UNKNOWN",value:""}):i.push(Rr(t,wr))}const o=t.shift();if(!o||"RIGHT_PAREN"!==o.type)throw new Error(a("Wrong function call"));return{type:"FUNCALL",value:e.value,args:i}}case"REFERENCE":return{type:"NORMALIZED_REFERENCE",value:parseInt(e.value,10)};case"INVALID_REFERENCE":throw new Error(a("Invalid reference"));case"SYMBOL":if(Kt.test(e.value))return{type:"REFERENCE",value:e.value};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 o=Rr(t,5);if(!t.length||"RIGHT_PAREN"!==t[0].type)throw new Error(a("Unmatched left parenthesis"));return t.shift(),o;default:if("OPERATOR"===e.type&&Cr.includes(e.value))return{type:"UNARY_OPERATION",value:e.value,right:Rr(t,yr[e.value])};throw new Error(a("Unexpected token: %s",e.value))}}(s,e);for(;e[0]&&xr(e[0])>t;)i=Tr(i,e.shift(),e);return i}function Lr(e){const t=ar(e).filter((e=>"SPACE"!==e.type));"OPERATOR"===t[0].type&&"="===t[0].value&&t.splice(0,1);const s=Rr(t,0);if(t.length)throw new Error(N);return s}function Mr(e,t,s){switch(t===e.type&&(e=s(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>Mr(e,t,s)))};case"UNARY_OPERATION":return{...e,right:Mr(e.right,t,s)};case"BIN_OPERATION":return{...e,right:Mr(e.right,t,s),left:Mr(e.left,t,s)};default:return e}}function Ar(e,t={references:[],numbers:[],strings:[]}){switch(e.type){case"FUNCALL":const s=e.args.map((e=>Ar(e,t)));return`${e.value}(${s.join(",")})`;case"NUMBER":return e.value.toString();case"NORMALIZED_STRING":return`"${t.strings[e.value]}"`;case"NORMALIZED_NUMBER":return t.numbers[e.value].toString();case"NORMALIZED_REFERENCE":return t.references[e.value].toString();case"REFERENCE":case"STRING":default:return e.value;case"BOOLEAN":return e.value?"TRUE":"FALSE";case"UNARY_OPERATION":return e.value+_r(e,t);case"BIN_OPERATION":return function(e,t){const s=e.value,i=e.left,o=i.value;return"BIN_OPERATION"===i.type&&yr[o]<yr[s]?`(${Ar(i,t)})`:Ar(i,t)}(e,t)+e.value+_r(e,t)}}function _r(e,t){const s=e.value,i=e.right,o=yr[i.value],n=yr[s];let r=!1;return"BIN_OPERATION"!==i.type?r=!1:o<n?r=!0:o!==n||Ir.includes(s)||(r=!0),r?`(${Ar(i,t)})`:Ar(i,t)}const Or=ir.content,Nr={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},kr={"-":"UMINUS","+":"UPLUS"};function Fr(e){return e.map((e=>e.split("\n"))).flat().filter((e=>""!==e.trim()))}const $r={};function Dr(e){if(!$r[e.text]){const t=Lr(e.text);let s=1;if("BIN_OPERATION"===t.type&&":"===t.value)throw new Error(a("Invalid formula"));if("UNKNOWN"===t.type)throw new Error(a("Invalid formula"));const i=l(t),o=Fr([`// ${e.text}`,i.code,`return ${i.id};`]).join("\n");let n=new Function("deps","sheetId","ref","range","ctx",o);function r(e){const t=Or[e.value.toUpperCase()],s=e.args,i=s.length;if(i<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(),i.toString()));if(i>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(),i.toString()));const o=t.nbrArgRepeating;if(o>1){const s=t.args.length-o;if((i-s)%o!=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(),o.toString()))}let n=[];for(let o=0;o<i;o++){const i=t.getArgToFocus(o+1)-1;if(0<=i&&i<t.args.length){const r=s[o],c=t.args[i],h=c.type||[],d=h.includes("META"),u=c.lazy,p=h.some((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e)),g=h.every((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e));if(g&&"NORMALIZED_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(),(o+1).toString(),r.type.toLowerCase().replace("normalized_","")));const f=l(r,u,d,p,{functionName:e.value.toUpperCase(),paramIndex:o+1});n.push(f)}}return n}function l(t,i=!1,o=!1,n=!1,c={}){const h=[];let d,u,p;if("NORMALIZED_REFERENCE"!==t.type&&("BIN_OPERATION"!==t.type||":"!==t.value)&&o)throw new Error(a("Argument must be a reference to a cell or range."));switch(t.debug&&h.push("debugger;"),t.type){case"BOOLEAN":case"NUMBER":case"STRING":if(!i)return{id:t.value,code:""};d=s++,p=`${t.value}`;break;case"NORMALIZED_NUMBER":d=s++,p=`deps.numbers[${t.value}]`;break;case"NORMALIZED_STRING":d=s++,p=`deps.strings[${t.value}]`;break;case"REFERENCE":throw new Error(`Only normalized references can be compiled: ${t.value}`);case"NORMALIZED_REFERENCE":if(!e.dependencies.references[t.value]){d=s++,p="null";break}d=s++,p=n?`range(${t.value}, deps.references, sheetId)`:`ref(${t.value}, deps.references, sheetId, ${o?"true":"false"}, "${c.functionName||Nr["="]}", ${c.paramIndex})`;break;case"FUNCALL":d=s++;const a=r(t);h.push(Fr(a.map((e=>e.code))).join("\n")),u=t.value.toUpperCase(),h.push(`ctx.__lastFnCalled = '${u}';`),p=`ctx['${u}'](${a.map((e=>e.id))})`;break;case"UNARY_OPERATION":{d=s++,u=kr[t.value];const e=l(t.right,!1,!1,!1,{functionName:u});h.push(e.code),h.push(`ctx.__lastFnCalled = '${u}';`),p=`ctx['${u}']( ${e.id})`;break}case"BIN_OPERATION":{d=s++,u=Nr[t.value];const e=l(t.left,!1,!1,!1,{functionName:u}),i=l(t.right,!1,!1,!1,{functionName:u});h.push(e.code),h.push(i.code),h.push(`ctx.__lastFnCalled = '${u}';`),p=`ctx['${u}'](${e.id}, ${i.id})`;break}case"UNKNOWN":if(!i)return{id:"undefined",code:""};d=s++,p="undefined"}if(i){return{id:`_${d}`,code:`const _${d} = () => {\n\t${Fr(h).join("\n\t")}\n\treturn ${p};\n}`}}return h.push(`let _${d} = ${p};`),{id:`_${d}`,code:Fr(h).join("\n")}}function c(t){let s;switch(t.type){case"NORMALIZED_REFERENCE":if(e.dependencies.references[t.value])return[t.value];break;case"FUNCALL":if(s=Or[t.value.toUpperCase()],s.returnFormat){if("FormatFromArgument"!==s.returnFormat)return[s.returnFormat.specificFormat];if(t.args.length>0){const e=0;if(!s.args[e].type.includes("META"))return c(t.args[e])}}break;case"UNARY_OPERATION":return c(t.right);case"BIN_OPERATION":if(s=Or[Nr[t.value]],s.returnFormat){if("FormatFromArgument"===s.returnFormat){const e=c(t.left);if("string"==typeof e[e.length-1])return e;const s=c(t.right);return e.concat(s)}return[s.returnFormat.specificFormat]}}return[]}$r[e.text]=n,$r[e.text].dependenciesFormat=c(t)}return $r[e.text]}function Pr(e,t=!1){let s,i,o,n;const r=()=>{n=void 0,i=void 0,s=void 0,o=void 0};for(let a=0;a<e.length;a++){const l=e[a];if(n)if(i){if("SPACE"===l.type)continue;if("OPERATOR"===l.type&&":"===l.value)s=a;else if(s&&"SYMBOL"===l.type)o=a;else if(n&&i&&s&&o){const s={type:"SYMBOL",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"SYMBOL"===l.type?(n=a,i=a,s=void 0):r()}else"SYMBOL"===l.type?(i=a,s=o=void 0):r();else["SPACE","SYMBOL"].includes(l.type)?(n=a,i="SYMBOL"===l.type?a:void 0,s=o=void 0):r()}const a=e.length-1;if(n&&i&&s&&o){const s={type:"SYMBOL",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(ar(e),!0)}function Br(e){return function(e){let t=[],s="";return e.map(((e,i)=>{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,i=Object.assign({},e,{start:t,end:t+s,length:s});return t=i.end,i}))}(Pr(ar(e)))))}function Vr(e){const t=Ur(e);let s={numbers:[],strings:[],references:[]};return{text:"".concat(...t.map((e=>{if("SYMBOL"===e.type&&Kt.test(e.value)){const t=e.value.trim();s.references.includes(t)||s.references.push(t);return zr(s.references.indexOf(t).toString())}if("STRING"===e.type){const t=e.value.slice(1).slice(0,e.value.length-2);s.strings.includes(t)||s.strings.push(t);const i=s.strings.indexOf(t);return zr(`${e.type[0]}${i}`)}if("NUMBER"===e.type){const t=ee(e.value);s.numbers.includes(t)||s.numbers.push(t);const i=s.numbers.indexOf(t);return zr(`${e.type[0]}${i}`)}return e.value}))),dependencies:s}}function zr(e){return`${$}${e}${$}`}const Hr=new Re;function Zr(e,t){switch(typeof e){case"string":return e;case"boolean":return e?"TRUE":"FALSE";case"number":return(null==t?void 0:t.match(A))?q({value:e,format:t}):t?function(e,t){const s=t.split(";"),i=s.length;return e<0?i>1?re(-e,s[1]):"-"+re(-e,s[0]):re(e,s[3===i&&0===e?2:0])}(e,t):se(e);case"object":return"0"}}function Gr(e){return""===e?"":Q(e)?ee(e):Es(e)?"TRUE"===e.toUpperCase():bs(e)?Z(e).value:e}class Wr{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 Zr(this.evaluated.value,this.format)}get composerContent(){return this.content}get defaultAlign(){switch(this.evaluated.type){case Ne.number:return"right";case Ne.boolean:case Ne.error:return"center";case Ne.text:case Ne.empty:return"left"}}get isAutoSummable(){var e;switch(this.evaluated.type){case Ne.empty:case Ne.text:return!0;case Ne.number:return!(null===(e=this.format)||void 0===e?void 0:e.match(A));case Ne.error:case Ne.boolean:return!1}}}class qr extends Wr{constructor(e,t={}){super(e,{value:"",type:Ne.empty},t),this.content=""}isEmpty(){return!0}}class jr extends Wr{constructor(e,t,s={}){super(e,{value:t,type:Ne.number},s),this.content=se(this.evaluated.value)}}class Xr extends Wr{constructor(e,t,s={}){super(e,{value:t,type:Ne.boolean},s),this.content=this.evaluated.value?"TRUE":"FALSE"}}class Yr extends Wr{constructor(e,t,s={}){super(e,{value:t,type:Ne.text},s),this.content=this.evaluated.value}}class Kr extends jr{constructor(e,t,s){super(e,t,s),this.format=s.format}get composerContent(){return Zr(this.evaluated.value,this.format)}}class Qr extends Wr{constructor(e,t,s={}){var i;const o=ws(t);s={...s,style:{...s.style,textColor:(null===(i=s.style)||void 0===i?void 0:i.textColor)||M,underline:!0}},super(e,{value:o.label,type:Ne.text},s),this.link=o,this.content=t}isLink(){return!0}get composerContent(){return this.link.label}}class Jr extends Qr{constructor(e,t,s={}){super(e,t,s),this.link.url=this.withHttp(this.link.url),this.link.isExternal=!0,this.content=ys(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 ea extends Qr{constructor(e,t,s={},i){super(e,t,s),this.sheetName=i,this.sheetId=Rs(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 ta extends Wr{constructor(e,t,s,i,o,n){super(t,{value:"Loading...",type:Ne.text},n),this.buildFormulaString=e,this.normalizedText=s,this.compiledFormula=i,this.dependencies=o}get content(){return this.buildFormulaString(this.normalizedText,this.dependencies)}isFormula(){return!0}assignValue(e){switch(typeof e){case"number":this.evaluated={value:e,type:Ne.number};break;case"boolean":this.evaluated={value:e,type:Ne.boolean};break;case"string":this.evaluated={value:e,type:Ne.text};break;case"object":case"undefined":this.evaluated={value:e,type:Ne.empty}}}assignError(e,t){this.evaluated={value:e,error:t,type:Ne.error}}}class sa extends Wr{constructor(e,t,s,i){super(e,{value:"#BAD_EXPR",type:Ne.error,error:s},i),this.content=t}}function ia(e){const t=Ur(e);let s=[];return{text:"".concat(...t.map((e=>{if("SYMBOL"===e.type&&Kt.test(e.value)){const t=e.value.trim();return s.includes(t)||s.push(t),`${$}${s.indexOf(t)}${$}`}return e.value}))),dependencies:s}}Hr.add("Formula",{sequence:10,match:e=>e.startsWith("="),createCell:(e,t,s,i,o)=>{const n=Vr(t),r=n.text,a=Dr(n),l=n.dependencies.references.map((e=>o.getRangeFromSheetXC(i,e))),c=s.format||function(e,t,s){var i;const o=t.dependenciesFormat;for(let t of o)switch(typeof t){case"string":return t;case"number":const o=s[t],n=e[o.sheetId];if(n){const e=null===(i=n.rows[o.zone.top])||void 0===i?void 0:i.cells[o.zone.left];if(e&&e.format)return e.format}}return F}(o.getEvaluationSheets(),a,l);return new ta(((e,t)=>o.buildFormulaContent(i,e,t)),e,r,a,{...n.dependencies,references:l},{...s,format:c})}}).add("Empty",{sequence:20,match:e=>""===e,createCell:(e,t,s)=>new qr(e,s)}).add("Number",{sequence:30,match:e=>Q(e),createCell:(e,t,s)=>(!s.format&&t.includes("%")&&(s.format=t.includes(".")?"0.00%":"0%"),new jr(e,ee(t),s))}).add("Boolean",{sequence:40,match:e=>Es(e),createCell:(e,t,s)=>new Xr(e,"TRUE"===t.toUpperCase(),s)}).add("DateTime",{sequence:50,match:e=>bs(e),createCell:(e,t,s)=>{const i=Z(t),o=s.format||i.format;return new Kr(e,i.value,{...s,format:o})}}).add("MarkdownSheetLink",{sequence:60,match:e=>Ts(e),createCell:(e,t,s,i,o)=>new ea(e,t,s,(e=>o.tryGetSheetName(e)))}).add("MarkdownLink",{sequence:70,match:e=>Is(e),createCell:(e,t,s)=>new Jr(e,t,s)}).add("WebLink",{sequence:80,match:e=>{return t=e,Cs.test(t);var t},createCell:(e,t,s)=>new Jr(e,ys(t,t),s)});const oa=10,na="Sheet1";function ra(e){return e?("version"in(e=JSON.parse(JSON.stringify(e)))&&e.version<oa&&(e=function(e){for(let t=aa.findIndex((t=>t.from===e.version));t<aa.length;t++)e=aa[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,s=new ti;for(const i of e.sheets||[])for(const e of i.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(da(),e,{version:oa}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(ha(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(ha(na,"Sheet1"));return e}(e),e}(e),e):da()}const aa=[{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=ia(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,...i}=t.figures[e].data,o=[];for(let e of s)if(e.labelCell){const t=_s(e.dataRange),s=e.labelCell+":"+ss(t.right,t.bottom);o.push(s)}else o.push(e.dataRange);i.dataSetsHaveTitle=Boolean(s[0].labelCell),i.dataSets=o,t.figures[e].data=i}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){var t;const s=[],i=new RegExp(k,"g");for(let o of e.sheets||[]){if(!o.name)continue;const e=o.name,n=e.replace(i,"_");let r=1,a=n;for(;s.includes(a);)a=`${n}${r}`,r++;o.name=a,s.push(a);const l=t=>{if(void 0===t)return t;let s=t.replace(e,a),i=t;for(;i!==s;)i=s,s=i.replace(e,a);return i};for(let e in o.cells){const t=o.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(l))}for(let e of o.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 o.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,i]of Object.entries(t)){const t=`\\${$}${s}\\${$}`;e=e.replace(new RegExp(t,"g"),i)}s.content=e,delete s.formula}}return e}}];function la(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const s=[],i=[],o=e=>{if("CREATE_SHEET"===e.type)s.push(e.sheetId);else if("sheetId"in e&&!s.includes(e.sheetId))return{...e,sheetId:na};return e};for(const e of t)"REMOTE_REVISION"===e.type?i.push({...e,commands:e.commands.map(o)}):i.push(e);return i}(e,t),t=ca(t,"SORT_CELLS"),t=ca(t,"SET_DECIMAL")}function ca(e,t){const s=[];for(const i of e)"REMOTE_REVISION"===i.type?s.push({...i,commands:i.commands.filter((e=>e.type!==t))}):s.push(i);return s}function ha(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[]}}function da(e="Sheet1"){return{version:oa,sheets:[ha(na,e)],entities:{},styles:{},borders:{},revisionId:O,uniqueFigureIds:!0}}class ua{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 i=e.filter((e=>0!==e));if(i.length)return i}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}ua.getters=[],ua.modes=["headless","normal"];class pa extends ua{constructor(e,t,s,i,o,n){super(t,i,o),this.dispatch=i,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 ga extends pa{constructor(){super(...arguments),this.borders={}}handle(e){switch(e.type){case"ADD_MERGE":if(!e.interactive)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,i;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),s=e.base-1,i=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),s=e.base,i=e.base+e.quantity+1),this.ensureColumnBorderContinuity(t,s,i)}handleAddRows(e){const t=this.getters.getSheet(e.sheetId);let s,i;"before"===e.position?(this.shiftBordersVertically(t.id,e.base,e.quantity,{moveFirstTopBorder:!0}),s=e.base-1,i=e.base+e.quantity):(this.shiftBordersVertically(t.id,e.base+1,e.quantity,{moveFirstTopBorder:!1}),s=e.base,i=e.base+e.quantity+1),this.ensureRowBorderContinuity(t,s,i)}getCellBorder(e,t,s){var i,o,n,r,a,l,c,h,d,u,p,g;const f={top:null===(n=null===(o=null===(i=this.borders[e])||void 0===i?void 0:i[t])||void 0===o?void 0:o[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 i=fs(t+1,s);for(let o=0;o<e.rows.length;o++){const n=this.getCellBorder(e.id,t,o),r=this.getCellBorder(e.id,s,o);if(n&&r){const t=this.getCommonSides(n,r);for(let s of i)this.addBorder(e.id,s,o,t)}}}ensureRowBorderContinuity(e,t,s){const i=fs(t+1,s);for(let o=0;o<e.cols.length;o++){const n=this.getCellBorder(e.id,o,t),r=this.getCellBorder(e.id,o,s);if(n&&r){const t=this.getCommonSides(n,r);for(let s of i)this.addBorder(e.id,o,s,t)}}}getCommonSides(e,t){const s={};for(let i of["top","bottom","left","right"])e[i]&&e[i]===t[i]&&(s[i]=e[i]);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 fs(0,this.getters.getSheet(e).rows.length+1)}shiftBordersHorizontally(e,t,s,{moveFirstLeftBorder:i}={}){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((o=>{(o===t&&i||o!==t)&&this.moveBordersOfColumn(e,o,s,"vertical"),this.moveBordersOfColumn(e,o,s,"horizontal")})))}shiftBordersVertically(e,t,s,{moveFirstTopBorder:i}={}){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((o=>{(o===t&&i||o!==t)&&this.moveBordersOfRow(e,o,s,"horizontal"),this.moveBordersOfRow(e,o,s,"vertical")})))}moveBordersOfRow(e,t,s,i,{destructive:o}={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[i],u=null===(h=null===(c=n[r])||void 0===c?void 0:c[t])||void 0===h?void 0:h[i];this.history.update("borders",e,r,t+s,i,o?u:u||d),this.history.update("borders",e,r,t,i,void 0)}))}moveBordersOfColumn(e,t,s,i,{destructive:o}={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[i],u=null===(h=null===(c=n[t])||void 0===c?void 0:c[r])||void 0===h?void 0:h[i];this.history.update("borders",e,t+s,r,i,o?u:u||d),this.history.update("borders",e,t,r,i,void 0)}))}setBorder(e,t,s,i){this.history.update("borders",e,t,s,{vertical:null==i?void 0:i.left,horizontal:null==i?void 0:i.top}),this.history.update("borders",e,t+1,s,"vertical",null==i?void 0:i.right),this.history.update("borders",e,t,s+1,"horizontal",null==i?void 0:i.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 i=s.left;i<=s.right;i++)this.history.update("borders",e,i,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,i){this.setBorder(e,t,s,{...this.getCellBorder(e,t,s),...i})}setBorders(e,t,s){const i=e.id;if("clear"===s)return this.clearBorders(i,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(i,s,t,{top:L});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(i,s,t,{left:L});if("left"===s||"all"===s||"external"===s)for(let t=e.top;t<=e.bottom;t++)this.addBorder(i,e.left,t,{left:L});if("right"===s||"all"===s||"external"===s)for(let t=e.top;t<=e.bottom;t++)this.addBorder(i,e.right+1,t,{left:L});if("top"===s||"all"===s||"external"===s)for(let t=e.left;t<=e.right;t++)this.addBorder(i,t,e.top,{top:L});if("bottom"===s||"all"===s||"external"===s)for(let t=e.left;t<=e.right;t++)this.addBorder(i,t,e.bottom+1,{top:L})}}addBordersToMerge(e,t){const s=this.getters.getSheet(e),{left:i,right:o,top:n,bottom:r}=t,a=this.getCellBorder(s.id,i,n),l=this.getCellBorder(s.id,o,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:i}],"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:o}],"right")}import(e){if(e.borders)for(let t of e.sheets)for(let[s,i]of Object.entries(t.cells))if(null==i?void 0:i.border){const o=e.borders[i.border],[n,r]=ts(s);this.setBorder(t.id,n,r,o)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,_s(e))}export(e){let t=0;const s={};function i(e){for(let[t,i]of Object.entries(s))if(cs(i)===cs(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 o=this.getCellBorder(t.id,e,s);if(o){const n=ss(e,s),r=t.cells[n],a=i(o);r?r.border=a:t.cells[n]={border:a}}}e.borders=s}exportForExcel(e){this.export(e)}}ga.getters=["getCellBorder"];const fa=new RegExp(String.fromCharCode(160),"g");class ma extends pa{constructor(){super(...arguments),this.cells={},this.createCell=function(e){const t=Hr.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(s,i,o,n){const r=t.find((e=>e.match(i)));if(!r)return new Yr(s,i,o);try{return r.createCell(s,i,o,n,e)}catch(e){return new sa(s,i,e.message||N,o)}}}(this.getters)}adaptRanges(e,t){for(const s of Object.keys(this.cells))for(const i of Object.values(this.cells[s]||{}))if(i.isFormula())for(const o of i.dependencies.references)if(!t||o.sheetId===t){const t=e(o);"NONE"!==t.changeType&&this.history.update("cells",s,i.id,"dependencies","references",i.dependencies.references.indexOf(o),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 i of t)for(let t=i.top;t<=i.bottom;t++)for(let o=i.left;o<=i.right;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:o,row:t,format:s})}clearStyles(e,t){for(let s of t)for(let t=s.left;t<=s.right;t++)for(let i=s.top;i<=s.bottom;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:null})}handleAddColumnsRows(e,t){const s=this.getters.getSheet(e.sheetId);let i,o;"before"===e.position?(i=fs(e.base,e.base+e.quantity),o=e.base+e.quantity):(i=fs(e.base+1,e.base+e.quantity+1),o=e.base),t(s,o,i)}import(e){for(let t of e.sheets){const s=this.getters.getSheet(t.id);for(let i in t.cells){const o=t.cells[i],[n,r]=ts(i);if((null==o?void 0:o.content)||(null==o?void 0:o.format)||(null==o?void 0:o.style)){const i=this.importCell(s,o,e.styles);this.history.update("cells",t.id,i.id,i),this.dispatch("UPDATE_CELL_POSITION",{cell:i,cellId:i.id,col:n,row:r,sheetId:t.id})}}}}export(e){let t=0;const s={};function i(e){for(let[t,i]of Object.entries(s))if(cs(i)===cs(e))return parseInt(t,10);return s[++t]=e,t}for(let t of e.sheets){const e={},s=Object.keys(this.cells[t.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:o,row:n}of s){const s=this.getters.getCell(t.id,o,n);e[ss(o,n)]={style:s.style&&i(s.style),format:s.format,content:s.content}}t.cells=e}e.styles=s}importCell(e,t,s){const i=t.style&&s[t.style]||void 0,o=this.uuidGenerator.uuidv4(),n={format:null==t?void 0:t.format,style:i};return this.createCell(o,(null==t?void 0:t.content)||"",n,e.id)}exportForExcel(e){this.export(e);for(let t of e.sheets)for(const e in t.cells){const[s,i]=ts(e),o=this.getters.getCell(t.id,s,i),n=t.cells[e];n.value=o.evaluated.value,n.isFormula=o.isFormula()}}getCells(e){return this.cells[e]||{}}getCellById(e){for(const t of Object.values(this.cells))if(t[e])return t[e]}buildFormulaContent(e,t,s){let i=t;for(let[t,o]of Object.entries(s.references)){const s=this.getters.getRangeString(o,e),n=`\\${$}${t}\\${$}`;i=i.replace(new RegExp(n,"g"),s)}for(let[e,t]of Object.entries(s.strings)){const s=`\\${$}S${e}\\${$}`;i=i.replace(new RegExp(s,"g"),`"${t}"`)}for(let[e,t]of Object.entries(s.numbers)){const s=`\\${$}N${e}\\${$}`;i=i.replace(new RegExp(s,"g"),t.toString())}return i}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t.normalizedText,t.dependencies)}getCellStyle(e){return e.style||{}}zoneToXC(e,t,s=[{colFixed:!1,rowFixed:!1}]){const i=ss((t=this.getters.expandZone(e,t)).left,t.top,s[0]),o=ss(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 i==o||a?i:i+":"+o}setStyle(e,t,s){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++){const i=this.getters.getCell(e,t,o);this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:s?{...null==i?void 0:i.style,...s}:void 0})}}copyColumnStyle(e,t,s){for(let i=0;i<e.rows.length;i++){const o=this.getFormat(e.id,t,i);if(o.style||o.format)for(let t of s)this.dispatch("UPDATE_CELL",{sheetId:e.id,col:t,row:i,...o})}}copyRowStyle(e,t,s){for(let i=0;i<e.cols.length;i++){const o=this.getFormat(e.id,i,t);if(o.style||o.format)for(let t of s)this.dispatch("UPDATE_CELL",{sheetId:e.id,col:i,row:t,...o})}}getFormat(e,t,s){const i={},[o,n]=this.getters.getMainCell(e,t,s),r=this.getters.getCell(e,o,n);return r&&(r.style&&(i.style=r.style),r.format&&(i.format=r.format)),i}updateCell(e,t,s,i){var o;const n=e.rows[s].cells[t],r="content"in i||"formula"in i,a=r?(null===(o=i.content)||void 0===o?void 0:o.replace(fa,""))||"":(null==n?void 0:n.content)||"";let l;l=void 0!==i.style?i.style||void 0:n?n.style:void 0;let c=("format"in i?i.format:n&&n.format)||F;if((r&&!a&&!i.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:n.id,col:t,row:s,sheetId:e.id,cell:void 0})));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===Ne.error&&p.assignError(n.evaluated.value,n.evaluated.error)),this.history.update("cells",e.id,p.id,p),this.dispatch("UPDATE_CELL_POSITION",{cell:p,cellId:p.id,col:t,row:s,sheetId:e.id})}checkCellOutOfSheet(e,t,s){const i=this.getters.tryGetSheet(e);if(!i)return 23;return Us(t,s,{top:0,left:0,bottom:i.rows.length-1,right:i.cols.length-1})?0:18}}ma.getters=["zoneToXC","getCells","getFormulaCellContent","getCellStyle","buildFormulaContent","getCellById"];class va extends pa{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 i of e.dataSets){if(i.labelCell){const o=s(i.labelCell);switch(o.changeType){case"REMOVE":this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(i),"labelCell",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(i),"labelCell",o.range)}}const o=s(i.dataRange);switch(o.changeType){case"REMOVE":const s=e.dataSets.filter((e=>e!==i));this.history.update("chartFigures",t,"dataSets",s);break;case"RESIZE":case"MOVE":case"CHANGE":if(this.getters.getRangeString(o.range,o.range.sheetId)!==_)this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(i),"dataRange",o.range);else{const s=e.dataSets.filter((e=>e!==i));this.history.update("chartFigures",t,"dataSets",s)}}}}adaptLabelRanges(e,t,s){if(e.labelRange){const i=s(e.labelRange);switch(i.changeType){case"REMOVE":this.history.update("chartFigures",t,"labelRange",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("chartFigures",t,"labelRange",i.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 i=e.position?e.position.x:0,o=e.position?e.position.y:0;this.addChartFigure(e.sheetId,this.createChartDefinition(e.definition,e.sheetId),{id:e.id,x:i,y:o,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 i of s)if("chart"===i.tag){const s=i.id.split("??").pop(),o=`${e.sheetIdTo}??${s}`,n={...ds(this.chartFigures[i.id]),id:o};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:o,x:i.x,y:i.y,height:i.height,width:i.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 i=s.dataSets.map((t=>t?this.getters.getRangeString(t.dataRange,e):"")).filter((e=>""!==e));return{title:s&&s.title?s.title:"",dataSets:i,labelRange:s.labelRange?this.getters.getRangeString(s.labelRange,e):void 0,type:s?s.type:"bar",dataSetsHaveTitle:!(!s||0===i.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],i=this.getChartDefinitionUI("forceSheetReference",t);if(!s||!i)return;const o=s.dataSets.map((e=>this.toExcelDataset(e))).filter((e=>""!==e.range));return{...i,backgroundColor:s.background,dataSets:o}}toExcelDataset(e){var t;const s=null===(t=e.labelCell)||void 0===t?void 0:t.zone;let i=e.dataRange.zone;if(s){const{height:e,width:t}=Hs(i);1===e?i={...i,left:i.left+1}:1===t&&(i={...i,top:i.top+1})}const o={...e.dataRange,zone:i};return{label:e.labelCell?this.getters.getRangeString(e.labelCell,"forceSheetReference"):void 0,range:this.getters.getRangeString(o,"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 i of e){const e=i;if(e&&"chart"===e.tag){const i=this.getChartDefinitionUI(t.id,e.id);i&&(e.data=i,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 i of e){const e=i;if(e&&"chart"===e.tag){const i=this.getChartDefinitionExcel(t.id,e.id);i&&(e.data=i,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 i=!!t.dataSetsHaveTitle,o=this.createDataSets(t.dataSets,s.sheetId,i);this.history.update("chartFigures",e,"dataSets",o)}if(void 0!==t.labelRange){const i=t.labelRange?this.getters.getRangeFromSheetXC(s.sheetId,t.labelRange):void 0;this.history.update("chartFigures",e,"labelRange",i)}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 i=[];for(const o of e){const e=this.getters.getRangeFromSheetXC(t,o),{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};i.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||i.push(this.createDataSet(r,n,void 0)):i.push(this.createDataSet(r,n,s?{top:n.top,bottom:n.top,left:n.left,right:n.left}:void 0))}return i}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: ${Ns(t)}`);if(s){const i=Ns(t),o=Ns(s);return{labelCell:this.getters.getRangeFromSheetXC(e,o),dataRange:this.getters.getRangeFromSheetXC(e,i)}}return{labelCell:void 0,dataRange:this.getters.getRangeFromSheetXC(e,Ns(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=>!Qt.test(e)));return t?28:0}checkLabelRange(e){if(!e.definition.labelRange)return 0;return!Qt.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 Ea(e){return""===e?NaN:Number(e)}va.getters=["getChartDefinition","getChartDefinitionUI","getChartsIdBySheet"];class ba extends pa{constructor(){super(...arguments),this.cfRules={}}loopThroughRangesOfSheet(e,t){for(const s of this.cfRules[e])for(const i of s.ranges){const o=t(i);switch(o.changeType){case"REMOVE":let t=s.ranges.slice();t.splice(s.ranges.indexOf(i),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(i),o.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(Ns)};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 i=t.top;i<=t.bottom;i++)for(let o=t.left;o<=t.right;o++){this.getRulesByCell(e,o,i).forEach((e=>{s.add(e.id)}))}return s}getRulesByCell(e,t,s){const i=[];for(let o of this.cfRules[e])for(let e of o.ranges)Us(t,s,e.zone)&&i.push(o);return new Set(i.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(),i=s.findIndex((t=>t.id===e.id)),o=this.mapToConditionalFormatInternal(t,e);i>-1?s.splice(i,1,o):s.push(o),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=[],i=e=>void 0===e||""===e;return e>=1&&i(s.values[0])&&t.push(36),e>=2&&i(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{Dr(Vr(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&&Ea(t)>=Ea(s)?32:0}checkMidBiggerThanMax(e){var t;const s=null===(t=e.midpoint)||void 0===t?void 0:t.value,i=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&Ea(s)>=Ea(i)?34:0}checkMinBiggerThanMid(e){var t;const s=e.minimum.value,i=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&&Ea(s)>=Ea(i)?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)}}}ba.getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];class Sa extends pa{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,...i}=e,o=i;this.updateFigure(s,o);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId)}}updateFigure(e,t){if("id"in t)for(const[s,i]of Object.entries(t))switch(s){case"x":case"y":void 0!==i&&this.history.update("figures",e,t.id,s,Math.max(i,0));break;case"width":case"height":void 0!==i&&this.history.update("figures",e,t.id,s,i)}}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(Ls)}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)}}Sa.getters=["getFigures","getFigure","getFigureSheetId"];class Ca extends pa{constructor(){super(...arguments),this.nextId=1,this.pending=null,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}}beforeHandle(e){switch(e.type){case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.exportAndRemoveMerges(e.sheetId,(t=>function(e,t){let{left:s,right:i,top:o,bottom:n}=_s(e);t=t.slice().sort(((e,t)=>t-e));for(let e of t)s>e&&(s-=1),(s>=e||i>=e)&&(i-=1);return s>i?null:ss(s,o)+":"+ss(i,n)}(t,e.elements)),!0):this.exportAndRemoveMerges(e.sheetId,(t=>function(e,t){let{left:s,right:i,top:o,bottom:n}=_s(e);t=t.slice().sort(((e,t)=>t-e));for(let e of t)o>e&&(o-=1),(o>=e||n>=e)&&(n-=1);return o>n?null:ss(s,o)+":"+ss(i,n)}(t,e.elements)),!1);break;case"ADD_COLUMNS_ROWS":const t="before"===e.position?e.base:e.base+1;"COL"===e.dimension?this.exportAndRemoveMerges(e.sheetId,(s=>function(e,t,s){let{left:i,right:o,top:n,bottom:r}=_s(e);return i>=t&&(i+=s),(i>=t||o>=t)&&(o+=s),i>o?null:ss(i,n)+":"+ss(o,r)}(s,t,e.quantity)),!0):this.exportAndRemoveMerges(e.sheetId,(s=>function(e,t,s){let{left:i,right:o,top:n,bottom:r}=_s(e);return n>=t&&(n+=s),(n>=t||r>=t)&&(r+=s),n>r?null:ss(i,n)+":"+ss(o,r)}(s,t,e.quantity)),!1)}}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":this.history.update("merges",e.sheetIdTo,Object.assign({},this.merges[e.sheetId])),this.history.update("mergeCellMap",e.sheetIdTo,Object.assign({},this.mergeCellMap[e.sheetId]));break;case"ADD_MERGE":if(!e.interactive)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);break;case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":this.pending&&(this.importMerges(this.pending.sheet,this.pending.merges),this.pending=null)}}getMerges(e){return Object.values(this.merges[e]||{}).filter(Ls)}getMerge(e,t,s){var i;const o=this.mergeCellMap[e],n=o?t in o&&(null===(i=o[t])||void 0===i?void 0:i[s]):void 0;return n?this.getMergeById(e,n):void 0}doesIntersectMerge(e,t){const{left:s,right:i,top:o,bottom:n}=t;for(let t=o;t<=n;t++)for(let o=s;o<=i;o++)if(this.getMerge(e,o,t))return!0;return!1}doesColumnsHaveCommonMerges(e,t,s){const i=this.getters.getSheet(e);for(let e=0;e<i.rows.length;e++)if(this.isInSameMerge(i.id,t,e,s,e))return!0;return!1}doesRowsHaveCommonMerges(e,t,s){const i=this.getters.getSheet(e);for(let e=0;e<=i.cols.length;e++)if(this.isInSameMerge(i.id,e,t,e,s))return!0;return!1}expandZone(e,t){let{left:s,right:i,top:o,bottom:n}=t,r={left:s,right:i,top:o,bottom:n};for(let t in this.merges[e]){const s=this.getMergeById(e,parseInt(t));s&&Ps(s,r)&&(r=$s(s,r))}return Ds(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,s,i,o){return!(!this.isInMerge(e,t,s)||!this.isInMerge(e,i,o))&&this.getMerge(e,t,s)===this.getMerge(e,i,o)}isInMerge(e,t,s){var i;const o=this.mergeCellMap[e];return!!o&&(t in o&&Boolean(null===(i=o[t])||void 0===i?void 0:i[s]))}getMainCell(e,t,s){if(!this.isInMerge(e,t,s))return[t,s];const i=this.getMerge(e,t,s).topLeft;return[i.col,i.row]}getBottomLeftCell(e,t,s){if(!this.isInMerge(e,t,s))return[t,s];const{bottom:i,left:o}=this.getMerge(e,t,s);return[o,i]}isMergeHidden(e,t){const s=this.getters.getHiddenColsGroups(e),i=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 i)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 Ds(t,s);const{width:i,height:o}=Hs(t);return 1===i&&1===o}isMergeDestructive(e,t){let{left:s,right:i,top:o,bottom:n}=t;i=ps(i,0,e.cols.length-1),n=ps(n,0,e.rows.length-1);for(let t=o;t<=n;t++){const n=this.getters.getRow(e.id,t);for(let e=s;e<=i;e++)if(e!==s||t!==o){const t=n.cells[e];if(t&&!t.isEmpty())return!0}}return!1}getMergeById(e,t){const s=this.merges[e];return void 0!==s?s[t]: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&&Ps(t,s))return 50;return 0}checkMergedContentUpdate(e){const{col:t,row:s,sheetId:i,content:o}=e;if(void 0===o)return 0;const[n,r]=this.getMainCell(i,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:i}=e,o=this.getMerge(t,s,i);if(void 0===o||!Ds(e,o))return 5}return 0}addMerge(e,t){let{left:s,right:i,top:o,bottom:n}=t;i=ps(i,0,e.cols.length-1),n=ps(n,0,e.rows.length-1);if(ss(s,o)===ss(i,n))return;const r=this.getters.getCell(e.id,s,o);let a=this.nextId++;this.history.update("merges",e.id,a,{id:a,left:s,top:o,right:i,bottom:n,topLeft:{col:s,row:o}});let l=new Set;for(let t=o;t<=n;t++)for(let n=s;n<=i;n++){n===s&&t===o||this.dispatch("UPDATE_CELL",{sheetId:e.id,col:n,row:t,style:r?r.style:null,content:void 0});const i=this.getMerge(e.id,n,t);i&&l.add(i.id),this.history.update("mergeCellMap",e.id,n,t,a)}for(let t of l){const{top:s,bottom:i,left:o,right:n}=this.getMergeById(e.id,t);for(let t=s;t<=i;t++)for(let s=o;s<=n;s++){const i=this.getMerge(e.id,s,t);i&&i.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:i,bottom:o,right:n}=t,r=this.getMerge(e,s,i);if(void 0!==r&&Ds(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=i;t<=o;t++)for(let i=s;i<=n;i++)this.history.update("mergeCellMap",e,i,t,void 0)}}removeAllMerges(e){for(let t in this.merges[e])this.history.update("merges",e,parseInt(t),void 0);for(let t in this.mergeCellMap[e])this.history.update("mergeCellMap",e,parseInt(t),void 0)}exportAndRemoveMerges(e,t,s){const i=this.merges[e];if(!i)return;const o=Ia(i),n=[];for(let e of o){const s=t(e);if(s){const[e,t]=s.split(":");e!==t&&n.push(s)}}this.removeAllMerges(e),this.pending={sheet:e,merges:n}}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,_s(e))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...Ia(e))}}exportForExcel(e){this.export(e)}}function Ia(e){return Object.values(e).filter(Ls).map((e=>ss(e.left,e.top)+":"+ss(e.right,e.bottom)))}Ca.getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCell","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","isSingleCellOrMerge"];class ya extends pa{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,i="COL"===e.dimension?t.cols:t.rows;return(s||[]).flat().concat(e.elements).length<i.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":e.interactive||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:i}=this.getImportedSheetSize(t),o={id:t.id,name:e,cols:Ks(t.cols||{},s),rows:Qs(t.rows||{},i),hiddenColsGroups:[],hiddenRowsGroups:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible};this.visibleSheets.push(o.id),this.sheets[o.id]=o,this.updateHiddenElementsGroups(o.id,"cols"),this.updateHiddenElementsGroups(o.id,"rows")}}exportSheets(e,t=!1){e.sheets=this.visibleSheets.filter(Ls).map((e=>{const s=this.sheets[e];return{id:s.id,name:s.name,colNumber:s.cols.length,rowNumber:s.rows.length,rows:ei(s.rows,t),cols:Js(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}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(Ls)}getVisibleSheets(){return this.visibleSheets}getEvaluationSheets(){return this.sheets}getCol(e,t){var s;return null===(s=this.sheets[e])||void 0===s?void 0:s.cols[t]}getRow(e,t){var s;return null===(s=this.sheets[e])||void 0===s?void 0:s.rows[t]}getCell(e,t,s){const i=this.tryGetSheet(e);return i&&i.rows[s]&&i.rows[s].cells[t]||void 0}getColCells(e,t){return this.getSheet(e).rows.reduce(((e,s)=>{const i=s.cells[t];return void 0!==i?e.concat(i):e}),[])}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 i=`${e}${t}`;for(;s.includes(i);)i=`${e}${t}`,t++;return i}isEmpty(e,t){return zs(t,this.getSheet(e),(e=>e),void 0).flat().every((e=>!e||e.isEmpty()))}setHeaderSize(e,t,s,i){let o,n;const r=e[t],a=r[s],l=i-a.size;this.history.update("sheets",e.id,t,s,"size",i),a.isHidden||this.history.update("sheets",e.id,t,s,"end",a.end+l),o=a.end;for(let i=s+1;i<r.length;i++){const s=r[i];n=s.isHidden?o:o+s.size,this.history.update("sheets",e.id,t,i,"start",o),this.history.update("sheets",e.id,t,i,"end",n),o=n}}updateCellPosition(e){if(e.cell){const t=this.cellPosition[e.cellId];t&&this.history.update("sheets",e.sheetId,"rows",t.row,"cells",t.col,void 0),this.history.update("cellPosition",e.cell.id,{row:e.row,col:e.col,sheetId:e.sheetId}),this.history.update("sheets",e.sheetId,"rows",e.row,"cells",e.col,e.cell)}else this.history.update("cellPosition",e.cellId,void 0),this.history.update("sheets",e.sheetId,"rows",e.row,"cells",e.col,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 i=s.top;i<=s.bottom;i++){this.sheets[e].rows[i].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:i})}}createSheet(e,t,s,i,o){const n={id:e,name:t,cols:Xs(s),rows:Ys(i),hiddenColsGroups:[],hiddenRowsGroups:[],areGridLinesVisible:!0},r=this.visibleSheets.slice();r.splice(o,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(),i=s.findIndex((t=>t===e)),o=s.splice(i,1);s.splice(i+("left"===t?-1:1),0,o[0]),this.history.update("visibleSheets",s)}checkSheetName(e){const{visibleSheets:t,sheets:s}=this,i=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())===i}))?11:k.test(i)?13:0}checkSheetPosition(e){const{visibleSheets:t}=this;return e.position>t.length||e.position<0?15:0}isRenameAllowed(e){if(e.interactive)return 0;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 i=Object.assign({},this.sheetIds);i[t]=e.id,delete i[s],this.history.update("sheetIds",i)}duplicateSheet(e,t){const s=this.getSheet(e),i=this.getDuplicateSheetName(s.name),o=JSON.parse(JSON.stringify(s));o.id=t,o.name=i;for(let e=0;e<=o.cols.length;e++)for(let t=0;t<=o.rows.length;t++)o.rows[t]&&(o.rows[t].cells[e]=void 0);const n=this.visibleSheets.slice(),r=n.findIndex((t=>t===e));n.splice(r+1,0,o.id),this.history.update("visibleSheets",n),this.history.update("sheets",Object.assign({},this.sheets,{[o.id]:o}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:s}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:o.id,col:e,row:s,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIds);a[o.name]=o.id,this.history.update("sheetIds",a)}getDuplicateSheetName(e){let t=1;const s=this.getters.getSheets().map((e=>e.name)),i=a("Copy of %s",e);let o=i.toString();for(;s.includes(o);)o=`${i} (${t})`,t++;return o}deleteSheet(e){const t=e.name,s=Object.assign({},this.sheets);delete s[e.id],this.history.update("sheets",s);const i=this.visibleSheets.slice(),o=i.findIndex((t=>t===e.id));i.splice(o,1),this.history.update("visibleSheets",i);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 ms(t))this.moveCellOnRowsDeletion(e,s[s.length-1],s[0]),s.map((t=>this.updateRowsStructureOnDeletion(t,e)))}addColumns(e,t,s,i){this.moveCellsOnAddition(e,"before"===s?t:t+1,i,"columns"),this.updateColumnsStructureOnAddition(e,t,i)}addRows(e,t,s,i){this.addEmptyRows(e,i),this.moveCellsOnAddition(e,"before"===s?t:t+1,i,"rows"),this.updateRowsStructureOnAddition(e,t,i)}moveCellOnColumnsDeletion(e,t){for(let[s,i]of Object.entries(e.rows)){const o=parseInt(s,10);for(let s in i.cells){const n=parseInt(s,10),r=i.cells[s];r&&(n===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:n,row:o}),n>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r.id,cell:r,col:n-1,row:o}))}}}moveCellsOnAddition(e,t,s,i){const o=[];for(const[n,r]of Object.entries(e.rows)){const a=parseInt(n,10);if("rows"!==i||a>=t)for(let n in r.cells){const l=parseInt(n,10),c=r.cells[n];c&&("rows"===i||l>=t)&&o.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c.id,cell:c,col:l+("columns"===i?s:0),row:a+("rows"===i?s:0)})}}for(let e of o.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,s){const i=s-t+1;for(let[o,n]of Object.entries(e.rows)){const r=parseInt(o,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),o=n.cells[t];o&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:o.id,cell:o,col:s,row:r-i})}}}updateColumnsStructureOnDeletion(e,t){const s=[];let i=0,o=0;for(let n in e.cols){if(t.includes(parseInt(n,10)))continue;const{size:r,isHidden:a}=e.cols[n],l=a?i:i+r;s.push({name:es(o),size:r,start:i,end:l,isHidden:a}),i=l,o++}this.history.update("sheets",e.id,"cols",s),this.updateHiddenElementsGroups(e.id,"cols")}updateColumnsStructureOnAddition(e,t,s){const i=[];let o=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++)i.push({name:es(n),size:t,start:o,end:o+t}),o+=t,n++}const{size:a,isHidden:l}=e.cols[r],c=l?o:o+a;i.push({name:es(n),size:a,start:o,end:c,isHidden:l}),o=c,n++}this.history.update("sheets",e.id,"cols",i),this.updateHiddenElementsGroups(e.id,"cols")}updateRowsStructureOnDeletion(e,t){const s=[];let i=0,o=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?i:i+l;parseInt(r,10)!==e&&(o++,s.push({start:i,end:h,size:l,cells:n.shift(),name:String(o),isHidden:c}),i=h)}this.history.update("sheets",t.id,"rows",s),this.updateHiddenElementsGroups(t.id,"rows")}updateRowsStructureOnAddition(e,t,s){const i=[];let o=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?o:o+c;(parseInt(l,10)<t||parseInt(l,10)>=t+s)&&r++,n++,i.push({start:o,end:d,size:c,cells:a.shift(),name:String(n),isHidden:h}),o=d}this.history.update("sheets",e.id,"rows",i),this.updateHiddenElementsGroups(e.id,"rows")}addEmptyRows(e,t){const s=e.rows[e.rows.length-1].end,i=e.rows.slice();for(let e=0;e<t;e++)i.push({start:s,end:s,size:0,name:(i.length+1).toString(),cells:{}});this.history.update("sheets",e.id,"rows",i)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(ts);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,i){let o=0;const n="hide"===i;for(let i=0;i<e[s].length;i++){const{size:r,isHidden:a}=e[s][i],l=t.includes(i)?n:a||!1,c=l?o:o+r;this.history.update("sheets",e.id,s,i,"start",o),this.history.update("sheets",e.id,s,i,"end",c),this.history.update("sheets",e.id,s,i,"isHidden",l),o=c}this.updateHiddenElementsGroups(e.id,s)}updateHiddenElementsGroups(e,t){var s;const i="cols"===t?"hiddenColsGroups":"hiddenRowsGroups",o=((null===(s=this.sheets[e])||void 0===s?void 0:s[t])||[]).reduce(((e,t,s)=>{if(!t.isHidden)return e;const i=e[e.length-1];return i&&i[i.length-1]==s-1||e.push([]),e[e.length-1].push(s),e}),[]);this.history.update("sheets",e,i,o)}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(Os))return 22;if(t.length&&"sheetId"in e){const s=this.getSheet(e.sheetId),i={top:0,left:0,bottom:s.rows.length-1,right:s.cols.length-1};return t.every((e=>{return Ds($s(t=i,e),t);var t}))?0:18}return 0}}ya.getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheets","getVisibleSheets","getEvaluationSheets","getCol","getRow","getCell","getCellPosition","getColCells","getColsZone","getRowsZone","getNumberCols","getNumberRows","getHiddenColsGroups","getHiddenRowsGroups","getGridLinesVisibility","getNextSheetName","isEmpty"];const wa=new Re;wa.add("INCREMENT_MODIFIER",{apply:(e,t)=>{var s;e.current+=e.increment;const i=e.current.toString(),o=Zr(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:i},tooltip:i?{props:{content:o}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,s)=>{var i,o;const n=(null===(i=t.cell)||void 0===i?void 0:i.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===(o=t.cell)||void 0===o?void 0:o.formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,s,i)=>{e.current+=e.increment;let o=0,n=0;switch(i){case 0:o=0,n=-e.current;break;case 1:o=0,n=e.current;break;case 2:o=-e.current,n=0;break;case 3:o=e.current,n=0}if(!t.cell||!t.cell.isFormula())return{cellData:{}};const r=t.sheetId,a=s.createAdaptedRanges(t.cell.dependencies.references,o,n,r),l=s.buildFormulaContent(r,t.cell.normalizedText,{...t.cell.dependencies,references:a});return{cellData:{border:t.border,style:t.cell.style,format:t.cell.format,content:l},tooltip:l?{props:{content:l}}:void 0}}});const xa=new Re;xa.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(A))},generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("copy_text",{condition:e=>!e.isFormula()&&e.evaluated.type===Ne.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===Ne.number,generateRule:(e,t)=>{const s=function(e,t){let s=[],i=!1;for(let o of t)if(o===e&&(i=!0),(null==o?void 0:o.evaluated.type)===Ne.number)s.push(o.evaluated.value);else{if(i)return s;s=[]}return s}(e,t);let i=1;return 2==s.length?i=2*(s[1]-s[0]):s.length>2&&(i=function(e){const t=[];let s=e[0];for(let i=1;i<e.length;i++){const o=e[i];t.push(o-s),s=o}return t.reduce(((e,t)=>e+t),0)/t.length}(s)*s.length),{type:"INCREMENT_MODIFIER",increment:i,current:e.evaluated.type===Ne.number?e.evaluated.value:0}},sequence:40});const Ta=new Re,Ra=(new Re).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let s=e.base;"after"===e.position&&s++;for(let i=0;i<e.quantity;i++)t.push(i+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 i of ms(s)){const s=0===i[0]?0:i[0]-1,o=0===i[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:i.length,base:s,sheetId:e.sheetId,position:o})}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 $e.values())Ra.contains(e)||Ra.add(e,La);function La(e){return[e]}const Ma=e=>({isVisible:()=>!0,isEnabled:()=>!0,isReadonlyAllowed:!1,shortCut:"",action:!1,children:[],separator:!1,icon:!1,id:e});function Aa(e,t){return Object.assign({},Ma(e),t)}class _a extends Re{add(e,t){return this.content[e]=Aa(e,t),this}addChild(e,t,s){const i=t.splice(0,1)[0];let o=this.content[i];if(!o)throw new Error(`Path ${i+":"+t.join(":")} not found`);for(let e of t)if(o="function"==typeof o.children?void 0:o.children.find((t=>t.id===e)),!o)throw new Error(`Path ${i+":"+t.join(":")} not found`);return o.children.push(Aa(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))}}function Oa(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 Na(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 ka(e,t){e.dispatch("SET_FORMATTING",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones(),format:t})}function Fa(e,t){e.dispatch("SET_FORMATTING",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones(),style:t})}const $a=async e=>{e.dispatch("COPY",{target:e.getters.getSelectedZones()}),await e.clipboard.writeText(e.getters.getClipboardContent())},Da=async e=>{e.dispatch("CUT",{target:e.getters.getSelectedZones()}),await e.clipboard.writeText(e.getters.getClipboardContent())},Pa=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 i=e.getters.getSelectedZones();s&&s!==t?e.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:i,text:s}):e.dispatch("PASTE",{target:i,interactive:!0})},Ua=e=>e.dispatch("PASTE",{target:e.getters.getSelectedZones(),pasteOption:"onlyValue"}),Ba=e=>e.dispatch("PASTE",{target:e.getters.getSelectedZones(),pasteOption:"onlyFormat"}),Va=e=>e.dispatch("DELETE_CONTENT",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones()}),za=e=>{let t,s;const i=e.getters.getActiveRows();if(0!==i.size)t=Math.min(...i),s=Math.max(...i);else{const i=e.getters.getSelectedZones()[0];t=i.top,s=i.bottom}return t===s?a("Delete row %s",(t+1).toString()):a("Delete rows %s - %s",(t+1).toString(),(s+1).toString())},Ha=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})},Za=e=>{let t,s;const i=e.getters.getActiveCols();if(0!==i.size)t=Math.min(...i),s=Math.max(...i);else{const i=e.getters.getSelectedZones()[0];t=i.left,s=i.right}return t===s?a("Delete column %s",es(t)):a("Delete columns %s - %s",es(t),es(s))},Ga=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})},Wa=e=>{const t=e.getters.getSelectedZone();e.dispatch("INSERT_CELL",{shiftDimension:"ROW",zone:t,interactive:!0})},qa=e=>{const t=e.getters.getSelectedZone();e.dispatch("INSERT_CELL",{shiftDimension:"COL",zone:t,interactive:!0})},ja=e=>{const t=e.getters.getSelectedZone();e.dispatch("DELETE_CELL",{shiftDimension:"ROW",zone:t,interactive:!0})},Xa=e=>{const t=e.getters.getSelectedZone();e.dispatch("DELETE_CELL",{shiftDimension:"COL",zone:t,interactive:!0})},Ya=e=>{const t=e.getters.getActiveRows();let s,i;if(t.size)s=Math.min(...t),i=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.top,i=t.bottom-t.top+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"before",base:s,quantity:i,dimension:"ROW"})},Ka=e=>{const t=e.getters.getActiveRows();let s,i;if(t.size)s=Math.max(...t),i=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.bottom,i=t.bottom-t.top+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"after",base:s,quantity:i,dimension:"ROW"})},Qa=e=>{const t=e.getters.getActiveCols();let s,i;if(t.size)s=Math.min(...t),i=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.left,i=t.right-t.left+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"before",dimension:"COL",base:s,quantity:i})},Ja=e=>{const t=e.getters.getActiveCols();let s,i;if(t.size)s=Math.max(...t),i=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.right,i=t.right-t.left+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"after",dimension:"COL",base:s,quantity:i})},el=e=>{e.openSidePanel("ConditionalFormatting",{selection:e.getters.getSelectedZones()})},tl=e=>{e.openLinkEditor()},sl=e=>{const{anchor:t,zones:s}=e.getters.getSelection();e.dispatch("SORT_CELLS",{interactive:!0,sheetId:e.getters.getActiveSheetId(),anchor:t,zone:s[0],sortDirection:"ascending"})},il=e=>{const{anchor:t,zones:s}=e.getters.getSelection();e.dispatch("SORT_CELLS",{interactive:!0,sheetId:e.getters.getActiveSheetId(),anchor:t,zone:s[0],sortDirection:"descending"})},ol=e=>1===e.getters.getSelectedZones().length,nl=new _a;nl.add("cut",{name:a("Cut"),shortCut:"Ctrl+X",sequence:10,action:Da}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:$a}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:Pa,isVisible:ol}).add("paste_special",{name:a("Paste special"),sequence:40,separator:!0,isVisible:ol}).addChild("paste_value_only",["paste_special"],{name:a("Paste values only"),sequence:10,action:Ua}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Ba}).add("sort_range",{name:a("Sort range"),sequence:50,isVisible:ol,separator:!0}).addChild("sort_ascending",["sort_range"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:sl}).addChild("sort_descending",["sort_range"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:il}).add("add_row_before",{name:e=>{const t=Na(e);return 1===t?a("Insert row"):a("Insert %s rows",t.toString())},sequence:70,action:Ya,isVisible:ol}).add("add_column_before",{name:e=>{const t=Oa(e);return 1===t?a("Insert column"):a("Insert %s columns",t.toString())},sequence:90,action:Qa,isVisible:ol}).add("insert_cell",{name:a("Insert cells"),sequence:100,isVisible:ol,separator:!0}).addChild("insert_cell_down",["insert_cell"],{name:a("Shift down"),sequence:10,action:Wa}).addChild("insert_cell_right",["insert_cell"],{name:a("Shift right"),sequence:20,action:qa}).add("delete_row",{name:za,sequence:110,action:Ha,isVisible:ol}).add("delete_column",{name:Za,sequence:120,action:Ga,isVisible:ol}).add("delete_cell",{name:a("Delete cells"),sequence:130,isVisible:ol}).addChild("delete_cell_up",["delete_cell"],{name:a("Shift up"),sequence:10,action:ja}).addChild("delete_cell_down",["delete_cell"],{name:a("Shift left"),sequence:20,action:Xa}).add("clear_cell",{name:a("Clear cells"),sequence:140,action:Va,isEnabled:e=>{const t=e.getters.getActiveCell();return Boolean(t)},separator:!0}).add("insert_link",{name:a("Insert link"),separator:!0,sequence:150,action:tl}).add("conditional_formatting",{name:a("Conditional formatting"),sequence:160,action:el,separator:!0});const rl=new _a;rl.add("cut",{name:a("Cut"),shortCut:"Ctrl+X",sequence:10,action:Da}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:$a}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:Pa}).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:Ua}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Ba}).add("sort_columns",{name:e=>e.getters.getActiveCols().size>1?a("Sort columns"):a("Sort column"),sequence:50,isVisible:ol,separator:!0}).addChild("sort_ascending",["sort_columns"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:sl}).addChild("sort_descending",["sort_columns"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:il}).add("add_column_before",{name:e=>{const t=Oa(e);return 1===t?a("Insert column left"):a("Insert %s columns left",t.toString())},sequence:70,action:Qa}).add("add_column_after",{name:e=>{const t=Oa(e);return 1===t?a("Insert column right"):a("Insert %s columns right",t.toString())},sequence:80,action:Ja}).add("delete_column",{name:Za,sequence:90,action:Ga}).add("clear_column",{name:e=>{let t,s;const i=e.getters.getActiveCols();if(0!==i.size)t=Math.min(...i),s=Math.max(...i);else{const i=e.getters.getSelectedZones()[0];t=i.left,s=i.right}return t===s?a("Clear column %s",es(t)):a("Clear columns %s - %s",es(t),es(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],i=t[t.length-1];return 1===t.length?a("Hide column %s",es(s).toString()):i-s+1===t.length?a("Hide columns %s - %s",es(s).toString(),es(i).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:el});const al=new _a;al.add("sheet",{name:a("Link sheet"),sequence:10,children:e=>e.getters.getSheets().map(((e,t)=>Aa(e.id,{name:e.name,sequence:t,action:()=>{return{link:{label:e.name,url:(t=e.id,`${xs}${t}`)},urlRepresentation:e.name,isUrlEditable:!1};var t}})))});const ll=new _a;ll.add("cut",{name:a("Cut"),sequence:10,shortCut:"Ctrl+X",action:Da}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:$a}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:Pa}).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:Ua}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Ba}).add("add_row_before",{name:e=>{const t=Na(e);return 1===t?a("Insert row above"):a("Insert %s rows above",t.toString())},sequence:50,action:Ya}).add("add_row_after",{name:e=>{const t=Na(e);return 1===t?a("Insert row below"):a("Insert %s rows below",t.toString())},sequence:60,action:Ka}).add("delete_row",{name:za,sequence:70,action:Ha}).add("clear_row",{name:e=>{let t,s;const i=e.getters.getActiveRows();if(0!==i.size)t=Math.min(...i),s=Math.max(...i);else{const i=e.getters.getSelectedZones()[0];t=i.top,s=i.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],i=t[t.length-1];return 1===t.length?a("Hide row %s",(s+1).toString()):i-s+1===t.length?a("Hide rows %s - %s",(s+1).toString(),(i+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:el});const cl=new _a;cl.add("delete",{name:a("Delete"),sequence:10,isVisible:e=>e.getters.getSheets().length>1,action:e=>e.dispatch("DELETE_SHEET_CONFIRMATION",{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=>e.dispatch("RENAME_SHEET",{interactive:!0,sheetId: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 hl=new _a;hl.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:$a}).addChild("cut",["edit"],{name:a("Cut"),shortCut:"Ctrl+X",sequence:40,action:Da}).addChild("paste",["edit"],{name:a("Paste"),shortCut:"Ctrl+V",sequence:50,action:Pa}).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:Ua}).addChild("paste_special_format",["edit","paste_special"],{name:a("Paste format only"),sequence:20,action:Ba}).addChild("sort_range",["edit"],{name:a("Sort range"),sequence:62,isVisible:ol,separator:!0}).addChild("sort_ascending",["edit","sort_range"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:sl}).addChild("sort_descending",["edit","sort_range"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:il}).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:Va}).addChild("edit_delete_row",["edit"],{name:za,sequence:80,action:Ha}).addChild("edit_delete_column",["edit"],{name:Za,sequence:90,action:Ga}).addChild("edit_delete_cell_shift_up",["edit"],{name:a("Delete cell and shift up"),sequence:93,action:ja}).addChild("edit_delete_cell_shift_left",["edit"],{name:a("Delete cell and shift left"),sequence:97,action:Xa}).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=Na(e);return 1===t?a("Row above"):a("%s Rows above",t.toString())},sequence:10,action:Ya,isVisible:e=>0===e.getters.getActiveCols().size}).addChild("insert_row_after",["insert"],{name:e=>{const t=Na(e);return 1===t?a("Row below"):a("%s Rows below",t.toString())},sequence:20,action:Ka,isVisible:e=>0===e.getters.getActiveCols().size,separator:!0}).addChild("insert_column_before",["insert"],{name:e=>{const t=Oa(e);return 1===t?a("Column left"):a("%s Columns left",t.toString())},sequence:30,action:Qa,isVisible:e=>0===e.getters.getActiveRows().size}).addChild("insert_column_after",["insert"],{name:e=>{const t=Oa(e);return 1===t?a("Column right"):a("%s Columns right",t.toString())},sequence:40,action:Ja,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:Wa}).addChild("insert_insert_cell_shift_right",["insert"],{name:a("Insert cells and shift right"),sequence:47,action:qa,separator:!0}).addChild("insert_chart",["insert"],{name:a("Chart"),sequence:50,action:e=>{var t,s;const i=e.getters.getSelectedZone();let o=i;const n=e.uuidGenerator.uuidv4();let r;i.left!==i.right&&(o={...i,left:i.left+1});const a=[Ns(o)],l=e.getters.getActiveSheetId(),c={x:(null===(t=e.getters.getCol(l,i.right+1))||void 0===t?void 0:t.start)||0,y:(null===(s=e.getters.getRow(l,i.top))||void 0===s?void 0:s.start)||0};let h=!1;for(let t=o.left;t<=o.right;t++){const s=e.getters.getCell(l,t,i.top);if(s&&s.evaluated.type!==Ne.number){h=!0;break}}i.left!==i.right&&(r=Ns({...i,right:i.left,top:h?i.top+1:i.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:tl}).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,i=e.uuidGenerator.uuidv4();e.dispatch("CREATE_SHEET",{sheetId:i,position:s}),e.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:i})},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=>ka(e,"")}).addChild("format_number_number",["format","format_number"],{name:a("Number (1,000.12)"),sequence:20,action:e=>ka(e,"#,##0.00")}).addChild("format_number_percent",["format","format_number"],{name:a("Percent (10.12%)"),sequence:30,separator:!0,action:e=>ka(e,"0.00%")}).addChild("format_number_date",["format","format_number"],{name:a("Date (9/26/2008)"),sequence:40,action:e=>ka(e,"m/d/yyyy")}).addChild("format_number_time",["format","format_number"],{name:a("Time (10:43:00 PM)"),sequence:50,action:e=>ka(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=>ka(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=>ka(e,"hhhh:mm:ss")}).addChild("format_bold",["format"],{name:a("Bold"),sequence:20,shortCut:"Ctrl+B",action:e=>Fa(e,{bold:!e.getters.getCurrentStyle().bold})}).addChild("format_italic",["format"],{name:a("Italic"),sequence:30,shortCut:"Ctrl+I",action:e=>Fa(e,{italic:!e.getters.getCurrentStyle().italic})}).addChild("format_underline",["format"],{name:a("Underline"),shortCut:"Ctrl+U",sequence:40,action:e=>Fa(e,{underline:!e.getters.getCurrentStyle().underline})}).addChild("format_strikethrough",["format"],{name:a("Strikethrough"),sequence:50,action:e=>Fa(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:el,separator:!0});for(let e of as)hl.addChild(`format_font_size_${e.pt}`,["format","format_font_size"],{name:e.pt.toString(),sequence:e.pt,action:t=>Fa(t,{fontSize:e.pt})});const dl=new class extends Re{addTransformation(e,t,s){for(let i of t)this.content[i]||(this.content[i]=new Map),this.content[i].set(e,s);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},{css:ul,xml:pl}=t.tags,gl=[["#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"]],fl=24*Math.max(...gl.map((e=>e.length)))+12;class ml extends t.Component{constructor(){super(...arguments),this.COLORS=gl}onColorClick(e){const t=e.target.dataset.color;t&&this.trigger("color-picked",{color:t})}}ml.template=pl`
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 i=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var i=s(t);let o=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(o(e),...t)},a=function(e,...t){return{toString:function(){return n(o(e),...t)}}},l="#f5f5f5",c="#F8F9FA",h="#E8EAED",d="#595959",u="#666666",p="#3266ca",g="#FFFFFF",f=26,m=48,v=63,E=96,b=23,S=15,C=14,I=4,y=200,w=1,x="400",T=10,R="'Roboto', arial",L=["thin","#000"],M="#00f",A=/[ymd:]/,_="#REF",O="START_REVISION",N=a("Invalid expression"),k=/'|\*|\?|\/|\\|\[|\]/,F=void 0,$="|",D=2e3,P=(new Date).getFullYear(),U=new Date(1899,11,30),B=new Date(0)-U,V=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,H=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,z=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function Z(e){let t;const s=(e=e.trim()).match(z);if(s){if(t=function(e){if(e=e.trim(),z.test(e)){const t=/AM/i.test(e),s=/PM/i.test(e),i=(t||s?e.substring(0,e.length-2).trim():e).split(/:/),o=i.length>=2,n=3===i.length;let r=Number(i[0]),a=o?Number(i[1]):0,l=n?Number(i[2]):0,c=n?"hh:mm:ss":"hh:mm";if(t||s)c+=" a";else if(!o)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 i;const o=e.match(V),n=e.match(H);if(o||n){let t;if(o?(t=o[0],i=G(t,"mdy")):(t=n[0],i=G(t,"ymd")),null===i)return null;e=e.replace(t,"").trim()}return""!==e||!i&&!t?null:i&&t?{value:i.value+t.value,format:i.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new Date(i.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,i.jsDate.getMonth()+t.jsDate.getMonth()-11,i.jsDate.getDate()+t.jsDate.getDate()-30,i.jsDate.getHours()+t.jsDate.getHours(),i.jsDate.getMinutes()+t.jsDate.getMinutes(),i.jsDate.getSeconds()+t.jsDate.getSeconds())}:i||t}function G(e,t){const s="mdy"===t;if(s||"ymd"===t){const t=e.split(/\/|-|\s/),i=s?0:1,o=s?1:2,n=s?2:0,r=Number(t[i]),a=Number(t[o]),l=2===t[i].length&&r<10||2===t[o].length&&a<10,c=t[n]?function(e){const t=Number(e);switch(e.length){case 1:return D+t;case 2:return D+(D+t>P+10?-100:0)+t;case 3:case 4:return t}return 0}(t[n]):P,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-U;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 W(e){const t=Math.trunc(e);let s=new Date(86400*t*1e3-B),i=e-t;i=i<0?1+i:i;const o=Math.round(24*i),n=Math.round(24*(i-o/24)*60),r=Math.round(24*(i-o/24-n/24/60)*60*60);return s.setHours(o),s.setMinutes(n),s.setSeconds(r),s}function q(e){const t=e.format,s=e.jsDate||W(e.value),i=t.indexOf("h");let o="",n="";return i>0?(o=j(s,t.substring(0,i-1)),n=X(s,t.substring(i))):0===i?n=X(s,t):i<0&&(o=j(s,t)),o+(o&&n?" ":"")+n}function j(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 X(e,t){let s=t.split(/:|\s/);const i=e.getHours(),o="a"===s[s.length-1];let n=i,r="";return o&&(n=0===n?12:n>12?n-12:n,r=i>=12?" PM":" AM",s.pop()),s.map((s=>{switch(s){case"hhhh":return Math.floor((e.getTime()-U)/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 Y=/(^-?\d+(\.?\d*(e\d+)?)?(\s*%)?|^-?\.\d+(\s*%)?)(?!\w|!)/,K=/^-?\d+(,\d+)*(\.?\d*(e\d+)?)?(\s*%)?$|^-?\.\d+(\s*%)?$/;function Q(e){return K.test(e.trim())}const J=/,/g;function ee(e){let t=Number(e.replace(J,""));return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}const te=new Intl.NumberFormat("en-US",{useGrouping:!1,maximumFractionDigits:10});function se(e){return Number.isInteger(e)?e.toString():te.format(e)}let ie=[];const oe=20;function ne(e,t,s=""){if(e<0)return"-"+ne(-e,t);const i=t>=oe?oe:t;let o=ie[i];o||(o=new Intl.NumberFormat("en-US",{minimumFractionDigits:i,maximumFractionDigits:i,useGrouping:!1}),ie[i]=o);let n=o.format(e);if(s){let e=n.indexOf(".");n=n.replace(/\d(?=(?:\d{3})+(?:\.|$))/g,((t,i)=>e<0||i<e?`${t}${s}`:t))}return n}function re(e,t){const s=t.split("."),i=1===s.length?0:s[1].match(/0/g).length,o=s[0].includes(",")?",":"",n=t.includes("%");n&&(e*=100);const r=ne(e,i,o);return n?r+"%":r}function ae(e,t){if(!e())throw new Error(t)}const le=e=>a("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function ce(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(Q(e)||""===e)return ee(e);const t=Z(e);if(t)return t.value;throw new Error(le(e));default:return 0}}function he(e){if(""===e)throw new Error(le(e));return ce(e)}function de(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}const ue=e=>a("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function pe(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(ue(e))}return!1;case"number":return!!e;default:return!1}}function ge(e){return W(ce(e))}function fe(e,t,s){for(let i of e)if(Array.isArray(i)){const e=i.length,s=i[0].length;for(let o=0;o<s;o++)for(let s=0;s<e;s++)t(i[s][o])}else s(i)}function me(e,t){fe(e,t,t)}function ve(e,t){fe(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(he(e))}))}function Ee(e,t,s,i){let o=i;for(let i of e)if(Array.isArray(i)){const e=i.length,s=i[0].length;for(let n=0;n<s;n++)for(let s=0;s<e;s++)o=t(o,i[s][n])}else o=s(o,i);return o}function be(e,t,s){return Ee(e,t,t,s)}function Se(e,t,s){return Ee(e,((e,s)=>"number"==typeof s?t(e,s):e),((e,s)=>t(e,he(s))),s)}function Ce(e,t,s){return Ee(e,((e,s)=>null!=s?t(e,"number"==typeof s?s:"boolean"==typeof s?ce(s):0):e),((e,s)=>t(e,ce(s))),s)}function Ie(e,t){return function(e,t,s){for(let i of e)if(Array.isArray(i)){const e=i.length,s=i[0].length;for(let o=0;o<s;o++)for(let s=0;s<e;s++)if(!t(i[s][o]))return}else if(!s(i))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(ue(e));return pe(e)}(e))))}function ye(e,t){let s,i,o=e.substring(0,2);"<="===o||">="===o||"<>"===o?(s=o,i=e.substring(2)):(o=e.substring(0,1),"<"===o||">"===o||"="===o?(s=o,i=e.substring(1)):(s="=",i=e)),Q(i)?i=ce(i):"TRUE"!==i&&"FALSE"!==i||(i=pe(i));const n={operator:s,operand:i};return"string"==typeof i&&(t&&(i+="*"),n.regexp=function(e){let t="",s="";for(let i of e)"?"===i&&"~"!==s?t+=".":"*"===i&&"~"!==s?t+=".*":("*"!==i&&"?"!==i||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(i)&&(t+="\\"),t+=i),s=i;return new RegExp("^"+t+"$","i")}(i)),n}function we(e,t){const{operator:s,operand:i}=t;if(void 0===e||void 0===i)return!1;if("number"==typeof i&&"="===s)return de(e)===de(i);if("<>"===s||"="===s){let o;return o=typeof e==typeof i&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===i),"="===s?o:!o}if(typeof e==typeof i)switch(s){case"<":return e<i;case">":return e>i;case"<=":return e<=i;case">=":return e>=i}return!1}function xe(e,t,s=!1){const i=e.length;if(i%2==1)throw new Error(a("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const o=e[0].length,n=e[0][0].length;let r=[];for(let t=0;t<i-1;t+=2){const i=e[t];if(!Array.isArray(i)||i.length!==o||i[0].length!==n)throw new Error(a("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=de(e[t+1]);r.push(ye(l,s))}for(let s=0;s<o;s++)for(let o=0;o<n;o++){let n=!0;for(let t=0;t<i-1;t+=2){if(n=we(e[t][s][o],r[t/2]),!n)break}n&&t(s,o)}}function Te(e,t){if(void 0===t)return-1;const s=typeof t;let i,o,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===i||i<a||i===a&&o<r)&&(i=a,o=r),l===s&&a>t?h=r-1:c=n+1}return void 0!==o?o:-1}class Re{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 Le=/(.*?)\((.*?)\)(.*)/,Me=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function Ae(e){let t=e.split("\n");const s=[];for(let e of t)e=e.trim(),e&&s.push(_e(e));return s}function _e(e){let t,s=e.match(Le),i=s[1].trim(),o=[],n=!1,r=!1,a=!1;for(let e of s[2].split(",")){const s=e.trim().toUpperCase();let i=Me.find((e=>s===e));i?o.push(i):"RANGE<ANY>"===s?o.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:i,description:s[3].trim(),type:o};return n&&(l.optional=!0),r&&(l.repeating=!0),a&&(l.lazy=!0),void 0!==t&&(l.default=!0,l.defaultValue=t),l}function Oe(e){let t=0,s=0,i=0;for(let o of e.args)t++,o.optional||o.repeating||o.default||s++,o.repeating&&i++;const o=e;return o.minArgRequired=s,o.maxArgPossible=i?1/0:t,o.nbrArgRepeating=i,o.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,i),o}var Ne;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(Ne||(Ne={}));const ke=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),Fe=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"]),$e=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 De(e){return $e.has(e.type)}class Pe{constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new Pe}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var Ue,Be,Ve,He;e.CommandResult=void 0,(Ue=e.CommandResult||(e.CommandResult={}))[Ue.Success=0]="Success",Ue[Ue.CancelledForUnknownReason=1]="CancelledForUnknownReason",Ue[Ue.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",Ue[Ue.MergeIsDestructive=3]="MergeIsDestructive",Ue[Ue.CellIsMerged=4]="CellIsMerged",Ue[Ue.InvalidTarget=5]="InvalidTarget",Ue[Ue.EmptyUndoStack=6]="EmptyUndoStack",Ue[Ue.EmptyRedoStack=7]="EmptyRedoStack",Ue[Ue.NotEnoughElements=8]="NotEnoughElements",Ue[Ue.NotEnoughSheets=9]="NotEnoughSheets",Ue[Ue.MissingSheetName=10]="MissingSheetName",Ue[Ue.DuplicatedSheetName=11]="DuplicatedSheetName",Ue[Ue.DuplicatedSheetId=12]="DuplicatedSheetId",Ue[Ue.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",Ue[Ue.WrongSheetMove=14]="WrongSheetMove",Ue[Ue.WrongSheetPosition=15]="WrongSheetPosition",Ue[Ue.InvalidAnchorZone=16]="InvalidAnchorZone",Ue[Ue.SelectionOutOfBound=17]="SelectionOutOfBound",Ue[Ue.TargetOutOfSheet=18]="TargetOutOfSheet",Ue[Ue.WrongPasteSelection=19]="WrongPasteSelection",Ue[Ue.EmptyClipboard=20]="EmptyClipboard",Ue[Ue.EmptyRange=21]="EmptyRange",Ue[Ue.InvalidRange=22]="InvalidRange",Ue[Ue.InvalidSheetId=23]="InvalidSheetId",Ue[Ue.InputAlreadyFocused=24]="InputAlreadyFocused",Ue[Ue.MaximumRangesReached=25]="MaximumRangesReached",Ue[Ue.InvalidChartDefinition=26]="InvalidChartDefinition",Ue[Ue.EmptyDataSet=27]="EmptyDataSet",Ue[Ue.InvalidDataSet=28]="InvalidDataSet",Ue[Ue.InvalidLabelRange=29]="InvalidLabelRange",Ue[Ue.InvalidAutofillSelection=30]="InvalidAutofillSelection",Ue[Ue.WrongComposerSelection=31]="WrongComposerSelection",Ue[Ue.MinBiggerThanMax=32]="MinBiggerThanMax",Ue[Ue.LowerBiggerThanUpper=33]="LowerBiggerThanUpper",Ue[Ue.MidBiggerThanMax=34]="MidBiggerThanMax",Ue[Ue.MinBiggerThanMid=35]="MinBiggerThanMid",Ue[Ue.FirstArgMissing=36]="FirstArgMissing",Ue[Ue.SecondArgMissing=37]="SecondArgMissing",Ue[Ue.MinNaN=38]="MinNaN",Ue[Ue.MidNaN=39]="MidNaN",Ue[Ue.MaxNaN=40]="MaxNaN",Ue[Ue.ValueUpperInflectionNaN=41]="ValueUpperInflectionNaN",Ue[Ue.ValueLowerInflectionNaN=42]="ValueLowerInflectionNaN",Ue[Ue.MinInvalidFormula=43]="MinInvalidFormula",Ue[Ue.MidInvalidFormula=44]="MidInvalidFormula",Ue[Ue.MaxInvalidFormula=45]="MaxInvalidFormula",Ue[Ue.ValueUpperInvalidFormula=46]="ValueUpperInvalidFormula",Ue[Ue.ValueLowerInvalidFormula=47]="ValueLowerInvalidFormula",Ue[Ue.InvalidSortZone=48]="InvalidSortZone",Ue[Ue.WaitingSessionConfirmation=49]="WaitingSessionConfirmation",Ue[Ue.MergeOverlap=50]="MergeOverlap",Ue[Ue.TooManyHiddenElements=51]="TooManyHiddenElements",Ue[Ue.Readonly=52]="Readonly",Ue[Ue.InvalidOffset=53]="InvalidOffset",Ue[Ue.InvalidViewportSize=54]="InvalidViewportSize",Ue[Ue.FigureDoesNotExist=55]="FigureDoesNotExist",Ue[Ue.DuplicatedFigureId=56]="DuplicatedFigureId",Ue[Ue.DuplicatedChartId=57]="DuplicatedChartId",Ue[Ue.ChartDoesNotExist=58]="ChartDoesNotExist",function(e){e.FormatFromArgument="FormatFromArgument"}(Be||(Be={})),function(e){e[e.UP=0]="UP",e[e.DOWN=1]="DOWN",e[e.LEFT=2]="LEFT",e[e.RIGHT=3]="RIGHT"}(Ve||(Ve={})),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"}(He||(He={}));const ze={description:a("Absolute value of a number."),args:Ae(`\n value (number) ${a("The number of which to return the absolute value.")}\n `),returns:["NUMBER"],compute:function(e){return Math.abs(ce(e))},isExported:!0},Ze={description:a("Inverse cosine of a value, in radians."),args:Ae(`\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=ce(e);return ae((()=>Math.abs(t)<=1),a("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},Ge={description:a("Inverse hyperbolic cosine of a number."),args:Ae(`\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=ce(e);return ae((()=>t>=1),a("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},We={description:a("Inverse cotangent of a value."),args:Ae(`\n value (number) ${a("The value for which to calculate the inverse cotangent.")}\n `),returns:["NUMBER"],compute:function(e){const t=ce(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},qe={description:a("Inverse hyperbolic cotangent of a value."),args:Ae(`\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=ce(e);return ae((()=>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},je={description:a("Inverse sine of a value, in radians."),args:Ae(`\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=ce(e);return ae((()=>Math.abs(t)<=1),a("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},Xe={description:a("Inverse hyperbolic sine of a number."),args:Ae(`\n value (number) ${a("The value for which to calculate the inverse hyperbolic sine.")}\n `),returns:["NUMBER"],compute:function(e){return Math.asinh(ce(e))},isExported:!0},Ye={description:a("Inverse tangent of a value, in radians."),args:Ae(`\n value (number) ${a("The value for which to calculate the inverse tangent.")}\n `),returns:["NUMBER"],compute:function(e){return Math.atan(ce(e))},isExported:!0},Ke={description:a("Angle from the X axis to a point (x,y), in radians."),args:Ae(`\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=ce(e),i=ce(t);return ae((()=>0!==s||0!==i),a("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(i,s)},isExported:!0},Qe={description:a("Inverse hyperbolic tangent of a number."),args:Ae(`\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=ce(e);return ae((()=>Math.abs(t)<1),a("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},Je={description:a("Rounds number up to nearest multiple of factor."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=1){const s=ce(e),i=ce(t);return ae((()=>i>=0||s<=0),a("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),s.toString())),i?Math.ceil(s/i)*i:0},isExported:!0},et={description:a("Rounds number up to nearest multiple of factor."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=1,s=0){let i=ce(t);if(0===i)return 0;const o=ce(e);if(i=Math.abs(i),o>=0)return Math.ceil(o/i)*i;return 0===ce(s)?-Math.floor(Math.abs(o)/i)*i:-Math.ceil(Math.abs(o)/i)*i},isExported:!0},tt={description:a("Rounds number up to nearest multiple of factor."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return et.compute(e,t,0)},isExported:!0},st={description:a("Cosine of an angle provided in radians."),args:Ae(`\n angle (number) ${a("The angle to find the cosine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cos(ce(e))},isExported:!0},it={description:a("Hyperbolic cosine of any real number."),args:Ae(`\n value (number) ${a("Any real value to calculate the hyperbolic cosine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cosh(ce(e))},isExported:!0},ot={description:a("Cotangent of an angle provided in radians."),args:Ae(`\n angle (number) ${a("The angle to find the cotangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=ce(e);return ae((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},nt={description:a("Hyperbolic cotangent of any real number."),args:Ae(`\n value (number) ${a("Any real value to calculate the hyperbolic cotangent of.")}\n `),returns:["NUMBER"],compute:function(e){const t=ce(e);return ae((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},rt={description:a("Number of empty values."),args:Ae(`\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 be(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},at={description:a("A conditional count across a range."),args:Ae(`\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 xe(e,((e,s)=>{t+=1})),t},isExported:!0},lt={description:a("Count values depending on multiple criteria."),args:Ae(`\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 xe(e,((e,s)=>{t+=1})),t},isExported:!0};function ct(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const ht={description:a("Counts number of unique values in a range."),args:Ae(`\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 be(e,((e,t)=>ct(t)?e.add(t):e),new Set).size}},dt={description:a("Counts number of unique values in a range, filtered by a set of criteria."),args:Ae(`\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 xe(t,((t,i)=>{const o=e[t][i];ct(o)&&s.add(o)})),s.size}},ut={description:a("Cosecant of an angle provided in radians."),args:Ae(`\n angle (number) ${a("The angle to find the cosecant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=ce(e);return ae((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},pt={description:a("Hyperbolic cosecant of any real number."),args:Ae(`\n value (number) ${a("Any real value to calculate the hyperbolic cosecant of.")}\n `),returns:["NUMBER"],compute:function(e){const t=ce(e);return ae((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},gt={description:a("Converts from another base to decimal."),args:Ae(`\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=ce(t);s=Math.floor(s),ae((()=>2<=s&&s<=36),a("The base (%s) must be between 2 and 36 inclusive.",s.toString()));const i=de(e);if(""===i)return 0;ae((()=>!!i.match(/^-?[a-z0-9]+$/i)),a("The value (%s) must be a valid base %s representation.",i,s.toString()));const o=parseInt(i,s);return ae((()=>!isNaN(o)),a("The value (%s) must be a valid base %s representation.",i,s.toString())),o},isExported:!0},ft={description:a("Converts an angle value in radians to degrees."),args:Ae(`\n angle (number) ${a("The angle to convert from radians to degrees.")}\n `),returns:["NUMBER"],compute:function(e){return 180*ce(e)/Math.PI},isExported:!0},mt={description:a("Euler's number, e (~2.718) raised to a power."),args:Ae(`\n value (number) ${a("The exponent to raise e.")}\n `),returns:["NUMBER"],compute:function(e){return Math.exp(ce(e))},isExported:!0},vt={description:a("Rounds number down to nearest multiple of factor."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=1){const s=ce(e),i=ce(t);return ae((()=>i>=0||s<=0),a("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),s.toString())),i?Math.floor(s/i)*i:0},isExported:!0},Et={description:a("Rounds number down to nearest multiple of factor."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=1,s=0){let i=ce(t);if(0===i)return 0;const o=ce(e);if(i=Math.abs(i),o>=0)return Math.floor(o/i)*i;return 0===ce(s)?-Math.ceil(Math.abs(o)/i)*i:-Math.floor(Math.abs(o)/i)*i},isExported:!0},bt={description:a("Rounds number down to nearest multiple of factor."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=1){return Et.compute(e,t,0)},isExported:!0},St={description:a("Whether the provided value is even."),args:Ae(`\n value (number) ${a("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=he(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},Ct={description:a("Rounds number up to nearest multiple of factor."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=1){return et.compute(e,t,0)},isExported:!0},It={description:a("Whether the provided value is even."),args:Ae(`\n value (number) ${a("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=he(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},yt={description:a("The logarithm of a number, base e (euler's number)."),args:Ae(`\n value (number) ${a("The value for which to calculate the logarithm, base e.")}\n `),returns:["NUMBER"],compute:function(e){const t=ce(e);return ae((()=>t>0),a("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},wt={description:a("Modulo (remainder) operator."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){const s=ce(t);ae((()=>0!==s),a("The divisor must be different from 0."));const i=ce(e)%s;return i>0&&s<0||i<0&&s>0?i+s:i},isExported:!0},xt={description:a("Rounds a number up to the nearest odd integer."),args:Ae(`\n value (number) ${a("The value to round to the next greatest odd number.")}\n `),returns:["NUMBER"],returnFormat:Be.FormatFromArgument,compute:function(e){const t=ce(e);let s=Math.ceil(Math.abs(t));return s=1&s?s:s+1,t<0?-s:s},isExported:!0},Tt={description:a("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},Rt={description:a("A number raised to a power."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){const s=ce(e),i=ce(t);return ae((()=>s>=0||Number.isInteger(i)),a("The exponent (%s) must be an integer when the base is negative.",i.toString())),Math.pow(s,i)},isExported:!0},Lt={description:a("Result of multiplying a series of numbers together."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){let t=0,s=1;for(let i of e)if(Array.isArray(i))for(let e of i)for(let i of e)"number"==typeof i&&(s*=i,t+=1);else null!=i&&(s*=he(i),t+=1);return 0===t?0:s},isExported:!0},Mt={description:a("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},At={description:a("Random integer between two values, inclusive."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){let s=ce(e);Number.isInteger(s)||(s=Math.ceil(s));let i=ce(t);return Number.isInteger(i)||(i=Math.floor(i)),ae((()=>s<=i),a("The high (%s) must be greater than or equal to the low (%s).",i.toString(),s.toString())),s+Math.ceil((i-s+1)*Math.random())-1},isExported:!0},_t={description:a("Rounds a number according to standard rules."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=0){const s=ce(e);let i=ce(t);const o=Math.abs(s);let n;return 0===i?n=Math.round(o):(Number.isInteger(i)||(i=Math.trunc(i)),n=Math.round(o*Math.pow(10,i))/Math.pow(10,i)),s>=0?n:-n},isExported:!0},Ot={description:a("Rounds down a number."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=0){const s=ce(e);let i=ce(t);const o=Math.abs(s);let n;return 0===i?n=Math.floor(o):(Number.isInteger(i)||(i=Math.trunc(i)),n=Math.floor(o*Math.pow(10,i))/Math.pow(10,i)),s>=0?n:-n},isExported:!0},Nt={description:a("Rounds up a number."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=0){const s=ce(e);let i=ce(t);const o=Math.abs(s);let n;return 0===i?n=Math.ceil(o):(Number.isInteger(i)||(i=Math.trunc(i)),n=Math.ceil(o*Math.pow(10,i))/Math.pow(10,i)),s>=0?n:-n},isExported:!0},kt={description:a("Secant of an angle provided in radians."),args:Ae(`\n angle (number) ${a("The angle to find the secant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cos(ce(e))},isExported:!0},Ft={description:a("Hyperbolic secant of any real number."),args:Ae(`\n value (number) ${a("Any real value to calculate the hyperbolic secant of.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cosh(ce(e))},isExported:!0},$t={description:a("Sine of an angle provided in radians."),args:Ae(`\n angle (number) ${a("The angle to find the sine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sin(ce(e))},isExported:!0},Dt={description:a("Hyperbolic sine of any real number."),args:Ae(`\n value (number) ${a("Any real value to calculate the hyperbolic sine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sinh(ce(e))},isExported:!0},Pt={description:a("Positive square root of a positive number."),args:Ae(`\n value (number) ${a("The number for which to calculate the positive square root.")}\n `),returns:["NUMBER"],returnFormat:Be.FormatFromArgument,compute:function(e){const t=ce(e);return ae((()=>t>=0),a("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},Ut={description:a("Sum of a series of numbers and/or cells."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){return Se(e,((e,t)=>e+t),0)},isExported:!0},Bt={description:a("A conditional sum across a range."),args:Ae(`\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 i=0;return xe([e,t],((e,t)=>{const o=s[e][t];"number"==typeof o&&(i+=o)})),i},isExported:!0},Vt={description:a("Sums a range depending on multiple criteria."),args:Ae(`\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 xe(t,((t,i)=>{const o=e[t][i];"number"==typeof o&&(s+=o)})),s},isExported:!0},Ht={description:a("Tangent of an angle provided in radians."),args:Ae(`\n angle (number) ${a("The angle to find the tangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tan(ce(e))},isExported:!0},zt={description:a("Hyperbolic tangent of any real number."),args:Ae(`\n value (number) ${a("Any real value to calculate the hyperbolic tangent of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tanh(ce(e))},isExported:!0},Zt={description:a("Truncates a number."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t=0){const s=ce(e);let i=ce(t);return 0===i?Math.trunc(s):(Number.isInteger(i)||(i=Math.trunc(i)),Math.trunc(s*Math.pow(10,i))/Math.pow(10,i))},isExported:!0};var Gt=Object.freeze({__proto__:null,ABS:ze,ACOS:Ze,ACOSH:Ge,ACOT:We,ACOTH:qe,ASIN:je,ASINH:Xe,ATAN:Ye,ATAN2:Ke,ATANH:Qe,CEILING:Je,CEILING_MATH:et,CEILING_PRECISE:tt,COS:st,COSH:it,COT:ot,COTH:nt,COUNTBLANK:rt,COUNTIF:at,COUNTIFS:lt,COUNTUNIQUE:ht,COUNTUNIQUEIFS:dt,CSC:ut,CSCH:pt,DECIMAL:gt,DEGREES:ft,EXP:mt,FLOOR:vt,FLOOR_MATH:Et,FLOOR_PRECISE:bt,ISEVEN:St,ISO_CEILING:Ct,ISODD:It,LN:yt,MOD:wt,ODD:xt,PI:Tt,POWER:Rt,PRODUCT:Lt,RAND:Mt,RANDBETWEEN:At,ROUND:_t,ROUNDDOWN:Ot,ROUNDUP:Nt,SEC:kt,SECH:Ft,SIN:$t,SINH:Dt,SQRT:Pt,SUM:Ut,SUMIF:Bt,SUMIFS:Vt,TAN:Ht,TANH:zt,TRUNC:Zt});const Wt=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function qt(e){return e.toString(16).padStart(6,"0")}let jt=0;function Xt(){return jt=++jt%Wt.length,Wt[jt]}function Yt(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 Kt=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),Qt=new RegExp(/^\s*(.*!)?\$?[A-Z]{1,3}\$?[0-9]{1,7}\s*(\s*:\s*\$?[A-Z]{1,3}\$?[0-9]{1,7}\s*)?$/,"i");function Jt(e){const t=e.split("!"),s=t.pop();return{sheetName:t.join("!")||void 0,xc:s}}function es(e){return e<26?String.fromCharCode(65+e):es(Math.floor(e/26)-1)+es(e%26)}function ts(e){e=e.toUpperCase().trim();const[t,s,i]=e.match(Kt);if(t!==e)throw new Error(`Invalid cell description: ${e}`);const o=function(e){let t=0;const s=e.length;for(let i=0;i<s;i++)t+=(e.charCodeAt(i)-65+(i<s-1?1:0))*26**(s-i-1);return t}(s);return[o,parseInt(i,10)-1]}function ss(e,t,s={colFixed:!1,rowFixed:!1}){return(s.colFixed?"$":"")+es(e)+(s.rowFixed?"$":"")+String(t+1)}const is=140,os=20,ns=.035;function rs(e){return os+(is-os)*Math.exp(-ns*(e-1))}const as=[{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}],ls={};for(let e of as)ls[e.pt]=e.px;function cs(e){return JSON.stringify(e,Object.keys(e).sort())}function hs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ds(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]=ds(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 us(e){var t;return(null===(t=e.match(/\w/g))||void 0===t?void 0:t.length)!==e.length&&(e=`'${e}'`),e}function ps(e,t,s){return e<t?t:e>s?s:e}function gs(e,t,s){const i=s.italic?"italic ":"",o=s.bold?"bold":x,n=s.fontSize||T,r=ls[n];return e.font=`${i}${o} ${r}px ${R}`,e.measureText(t).width}function fs(e,t,s=1){if(t<=e&&s>0)return[];if(0===s)throw new Error("range() step must not be zero");const i=Math.ceil(Math.abs((t-e)/s)),o=Array(i);for(let t=0;t<i;t++)o[t]=e+t*s;return o}function ms(e){return e.reduce(((e,t,s,i)=>{if(1===Math.abs(t-i[s-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*vs(e,t){t.next();for(const s of e){const e=t.next();yield{...s,next:e.done?void 0:e.value}}}function Es(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}function bs(e){return null!==Z(e)}const Ss=/^\[([^\[]+)\]\((.+)\)$/,Cs=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function Is(e){return Ss.test(e)}function ys(e,t){return`[${e}](${t})`}function ws(e){const t=e.match(Ss)||[],s=t[1],i=t[2];if(!s||!i)throw new Error(`Could not parse markdown link ${e}.`);return{label:s,url:i}}const xs="o-spreadsheet://";function Ts(e){if(!Is(e))return!1;const{url:t}=ws(e);return t.startsWith(xs)}function Rs(e){if(e.startsWith(xs))return e.substr(xs.length);throw new Error(`${e} is not a valid sheet link`)}function Ls(e){return void 0!==e}const Ms={};function As(e){const t=(e=e.split("!").pop()).replace(/\$/g,"").split(":");let s,i,o,n,r=ts(t[0].trim());if(o=n=r[0],s=i=r[1],2===t.length){let e=ts(t[1].trim());n=e[0],i=e[1]}return{top:s,bottom:i,left:o,right:n}}function _s(e){let{top:t,bottom:s,left:i,right:o}=As(e);return o<i&&([o,i]=[i,o]),s<t&&([s,t]=[t,s]),{top:t,bottom:s,left:i,right:o}}function Os(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 Ns(e){const{top:t,bottom:s,left:i,right:o}=e;return t===s&&i===o?ss(i,t):`${ss(i,t)}:${ss(o,s)}`}function ks(e,t,s,i,o){const n="left"===t?"columns":"rows",r="before"===i?s-1:s,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?Ws(e,n,"RESIZE",o):r<e[t]?Ws(e,n,"MOVE",o):{...e}}function Fs(e,t,s){const i="left"===t?"right":"bottom";let o=e[t],n=e[i];for(let r of s.sort(((e,t)=>t-e)))e[t]>r&&(o--,n--),e[t]<r&&e[i]>=r&&n--;return{...e,[t]:o,[i]:n}}function $s(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 Ds(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function Ps(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function Us(e,t,s){const{left:i,right:o,top:n,bottom:r}=s;return e>=i&&e<=o&&t>=n&&t<=r}function Bs(e,t){const s={};for(let t of e)if(t){const e=_s(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=_s(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 i=[];for(let[e,t]of Object.entries(s))i.push({col:parseInt(e),ranges:Vs(t)});return function(e){const t=e.sort(((e,t)=>e.col-t.col)),s=[];let i=[],o=0;for(let e=0;e<=t.length-1;e++){let n=[];if(o+1===t[e].col)for(let s of t[e].ranges){let o=!1;for(let e of i)s.top==e.top&&s.bottom==e.bottom&&(n.push(e),o=!0);o||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=i.filter((e=>!n.includes(e)));for(let e of r)s.push({top:e.top,bottom:e.bottom,left:e.startCol,right:o});o=t[e].col,i=n}for(let e of i)s.push({top:e.top,bottom:e.bottom,left:e.startCol,right:o});return s}(i).map(Ns)}function Vs(e){const t=new Set,s=new Set;for(let i of e)for(let e=i.top;e<=i.bottom;e++)i.remove?s.add(e):t.add(e);const i=[...t].filter((e=>!s.has(e))).sort(((e,t)=>e-t)),o=[];let n;for(let e of i)n?e===n.bottom+1?n.bottom=e:(o.push({top:n.top,bottom:n.bottom}),n={top:e,bottom:e}):n={top:e,bottom:e};return n&&o.push({top:n.top,bottom:n.bottom}),o}function Hs(e,t,s,i,o=1,n=1){var r;const{top:a,bottom:l,left:c,right:h}=e,d=new Array(Math.floor((h-c+1)/o));for(let e=c;e<=h;e+=o){let o=new Array(Math.floor((l-a+1)/n));d[e-c]=o;for(let c=a;c<=l;c+=n){let l=null===(r=t.rows[c])||void 0===r?void 0:r.cells[e];o[(c-a)/n]=l?s(l):i}}return d}function zs(e){return{height:e.bottom-e.top+1,width:e.right-e.left+1}}function Zs(e){const{width:t,height:s}=zs(e);return 1===t||1===s}function Gs(e){const t=[],[s,i]=[e.right,e.left].sort(((e,t)=>e-t)),[o,n]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of fs(s,i+1))for(const s of fs(o,n+1))t.push([e,s]);return t}function Ws(e,t,s,i){const o="columns"===t?"right":"bottom",n={...e};return"MOVE"===s&&(n["columns"===t?"left":"top"]+=i),n[o]+=i,n}function qs(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 js(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 Xs(e){const t=[];let s=0;for(let i=0;i<e;i++){const e={start:s,end:s+E,size:E,name:es(i)};t.push(e),s=e.end}return t}function Ys(e){const t=[];let s=0;for(let i=0;i<e;i++){const e={start:s,end:s+b,size:b,name:String(i+1),cells:{}};t.push(e),s=e.end}return t}function Ks(e,t){var s;const i=[];let o=0;for(let n=0;n<t;n++){const t=e[n]&&e[n].size||E,r=(null===(s=e[n])||void 0===s?void 0:s.isHidden)||!1,a={start:o,end:r?o:o+t,size:t,name:es(n)};r&&(a.isHidden=r),i.push(a),o=a.end}return i}function Qs(e,t){var s;const i=[];let o=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:o,end:r?o:o+t,size:t,name:String(n+1),cells:{}};r&&(a.isHidden=r),i.push(a),o=a.end}return i}function Js(e,t=!1){const s={};for(let i in e){const o=e[i];(o.size!==E||t)&&(s[i]={size:o.size}),o.isHidden&&(s[i]=s[i]||{},s[i].isHidden=o.isHidden)}return s}function ei(e,t=!1){const s={};for(let i in e){const o=e[i];(o.size!==b||t)&&(s[i]={size:o.size}),o.isHidden&&(s[i]=s[i]||{},s[i].isHidden=o.isHidden)}return s}class ti{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 si(e,t,s){return[ii(e,"cols",fs(t,e.cols.length)),ii(e,"rows",fs(s,e.rows.length))]}function ii(e,t,s){const i=e[t];return s.find((e=>!i[e].isHidden))}function oi(e,t){let s=e[t].length-1;for(;s>=0&&!0===e[t][s].isHidden;)s--;return e[t][s]}function ni(e,t,s){let i=[],o=[],n=0,r=0;me([e],(e=>{i.push(e),n+=1})),me([t],(e=>{o.push(e),r+=1})),ae((()=>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=i[e],s=o[e];"number"==typeof t&&"number"==typeof s&&(l+=1,c+=t,h+=s)}ae((()=>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=i[e],s=o[e];"number"==typeof t&&"number"==typeof s&&(p+=(t-d)*(s-u))}return p/(l-(s?1:0))}function ri(e,t,s){let i=0,o=0;const n=s?Ce:Se;o=n(e,((e,t)=>(i+=1,e+t)),0),ae((()=>0!==i&&(!t||1!==i)),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const r=o/i;return n(e,((e,t)=>e+Math.pow(t-r,2)),0)/(i-(t?1:0))}function ai(e,t,s){const i=ce(t);ae((()=>s?0<=i&&i<=1:0<i&&i<1),a("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let o,n=[],r=0;me(e,(e=>{"number"==typeof e&&(o=Te(n,e),n.splice(o+1,0,e),r++)})),ae((()=>0!==r),a("[[FUNCTION_NAME]] has no valid input data."));let l=(r+(s?-1:1))*i;if(s||(ae((()=>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 li={description:a("Average magnitude of deviations from mean."),args:Ae(`\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=Se(e,((e,s)=>(t+=1,e+s)),0);ae((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const i=s/t;return Se(e,((e,t)=>e+Math.abs(i-t)),0)/t},isExported:!0},ci={description:a("Numerical average value in a dataset, ignoring text."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){let t=0;const s=Se(e,((e,s)=>(t+=1,e+s)),0);return ae((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/t},isExported:!0},hi=a("[[FUNCTION_NAME]] has mismatched range sizes."),di=a("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),ui={description:a("Weighted average."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){let t,s,i=0,o=0;ae((()=>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)){ae((()=>Array.isArray(s)),hi);let e=t.length,n=t[0].length;ae((()=>e===s.length&&n===s[0].length),hi);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;ae((()=>c===h),a("[[FUNCTION_NAME]] expects number values.")),h&&(ae((()=>l>=0),di),i+=n*l,o+=l)}}else s=ce(s),t=ce(t),ae((()=>s>=0),di),i+=t*s,o+=s;return ae((()=>0!==o),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/o}},pi={description:a("Numerical average value in a dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){let t=0;const s=Ce(e,((e,s)=>(t+=1,e+s)),0);return ae((()=>0!==t),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/t},isExported:!0},gi={description:a("Average of values depending on criteria."),args:Ae(`\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 i=0,o=0;return xe([e,t],((t,n)=>{const r=(s||e)[t][n];"number"==typeof r&&(i+=1,o+=r)})),ae((()=>0!==i),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/i},isExported:!0},fi={description:a("Average of values depending on multiple criteria."),args:Ae(`\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,i=0;return xe(t,((t,o)=>{const n=e[t][o];"number"==typeof n&&(s+=1,i+=n)})),ae((()=>0!==s),a("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/s},isExported:!0},mi={description:a("The number of numeric values in dataset."),args:Ae(`\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||Q(s)||Z(s))&&(t+=1);return t},isExported:!0},vi={description:a("The number of values in a dataset."),args:Ae(`\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 be(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},Ei={description:a("The covariance of a dataset."),args:Ae(`\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 ni(e,t,!1)},isExported:!0},bi={description:a("The covariance of a dataset."),args:Ae(`\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 ni(e,t,!1)},isExported:!0},Si={description:a("The sample covariance of a dataset."),args:Ae(`\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 ni(e,t,!0)},isExported:!0},Ci={description:a("Nth largest element from a data set."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){const s=Math.trunc(ce(t));let i,o=[],n=0;me([e],(e=>{"number"==typeof e&&(i=Te(o,e),o.splice(i+1,0,e),n++,n>s&&(o.shift(),n--))}));const r=o.shift();return ae((()=>void 0!==r),a("[[FUNCTION_NAME]] has no valid input data.")),ae((()=>n>=s),a("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s.toString())),r},isExported:!0},Ii={description:a("Maximum value in a numeric dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){const t=Se(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},yi={description:a("Maximum numeric value in a dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){const t=Ce(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},wi={description:a("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:Ae(`\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 xe(t,((t,i)=>{const o=e[t][i];"number"==typeof o&&(s=s<o?o:s)})),s===-1/0?0:s},isExported:!0},xi={description:a("Median value in a numeric dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){let t=[];return ve(e,(e=>{t.push(e)})),ai(t,.5,!0)},isExported:!0},Ti={description:a("Minimum value in a numeric dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){const t=Se(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Ri={description:a("Minimum numeric value in a dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(...e){const t=Ce(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},Li={description:a("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:Ae(`\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 xe(t,((t,i)=>{const o=e[t][i];"number"==typeof o&&(s=s>o?o:s)})),s===1/0?0:s},isExported:!0},Mi={description:a("Value at a given percentile of a dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return _i.compute(e,t)},isExported:!0},Ai={description:a("Value at a given percentile of a dataset exclusive of 0 and 1."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return ai([e],t,!1)},isExported:!0},_i={description:a("Value at a given percentile of a dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return ai([e],t,!0)},isExported:!0},Oi={description:a("Value nearest to a specific quartile of a dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return ki.compute(e,t)},isExported:!0},Ni={description:a("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return ai([e],.25*Math.trunc(ce(t)),!1)},isExported:!0},ki={description:a("Value nearest to a specific quartile of a dataset."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return ai([e],.25*Math.trunc(ce(t)),!0)},isExported:!0},Fi={description:a("Nth smallest element in a data set."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){const s=Math.trunc(ce(t));let i,o=[],n=0;me([e],(e=>{"number"==typeof e&&(i=Te(o,e),o.splice(i+1,0,e),n++,n>s&&(o.pop(),n--))}));const r=o.pop();return ae((()=>void 0!==r),a("[[FUNCTION_NAME]] has no valid input data.")),ae((()=>n>=s),a("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",s.toString())),r},isExported:!0},$i={description:a("Standard deviation."),args:Ae(`\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(Hi.compute(...e))},isExported:!0},Di={description:a("Standard deviation of entire population."),args:Ae(`\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(zi.compute(...e))},isExported:!0},Pi={description:a("Standard deviation."),args:Ae(`\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(Zi.compute(...e))},isExported:!0},Ui={description:a("Standard deviation of sample (text as 0)."),args:Ae(`\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(Gi.compute(...e))},isExported:!0},Bi={description:a("Standard deviation of entire population."),args:Ae(`\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(Wi.compute(...e))},isExported:!0},Vi={description:a("Standard deviation of entire population (text as 0)."),args:Ae(`\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(qi.compute(...e))},isExported:!0},Hi={description:a("Variance."),args:Ae(`\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 ri(e,!0,!1)},isExported:!0},zi={description:a("Variance of entire population."),args:Ae(`\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 ri(e,!1,!1)},isExported:!0},Zi={description:a("Variance."),args:Ae(`\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 ri(e,!0,!1)},isExported:!0},Gi={description:a("Variance of sample (text as 0)."),args:Ae(`\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 ri(e,!0,!0)},isExported:!0},Wi={description:a("Variance of entire population."),args:Ae(`\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 ri(e,!1,!1)},isExported:!0},qi={description:a("Variance of entire population (text as 0)."),args:Ae(`\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 ri(e,!1,!0)},isExported:!0};var ji=Object.freeze({__proto__:null,AVEDEV:li,AVERAGE:ci,AVERAGE_WEIGHTED:ui,AVERAGEA:pi,AVERAGEIF:gi,AVERAGEIFS:fi,COUNT:mi,COUNTA:vi,COVAR:Ei,COVARIANCE_P:bi,COVARIANCE_S:Si,LARGE:Ci,MAX:Ii,MAXA:yi,MAXIFS:wi,MEDIAN:xi,MIN:Ti,MINA:Ri,MINIFS:Li,PERCENTILE:Mi,PERCENTILE_EXC:Ai,PERCENTILE_INC:_i,QUARTILE:Oi,QUARTILE_EXC:Ni,QUARTILE_INC:ki,SMALL:Fi,STDEV:$i,STDEV_P:Di,STDEV_S:Pi,STDEVA:Ui,STDEVP:Bi,STDEVPA:Vi,VAR:Hi,VAR_P:zi,VAR_S:Zi,VARA:Gi,VARP:Wi,VARPA:qi});function Xi(e,t,s){var i;const o=new Map,n=e.length;for(let t=n-1;t>=0;t--)o.set(de(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=de(t).toUpperCase();if(r=null!==(i=o.get(e))&&void 0!==i?i:-1,-1===r)throw new Error(a("The field (%s) must be one of %s.",de(t),[...o.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 i=[],n=!0;for(let r=0;r<s.length;r++){const a=de(s[r][0]).toUpperCase(),l=o.get(a),c=s[r][t];if(void 0!==c){if(void 0===l){n=!1;break}i.push([e[l].slice(1,h)]),i.push(c)}}if(n){if(!(i.length>0)){c=new Set(Array(h-1).keys());break}xe(i,((e,t)=>{c.add(t)}),!0)}}const d=e[r];return[...c].map((e=>d[e+1]))}const Yi=Ae(`\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`),Ki={description:a("Average of a set of values from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return ci.compute([i])},isExported:!0},Qi={description:a("Counts values from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return mi.compute([i])},isExported:!0},Ji={description:a("Counts values and text from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return vi.compute([i])},isExported:!0},eo={description:a("Single value from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return ae((()=>1===i.length),a("More than one match found in DGET evaluation.")),i[0]},isExported:!0},to={description:a("Maximum of values from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return Ii.compute([i])},isExported:!0},so={description:a("Minimum of values from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return Ti.compute([i])},isExported:!0},io={description:a("Product of values from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return Lt.compute([i])},isExported:!0},oo={description:a("Standard deviation of population sample from table."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return $i.compute([i])},isExported:!0},no={description:a("Standard deviation of entire population from table."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return Bi.compute([i])},isExported:!0},ro={description:a("Sum of values from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return Ut.compute([i])},isExported:!0},ao={description:a("Variance of population sample from table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return Hi.compute([i])},isExported:!0},lo={description:a("Variance of a population from a table-like range."),args:Yi,returns:["NUMBER"],compute:function(e,t,s){const i=Xi(e,t,s);return Wi.compute([i])},isExported:!0};var co=Object.freeze({__proto__:null,DAVERAGE:Ki,DCOUNT:Qi,DCOUNTA:Ji,DGET:eo,DMAX:to,DMIN:so,DPRODUCT:io,DSTDEV:oo,DSTDEVP:no,DSUM:ro,DVAR:ao,DVARP:lo});const ho=new Date(1899,11,30);function uo(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}const po={description:a("Converts year/month/day into a date."),args:Ae(`\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 i=Math.trunc(ce(e));const o=Math.trunc(ce(t)),n=Math.trunc(ce(s));ae((()=>0<=i&&i<=9999),a("The year (%s) must be between 0 and 9999 inclusive.",i.toString())),i<1900&&(i+=1900);const r=new Date(i,o-1,n).getTime()-ho.getTime();return ae((()=>r>=0),a("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),Math.round(r/864e5)},isExported:!0},go={description:a("Converts a date string to a date value."),args:Ae(`\n date_string (string) ${a("The string representing the date.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e),s=Z(t);return ae((()=>null!==s),a("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(s.value)},isExported:!0},fo={description:a("Day of the month that a specific date falls on."),args:Ae(`\n date (string) ${a("The date from which to extract the day.")}\n `),returns:["NUMBER"],compute:function(e){return ge(e).getDate()},isExported:!0},mo={description:a("Number of days between two dates."),args:Ae(`\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=ge(e),i=ge(t),o=s.getTime()-i.getTime();return Math.round(o/864e5)},isExported:!0},vo={description:a("Date a number of months before/after another date."),args:Ae(`\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=ge(e),i=Math.trunc(ce(t)),o=s.getFullYear(),n=s.getMonth(),r=s.getDate(),a=new Date(o,n+i,r).getTime()-ho.getTime();return Math.round(a/864e5)},isExported:!0},Eo={description:a("Last day of a month before or after a date."),args:Ae(`\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=ge(e),i=Math.trunc(ce(t)),o=s.getFullYear(),n=s.getMonth(),r=new Date(o,n+i+1,0).getTime()-ho.getTime();return Math.round(r/864e5)},isExported:!0},bo={description:a("Hour component of a specific time."),args:Ae(`\n time (date) ${a("The time from which to calculate the hour component.")}\n `),returns:["NUMBER"],compute:function(e){return ge(e).getHours()},isExported:!0},So={description:a("ISO week number of the year."),args:Ae(`\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=ge(e),s=t.getFullYear();let i=1;for(;4!==new Date(s,0,i).getDay();)i+=1;const o=new Date(s,0,i-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=o.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=o;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},Co={description:a("Minute component of a specific time."),args:Ae(`\n time (date) ${a("The time from which to calculate the minute component.")}\n `),returns:["NUMBER"],compute:function(e){return ge(e).getMinutes()},isExported:!0},Io={description:a("Month of the year a specific date falls in"),args:Ae(`\n date (date) ${a("The date from which to extract the month.")}\n `),returns:["NUMBER"],compute:function(e){return ge(e).getMonth()+1},isExported:!0},yo={description:a("Net working days between two provided days."),args:Ae(`\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 xo.compute(e,t,1,s)},isExported:!0};function wo(e){if("string"==typeof e){ae((()=>{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 ae((()=>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 xo={description:a("Net working days between two dates (specifying weekends)."),args:Ae(`\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,i){const o=ge(e),n=ge(t),r=wo(s);let a=new Set;void 0!==i&&me([i],(e=>{const t=ge(e);a.add(t.getTime())}));const l=o.getTime()>n.getTime(),c=new Date((l?o:n).getTime());let h=new Date((l?n:o).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},To={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()-ho.getTime(),s=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/864e5)+s},isExported:!0},Ro={description:a("Minute component of a specific time."),args:Ae(`\n time (date) ${a("The time from which to calculate the second component.")}\n `),returns:["NUMBER"],compute:function(e){return ge(e).getSeconds()},isExported:!0},Lo={description:a("Converts hour/minute/second into a time."),args:Ae(`\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 i=Math.trunc(ce(e)),o=Math.trunc(ce(t)),n=Math.trunc(ce(s));return o+=Math.floor(n/60),n=n%60+(n<0?60:0),i+=Math.floor(o/60),o=o%60+(o<0?60:0),i%=24,ae((()=>i>=0),a("The function [[FUNCTION_NAME]] result cannot be negative")),i/24+o/1440+n/86400},isExported:!0},Mo={description:a("Converts a time string into its serial number representation."),args:Ae(`\n time_string (string) ${a("The string that holds the time representation.")}\n `),returns:["NUMBER"],compute:function(e){const t=de(e),s=Z(t);ae((()=>null!==s),a("The time_string (%s) cannot be parsed to date/time.",t));const i=s.value-Math.trunc(s.value);return i<0?1+i:i},isExported:!0},Ao={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()-ho.getTime();return Math.round(t/864e5)},isExported:!0},_o={description:a("Day of the week of the date provided (as number)."),args:Ae(`\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=ge(e),i=Math.round(ce(t)),o=s.getDay();return ae((()=>[1,2,3].includes(i)),a("The type (%s) must be 1, 2 or 3.",i.toString())),1===i?o+1:2===i?0===o?7:o:0===o?6:o-1},isExported:!0},Oo={description:a("Week number of the year."),args:Ae(`\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=ge(e),i=Math.round(ce(t));if(ae((()=>1===i||2===i||11<=i&&i<=17||21===i),a("The type (%s) is out of range.",i.toString())),21===i)return So.compute(e);let o;o=1===i||2===i?i-1:i-10==7?0:i-10;const n=s.getFullYear();let r=1,l=new Date(n,0,r);for(;l.getDay()!==o;)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},No={description:a("Number of working days from start date."),args:Ae(`\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 ko.compute(e,t,1,s)},isExported:!0},ko={description:a("Net working days between two dates (specifying weekends)."),args:Ae(`\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,i){let o=ge(e),n=Math.trunc(ce(t));"string"==typeof s&&ae((()=>"1111111"!==s),a("The weekend (%s) must be different from '1111111'.",s));const r=wo(s);let l=new Set;void 0!==i&&me([i],(e=>{const t=ge(e);l.add(t.getTime())}));let c=new Date(o.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-ho.getTime();return Math.round(p/864e5)},isExported:!0},Fo={description:a("Year specified by a given date."),args:Ae(`\n date (date) ${a("The date from which to extract the year.")}\n `),returns:["NUMBER"],compute:function(e){return ge(e).getFullYear()},isExported:!0},$o={description:a("Exact number of years between two dates."),args:Ae(`\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 i=Math.trunc(ce(e)),o=Math.trunc(ce(t));const n=Math.trunc(ce(s));if(ae((()=>i>=0),a("The start_date (%s) must be positive or null.",i.toString())),ae((()=>o>=0),a("The end_date (%s) must be positive or null.",o.toString())),ae((()=>0<=n&&n<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",n.toString())),i===o)return 0;if(i>o){const e=o;o=i,i=e}const r=ge(i),l=ge(o);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===(uo(p)?29:28)&&(c=30,1===u&&h===(uo(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+=uo(e)?366:365;e=s/t}else t?uo(p)&&(e=366):(uo(p)&&d<2&&(e=366),uo(g)&&(u>1||1===u&&29===h)&&(e=366));f=i/e,m=o/e;break;case 2:f=i/360,m=o/360;break;case 3:f=i/365,m=o/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 Do=Object.freeze({__proto__:null,DATE:po,DATEVALUE:go,DAY:fo,DAYS:mo,EDATE:vo,EOMONTH:Eo,HOUR:bo,ISOWEEKNUM:So,MINUTE:Co,MONTH:Io,NETWORKDAYS:yo,NETWORKDAYS_INTL:xo,NOW:To,SECOND:Ro,TIME:Lo,TIMEVALUE:Mo,TODAY:Ao,WEEKDAY:_o,WEEKNUM:Oo,WORKDAY:No,WORKDAY_INTL:ko,YEAR:Fo,YEARFRAC:$o});function Po(e,t,s,i,o=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<o||Math.abs(l)<o,ae((()=>d<i),a("Function [[FUNCTION_NAME]] didn't find any result")),d++}while(!h);return c}const Uo={description:a("Depreciation via declining balance method."),args:Ae(`\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,i,...o){const n=ce(e),r=ce(t),l=ce(s),c=Math.trunc(ce(i)),h=o.length?Math.trunc(ce(o[0])):12,d=l+(12===h?0:1);ae((()=>n>0),a("The cost (%s) must be strictly positive.",n.toString())),ae((()=>r>=0),a("The salvage (%s) must be positive or null.",r.toString())),ae((()=>l>0),a("The life (%s) must be strictly positive.",l.toString())),ae((()=>c>0),a("The period (%s) must be strictly positive.",c.toString())),ae((()=>1<=h&&h<=12),a("The month (%s) must be between 1 and 12 inclusive.",h.toString())),ae((()=>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}},Bo={description:a("Number of periods for an investment to reach a value."),args:Ae(`\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,i,o,n=0){n=n||0;const r=Math.trunc(ce(e)),l=Math.trunc(ce(t)),c=ce(s),h=ce(i),d=Math.trunc(ce(o)),u=Math.trunc(ce(n));ae((()=>r<l),a("The maturity (%s) must be strictly greater than the settlement (%s).",l.toString(),r.toString())),ae((()=>c>=0),a("The rate (%s) must be positive or null.",c.toString())),ae((()=>h>=0),a("The yield (%s) must be positive or null.",h.toString())),ae((()=>[1,2,4].includes(d)),a("The frequency (%s) must be one of %s",d.toString(),[1,2,4].toString())),ae((()=>0<=u&&u<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",u.toString()));const p=$o.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}},Vo={description:a("Future value of an annuity investment."),args:Ae(`\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,i=0,o=0){i=i||0,o=o||0;const n=ce(e),r=ce(t),a=ce(s),l=ce(i),c=pe(o)?1:0;return n?-l*(1+n)**r-a*(1+n*c)*((1+n)**r-1)/n:-(l+a*r)}},Ho={description:a("Internal rate of return given periodic cashflows."),args:Ae(`\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=ce(t);ae((()=>s>-1),a("The rate_guess (%s) must be strictly greater than -1.",s.toString()));let i=!1,o=!1,n=[];ve([e],(e=>{e>0&&(i=!0),e<0&&(o=!0),n.push(e)})),ae((()=>i&&o),a("The cashflow_amounts must include negative and positive values."));const r=n.shift();return Po((function(e){return function(e,t,s){const i=s.length;let o=0;return s.reduce(((t,s)=>(o++,t+s*e**(i-o))),t*e**i)}(e,r,n)}),(function(e){return function(e,t,s){const i=s.length;let o=0;return s.reduce(((t,s)=>(o++,t+s*(i-o)*e**(i-o-1))),t*i*e**(i-1))}(e,r,n)}),s+1,20,1e-5)-1}},zo={description:a("Modified Macaulay duration."),args:Ae(`\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,i,o,n=0){return Bo.compute(e,t,s,i,o,n)/(1+ce(i)/Math.trunc(ce(o)))}};const Zo={description:a("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:Ae(`\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=ce(e);return ae((()=>-1!==s),a("The discount (%s) must be different from -1.",s.toString())),function(e,t,s){let i=0;return Se(s,((t,s)=>(i++,t+s/(1+e)**i)),t)}(s,0,t)}},Go={description:a("Computes the number of periods needed for an investment to reach a value."),args:Ae(`\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 i=ce(e),o=ce(t),n=ce(s);return ae((()=>i>0),a("The rate (%s) must be strictly positive.",i.toString())),ae((()=>o>0),a("The present_value (%s) must be strictly positive.",o.toString())),ae((()=>n>0),a("The future_value (%s) must be strictly positive.",n.toString())),(Math.log(n)-Math.log(o))/Math.log(1+i)}},Wo={description:a("Present value of an annuity investment."),args:Ae(`\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,i=0,o=0){i=i||0,o=o||0;const n=ce(e),r=ce(t),a=ce(s),l=ce(i),c=pe(o)?1:0;return n?-(a*(1+n*c)*((1+n)**r-1)/n+l)/(1+n)**r:-(l+a*r)}},qo={description:a("Price of a security paying periodic interest."),args:Ae(`\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,i,o,n,r=0){r=r||0;const l=Math.trunc(ce(e)),c=Math.trunc(ce(t)),h=ce(s),d=ce(i),u=ce(o),p=Math.trunc(ce(n)),g=Math.trunc(ce(r));ae((()=>c>l),a("The maturity (%s) must be strictly greater than the settlement (%s).",c.toString(),l.toString())),ae((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ae((()=>d>=0),a("The yield (%s) must be positive or null.",d.toString())),ae((()=>u>0),a("The redemption (%s) must be strictly positive.",u.toString())),ae((()=>[1,2,4].includes(p)),a("The frequency (%s) must be one of %s.",p.toString(),[1,2,4].toString())),ae((()=>0<=g&&g<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",g.toString()));const f=$o.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)}},jo={description:a("Annual yield of a security paying periodic interest."),args:Ae(`\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,i,o,n,r=0){r=r||0;const l=Math.trunc(ce(e)),c=Math.trunc(ce(t)),h=ce(s),d=ce(i),u=ce(o),p=Math.trunc(ce(n)),g=Math.trunc(ce(r));ae((()=>c>l),a("The maturity (%s) must be strictly greater than the settlement (%s).",c.toString(),l.toString())),ae((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ae((()=>d>0),a("The price (%s) must be strictly positive.",d.toString())),ae((()=>u>0),a("The redemption (%s) must be strictly positive.",u.toString())),ae((()=>[1,2,4].includes(p)),a("The frequency (%s) must be one of %s.",p.toString(),[1,2,4].toString())),ae((()=>0<=g&&g<=4),a("The day_count_convention (%s) must between 0 and 4 inclusive.",g.toString()));const f=$o.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=Po((function(e){return function(e,t,s,i,o,n){let r=n-(e+o*(1-t))*i**(s-1+t);for(let e=1;e<=s;e++)r+=o*i**(e-1);return r}(d,v,m,e,E,u)}),(function(e){return function(e,t,s,i,o){let n=-(e+o*(1-t))*(s-1+t)*i**(s-2+t);for(let e=1;e<=s;e++)n+=o*(e-1)*i**(e-2);return n}(d,v,m,e,E)}),1+(h+1)/p,100,1e-5);return(b-1)*p}},Xo={description:a("Annual yield of a security paying interest at maturity."),args:Ae(`\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,i,o,n=0){n=n||0;const r=Math.trunc(ce(e)),l=Math.trunc(ce(t)),c=Math.trunc(ce(s)),h=ce(i),d=ce(o),u=Math.trunc(ce(n));ae((()=>r>=c),a("The settlement (%s) must be greater than or equal to the issue (%s).",r.toString(),c.toString())),ae((()=>l>r),a("The maturity (%s) must be strictly greater than the settlement (%s).",l.toString(),r.toString())),ae((()=>h>=0),a("The rate (%s) must be positive or null.",h.toString())),ae((()=>d>0),a("The price (%s) must be strictly positive.",d.toString())),ae((()=>0<=u&&u<=4),a("The day_count_convention (%s) must be between 0 and 4 inclusive.",u.toString()));const p=$o.compute(c,l,u),g=$o.compute(c,r,u),f=$o.compute(r,l,u);return(100*(1+h*p)/(d+100*h*g)-1)/f}};var Yo=Object.freeze({__proto__:null,DB:Uo,DURATION:Bo,FV:Vo,IRR:Ho,MDURATION:zo,NPV:Zo,PDURATION:Go,PV:Wo,PRICE:qo,YIELD:jo,YIELDMAT:Xo});const Ko={description:a("Whether a value is an error."),args:Ae(`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},Qo={description:a("Whether a value is `true` or `false`."),args:Ae(`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},Jo={description:a("Whether a value is non-textual."),args:Ae(`value (any) ${a("The value to be checked.")}`),returns:["BOOLEAN"],compute:function(e){return"string"!=typeof e},isExported:!0},en={description:a("Whether a value is a number."),args:Ae(`value (any) ${a("The value to be verified as a number.")}`),returns:["BOOLEAN"],compute:function(e){return"number"==typeof e},isExported:!0},tn={description:a("Whether a value is text."),args:Ae(`value (any) ${a("The value to be verified as text.")}`),returns:["BOOLEAN"],compute:function(e){return"string"==typeof e},isExported:!0};var sn=Object.freeze({__proto__:null,ISERROR:Ko,ISLOGICAL:Qo,ISNONTEXT:Jo,ISNUMBER:en,ISTEXT:tn});const on={description:a("Logical `and` operator."),args:Ae(`\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))),ae((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0},nn={description:a("Returns value depending on logical expression."),args:Ae(`\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 i=pe(e)?t():s();return null==i?"":i},isExported:!0},rn={description:a("Value if it is not an error, otherwise 2nd argument."),args:Ae(`\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},an={description:a("Returns a value depending on multiple logical expressions."),args:Ae(`\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){ae((()=>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(pe(e[t]()))return e[t+1]();throw new Error(a("No match."))},isExported:!0},ln={description:a("Returns opposite of provided logical value."),args:Ae(`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!pe(e)},isExported:!0},cn={description:a("Logical `or` operator."),args:Ae(`\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))),ae((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0},hn={description:a("Logical `xor` operator."),args:Ae(`\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))),ae((()=>t),a("[[FUNCTION_NAME]] has no valid input data.")),s},isExported:!0};var dn=Object.freeze({__proto__:null,AND:on,IF:nn,IFERROR:rn,IFS:an,NOT:ln,OR:cn,XOR:hn});function un(e,t){for(let s=0;s<e.length;s++)if(e[s]===t)return s;return-1}const pn={description:a("Column number of a specified cell."),args:Ae(`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)),ae((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return _s(e).left+1},isExported:!0},gn={description:a("Number of columns in a specified array or range."),args:Ae(`range (meta) ${a("The range whose column count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=_s(e);return t.right-t.left+1},isExported:!0},fn={description:a("Horizontal lookup"),args:Ae(`\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,i=true){const o=Math.trunc(ce(s));ae((()=>1<=o&&o<=t[0].length),a("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const n=pe(i),r=t.map((e=>e[0]));let l;return l=n?Te(r,e):un(r,e),ae((()=>l>-1),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",de(e))),t[l][o-1]},isExported:!0},mn={description:a("Look up a value."),args:Ae(`\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 i=t.length,o=t[0].length;const n=o>=i,r=Te(n?t[0]:t.map((e=>e[0])),e);return ae((()=>r>=0),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",de(e))),void 0===s?n?t[i-1][r]:t[r][o-1]:(i=s.length,o=s[0].length,ae((()=>1===i||1===o),a("The result_range must be a single row or a single column.")),i>1?(ae((()=>r<=i-1),a("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(r+1).toString())),s[r][0]):(ae((()=>r<=o-1),a("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(r+1).toString())),s[0][r]))},isExported:!0},vn={description:a("Position of item in range that matches value."),args:Ae(`\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 i=ce(s);const o=t.length,n=t[0].length;ae((()=>1===o||1===n),a("The range must be a single row or a single column."));let r=-1;const l=t.flat();switch(i=Math.sign(i),i){case 1:r=Te(l,e);break;case 0:r=un(l,e);break;case-1:r=function(e,t){const s=typeof t;let i,o,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===i||i>a||i===a&&o>r)&&(i=a,o=r),l===s&&a<=t?h=r-1:c=n+1}return void 0!==o?o:-1}(l,e)}return ae((()=>r>=0),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",de(e))),r+1},isExported:!0},En={description:a("Row number of a specified cell."),args:Ae(`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)),ae((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return _s(e).top+1},isExported:!0},bn={description:a("Number of rows in a specified array or range."),args:Ae(`range (meta) ${a("The range whose row count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=_s(e);return t.bottom-t.top+1},isExported:!0},Sn={description:a("Vertical lookup."),args:Ae(`\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,i=true){const o=Math.trunc(ce(s));ae((()=>1<=o&&o<=t.length),a("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const n=pe(i),r=t[0];let l;return l=n?Te(r,e):un(r,e),ae((()=>l>-1),a("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",de(e))),t[o-1][l]},isExported:!0};var Cn=Object.freeze({__proto__:null,COLUMN:pn,COLUMNS:gn,HLOOKUP:fn,LOOKUP:mn,MATCH:vn,ROW:En,ROWS:bn,VLOOKUP:Sn});const In={description:a("Sum of two numbers."),args:Ae(`\n value1 (number) ${a("The first addend.")}\n value2 (number) ${a("The second addend.")}\n `),returns:["NUMBER"],returnFormat:Be.FormatFromArgument,compute:function(e,t){return ce(e)+ce(t)}},yn={description:a("Concatenation of two values."),args:Ae(`\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 de(e)+de(t)},isExported:!0},wn={description:a("One number divided by another."),args:Ae(`\n dividend (number) ${a("The number to be divided.")}\n divisor (number) ${a("The number to divide by.")}\n `),returns:["NUMBER"],returnFormat:Be.FormatFromArgument,compute:function(e,t){const s=ce(t);return ae((()=>0!==s),a("The divisor must be different from zero.")),ce(e)/s}};function xn(e){return null==e}const Tn={number:0,string:"",boolean:!1},Rn={description:a("Equal."),args:Ae(`\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=xn(e)?Tn[typeof t]:e,t=xn(t)?Tn[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function Ln(e,t,s){e=xn(e)?Tn[typeof t]:e,t=xn(t)?Tn[typeof e]:t,"number"!=typeof e&&(e=de(e).toUpperCase()),"number"!=typeof t&&(t=de(t).toUpperCase());const i=typeof e,o=typeof t;return"string"===i&&"number"===o||("string"!==o||"number"!==i)&&s(e,t)}const Mn={description:a("Strictly greater than."),args:Ae(`\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 Ln(e,t,((e,t)=>e>t))}},An={description:a("Greater than or equal to."),args:Ae(`\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 Ln(e,t,((e,t)=>e>=t))}},_n={description:a("Less than."),args:Ae(`\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!An.compute(e,t)}},On={description:a("Less than or equal to."),args:Ae(`\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!Mn.compute(e,t)}},Nn={description:a("Difference of two numbers."),args:Ae(`\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:Be.FormatFromArgument,compute:function(e,t){return ce(e)-ce(t)}},kn={description:a("Product of two numbers"),args:Ae(`\n factor1 (number) ${a("The first multiplicand.")}\n factor2 (number) ${a("The second multiplicand.")}\n `),returns:["NUMBER"],returnFormat:Be.FormatFromArgument,compute:function(e,t){return ce(e)*ce(t)}},Fn={description:a("Not equal."),args:Ae(`\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!Rn.compute(e,t)}},$n={description:a("A number raised to a power."),args:Ae(`\n base (number) ${a("The number to raise to the exponent power.")}\n exponent (number) ${a("The exponent to raise base to.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return Rt.compute(e,t)}},Dn={description:a("A number with the sign reversed."),args:Ae(`\n value (number) ${a("The number to have its sign reversed. Equivalently, the number to multiply by -1.")}\n `),returnFormat:Be.FormatFromArgument,returns:["NUMBER"],compute:function(e){return-ce(e)}},Pn={description:a("Value interpreted as a percentage."),args:Ae(`\n percentage (number) ${a("The value to interpret as a percentage.")}\n `),returns:["NUMBER"],compute:function(e){return ce(e)/100}},Un={description:a("A specified number, unchanged."),args:Ae(`\n value (any) ${a("The number to return.")}\n `),returnFormat:Be.FormatFromArgument,returns:["ANY"],compute:function(e){return e}};var Bn=Object.freeze({__proto__:null,ADD:In,CONCAT:yn,DIVIDE:wn,EQ:Rn,GT:Mn,GTE:An,LT:_n,LTE:On,MINUS:Nn,MULTIPLY:kn,NE:Fn,POW:$n,UMINUS:Dn,UNARY_PERCENT:Pn,UPLUS:Un});const Vn={description:a("Gets character associated with number."),args:Ae(`\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(ce(e));return ae((()=>t>=1),a("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},Hn={description:a("Appends strings to one another."),args:Ae(`\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 be(e,((e,t)=>e+de(t)),"")},isExported:!0},zn={description:a("Tests whether two strings are identical."),args:Ae(`\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 de(e)===de(t)},isExported:!0},Zn={description:a("First position of string found in text, case-sensitive."),args:Ae(`\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 i=de(e),o=de(t),n=ce(s);ae((()=>""!==o),a("The text_to_search must be non-empty.")),ae((()=>n>=1),a("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const r=o.indexOf(i,n-1);return ae((()=>r>=0),a("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i.toString(),o)),r+1},isExported:!0},Gn={description:a("Concatenates elements of arrays with delimiter."),args:Ae(`\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=de(e);return be(t,((e,t)=>(e?e+s:"")+de(t)),"")}},Wn={description:a("Substring from beginning of specified string."),args:Ae(`\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?ce(t[0]):1;return ae((()=>s>=0),a("The number_of_characters (%s) must be positive or null.",s.toString())),de(e).substring(0,s)},isExported:!0},qn={description:a("Length of a string."),args:Ae(`\n text (string) ${a("The string whose length will be returned.")}\n `),returns:["NUMBER"],compute:function(e){return de(e).length},isExported:!0},jn={description:a("Converts a specified string to lowercase."),args:Ae(`\n text (string) ${a("The string to convert to lowercase.")}\n `),returns:["STRING"],compute:function(e){return de(e).toLowerCase()},isExported:!0},Xn={description:a("Replaces part of a text string with different text."),args:Ae(`\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,i){const o=ce(t);ae((()=>o>=1),a("The position (%s) must be greater than or equal to 1.",o.toString()));const n=de(e),r=ce(s),l=de(i);return n.substring(0,o-1)+l+n.substring(o-1+r)},isExported:!0},Yn={description:a("A substring from the end of a specified string."),args:Ae(`\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?ce(t[0]):1;ae((()=>s>=0),a("The number_of_characters (%s) must be positive or null.",s.toString()));const i=de(e),o=i.length;return i.substring(o-s,o)},isExported:!0},Kn={description:a("First position of string found in text, ignoring case."),args:Ae(`\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 i=de(e).toLowerCase(),o=de(t).toLowerCase(),n=ce(s);ae((()=>""!==o),a("The text_to_search must be non-empty.")),ae((()=>n>=1),a("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const r=o.indexOf(i,n-1);return ae((()=>r>=0),a("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i,o)),r+1},isExported:!0},Qn={description:a("Replaces existing text with new text in a string."),args:Ae(`\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,i){const o=ce(i);ae((()=>o>=0),a("The occurrenceNumber (%s) must be positive or null.",o.toString()));const n=de(e),r=de(t);if(""===r)return n;const l=de(s),c=new RegExp(hs(r),"g");if(0===o)return n.replace(c,l);let h=0;return n.replace(c,(e=>++h===o?l:e))},isExported:!0},Jn={description:a("Combines text from multiple strings and/or arrays."),args:Ae(`\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 i=de(e),o=pe(t);let n=0;return be(s,((e,t)=>o&&""===de(t)?e:(n++?e+i:"")+de(t)),"")},isExported:!0},er={description:a("Removes space characters."),args:Ae(`\n text (string) ${a("The text or reference to a cell containing text to be trimmed.")}\n `),returns:["STRING"],compute:function(e){return de(e).trim()},isExported:!0},tr={description:a("Converts a specified string to uppercase."),args:Ae(`\n text (string) ${a("The string to convert to uppercase.")}\n `),returns:["STRING"],compute:function(e){return de(e).toUpperCase()},isExported:!0};const sr={database:co,date:Do,financial:Yo,info:sn,lookup:Cn,logical:dn,math:Gt,operators:Bn,statistical:ji,text:Object.freeze({__proto__:null,CHAR:Vn,CONCATENATE:Hn,EXACT:zn,FIND:Zn,JOIN:Gn,LEFT:Wn,LEN:qn,LOWER:jn,REPLACE:Xn,RIGHT:Yn,SEARCH:Kn,SUBSTITUTE:Qn,TEXTJOIN:Jn,TRIM:er,UPPER:tr})};const ir=new class extends Re{constructor(){super(...arguments),this.mapping={}}add(e,t){e=e.toUpperCase().replace("_",".");const s=Oe(t);return function(e){let t=!1,s=!1,i=!1;for(let o of e){if(o.type.includes("META")&&o.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&&!o.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||i,n=!(o.optional||o.repeating||o.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=o.repeating,s=o.optional,i=o.default}}(s.args),this.mapping[e]=s.compute,super.add(e,s),this}};for(let e in sr){const t=sr[e];for(let s in t){const i=t[s];i.category=e,ir.add(s,{isExported:!1,...i})}}const or=/^[S|N]?\d+/,nr=ir.content,rr="+,-,*,/,:,=,<>,>=,>,<=,<,%,^,&".split(",");function ar(e){const t=e.split(""),s=[];for(;t.length;){let e=br(t)||dr(t)||pr(t)||fr(t)||cr(t)||lr(t)||Sr(t)||gr(t)||vr(t);e||(e={type:"UNKNOWN",value:t.shift()}),s.push(e)}return s}function lr(e){if(e[0]===$){e.shift();const t=e.join("").match(or);if(!t)return null;e.splice(0,t[0].length),e[0]===$&&e.shift();const s=t[0];switch(s[0]){case"S":return{type:"NORMALIZED_STRING",value:s.substring(1)};case"N":return{type:"NORMALIZED_NUMBER",value:s.substring(1)};default:return{type:"REFERENCE",value:s}}}return null}function cr(e){return"?"===e[0]?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const hr={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function dr(e){if(e[0]in hr){const t=e.shift();return{type:hr[t],value:t}}return null}function ur(e,t){for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;return!0}function pr(e){for(let t of rr)if(ur(e,t))return e.splice(0,t.length),{type:"OPERATOR",value:t};return null}function gr(e){const t=e.join("").match(Y);return t?(e.splice(0,t[0].length),{type:"NUMBER",value:t[0]}):null}function fr(e){if('"'===e[0]){const t=e.shift(),s=[t];for(;e[0]&&(e[0]!==t||"\\"===s[s.length-1]);)s.push(e.shift());return'"'===e[0]&&s.push(e.shift()),{type:"STRING",value:s.join("")}}return null}const mr=/\w|\.|!|\$/;function vr(e){const t=[];if("'"===e[0]){let s=e.shift();for(t.push(s);e[0];)if(s=e.shift(),t.push(s),"'"===s){if(!e[0]||"'"!==e[0])break;s=e.shift(),t.push(s)}if("'"!==s)return{type:"UNKNOWN",value:t.join("")}}for(;e[0]&&e[0].match(mr);)t.push(e.shift());if(t.length){const e=t.join("");return{type:e.toUpperCase()in nr?"FUNCTION":"SYMBOL",value:e}}return null}const Er=/\s/;function br(e){let t=0;for(;e[0]&&e[0].match(Er);)t++,e.shift();return t?{type:"SPACE",value:" ".repeat(t)}:null}function Sr(e){return ur(e,_)?(e.splice(0,_.length),{type:"INVALID_REFERENCE",value:_}):null}const Cr=["-","+"],Ir=["*","+","&"],yr={"^":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10},wr=6;function xr(e){switch(e.type){case"NUMBER":case"SYMBOL":return 0;case"COMMA":return 3;case"LEFT_PAREN":case"RIGHT_PAREN":return 5;case"OPERATOR":return yr[e.value]||15}throw new Error(a("Unknown token: %s",e.value))}function Tr(e,t,s){if("OPERATOR"===t.type){const i=Rr(s,xr(t));return{type:"BIN_OPERATION",value:t.value,left:e,right:i}}throw new Error(N)}function Rr(e,t){const s=e.shift();if(!s)throw new Error(N);let i=function(e,t){var s;switch(e.type){case"DEBUGGER":const i=Rr(t,1e3);return i.debug=!0,i;case"NUMBER":return{type:"NUMBER",value:ee(e.value)};case"NORMALIZED_NUMBER":return{type:"NORMALIZED_NUMBER",value:parseInt(e.value,10)};case"STRING":return{type:"STRING",value:e.value};case"NORMALIZED_STRING":return{type:"NORMALIZED_STRING",value:parseInt(e.value,10)};case"FUNCTION":if("LEFT_PAREN"!==t.shift().type)throw new Error(a("Wrong function call"));{const i=[];if(t[0]&&"RIGHT_PAREN"!==t[0].type)for("COMMA"===t[0].type?i.push({type:"UNKNOWN",value:""}):i.push(Rr(t,wr));"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)){i.push({type:"UNKNOWN",value:""});break}"COMMA"===(null==e?void 0:e.type)?i.push({type:"UNKNOWN",value:""}):i.push(Rr(t,wr))}const o=t.shift();if(!o||"RIGHT_PAREN"!==o.type)throw new Error(a("Wrong function call"));return{type:"FUNCALL",value:e.value,args:i}}case"REFERENCE":return{type:"NORMALIZED_REFERENCE",value:parseInt(e.value,10)};case"INVALID_REFERENCE":throw new Error(a("Invalid reference"));case"SYMBOL":if(Kt.test(e.value))return{type:"REFERENCE",value:e.value};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 o=Rr(t,5);if(!t.length||"RIGHT_PAREN"!==t[0].type)throw new Error(a("Unmatched left parenthesis"));return t.shift(),o;default:if("OPERATOR"===e.type&&Cr.includes(e.value))return{type:"UNARY_OPERATION",value:e.value,right:Rr(t,yr[e.value])};throw new Error(a("Unexpected token: %s",e.value))}}(s,e);for(;e[0]&&xr(e[0])>t;)i=Tr(i,e.shift(),e);return i}function Lr(e){const t=ar(e).filter((e=>"SPACE"!==e.type));"OPERATOR"===t[0].type&&"="===t[0].value&&t.splice(0,1);const s=Rr(t,0);if(t.length)throw new Error(N);return s}function Mr(e,t,s){switch(t===e.type&&(e=s(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>Mr(e,t,s)))};case"UNARY_OPERATION":return{...e,right:Mr(e.right,t,s)};case"BIN_OPERATION":return{...e,right:Mr(e.right,t,s),left:Mr(e.left,t,s)};default:return e}}function Ar(e,t={references:[],numbers:[],strings:[]}){switch(e.type){case"FUNCALL":const s=e.args.map((e=>Ar(e,t)));return`${e.value}(${s.join(",")})`;case"NUMBER":return e.value.toString();case"NORMALIZED_STRING":return`"${t.strings[e.value]}"`;case"NORMALIZED_NUMBER":return t.numbers[e.value].toString();case"NORMALIZED_REFERENCE":return t.references[e.value].toString();case"REFERENCE":case"STRING":default:return e.value;case"BOOLEAN":return e.value?"TRUE":"FALSE";case"UNARY_OPERATION":return e.value+_r(e,t);case"BIN_OPERATION":return function(e,t){const s=e.value,i=e.left,o=i.value;return"BIN_OPERATION"===i.type&&yr[o]<yr[s]?`(${Ar(i,t)})`:Ar(i,t)}(e,t)+e.value+_r(e,t)}}function _r(e,t){const s=e.value,i=e.right,o=yr[i.value],n=yr[s];let r=!1;return"BIN_OPERATION"!==i.type?r=!1:o<n?r=!0:o!==n||Ir.includes(s)||(r=!0),r?`(${Ar(i,t)})`:Ar(i,t)}const Or=ir.content,Nr={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},kr={"-":"UMINUS","+":"UPLUS"};function Fr(e){return e.map((e=>e.split("\n"))).flat().filter((e=>""!==e.trim()))}const $r={};function Dr(e){if(!$r[e.text]){const t=Lr(e.text);let s=1;if("BIN_OPERATION"===t.type&&":"===t.value)throw new Error(a("Invalid formula"));if("UNKNOWN"===t.type)throw new Error(a("Invalid formula"));const i=l(t),o=Fr([`// ${e.text}`,i.code,`return ${i.id};`]).join("\n");let n=new Function("deps","sheetId","ref","range","ctx",o);function r(e){const t=Or[e.value.toUpperCase()],s=e.args,i=s.length;if(i<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(),i.toString()));if(i>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(),i.toString()));const o=t.nbrArgRepeating;if(o>1){const s=t.args.length-o;if((i-s)%o!=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(),o.toString()))}let n=[];for(let o=0;o<i;o++){const i=t.getArgToFocus(o+1)-1;if(0<=i&&i<t.args.length){const r=s[o],c=t.args[i],h=c.type||[],d=h.includes("META"),u=c.lazy,p=h.some((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e)),g=h.every((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e));if(g&&"NORMALIZED_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(),(o+1).toString(),r.type.toLowerCase().replace("normalized_","")));const f=l(r,u,d,p,{functionName:e.value.toUpperCase(),paramIndex:o+1});n.push(f)}}return n}function l(t,i=!1,o=!1,n=!1,c={}){const h=[];let d,u,p;if("NORMALIZED_REFERENCE"!==t.type&&("BIN_OPERATION"!==t.type||":"!==t.value)&&o)throw new Error(a("Argument must be a reference to a cell or range."));switch(t.debug&&h.push("debugger;"),t.type){case"BOOLEAN":case"NUMBER":case"STRING":if(!i)return{id:t.value,code:""};d=s++,p=`${t.value}`;break;case"NORMALIZED_NUMBER":d=s++,p=`deps.numbers[${t.value}]`;break;case"NORMALIZED_STRING":d=s++,p=`deps.strings[${t.value}]`;break;case"REFERENCE":throw new Error(`Only normalized references can be compiled: ${t.value}`);case"NORMALIZED_REFERENCE":if(!e.dependencies.references[t.value]){d=s++,p="null";break}d=s++,p=n?`range(${t.value}, deps.references, sheetId)`:`ref(${t.value}, deps.references, sheetId, ${o?"true":"false"}, "${c.functionName||Nr["="]}", ${c.paramIndex})`;break;case"FUNCALL":d=s++;const a=r(t);h.push(Fr(a.map((e=>e.code))).join("\n")),u=t.value.toUpperCase(),h.push(`ctx.__lastFnCalled = '${u}';`),p=`ctx['${u}'](${a.map((e=>e.id))})`;break;case"UNARY_OPERATION":{d=s++,u=kr[t.value];const e=l(t.right,!1,!1,!1,{functionName:u});h.push(e.code),h.push(`ctx.__lastFnCalled = '${u}';`),p=`ctx['${u}']( ${e.id})`;break}case"BIN_OPERATION":{d=s++,u=Nr[t.value];const e=l(t.left,!1,!1,!1,{functionName:u}),i=l(t.right,!1,!1,!1,{functionName:u});h.push(e.code),h.push(i.code),h.push(`ctx.__lastFnCalled = '${u}';`),p=`ctx['${u}'](${e.id}, ${i.id})`;break}case"UNKNOWN":if(!i)return{id:"undefined",code:""};d=s++,p="undefined"}if(i){return{id:`_${d}`,code:`const _${d} = () => {\n\t${Fr(h).join("\n\t")}\n\treturn ${p};\n}`}}return h.push(`let _${d} = ${p};`),{id:`_${d}`,code:Fr(h).join("\n")}}function c(t){let s;switch(t.type){case"NORMALIZED_REFERENCE":if(e.dependencies.references[t.value])return[t.value];break;case"FUNCALL":if(s=Or[t.value.toUpperCase()],s.returnFormat){if("FormatFromArgument"!==s.returnFormat)return[s.returnFormat.specificFormat];if(t.args.length>0){const e=0;if(!s.args[e].type.includes("META"))return c(t.args[e])}}break;case"UNARY_OPERATION":return c(t.right);case"BIN_OPERATION":if(s=Or[Nr[t.value]],s.returnFormat){if("FormatFromArgument"===s.returnFormat){const e=c(t.left);if("string"==typeof e[e.length-1])return e;const s=c(t.right);return e.concat(s)}return[s.returnFormat.specificFormat]}}return[]}$r[e.text]=n,$r[e.text].dependenciesFormat=c(t)}return $r[e.text]}function Pr(e,t=!1){let s,i,o,n;const r=()=>{n=void 0,i=void 0,s=void 0,o=void 0};for(let a=0;a<e.length;a++){const l=e[a];if(n)if(i){if("SPACE"===l.type)continue;if("OPERATOR"===l.type&&":"===l.value)s=a;else if(s&&"SYMBOL"===l.type)o=a;else if(n&&i&&s&&o){const s={type:"SYMBOL",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"SYMBOL"===l.type?(n=a,i=a,s=void 0):r()}else"SYMBOL"===l.type?(i=a,s=o=void 0):r();else["SPACE","SYMBOL"].includes(l.type)?(n=a,i="SYMBOL"===l.type?a:void 0,s=o=void 0):r()}const a=e.length-1;if(n&&i&&s&&o){const s={type:"SYMBOL",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(ar(e),!0)}function Br(e){return function(e){let t=[],s="";return e.map(((e,i)=>{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,i=Object.assign({},e,{start:t,end:t+s,length:s});return t=i.end,i}))}(Pr(ar(e)))))}function Vr(e){const t=Ur(e);let s={numbers:[],strings:[],references:[]};return{text:"".concat(...t.map((e=>{if("SYMBOL"===e.type&&Kt.test(e.value)){const t=e.value.trim();s.references.includes(t)||s.references.push(t);return Hr(s.references.indexOf(t).toString())}if("STRING"===e.type){const t=e.value.slice(1).slice(0,e.value.length-2);s.strings.includes(t)||s.strings.push(t);const i=s.strings.indexOf(t);return Hr(`${e.type[0]}${i}`)}if("NUMBER"===e.type){const t=ee(e.value);s.numbers.includes(t)||s.numbers.push(t);const i=s.numbers.indexOf(t);return Hr(`${e.type[0]}${i}`)}return e.value}))),dependencies:s}}function Hr(e){return`${$}${e}${$}`}const zr=new Re;function Zr(e,t){switch(typeof e){case"string":return e;case"boolean":return e?"TRUE":"FALSE";case"number":return(null==t?void 0:t.match(A))?q({value:e,format:t}):t?function(e,t){const s=t.split(";"),i=s.length;return e<0?i>1?re(-e,s[1]):"-"+re(-e,s[0]):re(e,s[3===i&&0===e?2:0])}(e,t):se(e);case"object":return"0"}}function Gr(e){return""===e?"":Q(e)?ee(e):Es(e)?"TRUE"===e.toUpperCase():bs(e)?Z(e).value:e}class Wr{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 Zr(this.evaluated.value,this.format)}get composerContent(){return this.content}get defaultAlign(){switch(this.evaluated.type){case Ne.number:return"right";case Ne.boolean:case Ne.error:return"center";case Ne.text:case Ne.empty:return"left"}}get isAutoSummable(){var e;switch(this.evaluated.type){case Ne.empty:case Ne.text:return!0;case Ne.number:return!(null===(e=this.format)||void 0===e?void 0:e.match(A));case Ne.error:case Ne.boolean:return!1}}}class qr extends Wr{constructor(e,t={}){super(e,{value:"",type:Ne.empty},t),this.content=""}isEmpty(){return!0}}class jr extends Wr{constructor(e,t,s={}){super(e,{value:t,type:Ne.number},s),this.content=se(this.evaluated.value)}}class Xr extends Wr{constructor(e,t,s={}){super(e,{value:t,type:Ne.boolean},s),this.content=this.evaluated.value?"TRUE":"FALSE"}}class Yr extends Wr{constructor(e,t,s={}){super(e,{value:t,type:Ne.text},s),this.content=this.evaluated.value}}class Kr extends jr{constructor(e,t,s){super(e,t,s),this.format=s.format}get composerContent(){return Zr(this.evaluated.value,this.format)}}class Qr extends Wr{constructor(e,t,s={}){var i;const o=ws(t);s={...s,style:{...s.style,textColor:(null===(i=s.style)||void 0===i?void 0:i.textColor)||M,underline:!0}},super(e,{value:o.label,type:Ne.text},s),this.link=o,this.content=t}isLink(){return!0}get composerContent(){return this.link.label}}class Jr extends Qr{constructor(e,t,s={}){super(e,t,s),this.link.url=this.withHttp(this.link.url),this.link.isExternal=!0,this.content=ys(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 ea extends Qr{constructor(e,t,s={},i){super(e,t,s),this.sheetName=i,this.sheetId=Rs(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 ta extends Wr{constructor(e,t,s,i,o,n){super(t,{value:"Loading...",type:Ne.text},n),this.buildFormulaString=e,this.normalizedText=s,this.compiledFormula=i,this.dependencies=o}get content(){return this.buildFormulaString(this.normalizedText,this.dependencies)}isFormula(){return!0}assignValue(e){switch(typeof e){case"number":this.evaluated={value:e,type:Ne.number};break;case"boolean":this.evaluated={value:e,type:Ne.boolean};break;case"string":this.evaluated={value:e,type:Ne.text};break;case"object":case"undefined":this.evaluated={value:e,type:Ne.empty}}}assignError(e,t){this.evaluated={value:e,error:t,type:Ne.error}}}class sa extends Wr{constructor(e,t,s,i){super(e,{value:"#BAD_EXPR",type:Ne.error,error:s},i),this.content=t}}function ia(e){const t=Ur(e);let s=[];return{text:"".concat(...t.map((e=>{if("SYMBOL"===e.type&&Kt.test(e.value)){const t=e.value.trim();return s.includes(t)||s.push(t),`${$}${s.indexOf(t)}${$}`}return e.value}))),dependencies:s}}zr.add("Formula",{sequence:10,match:e=>e.startsWith("="),createCell:(e,t,s,i,o)=>{const n=Vr(t),r=n.text,a=Dr(n),l=n.dependencies.references.map((e=>o.getRangeFromSheetXC(i,e))),c=s.format||function(e,t,s){var i;const o=t.dependenciesFormat;for(let t of o)switch(typeof t){case"string":return t;case"number":const o=s[t],n=e[o.sheetId];if(n){const e=null===(i=n.rows[o.zone.top])||void 0===i?void 0:i.cells[o.zone.left];if(e&&e.format)return e.format}}return F}(o.getEvaluationSheets(),a,l);return new ta(((e,t)=>o.buildFormulaContent(i,e,t)),e,r,a,{...n.dependencies,references:l},{...s,format:c})}}).add("Empty",{sequence:20,match:e=>""===e,createCell:(e,t,s)=>new qr(e,s)}).add("Number",{sequence:30,match:e=>Q(e),createCell:(e,t,s)=>(!s.format&&t.includes("%")&&(s.format=t.includes(".")?"0.00%":"0%"),new jr(e,ee(t),s))}).add("Boolean",{sequence:40,match:e=>Es(e),createCell:(e,t,s)=>new Xr(e,"TRUE"===t.toUpperCase(),s)}).add("DateTime",{sequence:50,match:e=>bs(e),createCell:(e,t,s)=>{const i=Z(t),o=s.format||i.format;return new Kr(e,i.value,{...s,format:o})}}).add("MarkdownSheetLink",{sequence:60,match:e=>Ts(e),createCell:(e,t,s,i,o)=>new ea(e,t,s,(e=>o.tryGetSheetName(e)))}).add("MarkdownLink",{sequence:70,match:e=>Is(e),createCell:(e,t,s)=>new Jr(e,t,s)}).add("WebLink",{sequence:80,match:e=>{return t=e,Cs.test(t);var t},createCell:(e,t,s)=>new Jr(e,ys(t,t),s)});const oa=10,na="Sheet1";function ra(e){return e?("version"in(e=JSON.parse(JSON.stringify(e)))&&e.version<oa&&(e=function(e){for(let t=aa.findIndex((t=>t.from===e.version));t<aa.length;t++)e=aa[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,s=new ti;for(const i of e.sheets||[])for(const e of i.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(da(),e,{version:oa}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(ha(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(ha(na,"Sheet1"));return e}(e),e}(e),e):da()}const aa=[{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=ia(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,...i}=t.figures[e].data,o=[];for(let e of s)if(e.labelCell){const t=_s(e.dataRange),s=e.labelCell+":"+ss(t.right,t.bottom);o.push(s)}else o.push(e.dataRange);i.dataSetsHaveTitle=Boolean(s[0].labelCell),i.dataSets=o,t.figures[e].data=i}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){var t;const s=[],i=new RegExp(k,"g");for(let o of e.sheets||[]){if(!o.name)continue;const e=o.name,n=e.replace(i,"_");let r=1,a=n;for(;s.includes(a);)a=`${n}${r}`,r++;o.name=a,s.push(a);const l=t=>{if(void 0===t)return t;let s=t.replace(e,a),i=t;for(;i!==s;)i=s,s=i.replace(e,a);return i};for(let e in o.cells){const t=o.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(l))}for(let e of o.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 o.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,i]of Object.entries(t)){const t=`\\${$}${s}\\${$}`;e=e.replace(new RegExp(t,"g"),i)}s.content=e,delete s.formula}}return e}}];function la(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const s=[],i=[],o=e=>{if("CREATE_SHEET"===e.type)s.push(e.sheetId);else if("sheetId"in e&&!s.includes(e.sheetId))return{...e,sheetId:na};return e};for(const e of t)"REMOTE_REVISION"===e.type?i.push({...e,commands:e.commands.map(o)}):i.push(e);return i}(e,t),t=ca(t,"SORT_CELLS"),t=ca(t,"SET_DECIMAL")}function ca(e,t){const s=[];for(const i of e)"REMOTE_REVISION"===i.type?s.push({...i,commands:i.commands.filter((e=>e.type!==t))}):s.push(i);return s}function ha(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[]}}function da(e="Sheet1"){return{version:oa,sheets:[ha(na,e)],entities:{},styles:{},borders:{},revisionId:O,uniqueFigureIds:!0}}class ua{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 i=e.filter((e=>0!==e));if(i.length)return i}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}ua.getters=[],ua.modes=["headless","normal"];class pa extends ua{constructor(e,t,s,i,o,n){super(t,i,o),this.dispatch=i,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 ga extends pa{constructor(){super(...arguments),this.borders={}}handle(e){switch(e.type){case"ADD_MERGE":if(!e.interactive)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,i;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),s=e.base-1,i=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),s=e.base,i=e.base+e.quantity+1),this.ensureColumnBorderContinuity(t,s,i)}handleAddRows(e){const t=this.getters.getSheet(e.sheetId);let s,i;"before"===e.position?(this.shiftBordersVertically(t.id,e.base,e.quantity,{moveFirstTopBorder:!0}),s=e.base-1,i=e.base+e.quantity):(this.shiftBordersVertically(t.id,e.base+1,e.quantity,{moveFirstTopBorder:!1}),s=e.base,i=e.base+e.quantity+1),this.ensureRowBorderContinuity(t,s,i)}getCellBorder(e,t,s){var i,o,n,r,a,l,c,h,d,u,p,g;const f={top:null===(n=null===(o=null===(i=this.borders[e])||void 0===i?void 0:i[t])||void 0===o?void 0:o[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 i=fs(t+1,s);for(let o=0;o<e.rows.length;o++){const n=this.getCellBorder(e.id,t,o),r=this.getCellBorder(e.id,s,o);if(n&&r){const t=this.getCommonSides(n,r);for(let s of i)this.addBorder(e.id,s,o,t)}}}ensureRowBorderContinuity(e,t,s){const i=fs(t+1,s);for(let o=0;o<e.cols.length;o++){const n=this.getCellBorder(e.id,o,t),r=this.getCellBorder(e.id,o,s);if(n&&r){const t=this.getCommonSides(n,r);for(let s of i)this.addBorder(e.id,o,s,t)}}}getCommonSides(e,t){const s={};for(let i of["top","bottom","left","right"])e[i]&&e[i]===t[i]&&(s[i]=e[i]);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 fs(0,this.getters.getSheet(e).rows.length+1)}shiftBordersHorizontally(e,t,s,{moveFirstLeftBorder:i}={}){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((o=>{(o===t&&i||o!==t)&&this.moveBordersOfColumn(e,o,s,"vertical"),this.moveBordersOfColumn(e,o,s,"horizontal")})))}shiftBordersVertically(e,t,s,{moveFirstTopBorder:i}={}){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((o=>{(o===t&&i||o!==t)&&this.moveBordersOfRow(e,o,s,"horizontal"),this.moveBordersOfRow(e,o,s,"vertical")})))}moveBordersOfRow(e,t,s,i,{destructive:o}={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[i],u=null===(h=null===(c=n[r])||void 0===c?void 0:c[t])||void 0===h?void 0:h[i];this.history.update("borders",e,r,t+s,i,o?u:u||d),this.history.update("borders",e,r,t,i,void 0)}))}moveBordersOfColumn(e,t,s,i,{destructive:o}={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[i],u=null===(h=null===(c=n[t])||void 0===c?void 0:c[r])||void 0===h?void 0:h[i];this.history.update("borders",e,t+s,r,i,o?u:u||d),this.history.update("borders",e,t,r,i,void 0)}))}setBorder(e,t,s,i){this.history.update("borders",e,t,s,{vertical:null==i?void 0:i.left,horizontal:null==i?void 0:i.top}),this.history.update("borders",e,t+1,s,"vertical",null==i?void 0:i.right),this.history.update("borders",e,t,s+1,"horizontal",null==i?void 0:i.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 i=s.left;i<=s.right;i++)this.history.update("borders",e,i,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,i){this.setBorder(e,t,s,{...this.getCellBorder(e,t,s),...i})}setBorders(e,t,s){const i=e.id;if("clear"===s)return this.clearBorders(i,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(i,s,t,{top:L});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(i,s,t,{left:L});if("left"===s||"all"===s||"external"===s)for(let t=e.top;t<=e.bottom;t++)this.addBorder(i,e.left,t,{left:L});if("right"===s||"all"===s||"external"===s)for(let t=e.top;t<=e.bottom;t++)this.addBorder(i,e.right+1,t,{left:L});if("top"===s||"all"===s||"external"===s)for(let t=e.left;t<=e.right;t++)this.addBorder(i,t,e.top,{top:L});if("bottom"===s||"all"===s||"external"===s)for(let t=e.left;t<=e.right;t++)this.addBorder(i,t,e.bottom+1,{top:L})}}addBordersToMerge(e,t){const s=this.getters.getSheet(e),{left:i,right:o,top:n,bottom:r}=t,a=this.getCellBorder(s.id,i,n),l=this.getCellBorder(s.id,o,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:i}],"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:o}],"right")}import(e){if(e.borders)for(let t of e.sheets)for(let[s,i]of Object.entries(t.cells))if(null==i?void 0:i.border){const o=e.borders[i.border],[n,r]=ts(s);this.setBorder(t.id,n,r,o)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,_s(e))}export(e){let t=0;const s={};function i(e){for(let[t,i]of Object.entries(s))if(cs(i)===cs(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 o=this.getCellBorder(t.id,e,s);if(o){const n=ss(e,s),r=t.cells[n],a=i(o);r?r.border=a:t.cells[n]={border:a}}}e.borders=s}exportForExcel(e){this.export(e)}}ga.getters=["getCellBorder"];const fa=new RegExp(String.fromCharCode(160),"g");class ma extends pa{constructor(){super(...arguments),this.cells={},this.createCell=function(e){const t=zr.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(s,i,o,n){const r=t.find((e=>e.match(i)));if(!r)return new Yr(s,i,o);try{return r.createCell(s,i,o,n,e)}catch(e){return new sa(s,i,e.message||N,o)}}}(this.getters)}adaptRanges(e,t){for(const s of Object.keys(this.cells))for(const i of Object.values(this.cells[s]||{}))if(i.isFormula())for(const o of i.dependencies.references)if(!t||o.sheetId===t){const t=e(o);"NONE"!==t.changeType&&this.history.update("cells",s,i.id,"dependencies","references",i.dependencies.references.indexOf(o),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 i of t)for(let t=i.top;t<=i.bottom;t++)for(let o=i.left;o<=i.right;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:o,row:t,format:s})}clearStyles(e,t){for(let s of t)for(let t=s.left;t<=s.right;t++)for(let i=s.top;i<=s.bottom;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:null})}handleAddColumnsRows(e,t){const s=this.getters.getSheet(e.sheetId);let i,o;"before"===e.position?(i=fs(e.base,e.base+e.quantity),o=e.base+e.quantity):(i=fs(e.base+1,e.base+e.quantity+1),o=e.base),t(s,o,i)}import(e){for(let t of e.sheets){const s=this.getters.getSheet(t.id);for(let i in t.cells){const o=t.cells[i],[n,r]=ts(i);if((null==o?void 0:o.content)||(null==o?void 0:o.format)||(null==o?void 0:o.style)){const i=this.importCell(s,o,e.styles);this.history.update("cells",t.id,i.id,i),this.dispatch("UPDATE_CELL_POSITION",{cell:i,cellId:i.id,col:n,row:r,sheetId:t.id})}}}}export(e){let t=0;const s={};function i(e){for(let[t,i]of Object.entries(s))if(cs(i)===cs(e))return parseInt(t,10);return s[++t]=e,t}for(let t of e.sheets){const e={},s=Object.keys(this.cells[t.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:o,row:n}of s){const s=this.getters.getCell(t.id,o,n);e[ss(o,n)]={style:s.style&&i(s.style),format:s.format,content:s.content}}t.cells=e}e.styles=s}importCell(e,t,s){const i=t.style&&s[t.style]||void 0,o=this.uuidGenerator.uuidv4(),n={format:null==t?void 0:t.format,style:i};return this.createCell(o,(null==t?void 0:t.content)||"",n,e.id)}exportForExcel(e){this.export(e);for(let t of e.sheets)for(const e in t.cells){const[s,i]=ts(e),o=this.getters.getCell(t.id,s,i),n=t.cells[e];n.value=o.evaluated.value,n.isFormula=o.isFormula()}}getCells(e){return this.cells[e]||{}}getCellById(e){for(const t of Object.values(this.cells))if(t[e])return t[e]}buildFormulaContent(e,t,s){let i=t;for(let[t,o]of Object.entries(s.references)){const s=this.getters.getRangeString(o,e),n=`\\${$}${t}\\${$}`;i=i.replace(new RegExp(n,"g"),s)}for(let[e,t]of Object.entries(s.strings)){const s=`\\${$}S${e}\\${$}`;i=i.replace(new RegExp(s,"g"),`"${t}"`)}for(let[e,t]of Object.entries(s.numbers)){const s=`\\${$}N${e}\\${$}`;i=i.replace(new RegExp(s,"g"),t.toString())}return i}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t.normalizedText,t.dependencies)}getCellStyle(e){return e.style||{}}zoneToXC(e,t,s=[{colFixed:!1,rowFixed:!1}]){const i=ss((t=this.getters.expandZone(e,t)).left,t.top,s[0]),o=ss(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 i==o||a?i:i+":"+o}setStyle(e,t,s){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++){const i=this.getters.getCell(e,t,o);this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:s?{...null==i?void 0:i.style,...s}:void 0})}}copyColumnStyle(e,t,s){for(let i=0;i<e.rows.length;i++){const o=this.getFormat(e.id,t,i);if(o.style||o.format)for(let t of s)this.dispatch("UPDATE_CELL",{sheetId:e.id,col:t,row:i,...o})}}copyRowStyle(e,t,s){for(let i=0;i<e.cols.length;i++){const o=this.getFormat(e.id,i,t);if(o.style||o.format)for(let t of s)this.dispatch("UPDATE_CELL",{sheetId:e.id,col:i,row:t,...o})}}getFormat(e,t,s){const i={},[o,n]=this.getters.getMainCell(e,t,s),r=this.getters.getCell(e,o,n);return r&&(r.style&&(i.style=r.style),r.format&&(i.format=r.format)),i}updateCell(e,t,s,i){var o;const n=e.rows[s].cells[t],r="content"in i||"formula"in i,a=r?(null===(o=i.content)||void 0===o?void 0:o.replace(fa,""))||"":(null==n?void 0:n.content)||"";let l;l=void 0!==i.style?i.style||void 0:n?n.style:void 0;let c=("format"in i?i.format:n&&n.format)||F;if((r&&!a&&!i.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:n.id,col:t,row:s,sheetId:e.id,cell:void 0})));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===Ne.error&&p.assignError(n.evaluated.value,n.evaluated.error)),this.history.update("cells",e.id,p.id,p),this.dispatch("UPDATE_CELL_POSITION",{cell:p,cellId:p.id,col:t,row:s,sheetId:e.id})}checkCellOutOfSheet(e,t,s){const i=this.getters.tryGetSheet(e);if(!i)return 23;return Us(t,s,{top:0,left:0,bottom:i.rows.length-1,right:i.cols.length-1})?0:18}}ma.getters=["zoneToXC","getCells","getFormulaCellContent","getCellStyle","buildFormulaContent","getCellById"];class va extends pa{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 i of e.dataSets){if(i.labelCell){const o=s(i.labelCell);switch(o.changeType){case"REMOVE":this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(i),"labelCell",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(i),"labelCell",o.range)}}const o=s(i.dataRange);switch(o.changeType){case"REMOVE":const s=e.dataSets.filter((e=>e!==i));this.history.update("chartFigures",t,"dataSets",s);break;case"RESIZE":case"MOVE":case"CHANGE":if(this.getters.getRangeString(o.range,o.range.sheetId)!==_)this.history.update("chartFigures",t,"dataSets",e.dataSets.indexOf(i),"dataRange",o.range);else{const s=e.dataSets.filter((e=>e!==i));this.history.update("chartFigures",t,"dataSets",s)}}}}adaptLabelRanges(e,t,s){if(e.labelRange){const i=s(e.labelRange);switch(i.changeType){case"REMOVE":this.history.update("chartFigures",t,"labelRange",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("chartFigures",t,"labelRange",i.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 i=e.position?e.position.x:0,o=e.position?e.position.y:0;this.addChartFigure(e.sheetId,this.createChartDefinition(e.definition,e.sheetId),{id:e.id,x:i,y:o,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 i of s)if("chart"===i.tag){const s=i.id.split("??").pop(),o=`${e.sheetIdTo}??${s}`,n={...ds(this.chartFigures[i.id]),id:o};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:o,x:i.x,y:i.y,height:i.height,width:i.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 i=s.dataSets.map((t=>t?this.getters.getRangeString(t.dataRange,e):"")).filter((e=>""!==e));return{title:s&&s.title?s.title:"",dataSets:i,labelRange:s.labelRange?this.getters.getRangeString(s.labelRange,e):void 0,type:s?s.type:"bar",dataSetsHaveTitle:!(!s||0===i.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],i=this.getChartDefinitionUI("forceSheetReference",t);if(!s||!i)return;const o=s.dataSets.map((e=>this.toExcelDataset(e))).filter((e=>""!==e.range));return{...i,backgroundColor:s.background,dataSets:o}}toExcelDataset(e){var t;const s=null===(t=e.labelCell)||void 0===t?void 0:t.zone;let i=e.dataRange.zone;if(s){const{height:e,width:t}=zs(i);1===e?i={...i,left:i.left+1}:1===t&&(i={...i,top:i.top+1})}const o={...e.dataRange,zone:i};return{label:e.labelCell?this.getters.getRangeString(e.labelCell,"forceSheetReference"):void 0,range:this.getters.getRangeString(o,"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 i of e){const e=i;if(e&&"chart"===e.tag){const i=this.getChartDefinitionUI(t.id,e.id);i&&(e.data=i,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 i of e){const e=i;if(e&&"chart"===e.tag){const i=this.getChartDefinitionExcel(t.id,e.id);i&&(e.data=i,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 i=!!t.dataSetsHaveTitle,o=this.createDataSets(t.dataSets,s.sheetId,i);this.history.update("chartFigures",e,"dataSets",o)}if(void 0!==t.labelRange){const i=t.labelRange?this.getters.getRangeFromSheetXC(s.sheetId,t.labelRange):void 0;this.history.update("chartFigures",e,"labelRange",i)}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 i=[];for(const o of e){const e=this.getters.getRangeFromSheetXC(t,o),{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};i.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||i.push(this.createDataSet(r,n,void 0)):i.push(this.createDataSet(r,n,s?{top:n.top,bottom:n.top,left:n.left,right:n.left}:void 0))}return i}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: ${Ns(t)}`);if(s){const i=Ns(t),o=Ns(s);return{labelCell:this.getters.getRangeFromSheetXC(e,o),dataRange:this.getters.getRangeFromSheetXC(e,i)}}return{labelCell:void 0,dataRange:this.getters.getRangeFromSheetXC(e,Ns(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=>!Qt.test(e)));return t?28:0}checkLabelRange(e){if(!e.definition.labelRange)return 0;return!Qt.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 Ea(e){return""===e?NaN:Number(e)}va.getters=["getChartDefinition","getChartDefinitionUI","getChartsIdBySheet"];class ba extends pa{constructor(){super(...arguments),this.cfRules={}}loopThroughRangesOfSheet(e,t){for(const s of this.cfRules[e])for(const i of s.ranges){const o=t(i);switch(o.changeType){case"REMOVE":let t=s.ranges.slice();t.splice(s.ranges.indexOf(i),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(i),o.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(Ns)};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 i=t.top;i<=t.bottom;i++)for(let o=t.left;o<=t.right;o++){this.getRulesByCell(e,o,i).forEach((e=>{s.add(e.id)}))}return s}getRulesByCell(e,t,s){const i=[];for(let o of this.cfRules[e])for(let e of o.ranges)Us(t,s,e.zone)&&i.push(o);return new Set(i.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(),i=s.findIndex((t=>t.id===e.id)),o=this.mapToConditionalFormatInternal(t,e);i>-1?s.splice(i,1,o):s.push(o),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=[],i=e=>void 0===e||""===e;return e>=1&&i(s.values[0])&&t.push(36),e>=2&&i(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{Dr(Vr(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&&Ea(t)>=Ea(s)?32:0}checkMidBiggerThanMax(e){var t;const s=null===(t=e.midpoint)||void 0===t?void 0:t.value,i=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&Ea(s)>=Ea(i)?34:0}checkMinBiggerThanMid(e){var t;const s=e.minimum.value,i=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&&Ea(s)>=Ea(i)?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)}}}ba.getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];class Sa extends pa{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,...i}=e,o=i;this.updateFigure(s,o);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId)}}updateFigure(e,t){if("id"in t)for(const[s,i]of Object.entries(t))switch(s){case"x":case"y":void 0!==i&&this.history.update("figures",e,t.id,s,Math.max(i,0));break;case"width":case"height":void 0!==i&&this.history.update("figures",e,t.id,s,i)}}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(Ls)}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)}}Sa.getters=["getFigures","getFigure","getFigureSheetId"];class Ca extends pa{constructor(){super(...arguments),this.nextId=1,this.pending=null,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}}beforeHandle(e){switch(e.type){case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.exportAndRemoveMerges(e.sheetId,(t=>function(e,t){let{left:s,right:i,top:o,bottom:n}=_s(e);t=t.slice().sort(((e,t)=>t-e));for(let e of t)s>e&&(s-=1),(s>=e||i>=e)&&(i-=1);return s>i?null:ss(s,o)+":"+ss(i,n)}(t,e.elements)),!0):this.exportAndRemoveMerges(e.sheetId,(t=>function(e,t){let{left:s,right:i,top:o,bottom:n}=_s(e);t=t.slice().sort(((e,t)=>t-e));for(let e of t)o>e&&(o-=1),(o>=e||n>=e)&&(n-=1);return o>n?null:ss(s,o)+":"+ss(i,n)}(t,e.elements)),!1);break;case"ADD_COLUMNS_ROWS":const t="before"===e.position?e.base:e.base+1;"COL"===e.dimension?this.exportAndRemoveMerges(e.sheetId,(s=>function(e,t,s){let{left:i,right:o,top:n,bottom:r}=_s(e);return i>=t&&(i+=s),(i>=t||o>=t)&&(o+=s),i>o?null:ss(i,n)+":"+ss(o,r)}(s,t,e.quantity)),!0):this.exportAndRemoveMerges(e.sheetId,(s=>function(e,t,s){let{left:i,right:o,top:n,bottom:r}=_s(e);return n>=t&&(n+=s),(n>=t||r>=t)&&(r+=s),n>r?null:ss(i,n)+":"+ss(o,r)}(s,t,e.quantity)),!1)}}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":this.history.update("merges",e.sheetIdTo,Object.assign({},this.merges[e.sheetId])),this.history.update("mergeCellMap",e.sheetIdTo,Object.assign({},this.mergeCellMap[e.sheetId]));break;case"ADD_MERGE":if(!e.interactive)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);break;case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":this.pending&&(this.importMerges(this.pending.sheet,this.pending.merges),this.pending=null)}}getMerges(e){return Object.values(this.merges[e]||{}).filter(Ls)}getMerge(e,t,s){var i;const o=this.mergeCellMap[e],n=o?t in o&&(null===(i=o[t])||void 0===i?void 0:i[s]):void 0;return n?this.getMergeById(e,n):void 0}doesIntersectMerge(e,t){const{left:s,right:i,top:o,bottom:n}=t;for(let t=o;t<=n;t++)for(let o=s;o<=i;o++)if(this.getMerge(e,o,t))return!0;return!1}doesColumnsHaveCommonMerges(e,t,s){const i=this.getters.getSheet(e);for(let e=0;e<i.rows.length;e++)if(this.isInSameMerge(i.id,t,e,s,e))return!0;return!1}doesRowsHaveCommonMerges(e,t,s){const i=this.getters.getSheet(e);for(let e=0;e<=i.cols.length;e++)if(this.isInSameMerge(i.id,e,t,e,s))return!0;return!1}expandZone(e,t){let{left:s,right:i,top:o,bottom:n}=t,r={left:s,right:i,top:o,bottom:n};for(let t in this.merges[e]){const s=this.getMergeById(e,parseInt(t));s&&Ps(s,r)&&(r=$s(s,r))}return Ds(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,s,i,o){return!(!this.isInMerge(e,t,s)||!this.isInMerge(e,i,o))&&this.getMerge(e,t,s)===this.getMerge(e,i,o)}isInMerge(e,t,s){var i;const o=this.mergeCellMap[e];return!!o&&(t in o&&Boolean(null===(i=o[t])||void 0===i?void 0:i[s]))}getMainCell(e,t,s){if(!this.isInMerge(e,t,s))return[t,s];const i=this.getMerge(e,t,s).topLeft;return[i.col,i.row]}getBottomLeftCell(e,t,s){if(!this.isInMerge(e,t,s))return[t,s];const{bottom:i,left:o}=this.getMerge(e,t,s);return[o,i]}isMergeHidden(e,t){const s=this.getters.getHiddenColsGroups(e),i=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 i)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 Ds(t,s);const{width:i,height:o}=zs(t);return 1===i&&1===o}isMergeDestructive(e,t){let{left:s,right:i,top:o,bottom:n}=t;i=ps(i,0,e.cols.length-1),n=ps(n,0,e.rows.length-1);for(let t=o;t<=n;t++){const n=this.getters.getRow(e.id,t);for(let e=s;e<=i;e++)if(e!==s||t!==o){const t=n.cells[e];if(t&&!t.isEmpty())return!0}}return!1}getMergeById(e,t){const s=this.merges[e];return void 0!==s?s[t]: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&&Ps(t,s))return 50;return 0}checkMergedContentUpdate(e){const{col:t,row:s,sheetId:i,content:o}=e;if(void 0===o)return 0;const[n,r]=this.getMainCell(i,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:i}=e,o=this.getMerge(t,s,i);if(void 0===o||!Ds(e,o))return 5}return 0}addMerge(e,t){let{left:s,right:i,top:o,bottom:n}=t;i=ps(i,0,e.cols.length-1),n=ps(n,0,e.rows.length-1);if(ss(s,o)===ss(i,n))return;const r=this.getters.getCell(e.id,s,o);let a=this.nextId++;this.history.update("merges",e.id,a,{id:a,left:s,top:o,right:i,bottom:n,topLeft:{col:s,row:o}});let l=new Set;for(let t=o;t<=n;t++)for(let n=s;n<=i;n++){n===s&&t===o||this.dispatch("UPDATE_CELL",{sheetId:e.id,col:n,row:t,style:r?r.style:null,content:void 0});const i=this.getMerge(e.id,n,t);i&&l.add(i.id),this.history.update("mergeCellMap",e.id,n,t,a)}for(let t of l){const{top:s,bottom:i,left:o,right:n}=this.getMergeById(e.id,t);for(let t=s;t<=i;t++)for(let s=o;s<=n;s++){const i=this.getMerge(e.id,s,t);i&&i.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:i,bottom:o,right:n}=t,r=this.getMerge(e,s,i);if(void 0!==r&&Ds(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=i;t<=o;t++)for(let i=s;i<=n;i++)this.history.update("mergeCellMap",e,i,t,void 0)}}removeAllMerges(e){for(let t in this.merges[e])this.history.update("merges",e,parseInt(t),void 0);for(let t in this.mergeCellMap[e])this.history.update("mergeCellMap",e,parseInt(t),void 0)}exportAndRemoveMerges(e,t,s){const i=this.merges[e];if(!i)return;const o=Ia(i),n=[];for(let e of o){const s=t(e);if(s){const[e,t]=s.split(":");e!==t&&n.push(s)}}this.removeAllMerges(e),this.pending={sheet:e,merges:n}}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,_s(e))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...Ia(e))}}exportForExcel(e){this.export(e)}}function Ia(e){return Object.values(e).filter(Ls).map((e=>ss(e.left,e.top)+":"+ss(e.right,e.bottom)))}Ca.getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCell","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","isSingleCellOrMerge"];class ya extends pa{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,i="COL"===e.dimension?t.cols:t.rows;return(s||[]).flat().concat(e.elements).length<i.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":e.interactive||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:i}=this.getImportedSheetSize(t),o={id:t.id,name:e,cols:Ks(t.cols||{},s),rows:Qs(t.rows||{},i),hiddenColsGroups:[],hiddenRowsGroups:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible};this.visibleSheets.push(o.id),this.sheets[o.id]=o,this.updateHiddenElementsGroups(o.id,"cols"),this.updateHiddenElementsGroups(o.id,"rows")}}exportSheets(e,t=!1){e.sheets=this.visibleSheets.filter(Ls).map((e=>{const s=this.sheets[e];return{id:s.id,name:s.name,colNumber:s.cols.length,rowNumber:s.rows.length,rows:ei(s.rows,t),cols:Js(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}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(Ls)}getVisibleSheets(){return this.visibleSheets}getEvaluationSheets(){return this.sheets}getCol(e,t){var s;return null===(s=this.sheets[e])||void 0===s?void 0:s.cols[t]}getRow(e,t){var s;return null===(s=this.sheets[e])||void 0===s?void 0:s.rows[t]}getCell(e,t,s){const i=this.tryGetSheet(e);return i&&i.rows[s]&&i.rows[s].cells[t]||void 0}getColCells(e,t){return this.getSheet(e).rows.reduce(((e,s)=>{const i=s.cells[t];return void 0!==i?e.concat(i):e}),[])}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 i=`${e}${t}`;for(;s.includes(i);)i=`${e}${t}`,t++;return i}isEmpty(e,t){return Hs(t,this.getSheet(e),(e=>e),void 0).flat().every((e=>!e||e.isEmpty()))}setHeaderSize(e,t,s,i){let o,n;const r=e[t],a=r[s],l=i-a.size;this.history.update("sheets",e.id,t,s,"size",i),a.isHidden||this.history.update("sheets",e.id,t,s,"end",a.end+l),o=a.end;for(let i=s+1;i<r.length;i++){const s=r[i];n=s.isHidden?o:o+s.size,this.history.update("sheets",e.id,t,i,"start",o),this.history.update("sheets",e.id,t,i,"end",n),o=n}}updateCellPosition(e){if(e.cell){const t=this.cellPosition[e.cellId];t&&this.history.update("sheets",e.sheetId,"rows",t.row,"cells",t.col,void 0),this.history.update("cellPosition",e.cell.id,{row:e.row,col:e.col,sheetId:e.sheetId}),this.history.update("sheets",e.sheetId,"rows",e.row,"cells",e.col,e.cell)}else this.history.update("cellPosition",e.cellId,void 0),this.history.update("sheets",e.sheetId,"rows",e.row,"cells",e.col,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 i=s.top;i<=s.bottom;i++){this.sheets[e].rows[i].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:i})}}createSheet(e,t,s,i,o){const n={id:e,name:t,cols:Xs(s),rows:Ys(i),hiddenColsGroups:[],hiddenRowsGroups:[],areGridLinesVisible:!0},r=this.visibleSheets.slice();r.splice(o,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(),i=s.findIndex((t=>t===e)),o=s.splice(i,1);s.splice(i+("left"===t?-1:1),0,o[0]),this.history.update("visibleSheets",s)}checkSheetName(e){const{visibleSheets:t,sheets:s}=this,i=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())===i}))?11:k.test(i)?13:0}checkSheetPosition(e){const{visibleSheets:t}=this;return e.position>t.length||e.position<0?15:0}isRenameAllowed(e){if(e.interactive)return 0;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 i=Object.assign({},this.sheetIds);i[t]=e.id,delete i[s],this.history.update("sheetIds",i)}duplicateSheet(e,t){const s=this.getSheet(e),i=this.getDuplicateSheetName(s.name),o=JSON.parse(JSON.stringify(s));o.id=t,o.name=i;for(let e=0;e<=o.cols.length;e++)for(let t=0;t<=o.rows.length;t++)o.rows[t]&&(o.rows[t].cells[e]=void 0);const n=this.visibleSheets.slice(),r=n.findIndex((t=>t===e));n.splice(r+1,0,o.id),this.history.update("visibleSheets",n),this.history.update("sheets",Object.assign({},this.sheets,{[o.id]:o}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:s}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:o.id,col:e,row:s,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIds);a[o.name]=o.id,this.history.update("sheetIds",a)}getDuplicateSheetName(e){let t=1;const s=this.getters.getSheets().map((e=>e.name)),i=a("Copy of %s",e);let o=i.toString();for(;s.includes(o);)o=`${i} (${t})`,t++;return o}deleteSheet(e){const t=e.name,s=Object.assign({},this.sheets);delete s[e.id],this.history.update("sheets",s);const i=this.visibleSheets.slice(),o=i.findIndex((t=>t===e.id));i.splice(o,1),this.history.update("visibleSheets",i);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 ms(t))this.moveCellOnRowsDeletion(e,s[s.length-1],s[0]),s.map((t=>this.updateRowsStructureOnDeletion(t,e)))}addColumns(e,t,s,i){this.moveCellsOnAddition(e,"before"===s?t:t+1,i,"columns"),this.updateColumnsStructureOnAddition(e,t,i)}addRows(e,t,s,i){this.addEmptyRows(e,i),this.moveCellsOnAddition(e,"before"===s?t:t+1,i,"rows"),this.updateRowsStructureOnAddition(e,t,i)}moveCellOnColumnsDeletion(e,t){for(let[s,i]of Object.entries(e.rows)){const o=parseInt(s,10);for(let s in i.cells){const n=parseInt(s,10),r=i.cells[s];r&&(n===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:n,row:o}),n>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r.id,cell:r,col:n-1,row:o}))}}}moveCellsOnAddition(e,t,s,i){const o=[];for(const[n,r]of Object.entries(e.rows)){const a=parseInt(n,10);if("rows"!==i||a>=t)for(let n in r.cells){const l=parseInt(n,10),c=r.cells[n];c&&("rows"===i||l>=t)&&o.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c.id,cell:c,col:l+("columns"===i?s:0),row:a+("rows"===i?s:0)})}}for(let e of o.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,s){const i=s-t+1;for(let[o,n]of Object.entries(e.rows)){const r=parseInt(o,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),o=n.cells[t];o&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:o.id,cell:o,col:s,row:r-i})}}}updateColumnsStructureOnDeletion(e,t){const s=[];let i=0,o=0;for(let n in e.cols){if(t.includes(parseInt(n,10)))continue;const{size:r,isHidden:a}=e.cols[n],l=a?i:i+r;s.push({name:es(o),size:r,start:i,end:l,isHidden:a}),i=l,o++}this.history.update("sheets",e.id,"cols",s),this.updateHiddenElementsGroups(e.id,"cols")}updateColumnsStructureOnAddition(e,t,s){const i=[];let o=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++)i.push({name:es(n),size:t,start:o,end:o+t}),o+=t,n++}const{size:a,isHidden:l}=e.cols[r],c=l?o:o+a;i.push({name:es(n),size:a,start:o,end:c,isHidden:l}),o=c,n++}this.history.update("sheets",e.id,"cols",i),this.updateHiddenElementsGroups(e.id,"cols")}updateRowsStructureOnDeletion(e,t){const s=[];let i=0,o=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?i:i+l;parseInt(r,10)!==e&&(o++,s.push({start:i,end:h,size:l,cells:n.shift(),name:String(o),isHidden:c}),i=h)}this.history.update("sheets",t.id,"rows",s),this.updateHiddenElementsGroups(t.id,"rows")}updateRowsStructureOnAddition(e,t,s){const i=[];let o=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?o:o+c;(parseInt(l,10)<t||parseInt(l,10)>=t+s)&&r++,n++,i.push({start:o,end:d,size:c,cells:a.shift(),name:String(n),isHidden:h}),o=d}this.history.update("sheets",e.id,"rows",i),this.updateHiddenElementsGroups(e.id,"rows")}addEmptyRows(e,t){const s=e.rows[e.rows.length-1].end,i=e.rows.slice();for(let e=0;e<t;e++)i.push({start:s,end:s,size:0,name:(i.length+1).toString(),cells:{}});this.history.update("sheets",e.id,"rows",i)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(ts);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,i){let o=0;const n="hide"===i;for(let i=0;i<e[s].length;i++){const{size:r,isHidden:a}=e[s][i],l=t.includes(i)?n:a||!1,c=l?o:o+r;this.history.update("sheets",e.id,s,i,"start",o),this.history.update("sheets",e.id,s,i,"end",c),this.history.update("sheets",e.id,s,i,"isHidden",l),o=c}this.updateHiddenElementsGroups(e.id,s)}updateHiddenElementsGroups(e,t){var s;const i="cols"===t?"hiddenColsGroups":"hiddenRowsGroups",o=((null===(s=this.sheets[e])||void 0===s?void 0:s[t])||[]).reduce(((e,t,s)=>{if(!t.isHidden)return e;const i=e[e.length-1];return i&&i[i.length-1]==s-1||e.push([]),e[e.length-1].push(s),e}),[]);this.history.update("sheets",e,i,o)}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(Os))return 22;if(t.length&&"sheetId"in e){const s=this.getSheet(e.sheetId),i={top:0,left:0,bottom:s.rows.length-1,right:s.cols.length-1};return t.every((e=>{return Ds($s(t=i,e),t);var t}))?0:18}return 0}}ya.getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheets","getVisibleSheets","getEvaluationSheets","getCol","getRow","getCell","getCellPosition","getColCells","getColsZone","getRowsZone","getNumberCols","getNumberRows","getHiddenColsGroups","getHiddenRowsGroups","getGridLinesVisibility","getNextSheetName","isEmpty"];const wa=new Re;wa.add("INCREMENT_MODIFIER",{apply:(e,t)=>{var s;e.current+=e.increment;const i=e.current.toString(),o=Zr(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:i},tooltip:i?{props:{content:o}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,s)=>{var i,o;const n=(null===(i=t.cell)||void 0===i?void 0:i.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===(o=t.cell)||void 0===o?void 0:o.formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,s,i)=>{e.current+=e.increment;let o=0,n=0;switch(i){case 0:o=0,n=-e.current;break;case 1:o=0,n=e.current;break;case 2:o=-e.current,n=0;break;case 3:o=e.current,n=0}if(!t.cell||!t.cell.isFormula())return{cellData:{}};const r=t.sheetId,a=s.createAdaptedRanges(t.cell.dependencies.references,o,n,r),l=s.buildFormulaContent(r,t.cell.normalizedText,{...t.cell.dependencies,references:a});return{cellData:{border:t.border,style:t.cell.style,format:t.cell.format,content:l},tooltip:l?{props:{content:l}}:void 0}}});const xa=new Re;xa.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(A))},generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("copy_text",{condition:e=>!e.isFormula()&&e.evaluated.type===Ne.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===Ne.number,generateRule:(e,t)=>{const s=function(e,t){let s=[],i=!1;for(let o of t)if(o===e&&(i=!0),(null==o?void 0:o.evaluated.type)===Ne.number)s.push(o.evaluated.value);else{if(i)return s;s=[]}return s}(e,t);let i=1;return 2==s.length?i=2*(s[1]-s[0]):s.length>2&&(i=function(e){const t=[];let s=e[0];for(let i=1;i<e.length;i++){const o=e[i];t.push(o-s),s=o}return t.reduce(((e,t)=>e+t),0)/t.length}(s)*s.length),{type:"INCREMENT_MODIFIER",increment:i,current:e.evaluated.type===Ne.number?e.evaluated.value:0}},sequence:40});const Ta=new Re,Ra=(new Re).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let s=e.base;"after"===e.position&&s++;for(let i=0;i<e.quantity;i++)t.push(i+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 i of ms(s)){const s=0===i[0]?0:i[0]-1,o=0===i[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:i.length,base:s,sheetId:e.sheetId,position:o})}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 $e.values())Ra.contains(e)||Ra.add(e,La);function La(e){return[e]}const Ma=e=>({isVisible:()=>!0,isEnabled:()=>!0,isReadonlyAllowed:!1,shortCut:"",action:!1,children:[],separator:!1,icon:!1,id:e});function Aa(e,t){return Object.assign({},Ma(e),t)}class _a extends Re{add(e,t){return this.content[e]=Aa(e,t),this}addChild(e,t,s){const i=t.splice(0,1)[0];let o=this.content[i];if(!o)throw new Error(`Path ${i+":"+t.join(":")} not found`);for(let e of t)if(o="function"==typeof o.children?void 0:o.children.find((t=>t.id===e)),!o)throw new Error(`Path ${i+":"+t.join(":")} not found`);return o.children.push(Aa(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))}}function Oa(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 Na(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 ka(e,t){e.dispatch("SET_FORMATTING",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones(),format:t})}function Fa(e,t){e.dispatch("SET_FORMATTING",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones(),style:t})}const $a=async e=>{e.dispatch("COPY",{target:e.getters.getSelectedZones()}),await e.clipboard.writeText(e.getters.getClipboardContent())},Da=async e=>{e.dispatch("CUT",{target:e.getters.getSelectedZones()}),await e.clipboard.writeText(e.getters.getClipboardContent())},Pa=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 i=e.getters.getSelectedZones();s&&s!==t?e.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:i,text:s}):e.dispatch("PASTE",{target:i,interactive:!0})},Ua=e=>e.dispatch("PASTE",{target:e.getters.getSelectedZones(),pasteOption:"onlyValue"}),Ba=e=>e.dispatch("PASTE",{target:e.getters.getSelectedZones(),pasteOption:"onlyFormat"}),Va=e=>e.dispatch("DELETE_CONTENT",{sheetId:e.getters.getActiveSheetId(),target:e.getters.getSelectedZones()}),Ha=e=>{let t,s;const i=e.getters.getActiveRows();if(0!==i.size)t=Math.min(...i),s=Math.max(...i);else{const i=e.getters.getSelectedZones()[0];t=i.top,s=i.bottom}return t===s?a("Delete row %s",(t+1).toString()):a("Delete rows %s - %s",(t+1).toString(),(s+1).toString())},za=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})},Za=e=>{let t,s;const i=e.getters.getActiveCols();if(0!==i.size)t=Math.min(...i),s=Math.max(...i);else{const i=e.getters.getSelectedZones()[0];t=i.left,s=i.right}return t===s?a("Delete column %s",es(t)):a("Delete columns %s - %s",es(t),es(s))},Ga=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})},Wa=e=>{const t=e.getters.getSelectedZone();e.dispatch("INSERT_CELL",{shiftDimension:"ROW",zone:t,interactive:!0})},qa=e=>{const t=e.getters.getSelectedZone();e.dispatch("INSERT_CELL",{shiftDimension:"COL",zone:t,interactive:!0})},ja=e=>{const t=e.getters.getSelectedZone();e.dispatch("DELETE_CELL",{shiftDimension:"ROW",zone:t,interactive:!0})},Xa=e=>{const t=e.getters.getSelectedZone();e.dispatch("DELETE_CELL",{shiftDimension:"COL",zone:t,interactive:!0})},Ya=e=>{const t=e.getters.getActiveRows();let s,i;if(t.size)s=Math.min(...t),i=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.top,i=t.bottom-t.top+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"before",base:s,quantity:i,dimension:"ROW"})},Ka=e=>{const t=e.getters.getActiveRows();let s,i;if(t.size)s=Math.max(...t),i=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.bottom,i=t.bottom-t.top+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"after",base:s,quantity:i,dimension:"ROW"})},Qa=e=>{const t=e.getters.getActiveCols();let s,i;if(t.size)s=Math.min(...t),i=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.left,i=t.right-t.left+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"before",dimension:"COL",base:s,quantity:i})},Ja=e=>{const t=e.getters.getActiveCols();let s,i;if(t.size)s=Math.max(...t),i=t.size;else{const t=e.getters.getSelectedZones()[0];s=t.right,i=t.right-t.left+1}e.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.getters.getActiveSheetId(),position:"after",dimension:"COL",base:s,quantity:i})},el=e=>{e.openSidePanel("ConditionalFormatting",{selection:e.getters.getSelectedZones()})},tl=e=>{e.openLinkEditor()},sl=e=>{const{anchor:t,zones:s}=e.getters.getSelection();e.dispatch("SORT_CELLS",{interactive:!0,sheetId:e.getters.getActiveSheetId(),anchor:t,zone:s[0],sortDirection:"ascending"})},il=e=>{const{anchor:t,zones:s}=e.getters.getSelection();e.dispatch("SORT_CELLS",{interactive:!0,sheetId:e.getters.getActiveSheetId(),anchor:t,zone:s[0],sortDirection:"descending"})},ol=e=>1===e.getters.getSelectedZones().length,nl=new _a;nl.add("cut",{name:a("Cut"),shortCut:"Ctrl+X",sequence:10,action:Da}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:$a}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:Pa,isVisible:ol}).add("paste_special",{name:a("Paste special"),sequence:40,separator:!0,isVisible:ol}).addChild("paste_value_only",["paste_special"],{name:a("Paste values only"),sequence:10,action:Ua}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Ba}).add("sort_range",{name:a("Sort range"),sequence:50,isVisible:ol,separator:!0}).addChild("sort_ascending",["sort_range"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:sl}).addChild("sort_descending",["sort_range"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:il}).add("add_row_before",{name:e=>{const t=Na(e);return 1===t?a("Insert row"):a("Insert %s rows",t.toString())},sequence:70,action:Ya,isVisible:ol}).add("add_column_before",{name:e=>{const t=Oa(e);return 1===t?a("Insert column"):a("Insert %s columns",t.toString())},sequence:90,action:Qa,isVisible:ol}).add("insert_cell",{name:a("Insert cells"),sequence:100,isVisible:ol,separator:!0}).addChild("insert_cell_down",["insert_cell"],{name:a("Shift down"),sequence:10,action:Wa}).addChild("insert_cell_right",["insert_cell"],{name:a("Shift right"),sequence:20,action:qa}).add("delete_row",{name:Ha,sequence:110,action:za,isVisible:ol}).add("delete_column",{name:Za,sequence:120,action:Ga,isVisible:ol}).add("delete_cell",{name:a("Delete cells"),sequence:130,isVisible:ol}).addChild("delete_cell_up",["delete_cell"],{name:a("Shift up"),sequence:10,action:ja}).addChild("delete_cell_down",["delete_cell"],{name:a("Shift left"),sequence:20,action:Xa}).add("clear_cell",{name:a("Clear cells"),sequence:140,action:Va,isEnabled:e=>{const t=e.getters.getActiveCell();return Boolean(t)},separator:!0}).add("insert_link",{name:a("Insert link"),separator:!0,sequence:150,action:tl}).add("conditional_formatting",{name:a("Conditional formatting"),sequence:160,action:el,separator:!0});const rl=new _a;rl.add("cut",{name:a("Cut"),shortCut:"Ctrl+X",sequence:10,action:Da}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:$a}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:Pa}).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:Ua}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Ba}).add("sort_columns",{name:e=>e.getters.getActiveCols().size>1?a("Sort columns"):a("Sort column"),sequence:50,isVisible:ol,separator:!0}).addChild("sort_ascending",["sort_columns"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:sl}).addChild("sort_descending",["sort_columns"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:il}).add("add_column_before",{name:e=>{const t=Oa(e);return 1===t?a("Insert column left"):a("Insert %s columns left",t.toString())},sequence:70,action:Qa}).add("add_column_after",{name:e=>{const t=Oa(e);return 1===t?a("Insert column right"):a("Insert %s columns right",t.toString())},sequence:80,action:Ja}).add("delete_column",{name:Za,sequence:90,action:Ga}).add("clear_column",{name:e=>{let t,s;const i=e.getters.getActiveCols();if(0!==i.size)t=Math.min(...i),s=Math.max(...i);else{const i=e.getters.getSelectedZones()[0];t=i.left,s=i.right}return t===s?a("Clear column %s",es(t)):a("Clear columns %s - %s",es(t),es(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],i=t[t.length-1];return 1===t.length?a("Hide column %s",es(s).toString()):i-s+1===t.length?a("Hide columns %s - %s",es(s).toString(),es(i).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:el});const al=new _a;al.add("sheet",{name:a("Link sheet"),sequence:10,children:e=>e.getters.getSheets().map(((e,t)=>Aa(e.id,{name:e.name,sequence:t,action:()=>{return{link:{label:e.name,url:(t=e.id,`${xs}${t}`)},urlRepresentation:e.name,isUrlEditable:!1};var t}})))});const ll=new _a;ll.add("cut",{name:a("Cut"),sequence:10,shortCut:"Ctrl+X",action:Da}).add("copy",{name:a("Copy"),shortCut:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:$a}).add("paste",{name:a("Paste"),shortCut:"Ctrl+V",sequence:30,action:Pa}).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:Ua}).addChild("paste_format_only",["paste_special"],{name:a("Paste format only"),sequence:20,action:Ba}).add("add_row_before",{name:e=>{const t=Na(e);return 1===t?a("Insert row above"):a("Insert %s rows above",t.toString())},sequence:50,action:Ya}).add("add_row_after",{name:e=>{const t=Na(e);return 1===t?a("Insert row below"):a("Insert %s rows below",t.toString())},sequence:60,action:Ka}).add("delete_row",{name:Ha,sequence:70,action:za}).add("clear_row",{name:e=>{let t,s;const i=e.getters.getActiveRows();if(0!==i.size)t=Math.min(...i),s=Math.max(...i);else{const i=e.getters.getSelectedZones()[0];t=i.top,s=i.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],i=t[t.length-1];return 1===t.length?a("Hide row %s",(s+1).toString()):i-s+1===t.length?a("Hide rows %s - %s",(s+1).toString(),(i+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:el});const cl=new _a;cl.add("delete",{name:a("Delete"),sequence:10,isVisible:e=>e.getters.getSheets().length>1,action:e=>e.dispatch("DELETE_SHEET_CONFIRMATION",{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=>e.dispatch("RENAME_SHEET",{interactive:!0,sheetId: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 hl=new _a;hl.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:$a}).addChild("cut",["edit"],{name:a("Cut"),shortCut:"Ctrl+X",sequence:40,action:Da}).addChild("paste",["edit"],{name:a("Paste"),shortCut:"Ctrl+V",sequence:50,action:Pa}).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:Ua}).addChild("paste_special_format",["edit","paste_special"],{name:a("Paste format only"),sequence:20,action:Ba}).addChild("sort_range",["edit"],{name:a("Sort range"),sequence:62,isVisible:ol,separator:!0}).addChild("sort_ascending",["edit","sort_range"],{name:a("Ascending (A ⟶ Z)"),sequence:10,action:sl}).addChild("sort_descending",["edit","sort_range"],{name:a("Descending (Z ⟶ A)"),sequence:20,action:il}).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:Va}).addChild("edit_delete_row",["edit"],{name:Ha,sequence:80,action:za}).addChild("edit_delete_column",["edit"],{name:Za,sequence:90,action:Ga}).addChild("edit_delete_cell_shift_up",["edit"],{name:a("Delete cell and shift up"),sequence:93,action:ja}).addChild("edit_delete_cell_shift_left",["edit"],{name:a("Delete cell and shift left"),sequence:97,action:Xa}).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=Na(e);return 1===t?a("Row above"):a("%s Rows above",t.toString())},sequence:10,action:Ya,isVisible:e=>0===e.getters.getActiveCols().size}).addChild("insert_row_after",["insert"],{name:e=>{const t=Na(e);return 1===t?a("Row below"):a("%s Rows below",t.toString())},sequence:20,action:Ka,isVisible:e=>0===e.getters.getActiveCols().size,separator:!0}).addChild("insert_column_before",["insert"],{name:e=>{const t=Oa(e);return 1===t?a("Column left"):a("%s Columns left",t.toString())},sequence:30,action:Qa,isVisible:e=>0===e.getters.getActiveRows().size}).addChild("insert_column_after",["insert"],{name:e=>{const t=Oa(e);return 1===t?a("Column right"):a("%s Columns right",t.toString())},sequence:40,action:Ja,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:Wa}).addChild("insert_insert_cell_shift_right",["insert"],{name:a("Insert cells and shift right"),sequence:47,action:qa,separator:!0}).addChild("insert_chart",["insert"],{name:a("Chart"),sequence:50,action:e=>{var t,s;const i=e.getters.getSelectedZone();let o=i;const n=e.uuidGenerator.uuidv4();let r;i.left!==i.right&&(o={...i,left:i.left+1});const a=[Ns(o)],l=e.getters.getActiveSheetId(),c={x:(null===(t=e.getters.getCol(l,i.right+1))||void 0===t?void 0:t.start)||0,y:(null===(s=e.getters.getRow(l,i.top))||void 0===s?void 0:s.start)||0};let h=!1;for(let t=o.left;t<=o.right;t++){const s=e.getters.getCell(l,t,i.top);if(s&&s.evaluated.type!==Ne.number){h=!0;break}}i.left!==i.right&&(r=Ns({...i,right:i.left,top:h?i.top+1:i.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:tl}).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,i=e.uuidGenerator.uuidv4();e.dispatch("CREATE_SHEET",{sheetId:i,position:s}),e.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:i})},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=>ka(e,"")}).addChild("format_number_number",["format","format_number"],{name:a("Number (1,000.12)"),sequence:20,action:e=>ka(e,"#,##0.00")}).addChild("format_number_percent",["format","format_number"],{name:a("Percent (10.12%)"),sequence:30,separator:!0,action:e=>ka(e,"0.00%")}).addChild("format_number_date",["format","format_number"],{name:a("Date (9/26/2008)"),sequence:40,action:e=>ka(e,"m/d/yyyy")}).addChild("format_number_time",["format","format_number"],{name:a("Time (10:43:00 PM)"),sequence:50,action:e=>ka(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=>ka(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=>ka(e,"hhhh:mm:ss")}).addChild("format_bold",["format"],{name:a("Bold"),sequence:20,shortCut:"Ctrl+B",action:e=>Fa(e,{bold:!e.getters.getCurrentStyle().bold})}).addChild("format_italic",["format"],{name:a("Italic"),sequence:30,shortCut:"Ctrl+I",action:e=>Fa(e,{italic:!e.getters.getCurrentStyle().italic})}).addChild("format_underline",["format"],{name:a("Underline"),shortCut:"Ctrl+U",sequence:40,action:e=>Fa(e,{underline:!e.getters.getCurrentStyle().underline})}).addChild("format_strikethrough",["format"],{name:a("Strikethrough"),sequence:50,action:e=>Fa(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:el,separator:!0});for(let e of as)hl.addChild(`format_font_size_${e.pt}`,["format","format_font_size"],{name:e.pt.toString(),sequence:e.pt,action:t=>Fa(t,{fontSize:e.pt})});const dl=new class extends Re{addTransformation(e,t,s){for(let i of t)this.content[i]||(this.content[i]=new Map),this.content[i].set(e,s);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},{css:ul,xml:pl}=t.tags,gl=[["#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"]],fl=24*Math.max(...gl.map((e=>e.length)))+12;class ml extends t.Component{constructor(){super(...arguments),this.COLORS=gl}onColorClick(e){const t=e.target.dataset.color;t&&this.trigger("color-picked",{color:t})}}ml.template=pl`
2
2
  <div class="o-color-picker"
3
3
  t-att-class="props.dropdownDirection || 'right'"
4
4
  t-on-click="onColorClick">
@@ -44,7 +44,7 @@
44
44
  left: calc(50% - ${fl/2}px);
45
45
  }
46
46
  }
47
- `;const vl='<svg class="o-icon"><polygon fill="#000000" points="0 0 4 4 8 0" transform="translate(5 7)"/></svg>',El='<svg class="o-icon"><polygon fill="#000000" points="0 0 4 4 0 8" transform="translate(5 5)"/></svg>',bl='<svg class="o-icon"><path fill="#000000" fill-rule="evenodd" d="M9,3.5 C9,1.57 7.43,0 5.5,0 L1.77635684e-15,0 L1.77635684e-15,12 L6.25,12 C8.04,12 9.5,10.54 9.5,8.75 C9.5,7.45 8.73,6.34 7.63,5.82 C8.46,5.24 9,4.38 9,3.5 Z M5,2 C5.82999992,2 6.5,2.67 6.5,3.5 C6.5,4.33 5.82999992,5 5,5 L3,5 L3,2 L5,2 Z M3,10 L3,7 L5.5,7 C6.32999992,7 7,7.67 7,8.5 C7,9.33 6.32999992,10 5.5,10 L3,10 Z" transform="translate(4 3)"/></svg>',Sl='<svg class="o-icon"><polygon fill="#000000" fill-rule="evenodd" points="4 0 4 2 6.58 2 2.92 10 0 10 0 12 8 12 8 10 5.42 10 9.08 2 12 2 12 0" transform="translate(3 3)"/></svg>',Cl='<svg class="o-icon"><path fill="#010101" fill-rule="evenodd" d="M2.8875,3.06 C2.8875,2.6025 2.985,2.18625 3.18375,1.8075 C3.3825,1.42875 3.66,1.10625 4.02,0.84 C4.38,0.57375 4.80375,0.3675 5.29875,0.22125 C5.79375,0.075 6.33375,0 6.92625,0 C7.53375,0 8.085,0.0825 8.58,0.25125 C9.075,0.42 9.49875,0.6525 9.85125,0.95625 C10.20375,1.25625 10.47375,1.6125 10.665,2.02875 C10.85625,2.44125 10.95,2.895 10.95,3.38625 L8.6925,3.38625 C8.6925,3.1575 8.655,2.94375 8.58375,2.74875 C8.5125,2.55 8.4,2.38125 8.25,2.2425 C8.1,2.10375 7.9125,1.99125 7.6875,1.91625 C7.4625,1.8375 7.19625,1.8 6.88875,1.8 C6.5925,1.8 6.3375,1.83375 6.11625,1.8975 C5.89875,1.96125 5.71875,2.05125 5.57625,2.1675 C5.43375,2.28375 5.325,2.41875 5.25375,2.5725 C5.1825,2.72625 5.145,2.895 5.145,3.0675 C5.145,3.4275 5.32875,3.73125 5.69625,3.975 C5.71780203,3.98908066 5.73942012,4.00311728 5.76118357,4.01733315 C6.02342923,4.18863185 6.5,4.5 7,5 L4,5 C4,5 3.21375,4.37625 3.17625,4.30875 C2.985,3.9525 2.8875,3.53625 2.8875,3.06 Z M14,6 L0,6 L0,8 L7.21875,8 C7.35375,8.0525 7.51875,8.105 7.63125,8.15375 C7.90875,8.2775 8.12625,8.40875 8.28375,8.53625 C8.44125,8.6675 8.54625,8.81 8.6025,8.96 C8.65875,9.11375 8.685,9.28625 8.685,9.47375 C8.685,9.65 8.65125,9.815 8.58375,9.965 C8.51625,10.11875 8.41125,10.25 8.2725,10.35875 C8.13375,10.4675 7.95375,10.55375 7.74,10.6175 C7.5225,10.68125 7.27125,10.71125 6.97875,10.71125 C6.6525,10.71125 6.35625,10.6775 6.09,10.61375 C5.82375,10.55 5.59875,10.445 5.41125,10.3025 C5.22375,10.16 5.0775,9.9725 4.9725,9.74375 C4.8675,9.515 4.78125,9.17 4.78125,9 L2.55,9 C2.55,9.2525 2.61,9.6875 2.72625,10.025 C2.8425,10.3625 3.0075,10.66625 3.21375,10.9325 C3.42,11.19875 3.6675,11.4275 3.94875,11.6225 C4.23,11.8175 4.53375,11.9825 4.86375,12.11 C5.19375,12.24125 5.535,12.33875 5.89875,12.39875 C6.25875,12.4625 6.6225,12.4925 6.9825,12.4925 C7.5825,12.4925 8.13,12.425 8.6175,12.28625 C9.105,12.1475 9.525,11.94875 9.87,11.69375 C10.215,11.435 10.48125,11.12 10.6725,10.74125 C10.86375,10.3625 10.95375,9.935 10.95375,9.455 C10.95375,9.005 10.875,8.6 10.72125,8.24375 C10.68375,8.1575 10.6425,8.075 10.59375,7.9925 L14,8 L14,6 Z" transform="translate(2 3)"/></svg>',Il='<svg class="o-icon"><path fill="#000000" d="M7,0 L5,0 L0.5,12 L2.5,12 L3.62,9 L8.37,9 L9.49,12 L11.49,12 L7,0 L7,0 Z M4.38,7 L6,2.67 L7.62,7 L4.38,7 L4.38,7 Z" transform="translate(3 1)"/></svg>',yl='<svg class="o-icon"><path fill="#000000" d="M14.5,8.87 C14.5,8.87 13,10.49 13,11.49 C13,12.32 13.67,12.99 14.5,12.99 C15.33,12.99 16,12.32 16,11.49 C16,10.5 14.5,8.87 14.5,8.87 L14.5,8.87 Z M12.71,6.79 L5.91,0 L4.85,1.06 L6.44,2.65 L2.29,6.79 C1.9,7.18 1.9,7.81 2.29,8.2 L6.79,12.7 C6.99,12.9 7.24,13 7.5,13 C7.76,13 8.01,12.9 8.21,12.71 L12.71,8.21 C13.1,7.82 13.1,7.18 12.71,6.79 L12.71,6.79 Z M4.21,7 L7.5,3.71 L10.79,7 L4.21,7 L4.21,7 Z"/></svg>',wl='<svg class="o-icon"><path fill="#000000" d="M0,14 L10,14 L10,12 L0,12 L0,14 Z M10,4 L0,4 L0,6 L10,6 L10,4 Z M0,0 L0,2 L14,2 L14,0 L0,0 Z M0,10 L14,10 L14,8 L0,8 L0,10 Z" transform="translate(2 2)"/></svg>',xl='<svg class="o-icon"><path fill="#000000" d="M2,12 L2,14 L12,14 L12,12 L2,12 Z M2,4 L2,6 L12,6 L12,4 L2,4 Z M0,10 L14,10 L14,8 L0,8 L0,10 Z M0,0 L0,2 L14,2 L14,0 L0,0 Z" transform="translate(2 2)"/></svg>',Tl='<svg class="o-icon"><path fill="#000000" d="M4,14 L14,14 L14,12 L4,12 L4,14 Z M0,10 L14,10 L14,8 L0,8 L0,10 Z M0,0 L0,2 L14,2 L14,0 L0,0 Z M4,6 L14,6 L14,4 L4,4 L4,6 Z" transform="translate(2 2)"/></svg>',Rl='<svg class="o-icon"><path fill="#000000" d="M0,0 L0,14 L14,14 L14,0 L0,0 L0,0 Z M6,12 L2,12 L2,8 L6,8 L6,12 L6,12 Z M6,6 L2,6 L2,2 L6,2 L6,6 L6,6 Z M12,12 L8,12 L8,8 L12,8 L12,12 L12,12 Z M12,6 L8,6 L8,2 L12,2 L12,6 L12,6 Z" transform="translate(2 2)"/></svg>',Ll='<svg class="o-icon" viewBox="0 0 384 384"><rect x="0" y="277.333" width="384" height="42.667"/><rect x="0" y="170.667" width="384" height="42.667"/><rect x="0" y="64" width="384" height="42.667"/></svg>',Ml='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon arrow-down" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#DC6965" d="M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z"></path></svg>',Al='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon arrow-up" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#00A04A" d="M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z"></path></svg>',_l='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon arrow-right" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#F0AD4E" d="M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"></path></svg>',Ol='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon smile" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#00A04A" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160 0c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm4 72.6c-20.8 25-51.5 39.4-84 39.4s-63.2-14.3-84-39.4c-8.5-10.2-23.7-11.5-33.8-3.1-10.2 8.5-11.5 23.6-3.1 33.8 30 36 74.1 56.6 120.9 56.6s90.9-20.6 120.9-56.6c8.5-10.2 7.1-25.3-3.1-33.8-10.1-8.4-25.3-7.1-33.8 3.1z"></path></svg>',Nl='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon meh" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#F0AD4E" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm8 144H160c-13.2 0-24 10.8-24 24s10.8 24 24 24h176c13.2 0 24-10.8 24-24s-10.8-24-24-24z"></path></svg>',kl='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon frown" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#DC6965" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm-80 128c-40.2 0-78 17.7-103.8 48.6-8.5 10.2-7.1 25.3 3.1 33.8 10.2 8.4 25.3 7.1 33.8-3.1 16.6-19.9 41-31.4 66.9-31.4s50.3 11.4 66.9 31.4c8.1 9.7 23.1 11.9 33.8 3.1 10.2-8.5 11.5-23.6 3.1-33.8C326 321.7 288.2 304 248 304z"></path></svg>',Fl='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon green-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#00A04A" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>',$l='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon yellow-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#F0AD4E" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>',Dl='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon red-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#DC6965" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>';function Pl(e){const t=new Image;return t.src="data:image/svg+xml; charset=utf8, "+encodeURIComponent(e),t}const Ul={arrowGood:{img:Pl(Al),svg:Al},arrowNeutral:{img:Pl(_l),svg:_l},arrowBad:{img:Pl(Ml),svg:Ml},smileyGood:{img:Pl(Ol),svg:Ol},smileyNeutral:{img:Pl(Nl),svg:Nl},smileyBad:{img:Pl(kl),svg:kl},dotGood:{img:Pl(Fl),svg:Fl},dotNeutral:{img:Pl($l),svg:$l},dotBad:{img:Pl(Dl),svg:Dl}},Bl={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}},{xml:Vl,css:zl}=t.tags,Hl=new ti,Zl=Vl`
47
+ `;const vl='<svg class="o-icon"><polygon fill="#000000" points="0 0 4 4 8 0" transform="translate(5 7)"/></svg>',El='<svg class="o-icon"><polygon fill="#000000" points="0 0 4 4 0 8" transform="translate(5 5)"/></svg>',bl='<svg class="o-icon"><path fill="#000000" fill-rule="evenodd" d="M9,3.5 C9,1.57 7.43,0 5.5,0 L1.77635684e-15,0 L1.77635684e-15,12 L6.25,12 C8.04,12 9.5,10.54 9.5,8.75 C9.5,7.45 8.73,6.34 7.63,5.82 C8.46,5.24 9,4.38 9,3.5 Z M5,2 C5.82999992,2 6.5,2.67 6.5,3.5 C6.5,4.33 5.82999992,5 5,5 L3,5 L3,2 L5,2 Z M3,10 L3,7 L5.5,7 C6.32999992,7 7,7.67 7,8.5 C7,9.33 6.32999992,10 5.5,10 L3,10 Z" transform="translate(4 3)"/></svg>',Sl='<svg class="o-icon"><polygon fill="#000000" fill-rule="evenodd" points="4 0 4 2 6.58 2 2.92 10 0 10 0 12 8 12 8 10 5.42 10 9.08 2 12 2 12 0" transform="translate(3 3)"/></svg>',Cl='<svg class="o-icon"><path fill="#010101" fill-rule="evenodd" d="M2.8875,3.06 C2.8875,2.6025 2.985,2.18625 3.18375,1.8075 C3.3825,1.42875 3.66,1.10625 4.02,0.84 C4.38,0.57375 4.80375,0.3675 5.29875,0.22125 C5.79375,0.075 6.33375,0 6.92625,0 C7.53375,0 8.085,0.0825 8.58,0.25125 C9.075,0.42 9.49875,0.6525 9.85125,0.95625 C10.20375,1.25625 10.47375,1.6125 10.665,2.02875 C10.85625,2.44125 10.95,2.895 10.95,3.38625 L8.6925,3.38625 C8.6925,3.1575 8.655,2.94375 8.58375,2.74875 C8.5125,2.55 8.4,2.38125 8.25,2.2425 C8.1,2.10375 7.9125,1.99125 7.6875,1.91625 C7.4625,1.8375 7.19625,1.8 6.88875,1.8 C6.5925,1.8 6.3375,1.83375 6.11625,1.8975 C5.89875,1.96125 5.71875,2.05125 5.57625,2.1675 C5.43375,2.28375 5.325,2.41875 5.25375,2.5725 C5.1825,2.72625 5.145,2.895 5.145,3.0675 C5.145,3.4275 5.32875,3.73125 5.69625,3.975 C5.71780203,3.98908066 5.73942012,4.00311728 5.76118357,4.01733315 C6.02342923,4.18863185 6.5,4.5 7,5 L4,5 C4,5 3.21375,4.37625 3.17625,4.30875 C2.985,3.9525 2.8875,3.53625 2.8875,3.06 Z M14,6 L0,6 L0,8 L7.21875,8 C7.35375,8.0525 7.51875,8.105 7.63125,8.15375 C7.90875,8.2775 8.12625,8.40875 8.28375,8.53625 C8.44125,8.6675 8.54625,8.81 8.6025,8.96 C8.65875,9.11375 8.685,9.28625 8.685,9.47375 C8.685,9.65 8.65125,9.815 8.58375,9.965 C8.51625,10.11875 8.41125,10.25 8.2725,10.35875 C8.13375,10.4675 7.95375,10.55375 7.74,10.6175 C7.5225,10.68125 7.27125,10.71125 6.97875,10.71125 C6.6525,10.71125 6.35625,10.6775 6.09,10.61375 C5.82375,10.55 5.59875,10.445 5.41125,10.3025 C5.22375,10.16 5.0775,9.9725 4.9725,9.74375 C4.8675,9.515 4.78125,9.17 4.78125,9 L2.55,9 C2.55,9.2525 2.61,9.6875 2.72625,10.025 C2.8425,10.3625 3.0075,10.66625 3.21375,10.9325 C3.42,11.19875 3.6675,11.4275 3.94875,11.6225 C4.23,11.8175 4.53375,11.9825 4.86375,12.11 C5.19375,12.24125 5.535,12.33875 5.89875,12.39875 C6.25875,12.4625 6.6225,12.4925 6.9825,12.4925 C7.5825,12.4925 8.13,12.425 8.6175,12.28625 C9.105,12.1475 9.525,11.94875 9.87,11.69375 C10.215,11.435 10.48125,11.12 10.6725,10.74125 C10.86375,10.3625 10.95375,9.935 10.95375,9.455 C10.95375,9.005 10.875,8.6 10.72125,8.24375 C10.68375,8.1575 10.6425,8.075 10.59375,7.9925 L14,8 L14,6 Z" transform="translate(2 3)"/></svg>',Il='<svg class="o-icon"><path fill="#000000" d="M7,0 L5,0 L0.5,12 L2.5,12 L3.62,9 L8.37,9 L9.49,12 L11.49,12 L7,0 L7,0 Z M4.38,7 L6,2.67 L7.62,7 L4.38,7 L4.38,7 Z" transform="translate(3 1)"/></svg>',yl='<svg class="o-icon"><path fill="#000000" d="M14.5,8.87 C14.5,8.87 13,10.49 13,11.49 C13,12.32 13.67,12.99 14.5,12.99 C15.33,12.99 16,12.32 16,11.49 C16,10.5 14.5,8.87 14.5,8.87 L14.5,8.87 Z M12.71,6.79 L5.91,0 L4.85,1.06 L6.44,2.65 L2.29,6.79 C1.9,7.18 1.9,7.81 2.29,8.2 L6.79,12.7 C6.99,12.9 7.24,13 7.5,13 C7.76,13 8.01,12.9 8.21,12.71 L12.71,8.21 C13.1,7.82 13.1,7.18 12.71,6.79 L12.71,6.79 Z M4.21,7 L7.5,3.71 L10.79,7 L4.21,7 L4.21,7 Z"/></svg>',wl='<svg class="o-icon"><path fill="#000000" d="M0,14 L10,14 L10,12 L0,12 L0,14 Z M10,4 L0,4 L0,6 L10,6 L10,4 Z M0,0 L0,2 L14,2 L14,0 L0,0 Z M0,10 L14,10 L14,8 L0,8 L0,10 Z" transform="translate(2 2)"/></svg>',xl='<svg class="o-icon"><path fill="#000000" d="M2,12 L2,14 L12,14 L12,12 L2,12 Z M2,4 L2,6 L12,6 L12,4 L2,4 Z M0,10 L14,10 L14,8 L0,8 L0,10 Z M0,0 L0,2 L14,2 L14,0 L0,0 Z" transform="translate(2 2)"/></svg>',Tl='<svg class="o-icon"><path fill="#000000" d="M4,14 L14,14 L14,12 L4,12 L4,14 Z M0,10 L14,10 L14,8 L0,8 L0,10 Z M0,0 L0,2 L14,2 L14,0 L0,0 Z M4,6 L14,6 L14,4 L4,4 L4,6 Z" transform="translate(2 2)"/></svg>',Rl='<svg class="o-icon"><path fill="#000000" d="M0,0 L0,14 L14,14 L14,0 L0,0 L0,0 Z M6,12 L2,12 L2,8 L6,8 L6,12 L6,12 Z M6,6 L2,6 L2,2 L6,2 L6,6 L6,6 Z M12,12 L8,12 L8,8 L12,8 L12,12 L12,12 Z M12,6 L8,6 L8,2 L12,2 L12,6 L12,6 Z" transform="translate(2 2)"/></svg>',Ll='<svg class="o-icon" viewBox="0 0 384 384"><rect x="0" y="277.333" width="384" height="42.667"/><rect x="0" y="170.667" width="384" height="42.667"/><rect x="0" y="64" width="384" height="42.667"/></svg>',Ml='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon arrow-down" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#DC6965" d="M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z"></path></svg>',Al='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon arrow-up" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#00A04A" d="M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z"></path></svg>',_l='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon arrow-right" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#F0AD4E" d="M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"></path></svg>',Ol='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon smile" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#00A04A" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160 0c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm4 72.6c-20.8 25-51.5 39.4-84 39.4s-63.2-14.3-84-39.4c-8.5-10.2-23.7-11.5-33.8-3.1-10.2 8.5-11.5 23.6-3.1 33.8 30 36 74.1 56.6 120.9 56.6s90.9-20.6 120.9-56.6c8.5-10.2 7.1-25.3-3.1-33.8-10.1-8.4-25.3-7.1-33.8 3.1z"></path></svg>',Nl='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon meh" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#F0AD4E" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm8 144H160c-13.2 0-24 10.8-24 24s10.8 24 24 24h176c13.2 0 24-10.8 24-24s-10.8-24-24-24z"></path></svg>',kl='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon frown" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#DC6965" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm-80 128c-40.2 0-78 17.7-103.8 48.6-8.5 10.2-7.1 25.3 3.1 33.8 10.2 8.4 25.3 7.1 33.8-3.1 16.6-19.9 41-31.4 66.9-31.4s50.3 11.4 66.9 31.4c8.1 9.7 23.1 11.9 33.8 3.1 10.2-8.5 11.5-23.6 3.1-33.8C326 321.7 288.2 304 248 304z"></path></svg>',Fl='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon green-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#00A04A" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>',$l='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon yellow-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#F0AD4E" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>',Dl='<svg xmlns="http://www.w3.org/2000/svg" class="o-cf-icon red-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#DC6965" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>';function Pl(e){const t=new Image;return t.src="data:image/svg+xml; charset=utf8, "+encodeURIComponent(e),t}const Ul={arrowGood:{img:Pl(Al),svg:Al},arrowNeutral:{img:Pl(_l),svg:_l},arrowBad:{img:Pl(Ml),svg:Ml},smileyGood:{img:Pl(Ol),svg:Ol},smileyNeutral:{img:Pl(Nl),svg:Nl},smileyBad:{img:Pl(kl),svg:kl},dotGood:{img:Pl(Fl),svg:Fl},dotNeutral:{img:Pl($l),svg:$l},dotBad:{img:Pl(Dl),svg:Dl}},Bl={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}},{xml:Vl,css:Hl}=t.tags,zl=new ti,Zl=Vl`
48
48
  <div class="o-selection">
49
49
  <div t-foreach="ranges" t-as="range" t-key="range.id" class="o-selection-input">
50
50
  <input
@@ -80,7 +80,7 @@
80
80
  t-on-click="disable">Confirm</button>
81
81
  </div>
82
82
 
83
- </div>`,Gl=zl`
83
+ </div>`,Gl=Hl`
84
84
  .o-selection {
85
85
  .o-selection-input {
86
86
  display: flex;
@@ -125,7 +125,7 @@
125
125
  }
126
126
  }
127
127
  }
128
- `;class Wl extends t.Component{constructor(){super(...arguments),this.id=Hl.uuidv4(),this.previousRanges=this.props.ranges||[],this.getters=this.env.getters,this.dispatch=this.env.dispatch,this.originSheet=this.env.getters.getActiveSheetId(),this.state=t.useState({isMissing:!1})}get ranges(){const e=this.getters.getSelectionInput(this.id);return(e.length?e:this.props.ranges?this.props.ranges.map(((e,t)=>({xc:e,id:t.toString(),isFocused:!1}))):[]).map((e=>({...e,isValidRange:""===e.xc||this.getters.isRangeValid(e.xc)})))}get hasFocus(){return this.ranges.filter((e=>e.isFocused)).length>0}get canAddRange(){return!this.props.hasSingleRange}get isInvalid(){return this.props.isInvalid||this.state.isMissing}mounted(){this.dispatch("ENABLE_NEW_SELECTION_INPUT",{id:this.id,initialRanges:this.props.ranges,hasSingleRange:this.props.hasSingleRange})}async willUnmount(){this.dispatch("DISABLE_SELECTION_INPUT",{id:this.id})}async patched(){const e=this.getters.getSelectionInputValue(this.id);this.previousRanges.join()!==e.join()&&this.triggerChange()}getColor(e){return"color: "+(e.color||"#000")+";"}triggerChange(){const e=this.getters.getSelectionInputValue(this.id);this.trigger("selection-changed",{ranges:e}),this.previousRanges=e}focus(e){this.state.isMissing=!1,this.dispatch("STOP_EDITION",{cancel:!0}),this.dispatch("FOCUS_RANGE",{id:this.id,rangeId:e})}addEmptyInput(){this.dispatch("ADD_EMPTY_RANGE",{id:this.id})}removeInput(e){this.dispatch("REMOVE_RANGE",{id:this.id,rangeId:e}),this.triggerChange(),this.trigger("selection-confirmed")}onInputChanged(e,t){const s=t.target;this.dispatch("CHANGE_RANGE",{id:this.id,rangeId:e,value:s.value}),s.blur(),this.triggerChange()}disable(){this.dispatch("UNFOCUS_SELECTION_INPUT");const e=this.getters.getSelectionInputValue(this.id);this.props.required&&0===e.length&&(this.state.isMissing=!0);const t=this.getters.getActiveSheetId();this.originSheet!==t&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:this.originSheet}),this.trigger("selection-confirmed")}}Wl.template=Zl,Wl.style=Gl;const ql={CF_TITLE:a("Format rules"),IS_RULE:a("Format cells if..."),FORMATTING_STYLE:a("Formatting style"),BOLD:a("Bold"),ITALIC:a("Italic"),UNDERLINE:a("Underline"),STRIKE_THROUGH:a("Strikethrough"),TEXT_COLOR:a("Text Color"),FILL_COLOR:a("Fill Color"),CANCEL:a("Cancel"),SAVE:a("Save"),PREVIEW_TEXT:a("Preview text"),Errors:{22:a("The range is invalid"),36:a("The argument is missing. Please provide a value"),37:a("The second argument is missing. Please provide a value"),38:a("The minpoint must be a number"),39:a("The midpoint must be a number"),40:a("The maxpoint must be a number"),41:a("The first value must be a number"),42:a("The second value must be a number"),32:a("Minimum must be smaller then Maximum"),35:a("Minimum must be smaller then Midpoint"),34:a("Midpoint must be smaller then Maximum"),33:a("Lower inflection point must be smaller then upper inflection point"),43:a("Invalid Minpoint formula"),45:a("Invalid Maxpoint formula"),44:a("Invalid Midpoint formula"),46:a("Invalid upper inflection point formula"),47:a("Invalid lower inflection point formula"),21:a("A range needs to be defined"),unexpected:a("The rule is invalid for an unknown reason")},SingleColor:a("Single color"),ColorScale:a("Color scale"),IconSet:a("Icon set"),newRule:a("Add another rule"),FixedNumber:a("Number"),Percentage:a("Percentage"),Percentile:a("Percentile"),Formula:a("Formula")},jl=a("Cell values"),Xl=a("None"),Yl=a("Preview"),Kl=a("Minpoint"),Ql=a("Maxpoint"),Jl=a("Midpoint"),ec=a("When value is"),tc=a("Else"),sc=a("Reverse icons"),ic=a("Icons"),oc=a("Type"),nc=a("Value"),rc={IsEmpty:a("Is empty"),IsNotEmpty:a("Is not empty"),ContainsText:a("Contains"),NotContains:a("Does not contain"),BeginsWith:a("Starts with"),EndsWith:a("Ends with"),Equal:a("Is equal to"),NotEqual:a("Is not equal to"),GreaterThan:a("Is greater than"),GreaterThanOrEqual:a("Is greater than or equal to"),LessThan:a("Is less than"),LessThanOrEqual:a("Is less than or equal to"),Between:a("Is between"),NotBetween:a("Is not between")},ac={ChartType:a("Chart type"),Line:a("Line"),Bar:a("Bar"),Pie:a("Pie"),StackedBar:a("Stacked barchart"),Title:a("Title"),Series:a("Series"),DataSeries:a("Data Series"),MyDataHasTitle:a("Data series include title"),DataCategories:a("Categories / Labels"),UpdateChart:a("Update chart"),CreateChart:a("Create chart"),TitlePlaceholder:a("New Chart"),BackgroundColor:a("Background color"),SelectColor:a("Select a color..."),VerticalAxisPosition:a("Vertical axis position"),LegendPosition:a("Legend position"),Left:a("Left"),Right:a("Right"),None:a("None"),Top:a("Top"),Bottom:a("Bottom"),Center:a("Center"),Linear:a("Linear"),Exponential:a("Exponential"),Logarithmic:a("Logarithmic"),Errors:{27:a("A dataset needs to be defined"),28:a("The dataset is invalid"),29:a("Labels are invalid"),unexpected:a("The chart definition is invalid for an unknown reason")}},lc=a("Search"),cc=a("Replace"),hc=a("Next"),dc=a("Previous"),uc=a("Match case"),pc=a("Match entire cell content"),gc=a("Search in formulas"),fc=a("Replace all"),mc=a("Also modify formulas"),vc=a("Text"),Ec=a("Link"),bc=a("Confirm"),Sc=a("Cancel"),Cc=a("Edit link"),Ic=a("Remove link"),yc=a("and"),{xml:wc,css:xc}=t.tags,Tc=wc`
128
+ `;class Wl extends t.Component{constructor(){super(...arguments),this.id=zl.uuidv4(),this.previousRanges=this.props.ranges||[],this.getters=this.env.getters,this.dispatch=this.env.dispatch,this.originSheet=this.env.getters.getActiveSheetId(),this.state=t.useState({isMissing:!1})}get ranges(){const e=this.getters.getSelectionInput(this.id);return(e.length?e:this.props.ranges?this.props.ranges.map(((e,t)=>({xc:e,id:t.toString(),isFocused:!1}))):[]).map((e=>({...e,isValidRange:""===e.xc||this.getters.isRangeValid(e.xc)})))}get hasFocus(){return this.ranges.filter((e=>e.isFocused)).length>0}get canAddRange(){return!this.props.hasSingleRange}get isInvalid(){return this.props.isInvalid||this.state.isMissing}mounted(){this.dispatch("ENABLE_NEW_SELECTION_INPUT",{id:this.id,initialRanges:this.props.ranges,hasSingleRange:this.props.hasSingleRange})}async willUnmount(){this.dispatch("DISABLE_SELECTION_INPUT",{id:this.id})}async patched(){const e=this.getters.getSelectionInputValue(this.id);this.previousRanges.join()!==e.join()&&this.triggerChange()}getColor(e){return"color: "+(e.color||"#000")+";"}triggerChange(){const e=this.getters.getSelectionInputValue(this.id);this.trigger("selection-changed",{ranges:e}),this.previousRanges=e}focus(e){this.state.isMissing=!1,this.dispatch("STOP_EDITION",{cancel:!0}),this.dispatch("FOCUS_RANGE",{id:this.id,rangeId:e})}addEmptyInput(){this.dispatch("ADD_EMPTY_RANGE",{id:this.id})}removeInput(e){this.dispatch("REMOVE_RANGE",{id:this.id,rangeId:e}),this.triggerChange(),this.trigger("selection-confirmed")}onInputChanged(e,t){const s=t.target;this.dispatch("CHANGE_RANGE",{id:this.id,rangeId:e,value:s.value}),s.blur(),this.triggerChange()}disable(){this.dispatch("UNFOCUS_SELECTION_INPUT");const e=this.getters.getSelectionInputValue(this.id);this.props.required&&0===e.length&&(this.state.isMissing=!0);const t=this.getters.getActiveSheetId();this.originSheet!==t&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:this.originSheet}),this.trigger("selection-confirmed")}}Wl.template=Zl,Wl.style=Gl;const ql={CF_TITLE:a("Format rules"),IS_RULE:a("Format cells if..."),FORMATTING_STYLE:a("Formatting style"),BOLD:a("Bold"),ITALIC:a("Italic"),UNDERLINE:a("Underline"),STRIKE_THROUGH:a("Strikethrough"),TEXT_COLOR:a("Text Color"),FILL_COLOR:a("Fill Color"),CANCEL:a("Cancel"),SAVE:a("Save"),PREVIEW_TEXT:a("Preview text"),Errors:{22:a("The range is invalid"),36:a("The argument is missing. Please provide a value"),37:a("The second argument is missing. Please provide a value"),38:a("The minpoint must be a number"),39:a("The midpoint must be a number"),40:a("The maxpoint must be a number"),41:a("The first value must be a number"),42:a("The second value must be a number"),32:a("Minimum must be smaller then Maximum"),35:a("Minimum must be smaller then Midpoint"),34:a("Midpoint must be smaller then Maximum"),33:a("Lower inflection point must be smaller then upper inflection point"),43:a("Invalid Minpoint formula"),45:a("Invalid Maxpoint formula"),44:a("Invalid Midpoint formula"),46:a("Invalid upper inflection point formula"),47:a("Invalid lower inflection point formula"),21:a("A range needs to be defined"),unexpected:a("The rule is invalid for an unknown reason")},SingleColor:a("Single color"),ColorScale:a("Color scale"),IconSet:a("Icon set"),newRule:a("Add another rule"),FixedNumber:a("Number"),Percentage:a("Percentage"),Percentile:a("Percentile"),Formula:a("Formula")},jl=a("Cell values"),Xl=a("None"),Yl=a("Preview"),Kl=a("Minpoint"),Ql=a("Maxpoint"),Jl=a("Midpoint"),ec=a("When value is"),tc=a("Else"),sc=a("Reverse icons"),ic=a("Icons"),oc=a("Type"),nc=a("Value"),rc={IsEmpty:a("Is empty"),IsNotEmpty:a("Is not empty"),ContainsText:a("Contains"),NotContains:a("Does not contain"),BeginsWith:a("Starts with"),EndsWith:a("Ends with"),Equal:a("Is equal to"),NotEqual:a("Is not equal to"),GreaterThan:a("Is greater than"),GreaterThanOrEqual:a("Is greater than or equal to"),LessThan:a("Is less than"),LessThanOrEqual:a("Is less than or equal to"),Between:a("Is between"),NotBetween:a("Is not between")},ac={ChartType:a("Chart type"),Line:a("Line"),Bar:a("Bar"),Pie:a("Pie"),StackedBar:a("Stacked barchart"),Title:a("Title"),Series:a("Series"),DataSeries:a("Data Series"),MyDataHasTitle:a("Data series include title"),DataCategories:a("Categories / Labels"),UpdateChart:a("Update chart"),CreateChart:a("Create chart"),TitlePlaceholder:a("New Chart"),BackgroundColor:a("Background color"),SelectColor:a("Select a color..."),VerticalAxisPosition:a("Vertical axis position"),LegendPosition:a("Legend position"),Left:a("Left"),Right:a("Right"),None:a("None"),Top:a("Top"),Bottom:a("Bottom"),Center:a("Center"),Linear:a("Linear"),Exponential:a("Exponential"),Logarithmic:a("Logarithmic"),Errors:{27:a("A dataset needs to be defined"),28:a("The dataset is invalid"),29:a("Labels are invalid"),unexpected:a("The chart definition is invalid for an unknown reason")}},lc=a("Search"),cc=a("Replace"),hc=a("Next"),dc=a("Previous"),uc=a("Match case"),pc=a("Match entire cell content"),gc=a("Search in formulas"),fc=a("Replace all"),mc=a("Also modify formulas"),vc=a("Text"),Ec=a("Link"),bc=a("Confirm"),Sc=a("Cancel"),Cc=a("Edit link"),Ic=a("Remove link"),yc=a("and"),{xml:wc,css:xc}=t.tags,Tc=wc`
129
129
  <div class="o-chart">
130
130
  <div class="o-panel">
131
131
  <div class="o-panel-element"
@@ -336,7 +336,7 @@
336
336
  <div class="o-cf-preview-gradient" t-attf-style="{{getPreviewGradient()}}">
337
337
  <t t-esc="env._t('${ql.PREVIEW_TEXT}')"/>
338
338
  </div>
339
- `,zc=Uc`
339
+ `,Hc=Uc`
340
340
  <div t-attf-class="o-threshold o-threshold-{{thresholdType}}">
341
341
  <select class="o-input" name="valueType" t-model="threshold.type" t-on-click="closeMenus">
342
342
  <option value="value" t-if="thresholdType!=='midpoint'">
@@ -373,7 +373,7 @@
373
373
  <ColorPicker t-if="stateColorScale[thresholdType+'ColorTool']" dropdownDirection="'left'" t-on-color-picked="setColor(thresholdType)"/>
374
374
  </div>
375
375
  </div>
376
- </div>`,Hc=Uc`
376
+ </div>`,zc=Uc`
377
377
  <div>
378
378
  <div class="o-cf-title-text">
379
379
  <t t-esc="env._t('${Yl}')"/>
@@ -382,21 +382,21 @@
382
382
  <div class="o-cf-title-text">
383
383
  <t t-esc="env._t('${Kl}')"/>
384
384
  </div>
385
- <t t-call="${zc}">
385
+ <t t-call="${Hc}">
386
386
  <t t-set="threshold" t-value="stateColorScale.minimum" ></t>
387
387
  <t t-set="thresholdType" t-value="'minimum'" ></t>
388
388
  </t>
389
389
  <div class="o-cf-title-text">
390
390
  <t t-esc="env._t('${Jl}')"/>
391
391
  </div>
392
- <t t-call="${zc}">
392
+ <t t-call="${Hc}">
393
393
  <t t-set="threshold" t-value="stateColorScale.midpoint" ></t>
394
394
  <t t-set="thresholdType" t-value="'midpoint'" ></t>
395
395
  </t>
396
396
  <div class="o-cf-title-text">
397
397
  <t t-esc="env._t('${Ql}')"/>
398
398
  </div>
399
- <t t-call="${zc}">
399
+ <t t-call="${Hc}">
400
400
  <t t-set="threshold" t-value="stateColorScale.maximum" ></t>
401
401
  <t t-set="thresholdType" t-value="'maximum'" ></t>
402
402
  </t>
@@ -421,7 +421,7 @@
421
421
  padding: 10px;
422
422
  border-radius: 4px;
423
423
  }
424
- `;class Gc extends t.Component{constructor(){super(...arguments),this.colorNumberString=qt,this.stateColorScale=t.useState({minimum:this.props.rule.minimum,maximum:this.props.rule.maximum,midpoint:this.props.rule.midpoint?this.props.rule.midpoint:{color:11982760,type:"none"},maximumColorTool:!1,minimumColorTool:!1,midpointColorTool:!1}),Pc(window,"click",this.closeMenus)}getRule(){const e={...this.stateColorScale.minimum},t={...this.stateColorScale.midpoint};return{type:"ColorScaleRule",minimum:e,maximum:{...this.stateColorScale.maximum},midpoint:"none"===t.type?void 0:t}}toggleMenu(e){const t=this.stateColorScale[e];this.closeMenus(),this.stateColorScale[e]=!t}setColor(e,t){const s=t.detail.color;this.stateColorScale[e].color=Number.parseInt(s.substr(1),16),this.closeMenus()}getPreviewGradient(){const e=qt(this.stateColorScale.minimum.color),t=qt(this.stateColorScale.midpoint.color),s=qt(this.stateColorScale.maximum.color),i="background-image: linear-gradient(to right, #";return"none"===this.stateColorScale.midpoint.type?i+e+", #"+s+")":i+e+", #"+t+", #"+s+")"}isValueInvalid(e){switch(e){case"minimum":return this.props.errors.includes(43)||this.props.errors.includes(35)||this.props.errors.includes(32)||this.props.errors.includes(38);case"midpoint":return this.props.errors.includes(44)||this.props.errors.includes(39)||this.props.errors.includes(34);case"maximum":return this.props.errors.includes(45)||this.props.errors.includes(40);default:return!1}}closeMenus(){this.stateColorScale.minimumColorTool=!1,this.stateColorScale.midpointColorTool=!1,this.stateColorScale.maximumColorTool=!1}static getDefaultRule(){return{type:"ColorScaleRule",minimum:{type:"value",color:16777215},midpoint:void 0,maximum:{type:"value",color:6989903}}}}Gc.template=Hc,Gc.style=Zc,Gc.components={ColorPicker:ml},Gc.defaultProps={errors:[]};const{css:Wc,xml:qc}=t.tags;class jc extends t.Component{constructor(){super(...arguments),this.icons=Ul,this.iconSets=Bl}onIconClick(e){e&&this.trigger("icon-picked",{icon:e})}}jc.template=qc`
424
+ `;class Gc extends t.Component{constructor(){super(...arguments),this.colorNumberString=qt,this.stateColorScale=t.useState({minimum:this.props.rule.minimum,maximum:this.props.rule.maximum,midpoint:this.props.rule.midpoint?this.props.rule.midpoint:{color:11982760,type:"none"},maximumColorTool:!1,minimumColorTool:!1,midpointColorTool:!1}),Pc(window,"click",this.closeMenus)}getRule(){const e={...this.stateColorScale.minimum},t={...this.stateColorScale.midpoint};return{type:"ColorScaleRule",minimum:e,maximum:{...this.stateColorScale.maximum},midpoint:"none"===t.type?void 0:t}}toggleMenu(e){const t=this.stateColorScale[e];this.closeMenus(),this.stateColorScale[e]=!t}setColor(e,t){const s=t.detail.color;this.stateColorScale[e].color=Number.parseInt(s.substr(1),16),this.closeMenus()}getPreviewGradient(){const e=qt(this.stateColorScale.minimum.color),t=qt(this.stateColorScale.midpoint.color),s=qt(this.stateColorScale.maximum.color),i="background-image: linear-gradient(to right, #";return"none"===this.stateColorScale.midpoint.type?i+e+", #"+s+")":i+e+", #"+t+", #"+s+")"}isValueInvalid(e){switch(e){case"minimum":return this.props.errors.includes(43)||this.props.errors.includes(35)||this.props.errors.includes(32)||this.props.errors.includes(38);case"midpoint":return this.props.errors.includes(44)||this.props.errors.includes(39)||this.props.errors.includes(34);case"maximum":return this.props.errors.includes(45)||this.props.errors.includes(40);default:return!1}}closeMenus(){this.stateColorScale.minimumColorTool=!1,this.stateColorScale.midpointColorTool=!1,this.stateColorScale.maximumColorTool=!1}static getDefaultRule(){return{type:"ColorScaleRule",minimum:{type:"value",color:16777215},midpoint:void 0,maximum:{type:"value",color:6989903}}}}Gc.template=zc,Gc.style=Zc,Gc.components={ColorPicker:ml},Gc.defaultProps={errors:[]};const{css:Wc,xml:qc}=t.tags;class jc extends t.Component{constructor(){super(...arguments),this.icons=Ul,this.iconSets=Bl}onIconClick(e){e&&this.trigger("icon-picked",{icon:e})}}jc.template=qc`
425
425
  <div class="o-icon-picker" >
426
426
  <t t-foreach="iconSets" t-as="iconSet" t-key="iconset">
427
427
  <div class="o-cf-icon-line">
@@ -1041,9 +1041,9 @@
1041
1041
  }
1042
1042
  }
1043
1043
  }
1044
- `;class ph 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()}mounted(){this.focusInput()}async willUnmount(){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}}}}ph.template=dh,ph.style=uh;const gh=new Re;gh.add("ConditionalFormatting",{title:a("Conditional formatting"),Body:lh}),gh.add("ChartPanel",{title:a("Chart"),Body:Lc}),gh.add("FindAndReplace",{title:a("Find and Replace"),Body:ph});const fh=new Re;class mh extends ua{constructor(e,t,s,i){super(t,s,i),this.getters=e,this.ui=i}drawGrid(e,t){}}mh.layers=[];class vh{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:i}=wa.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:s,tooltip:i,origin:{col:e.data.col,row:e.data.row}}}}class Eh extends mh{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:ps(e.col,0,this.getters.getSheet(t).cols.length),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:ps(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 i=t.left;i<=t.right;i++){const o=[];for(let e=t.top;e<=t.bottom;e++)o.push(ss(i,e));const n=this.createGenerator(o);for(let t=s.top;t<=s.bottom;t++)this.computeNewCell(n,i,t,e)}break;case 0:for(let i=t.left;i<=t.right;i++){const o=[];for(let e=t.bottom;e>=t.top;e--)o.push(ss(i,e));const n=this.createGenerator(o);for(let t=s.bottom;t>=s.top;t--)this.computeNewCell(n,i,t,e)}break;case 2:for(let i=t.top;i<=t.bottom;i++){const o=[];for(let e=t.right;e>=t.left;e--)o.push(ss(e,i));const n=this.createGenerator(o);for(let t=s.right;t>=s.left;t--)this.computeNewCell(n,t,i,e)}break;case 3:for(let i=t.top;i<=t.bottom;i++){const o=[];for(let e=t.left;e<=t.right;e++)o.push(ss(e,i));const n=this.createGenerator(o);for(let t=s.left;t<=s.right;t++)this.computeNewCell(n,t,i,e)}}if(e){const e=$s(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(Us(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,i=e.bottom;if(s>0){let e=this.getters.getCell(t,s-1,i);for(;e&&!e.isEmpty();)i+=1,e=this.getters.getCell(t,s-1,i)}if(i===e.bottom&&(s=e.right,s<=this.getters.getActiveSheet().cols.length)){let e=this.getters.getCell(t,s+1,i);for(;e&&!e.isEmpty();)i+=1,e=this.getters.getCell(t,s+1,i)}i!==e.bottom&&(this.select(e.left,i-1),this.autofill(!0))}computeNewCell(e,t,s,i){const{cellData:o,tooltip:n,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=o;this.tooltip=n,i&&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=xa.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=[],i=this.getters.getActiveSheetId();for(let t of e){const[e,o]=ts(t),n=this.getters.getCell(i,e,o);s.push({col:e,row:o,cell:n,sheetId:i})}const o=s.map((e=>e.cell));for(let e of s){let s={type:"COPY_MODIFIER"};if(e&&e.cell){s=this.getRule(e.cell,o)||s}const{sheetId:i,col:n,row:r}=e,a=this.getters.getCellBorder(i,n,r)||void 0;t.push({data:{...e,border:a},rule:s})}return new vh(t,this.getters,this.direction)}saveZone(e,t,s,i){this.autofillZone={top:e,bottom:t,left:s,right:i}}getDirection(e,t){const s=this.getters.getSelectedZone(),i={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(i).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(i).find((e=>e.number>0?1:0)).value;const o=i.up.number>0?"up":"down",n=i.left.number>0?"left":"right";return Math.abs(i[o].number)>=Math.abs(i[n].number)?i[o].value:i[n].value}autoFillMerge(e,t,s,i){const o=this.getters.getActiveSheet();if(this.getters.isInMerge(o.id,s,i)&&!this.getters.isInMerge(o.id,e,t)){const e=this.getters.getMerge(o.id,s,i);e&&this.dispatch("REMOVE_MERGE",{sheetId:o.id,target:[e]})}const n=this.getters.getMerge(o.id,e,t);(null==n?void 0:n.topLeft.col)===e&&(null==n?void 0:n.topLeft.row)===t&&this.dispatch("ADD_MERGE",{sheetId:o.id,target:[{top:i,bottom:i+n.bottom-n.top,left:s,right:s+n.right-n.left}]})}drawGrid(e){if(!this.autofillZone)return;const{viewport:t,ctx:s,thinLineWidth:i}=e,[o,n,r,a]=this.getters.getRect(this.autofillZone,t);r>0&&a>0&&(s.strokeStyle="black",s.lineWidth=i,s.setLineDash([3]),s.strokeRect(o,n,r,a),s.setLineDash([]))}}Eh.layers=[6],Eh.getters=["getAutofillTooltip"],Eh.modes=["normal"];class bh extends mh{handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:s}=this.getters.getSelection();for(const i of t){const t=this.getAutomaticSums(e,i,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),i=this.sumDimensions(e,t,s).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return s.has("ROW")&&s.has("COL")&&i.push(this.sumTotal(t)),i}sumAdjacentData(e,t,s){const[i,o]=Us(s[0],s[1],t)?s:[t.left,t.top],n=this.findAdjacentData(e,i,o);return n?this.getters.isSingleCellOrMerge(e,t)||Zs($s(n,t))?[{position:[i,o],zone:n}]:this.sumDimensions(e,$s(n,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,s){const i=this.getters.getSheet(e),o=this.findSuitableZoneToSum(i,...this.getters.getMainCell(e,t,s));if(o)return this.getters.expandZone(e,o)}findSuitableZoneToSum(e,t,s){const i=this.getters.getCell(e.id,t,s-1),o=this.getters.getCell(e.id,t-1,s);if(this.isNumber(o)&&!this.isNumber(i))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 i={top:0,bottom:s-1,left:t,right:t},o=this.reduceZoneStart(e,i,i.bottom);return{...i,top:o}}findHorizontalZone(e,t,s){const i={top:s,bottom:s,left:0,right:t-1},o=this.reduceZoneStart(e,i,i.right);return{...i,left:o}}reduceZoneStart(e,t,s){const i=zs(t,e,(e=>e),void 0).flat(),o=fs(s,-1,-1),n=o.filter((e=>{var t;return i[e]&&!(null===(t=i[e])||void 0===t?void 0:t.isAutoSummable)})),r=Math.max(...n),a=ms(o.filter((e=>this.isNumber(i[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)===Ne.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(A))}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 Zs(t)?(s.add(1===Hs(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)},Gs(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)},Gs(s).map((t=>({position:t,zone:{...e,top:t[1],bottom:t[1]}})))}dispatchCellUpdates(e,t){for(const s of t){const[t,i]=s.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,content:`=SUM(${this.getters.zoneToXC(e,s.zone)})`})}}nextEmptyRow(e,t){let s=t.bottom+1;const{left:i,right:o}=t;for(;!this.getters.isEmpty(e,{bottom:s,top:s,left:i,right:o});)s++;return{...t,top:s,bottom:s}}nextEmptyCol(e,t){let s=t.right+1;const{top:i,bottom:o}=t;for(;!this.getters.isEmpty(e,{left:s,right:s,top:i,bottom:o});)s++;return{...t,left:s,right:s}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}bh.getters=["getAutomaticSums"],bh.modes=["normal","headless"];class Sh extends mh{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),i=this.getClipboardState(t,"CUT");return this.isPasteAllowed(i,s,!1)}case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),i=this.getClipboardState(t,"CUT");return this.isPasteAllowed(i,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 i=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);if(this._isPaintingFormat=!1,e.interactive)this.interactivePaste(this.state,e.target,e);else{const t=this.state.cells.length,s=this.state.cells[0].length;this.paste(this.state,e.target,i),this.selectPastedZone(s,t,e.target),this.status="invisible"}break;case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Os(t[0])){for(const[t,s]of Gs(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:s,sheetId:this.getters.getActiveSheetId()});break}const i=this.getClipboardState(t,"CUT");e.interactive?this.interactivePaste(i,s,e):this.paste(i,s);break}case"INSERT_CELL":{const{cut:t,paste:s}=this.getInsertCellsTargets(e.zone,e.shiftDimension),i=this.getClipboardState(t,"CUT");e.interactive?this.interactivePaste(i,s,e):this.paste(i,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:De(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 i;return i="COL"===t?{...e,left:e.right+1,right:s.cols.length-1}:{...e,top:e.bottom+1,bottom:s.rows.length-1},{cut:[i],paste:[e]}}getInsertCellsTargets(e,t){const s=this.getters.getActiveSheet();let i,o;return"COL"===t?(i={...e,right:s.cols.length-1},o={...e,left:e.right+1,right:e.right+1}):(i={...e,bottom:s.rows.length-1},o={...e,top:e.bottom+1,bottom:s.rows.length-1}),{cut:[i],paste:[o]}}removeMergeIfTopLeft(e){const{sheetId:t,col:s,row:i}=e,[o,n]=this.getters.getMainCell(t,s,i);if(n===i&&o===s){const e=this.getters.getMerge(t,s,i);e&&this.dispatch("REMOVE_MERGE",{sheetId:t,target:[e]})}}pasteMergeIfExist(e,t){let{sheetId:s,col:i,row:o}=e;const[n,r]=this.getters.getMainCell(s,i,o);if(n===i&&r===o){const e=this.getters.getMerge(s,i,o);if(!e)return;({sheetId:s,col:i,row:o}=t),this.dispatch("ADD_MERGE",{sheetId:s,force:!0,target:[{left:i,top:o,right:i+e.right-e.left,bottom:o+e.bottom-e.top}]})}}getPasteZones(e,t){if(!t.length||!t[0].length)return e;const s=[],i=t.length,o=t[0].length,n=e[e.length-1],r=n.left,a=n.top,l=Math.max(1,Math.floor((n.right+1-r)/o)),c=Math.max(1,Math.floor((n.bottom+1-a)/i));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)s.push({left:r,top:a,right:r-1+e*o,bottom:a-1+t*i});return s}getClipboardState(e,t){const s=new Set(e.map((e=>e.top))),i=new Set(e.map((e=>e.bottom)));let o=1===s.size&&1===i.size?e:[e[e.length-1]];o=o.map((e=>({...e})));const n=[],r=[],a=this.getters.getActiveSheetId(),{top:l,bottom:c}=o[0];for(let e=l;e<=c;e++){const t=[];n.push(t);for(let s of o)for(let i=s.left;i<=s.right;i++){const s=this.getters.getCell(a,i,e),o=this.getters.getCellBorder(a,i,e)||void 0;t.push({cell:s,border:o,position:{col:i,row:e,sheetId:a}});const n=this.getters.getMerge(a,i,e);n&&n.top===e&&n.left===i&&r.push(n)}}return{cells:n,operation:t,sheetId:a,zones:o,merges:r}}pasteFromClipboard(e,t){this.status="invisible";const s=t.replace(/\r/g,"").split("\n").map((e=>e.split("\t"))),{left:i,top:o}=e[0],n=Math.max.apply(Math,s.map((e=>e.length))),r=s.length,a=this.getters.getActiveSheet();this.addMissingDimensions(a,n,r,i,o);for(let e=0;e<s.length;e++)for(let t=0;t<s[e].length;t++)this.dispatch("UPDATE_CELL",{row:o+e,col:i+t,content:s[e][t],sheetId:a.id});const l={left:i,top:o,right:i+n-1,bottom:o+r-1};this.dispatch("SET_SELECTION",{anchor:[i,o],zones:[l],anchorZone:l})}isPasteAllowed(e,t,s){const i=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(i,s))return 2;return 0}paste(e,t,s){if("CUT"===e.operation&&this.clearClippedZones(e),t.length>1)for(const i of t)for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++)this.pasteZone(e,t,o,s);else{const i=e.cells.length,o=e.cells[0].length,n=t[0],r=Math.max(1,Math.floor((n.right+1-n.left)/o)),a=Math.max(1,Math.floor((n.bottom+1-n.top)/i));for(let t=0;t<r;t++)for(let r=0;r<a;r++)this.pasteZone(e,n.left+t*o,n.top+r*i,s)}"CUT"===e.operation&&(this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:e.merges}),this.state=void 0)}selectPastedZone(e,t,s){const i=s[0],o=i.left,n=i.top,r=Math.max(1,Math.floor((i.right+1-i.left)/e)),a=Math.max(1,Math.floor((i.bottom+1-i.top)/t));if(t>1||e>1){const s={left:o,top:n,right:o+r*e-1,bottom:n+a*t-1},[i,l]=this.getters.getSelection().anchor,c=ps(i,o,o+r*e-1),h=ps(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,i){const o=e.cells.length,n=e.cells[0].length,r="onlyValue"!==i&&this.state&&this.state===e,a=this.getters.getActiveSheet();this.addMissingDimensions(a,n,o,t,s);for(let l=0;l<o;l++){const o=e.cells[l];for(let c=0;c<n;c++){const n=o[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,i),r&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:n.position,target:h,operation:e.operation})}}}addMissingDimensions(e,t,s,i,o){const{cols:n,rows:r,id:a}=e,l=s+o-r.length;l>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:r.length-1,sheetId:a,quantity:l,position:"after"});const c=t+i-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,i,o){const{sheetId:n,col:r,row:a}=t,l=this.getters.getCell(n,r,a);if("onlyValue"!==o&&this.dispatch("SET_BORDER",{sheetId:n,col:r,row:a,border:e.border}),e.cell){if("onlyFormat"===o)return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.cell.format});if("onlyValue"===o){const s=Zr(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,o=a-e.position.row;l=this.getUpdatedContent(n,e.cell,t,o,i,s)}this.dispatch("UPDATE_CELL",{...t,content:l,style:e.cell.style||null,format:e.cell.format})}else l&&("onlyValue"===o?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===o?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,s,i,o,n){if("CUT"===n){const n=[];for(const r of t.dependencies.references)this.isZoneOverlapClippedZone(o,r.zone)?n.push(...this.getters.createAdaptedRanges([r],s,i,e)):n.push(r);const r={...t.dependencies,references:n};return this.getters.buildFormulaContent(e,t.normalizedText,r)}const r=this.getters.createAdaptedRanges(t.dependencies.references,s,i,e),a={...t.dependencies,references:r};return this.getters.buildFormulaContent(e,t.normalizedText,a)}isZoneOverlapClippedZone(e,t){return e.some((e=>Ps(t,e)))}interactivePaste(e,t,s){const i=this.isPasteAllowed(e,t,!1);0!==i?(19===i&&this.ui.notifyUser(a("This operation is not allowed with multiple selections.")),2===i&&this.ui.notifyUser(a("This operation is not possible due to a merge. Please remove the merges first than try again."))):this.dispatch(s.type,{...s,interactive:!1})}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:i}=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*i;for(const e of this.state.zones){const[i,o,n,r]=this.getters.getRect(e,t);n>0&&r>0&&s.strokeRect(i,o,n,r)}}}}var Ch;Sh.layers=[2],Sh.getters=["getClipboardContent","isPaintingFormat"],Sh.modes=["normal"],function(e){e[e.idle=0]="idle",e[e.selecting=1]="selecting",e[e.readyToExpand=2]="readyToExpand",e[e.expanding=3]="expanding"}(Ch||(Ch={}));class Ih extends mh{constructor(e,t,s,i){super(e,t,s,i),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=Ch.idle,this.sheetsData={},this.activeSheet=null,this.moveClient=i.moveClient}allowDispatch(e){switch(e.type){case"SET_SELECTION":if(-1===e.zones.findIndex((t=>Ds(t,e.anchorZone))))return 16;break;case"ALTER_SELECTION":if(e.delta){const{left:t,right:s,top:i,bottom:o}=this.getSelectedZone(),n=this.getters.getActiveSheet(),r=ii(n,"cols",fs(t,s+1)),a=ii(n,"rows",fs(i,o+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:i,row:o}=this.getNextAvailablePosition(e.deltaX,e.deltaY);if(o<0||o>s.length-1||i<0||i>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":const t=this.isMoveElementAllowed(e);return 2===t&&this.ui.notifyUser(a("Merged cells are preventing this operation. Unmerge those cells and try again.")),t}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=si(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(...si(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=Ch.selecting;break;case"PREPARE_SELECTION_EXPANSION":this.mode=Ch.readyToExpand;break;case"START_SELECTION_EXPANSION":this.mode=Ch.expanding;break;case"STOP_SELECTION":this.mode=Ch.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]:si(this.getters.getSheet(e),0,0)}}getAggregate(){let e=0,t=0;for(let s of this.selection.zones)for(let i=s.top;i<=s.bottom;i++){const o=this.getters.getRow(this.getters.getActiveSheetId(),i);if(void 0!==o)for(let i=s.left;i<=s.right;i++){const s=o.cells[i];(null==s?void 0:s.evaluated.type)===Ne.number&&(t++,e+=s.evaluated.value)}}return t<2?null:se(e)}getSelectionMode(){return this.mode}isSelected(e){return!!this.getters.getSelectedZones().find((t=>Ds(t,e)))}getVisibleFigures(e){const t=[],s=this.getters.getFigures(e),{offsetX:i,offsetY:o}=this.getters.getSnappedViewport(e),{width:n,height:r}=this.getters.getViewportDimension();for(let e of s)e.x>=i+n||e.x+e.width<=i||e.y>=o+r||e.y+e.height<=o||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 i="COL"===e?"left":"top",o="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[o]-e[i]+1},((t,s)=>e[i]+s));s=s.concat(t)}return[...new Set(s)].sort()}selectColumn(e,t,s){const i=this.getters.getActiveSheet().rows.length-1;let o={left:e,right:e,top:0,bottom:i};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;o=$s(o,{left:e,right:e,top:l,bottom:i}),r=this.updateSelectionZones(o),a=[e,t]}else r=t?n.concat(o):[o],a=[e,l];this.dispatch("SET_SELECTION",{zones:r,anchor:a,strict:!0,anchorZone:o})}selectRow(e,t,s){const i=this.getters.getActiveSheet().cols.length-1;let o={top:e,bottom:e,left:0,right:i};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;o=$s(o,{left:l,right:i,top:t,bottom:t}),r=this.updateSelectionZones(o),a=[e,t]}else r=t?n.concat(o):[o],a=[l,e];this.dispatch("SET_SELECTION",{zones:r,anchor:a,strict:!0,anchorZone:o})}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});let i=this.getters.expandZone(s.id,{left:e,right:e,top:t,bottom:t});this.mode===Ch.expanding?this.selection.zones.push(i):this.selection.zones=[i],this.selection.zones=qs(this.selection.zones),this.selection.anchorZone=i,this.selection.anchor=[e,t],this.activeCol=e,this.activeRow=t}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:i,id:o}=this.getActiveSheet(),n={col:t,row:s};return this.getNextAvailableHeader(e,i,t,n,(e=>this.getters.isInSameMerge(o,t,s,e,s)))}getNextAvailableRow(e,t,s){const{rows:i,id:o}=this.getActiveSheet(),n={col:t,row:s};return this.getNextAvailableHeader(e,i,s,n,(e=>this.getters.isInSameMerge(o,t,s,t,e)))}getNextAvailableHeader(e,t,s,i,o){var n,r,a;const l=this.getters.getActiveSheetId(),{col:c,row:h}=i;if(0===e)return s;let d=s+e;if(this.getters.isInMerge(l,c,h)){for(;o(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,i,o):s:d}movePosition(e,t){const{col:s,row:i}=this.getNextAvailablePosition(e,t);this.selectCell(s,i)}setSelection(e,t,s,i=!1){this.selectCell(...e);const o=this.getters.getActiveSheetId();let n;t=qs(t),n=i?{zones:t,anchorZone:s,anchor:e}:{anchor:e,zones:t.map((e=>this.getters.expandZone(o,e))),anchorZone:this.getters.expandZone(o,s)},this.selection=this.clipSelection(o,n)}getReferencePosition(){const e=this.getters.getActiveSheet(),t=this.selection,{left:s,right:i,top:o,bottom:n}=t.anchorZone,[r,a]=t.anchor;return{col:e.cols[r].isHidden&&ii(e,"cols",fs(s,i+1))||r,row:e.rows[a].isHidden&&ii(e,"rows",fs(o,n+1))||a}}moveSelection(e,t){const s=this.selection;let i=[];const[o,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:i,bottom:o}=this.getters.expandZone(d.id,e);return{left:Math.max(0,t),right:Math.min(d.cols.length-1,s),top:Math.max(0,i),bottom:Math.min(d.rows.length-1,o)}},{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?js(h):h,h&&!Ds(h,s.anchorZone))return i=this.updateSelectionZones(h),void this.dispatch("SET_SELECTION",{zones:i,anchor:[o,n],anchorZone:h})}h=u($s({top:n,bottom:n,left:o,right:o},js({top:this.getNextAvailableRow(t,p,l),left:this.getNextAvailableCol(e,r,g),bottom:this.getNextAvailableRow(t,p,c),right:this.getNextAvailableCol(e,a,g)}))),Ds(h,s.anchorZone)||(i=this.updateSelectionZones(h),this.dispatch("SET_SELECTION",{zones:i,anchor:[o,n],anchorZone:h}))}addCellToSelection(e,t){const s=this.selection,[i,o]=s.anchor,n={left:Math.min(i,e),top:Math.min(o,t),right:Math.max(i,e),bottom:Math.max(o,t)},r=this.updateSelectionZones(n);this.dispatch("SET_SELECTION",{zones:r,anchor:[i,o],anchorZone:n})}ensureSelectionValidity(){const{anchor:e,zones:t,anchorZone:s}=this.clipSelection(this.getActiveSheetId(),this.selection);this.setSelection(e,t,s);const i=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of i)delete this.sheetsData[e];for(const e in this.sheetsData){const{anchor:t,zones:s,anchorZone:i}=this.clipSelection(e,this.sheetsData[e].selection);this.sheetsData[e]={selection:{anchor:t,zones:s,anchorZone:i},activeCol:t[0],activeRow:t[1]}}}clipSelection(e,t){const s=this.getters.getSheet(e),i=s.cols.length-1,o=s.rows.length-1,n=t.zones.map((e=>({left:ps(e.left,0,i),right:ps(e.right,0,i),top:ps(e.top,0,o),bottom:ps(e.bottom,0,o)})));return{anchor:[ps(t.anchor[0],0,i),ps(t.anchor[1],0,o)],zones:n,anchorZone:{left:ps(t.anchorZone.left,0,i),right:ps(t.anchorZone.right,0,i),top:ps(t.anchorZone.top,0,o),bottom:ps(t.anchorZone.bottom,0,o)}}}onColumnsRemoved(e){const t=Fs(this.getSelectedZone(),"left",e.elements);this.setSelection([t.left,t.top],[t],t,!0),this.ensureSelectionValidity()}onRowsRemoved(e){const t=Fs(this.getSelectedZone(),"top",e.elements);this.setSelection([t.left,t.top],[t],t,!0),this.ensureSelectionValidity()}onAddElements(e){const t=ks(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,i=t.findIndex((e=>Ds(e,s)));return i>=0&&(t[i]=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,i=e.elements[0],o=e.elements[t-1],n=e.base<i,r=n&&s?t:0,a=n&&!s?t:0,l=this.getters.getSheet(e.sheetId);this.dispatch("CUT",{target:[{left:s?i+r:0,right:s?o+r:l.cols.length-1,top:s?0:i+a,bottom:s?l.rows.length-1:o+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],i=e.elements[e.elements.length-1],o=e.sheetId,n=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;return n(o,s-1,s)||n(o,i,i+1)||n(o,e.base-1,e.base)?2:0}drawGrid(e){if("inactive"!==this.getters.getEditionMode())return;const{viewport:t,ctx:s,thinLineWidth:i}=e,o=this.getSelectedZones();s.fillStyle="#f3f7fe";const n=1===o.length&&o[0].left===o[0].right&&o[0].top===o[0].bottom;s.fillStyle=n?"#f3f7fe":"#e9f0ff",s.strokeStyle=p,s.lineWidth=1.5*i,s.globalCompositeOperation="multiply";for(const e of o){const[i,o,n,r]=this.getters.getRect(e,t);s.fillRect(i,o,n,r),s.strokeRect(i,o,n,r)}s.globalCompositeOperation="source-over";const r=this.getters.getActiveSheetId(),[a,l]=this.getPosition();let c;s.strokeStyle=p,s.lineWidth=3*i,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)}}Ih.layers=[5],Ih.modes=["normal"],Ih.getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getAggregate","getSelectedFigureId","getVisibleFigures","getSelection","getPosition","getSheetPosition","getSelectionMode","isSelected","getElementsFromSelection"];const yh=a("The cell you are trying to edit has been deleted.");class wh extends mh{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()===Ch.expanding?this.insertSelectedRange():this.replaceAllSelectedRanges();break;case"SET_SELECTION":e.strict?this.getters.getSelectionMode()===Ch.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=>"SYMBOL"===e.type)).find((t=>{let s=t.value;const{xc:i,sheetName:o}=Jt(s),n=o||this.getters.getSheetName(this.sheet),r=this.getters.getActiveSheetId();return Ds(this.getters.expandZone(r,_s(i)),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.notifyUser(yh))}}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.notifyUser(yh);const{top:t,left:s}=Fs({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.notifyUser(yh);const{top:t,left:s}=Fs({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}=ks({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[i,o]=this.getters.getPosition();this.col=i,this.row=o,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,i]=this.getters.getMainCell(t,this.col,this.row);let o=this.currentContent;if(!(this.initialContent!==o))return;if(o){const t=this.getters.getCell(e,s,i);if(o.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&&(o+=new Array(s).fill(")").join(""))}else(null==t?void 0:t.isLink())&&(o=ys(o,t.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheet,col:s,row:i,content:o})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheet,content:"",col:s,row:i});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 i=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(i||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?Br(e):[],this.currentTokens.length>100&&s&&this.ui.notifyUser(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 i=this.getters.zoneToXC(s,e,t);if(this.getters.getEditionSheet()!==this.getters.getActiveSheetId()){i=`${us(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${i}`}return i}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),i=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:s,selection:{start:i,end:i}})}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=[],t={};for(let s of this.currentTokens.filter((e=>"SYMBOL"===e.type))){let i=s.value;const{xc:o,sheetName:n}=Jt(i);if(Qt.test(o)){const s=(n?`${n}!`:`${this.getters.getSheetName(this.getters.getEditionSheet())}!`)+o.replace(/\$/g,"");e.push(s);const i=this.colorIndexByRange[s];void 0!==i&&(t[s]=i)}}this.colorIndexByRange=t;let s=Object.values(t),i=0;return e.map((e=>{if(void 0===this.colorIndexByRange[e]){for(;s.includes(i);)i++;s.push(i),this.colorIndexByRange[e]=i}return[e,Wt[this.colorIndexByRange[e]%Wt.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,i=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(i.type);){if("SPACE"!==i.type||s<1)return!1;s--,i=this.currentTokens[s]}for(s=t+1,i=this.currentTokens[s];i&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(i.type);){if("SPACE"!==i.type)return!1;s++,i=this.currentTokens[s]}s++,i=this.currentTokens[s]}return!0}return!1}}wh.getters=["getEditionMode","isSelectingForComposer","getCurrentContent","getEditionSheet","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights"],wh.modes=["normal"];const xh=ir.mapping;class Th extends mh{constructor(e,t,s,i){super(e,t,s,i),this.isUpToDate=new Set,this.evalContext=i.evalContext,i.dataSources.on("data-loaded",this,(()=>{this.dispatch("EVALUATE_CELLS",{sheetId:this.getters.getActiveSheetId()})}))}handle(e){switch(ke.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()){let s=Vr(e);const i=Dr(s),o=this.getFormulaParameters((()=>{})),n=[];for(let e of s.dependencies.references)n.push(this.getters.getRangeFromSheetXC(t,e));return i({...s.dependencies,references:n},t,...o)}getRangeFormattedValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[[]]:zs(e.zone,t,(e=>this.getters.getCellText(e,this.getters.shouldShowFormulas())),"")}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[[]]:zs(e.zone,t,(e=>e.evaluated.value))}evaluate(e){const t=this.getters.getCells(e),s=this.getFormulaParameters(o),i={};for(let s of Object.values(t))o(s,e);function o(e,t){if(!e.isFormula())return;const o=e.id;if(o in i)null===i[o]&&e.assignError("#CYCLE",a("Circular reference"));else{i[o]=null;try{if(s[2].__originCellXC=()=>{const e=s[2].getters.getCellPosition(o);return ss(e.col,e.row)},e.assignValue(e.compiledFormula(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 i=s[2].__lastFnCalled||"";t.assignError("#ERROR",e.message.replace("[[FUNCTION_NAME]]",i))}}(t,e)}i[o]=!0}}}getFormulaParameters(e){const t=Object.assign(Object.create(xh),this.evalContext,{getters:this.getters}),s=this.getters.getEvaluationSheets();function i(t,s){if(e(t,s),t.evaluated.type===Ne.error)throw new Error(a("This formula depends on invalid values"));return t.evaluated.value}function o(e){const o=s[e.sheetId];if(!Os(e.zone))throw new Error(a("Invalid reference"));const n={top:0,bottom:o.rows.length-1,left:0,right:o.cols.length-1},r=[],l=function(e,t){if(Ps(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 o=[];for(let n=l.top;n<=l.bottom;n++){const r=t.getters.getCell(e.sheetId,s,n);o.push(r?i(r,e.sheetId):void 0)}r.push(o)}return r}return[function(e,o,n,r,l,c){const h=o[e];if(r)return t.getters.getRangeString(h,n);if(!Os(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){var t;let o;const n=s[e.sheetId];if(!n)throw new Error(a("Invalid sheet name"));return o=null===(t=n.rows[e.zone.top])||void 0===t?void 0:t.cells[e.zone.left],!o||o.isEmpty()?null:i(o,e.sheetId)}(h)},function(e,t,s){return o(t[e])},t]}evaluateAllSheets(){for(const e of this.getters.getVisibleSheets())this.evaluate(e),this.isUpToDate.add(e)}}Th.getters=["evaluateFormula","getRangeFormattedValues","getRangeValues"],Th.modes=["normal"];const Rh=["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 Lh{constructor(){this.graphColorIndex=0}next(){return Rh[this.graphColorIndex++%Rh.length]}}class Mh extends mh{constructor(){super(...arguments),this.chartRuntime={},this.outOfDate=new Set}handle(e){if(ke.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 i={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?(i.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2}}],yAxes:[{position:e.verticalAxisPosition,ticks:{beginAtZero:!0}}]},"bar"===e.type&&e.stackedBar&&(i.options.scales.xAxes[0].stacked=!0,i.options.scales.yAxes[0].stacked=!0)):i.options.tooltips={callbacks:{title:function(e,t){return t.datasets[e[0].datasetIndex].label}}},i}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).flat(1));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=fs(0,this.getData(e.dataSets[0],e.sheetId).length).map((e=>e.toString()))}const s=this.getDefaultConfiguration(e,t),i=new Lh,o=[];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++)o.push(i.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=`${ac.Series} ${parseInt(t)+1}`}else r=r=`${ac.Series} ${parseInt(t)+1}`;const a="pie"!==e.type?i.next():"#FFFFFF",l={label:r,data:n.dataRange?this.getData(n,e.sheetId):[],lineTension:0,borderColor:a,backgroundColor:a};"pie"===e.type&&(l.backgroundColor=o),s.data.datasets.push(l)}return s}getData(e,t){if(e.dataRange){const t=e.labelCell?[Ns(e.labelCell.zone)]:[],s=Bs([Ns(e.dataRange.zone)],t)[0];if(void 0===s)return[];const i=this.getters.getRangeFromSheetXC(e.dataRange.sheetId,s);return this.getters.getRangeValues(i).flat(1)}return[]}}Mh.getters=["getChartRuntime"],Mh.modes=["normal"];class Ah extends mh{constructor(){super(...arguments),this.isStale=!0,this.computedStyles={},this.computedIcons={},this.rulePredicate={CellIsRule:(e,t)=>{if(e&&e.evaluated.type===Ne.error)return!1;const s=t.values.map(Gr);switch(t.operator){case"IsEmpty":return!Ls(e)||""===e.evaluated.value.toString().trim();case"IsNotEmpty":return Ls(e)&&""!==e.evaluated.value.toString().trim();case"BeginsWith":return!(!e&&""===s[0])&&(Ls(e)&&(null==e?void 0:e.evaluated.value.toString().startsWith(s[0].toString())));case"EndsWith":return!(!e&&""===s[0])&&(Ls(e)&&e.evaluated.value.toString().endsWith(s[0].toString()));case"Between":return Ls(e)&&e.evaluated.value>=s[0]&&e.evaluated.value<=s[1];case"NotBetween":return!(Ls(e)&&e.evaluated.value>=s[0]&&e.evaluated.value<=s[1]);case"ContainsText":return Ls(e)&&e.evaluated.value.toString().indexOf(s[0].toString())>-1;case"NotContains":return!Ls(e)||!e.evaluated.value||-1==e.evaluated.value.toString().indexOf(s[0].toString());case"GreaterThan":return Ls(e)&&e.evaluated.value>s[0];case"GreaterThanOrEqual":return Ls(e)&&e.evaluated.value>=s[0];case"LessThan":return Ls(e)&&e.evaluated.value<s[0];case"LessThanOrEqual":return Ls(e)&&e.evaluated.value<=s[0];case"NotEqual":return!(!Ls(e)&&""===s[0])&&(Ls(e)&&e.evaluated.value!==s[0]);case"Equal":return!e&&""===s[0]||Ls(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(),i=this.getters.getRulesByCell(s,e.originCol,e.originRow);for(const t of i)this.adaptRules(s,t,[ss(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 i=this.getters.getActiveSheetId(),o=this.computedStyles[i];return o&&(null===(s=o[e])||void 0===s?void 0:s[t])}getConditionalIcon(e,t){var s;const i=this.getters.getActiveSheetId(),o=this.computedIcons[i];return o&&(null===(s=o[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 i of this.getters.getConditionalFormats(t))try{switch(i.rule.type){case"ColorScaleRule":for(let e of i.ranges)this.applyColorScale(e,i.rule);break;case"IconSetRule":for(let e of i.ranges)this.applyIcon(e,i.rule);break;default:for(let o of i.ranges){const n=_s(o);for(let o=n.top;o<=n.bottom;o++)for(let r=n.left;r<=n.right;r++){const n=this.rulePredicate[i.rule.type];let a=this.getters.getCell(t,r,o);n&&n(a,i.rule)&&(s[r]||(s[r]=[]),s[r][o]=Object.assign((null===(e=s[r])||void 0===e?void 0:e[o])||{},i.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 i=this.getters.evaluateFormula(`=min(${e})`);return i+(this.getters.evaluateFormula(`=max(${e})`)-i)*Number(t.value)/100;case"percentile":return this.getters.evaluateFormula(`=PERCENTILE(${e},${Number(t.value)/100})`);case"formula":const o=t.value&&this.getters.evaluateFormula(t.value);return o instanceof Promise?null:o;default:return null}}applyIcon(e,t){const s=this.parsePoint(e,t.lowerInflectionPoint),i=this.parsePoint(e,t.upperInflectionPoint);if(null===s||null===i||s>i)return;const o=_s(e),n=this.getters.getActiveSheetId(),r=this.computedIcons[n],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=o.top;e<=o.bottom;e++)for(let l=o.left;l<=o.right;l++){const o=this.getters.getCell(n,l,e);if((null==o?void 0:o.evaluated.type)!==Ne.number)continue;const c=this.computeIcon(o.evaluated.value,i,t.upperInflectionPoint.operator,s,t.lowerInflectionPoint.operator,a);r[l]||(r[l]=[]),r[l][e]=c}}computeIcon(e,t,s,i,o,n){return"ge"===s&&e>=t||"gt"===s&&e>t?n[0]:"ge"===o&&e>=i||"gt"===o&&e>i?n[1]:n[2]}applyColorScale(e,t){var s;const i=this.parsePoint(e,t.minimum,"min"),o=t.midpoint?this.parsePoint(e,t.midpoint):null,n=this.parsePoint(e,t.maximum,"max");if(null===i||null===n||i>=n||o&&(i>=o||o>=n))return;const r=_s(e),a=this.getters.getActiveSheetId(),l=this.computedStyles[a],c=[];t.midpoint&&o?(c.push({minValue:i,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,o,t.minimum.color,t.midpoint.color)}),c.push({minValue:o,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(o,n,t.midpoint.color,t.maximum.color)})):c.push({minValue:i,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,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)===Ne.number){const a=ps(r.evaluated.value,i,n);let h;h=2===c.length&&o?a<=o?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="#"+qt(h)}}}computeColorDiffUnits(e,t,s,i){const o=t-e;return[((s>>16)%256-(i>>16)%256)/o,((s>>8)%256-(i>>8)%256)/o,(s%256-i%256)/o]}colorCell(e,t,s,i){const[o,n,r]=i;return Math.round((s>>16)%256-o*(e-t))<<16|Math.round((s>>8)%256-n*(e-t))<<8|Math.round(s%256-r*(e-t))}adaptRules(e,t,s,i){if(0===s.length&&0===i.length)return;const o=this.getters.getConditionalFormats(e),n=o.findIndex((e=>e.id===t.id));let r=[];n>-1&&(r=o[n].ranges),r=r.concat(s);const a=Bs(r,i);this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:t.id,rule:t.rule,stopIfTrue:t.stopIfTrue},target:a.map(_s),sheetId:e})}pasteCf(e,t,s){const i=ss(t.col,t.row);for(let o of this.getters.getConditionalFormats(e.sheetId))for(let n of o.ranges)if(Us(e.col,e.row,_s(n))){const n=o,r=[];"CUT"===s&&r.push(ss(e.col,e.row)),e.sheetId===t.sheetId?this.adaptRules(e.sheetId,n,[i],r):(this.adaptRules(t.sheetId,n,[i],[]),this.adaptRules(e.sheetId,n,[],r))}}}Ah.getters=["getConditionalStyle","getConditionalIcon"],Ah.modes=["normal"];var _h;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(_h||(_h={}));class Oh extends mh{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(_h.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(_h.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(_h.current)}updateRegex(){let e=hs(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),i={col:t.col,row:t.row,selected:!1};s.push(i)}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],i=this.getters.getActiveSheetId(),o=this.getters.getCell(i,s.col,s.row),n=this.toReplace(o,i);if(o&&n){const t=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),i=n.toString().replace(t,e);this.dispatch("UPDATE_CELL",{sheetId:this.getters.getActiveSheetId(),col:s.col,row:s.row,content:i}),this.searchMatches.splice(this.selectedMatchIndex,1),this.selectNextCell(_h.current)}else this.selectNextCell(_h.next)}replaceAll(e,t){const s=this.searchMatches.length;for(let i=0;i<s;i++)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,i=this.getters.getActiveSheetId();for(const e of this.searchMatches){const o=this.getters.getMerge(i,e.col,e.row),n=o?o.left:e.col,r=o?o.right:e.col,a=o?o.top:e.row,l=o?o.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)))}}}Oh.layers=[3],Oh.getters=["getSearchMatches","getCurrentSelectedMatchIndex"];class Nh extends mh{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,s){const i=this.searchNumberFormat(e,t);if(void 0!==i){const o=this.changeDecimalFormat(i,s);this.dispatch("SET_FORMATTING",{sheetId:e,target:t,format:o})}}searchNumberFormat(e,t){var s;for(let i of t)for(let t=i.top;t<=i.bottom;t++)for(let o=i.left;o<=i.right;o++){const i=this.getters.getCell(e,o,t);if((null==i?void 0:i.evaluated.type)===Ne.number&&!(null===(s=i.format)||void 0===s?void 0:s.match(A)))return i.format||this.setDefaultNumberFormat(i.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),i=e.split(";");let o=[];for(let e of i){const t=e.indexOf("."),i=e.toUpperCase().indexOf("E");let n;const r=i>-1?e.slice(0,i):e,a=t>-1?r.slice(t).match(/0/g).length:0,l=r.lastIndexOf("0");l>-1?s>0?n=a<oe?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,o.push(n)}return o.join(";")}}Nh.modes=["normal"];class kh extends mh{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[i,o]of e){const{xc:e,sheetName:n}=Jt(i),r=n?this.getters.getSheetIdByName(n):t;if(r){let i=_s(e);const{height:n,width:a}=Hs(i);i=n*a==1?this.getters.expandZone(t,_s(e)):i,s.push({zone:i,color:o,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:i}=e,o=this.getters.getActiveSheetId(),n=3*i;t.lineWidth=n;for(let e of this.getHighlights().filter(((e,t)=>this.getHighlights().findIndex((t=>Ds(t.zone,e.zone)&&t.sheet===o))===t))){const[i,o,r,a]=this.getters.getRect(e.zone,s);r>0&&a>0&&(t.strokeStyle=e.color,t.strokeRect(i+n/2,o+n/2,r-n,a-n),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(i+n,o+n,r-2*n,a-2*n))}}}function Fh(e,t){return e.isFormula()&&t?"left":e.defaultAlign}function $h(e,t){let s=0,i=e.length-1;for(;s<=i;){const o=Math.floor((s+i)/2),n=e[o];if(t<n.start)i=o-1;else if(t>n.end)s=o+1;else{if(!n.isHidden)return o;s+=1}}return-1}kh.modes=["normal"],kh.layers=[1],kh.getters=["getHighlights"];class Dh extends mh{constructor(){super(...arguments),this.boxes=[]}getColIndex(e,t,s){if(e<m)return-1;const i=(s||this.getters.getActiveSheet()).cols;return $h(i,e-m+i[t].start+1)}getRowIndex(e,t,s){if(e<f)return-1;const i=(s||this.getters.getActiveSheet()).rows;return $h(i,e-f+i[t].start+1)}getRect(e,t){const{left:s,top:i,right:o,bottom:n}=e;let{offsetY:r,offsetX:a}=t;a-=m,r-=f;const{cols:l,rows:c}=this.getters.getActiveSheet(),h=Math.max(l[s].start-a,m),d=l[o].end-a-h,u=Math.max(c[i].start-r,f);return[h,u,d,c[n].end-r-u]}isVisibleInViewport(e,t,s){const{right:i,left:o,top:n,bottom:r}=s;return t<=r&&t>=n&&e>=o&&e<=i}getEdgeScrollCol(e){let t=!1,s=0,i=0;const{width:o}=this.getters.getViewportDimension(),{width:n}=this.getters.getGridDimension(this.getters.getActiveSheet()),{left:r,offsetX:a}=this.getters.getActiveSnappedViewport();return e<m&&r>0?(t=!0,s=-1,i=rs(m-e)):e>o&&a<n-o&&(t=!0,s=1,i=rs(e-o)),{canEdgeScroll:t,direction:s,delay:i}}getEdgeScrollRow(e){let t=!1,s=0,i=0;const{height:o}=this.getters.getViewportDimension(),{height:n}=this.getters.getGridDimension(this.getters.getActiveSheet()),{top:r,offsetY:a}=this.getters.getActiveSnappedViewport();return e<f&&r>0?(t=!0,s=-1,i=rs(f-e)):e>o&&a<n-o&&(t=!0,s=1,i=rs(e-o)),{canEdgeScroll:t,direction:s,delay:i}}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,viewport:s,thinLineWidth:i}=e;let{offsetX:o,offsetY:n,top:r,left:a,bottom:l,right:c}=s;const{width:h,height:d}=this.getters.getViewportDimension(),{cols:u,rows:p,id:g}=this.getters.getActiveSheet();if(t.fillStyle="white",t.fillRect(0,0,h,d),o-=m,n-=f,!this.getters.getGridLinesVisibility(g))return;t.lineWidth=2*i,t.strokeStyle="#E2E3E3",t.beginPath();const v=Math.min(d,p[l].end-n);for(let e=a;e<=c;e++){if(u[e].isHidden)continue;const s=u[e].end-o;t.moveTo(s,0),t.lineTo(s,v)}const E=Math.min(h,u[c].end-o);for(let e=r;e<=l;e++){if(p[e].isHidden)continue;const s=p[e].end-n;t.moveTo(0,s),t.lineTo(E,s)}t.stroke()}drawCellBackground(e){const{ctx:t,thinLineWidth:s}=e;t.lineWidth=.3*s;const i=.1*s;t.strokeStyle="#111";const o=this.getters.getGridLinesVisibility(this.getters.getActiveSheetId());for(let e of this.boxes){let s=e.style;s&&s.fillColor&&"#ffffff"!==s.fillColor&&(t.fillStyle=s.fillColor,t.fillRect(e.x,e.y,e.width,e.height),o&&t.strokeRect(e.x+i,e.y+i,e.width-2*i,e.height-2*i)),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:o,width:n,height:r}=e;t.left&&i(t.left,s,o,s,o+r),t.top&&i(t.top,s,o,s+n,o),t.right&&i(t.right,s+n,o,s+n,o+r),t.bottom&&i(t.bottom,s,o+r,s+n,o+r)}}function i([e,i],o,n,r,a){t.strokeStyle=i,t.lineWidth=("thin"===e?2:3)*s,t.beginPath(),t.moveTo(o,n),t.lineTo(r,a),t.stroke()}}drawTexts(e){const{ctx:t,thinLineWidth:s}=e;let i;t.textBaseline="middle";for(let e of this.boxes)if(e.text){const o=e.style||{},n=e.align,r=o.italic?"italic ":"",a=o.bold?"bold":x,l=o.fontSize||T,c=ls[l],h=`${r}${a} ${c}px ${R}`;let d;h!==i&&(i=h,t.font=h),t.fillStyle=o.textColor||"#000";let u=e.y+e.height/2+1;d="left"===n?e.x+(e.image?e.image.size+2*I: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.text,Math.round(d),Math.round(u)),(o.strikethrough||o.underline)&&("right"===n?d-=e.textWidth:"center"===n&&(d-=e.textWidth/2),o.strikethrough&&t.fillRect(d,u,e.textWidth,2.6*s),o.underline&&(u=e.y+e.height/2+1+c/2,t.fillRect(d,u,e.textWidth,1.3*s))),e.clipRect&&t.restore()}}async drawIcon(e){const{ctx:t}=e;for(let e of this.boxes)if(e.image){let s=e.x,i=e.y;const o=e.image.image,n=e.image.size,r=(e.height-n)/2;e.image.clipIcon&&(t.save(),t.beginPath(),t.rect(...e.image.clipIcon),t.clip()),t.drawImage(o,s+I,i+r,n,n),e.image.clipIcon&&t.restore()}}drawHeaders(e){const{ctx:t,viewport:s,thinLineWidth:i}=e;let{offsetX:o,offsetY:n,left:r,top:a,right:l,bottom:p}=s;const{width:g,height:v}=this.getters.getViewportDimension();o-=m,n-=f;const E=this.getters.getSelectedZones(),{cols:b,rows:S}=this.getters.getActiveSheet(),C=this.getters.getActiveCols(),I=this.getters.getActiveRows();t.fillStyle=c,t.font=`400 11px ${R}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=i,t.strokeStyle="#333",t.fillRect(0,0,g,f),t.fillRect(0,0,m,v),t.fillStyle=h;for(let e of E){const s=Math.max(m,b[e.left].start-o),i=Math.max(m,b[e.right].end-o),r=Math.max(f,S[e.top].start-n),a=Math.max(f,S[e.bottom].end-n);t.fillStyle=C.has(e.left)?d:h,t.fillRect(s,0,i-s,f),t.fillStyle=I.has(e.top)?d:h,t.fillRect(0,r,m,a-r)}t.beginPath(),t.moveTo(m,0),t.lineTo(m,v),t.moveTo(0,f),t.lineTo(g,f),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(let e=r;e<=l;e++){const s=b[e];s.isHidden||(t.fillStyle=C.has(e)?"#fff":u,t.fillText(s.name,(s.start+s.end)/2-o,13),t.moveTo(s.end-o,0),t.lineTo(s.end-o,f))}for(let e=a;e<=p;e++){const s=S[e];s.isHidden||(t.fillStyle=I.has(e)?"#fff":u,t.fillText(s.name,24,(s.start+s.end)/2-n),t.moveTo(0,s.end-n),t.lineTo(m,s.end-n))}t.stroke()}hasContent(e,t){const s=this.getters.getActiveSheetId(),i=this.getters.getCell(s,e,t);return i&&!i.isEmpty()||this.getters.isInMerge(s,e,t)}getGridBoxes(e){const{viewport:t}=e;let{right:s,left:i,top:o,bottom:n,offsetX:r,offsetY:a}=t;r-=m,a-=f;const l=this.getters.shouldShowFormulas(),c=[],{cols:h,rows:d,id:u}=this.getters.getActiveSheet();for(let e=o;e<=n;e++){const t=d[e];if(!t.isHidden)for(let o=i;o<=s;o++){const n=h[o];if(n.isHidden)continue;let d=t.cells[o];const p=this.getters.getCellBorder(u,o,e),g=this.getters.getConditionalStyle(o,e),f=this.getters.getConditionalIcon(o,e);if(!this.getters.isInMerge(u,o,e))if(d){const u=this.getters.getCellText(d,l);let m=this.getters.getCellStyle(d);g&&(m=Object.assign({},m,g));let v=u?m&&m.align||Fh(d,l):void 0,E=null,b=null;const S=this.getters.getTextWidth(d),C=m.fontSize||T,y=ls[C],w=f?y+2*I:0,x=w+S>h[o].size||ls[C]>t.size;if(x&&d.evaluated.type===Ne.number&&(v="center"!==v?"left":v),f){const e=n.end-n.start;E=[n.start-r+w,t.start-a,Math.max(0,e-w),t.size],b=[n.start-r,t.start-a,Math.min(w,e),t.size]}else if(x){let l,c;switch(v){case"left":for(l=o;l<s&&!this.hasContent(l+1,e);)l++;c=h[l].end-n.start,(c<S||ls[C]>t.size)&&(E=[n.start-r,t.start-a,c,t.size]);break;case"right":for(l=o;l>i&&!this.hasContent(l-1,e);)l--;c=n.end-h[l].start,(c<S||ls[C]>t.size)&&(E=[h[l].start-r,t.start-a,c,t.size]);break;case"center":let d=o;for(;d>i&&!this.hasContent(d-1,e);)d--;let u=o;for(;u<s&&!this.hasContent(u+1,e);)u++;const p=Math.min(d,o),g=Math.max(u,o);c=h[g].end-h[p].start,(c<S||p===o||g===o||ls[C]>t.size)&&(E=[h[p].start-r,t.start-a,c,t.size])}}c.push({x:n.start-r,y:t.start-a,width:n.size,height:t.size,text:u,textWidth:S,border:p,style:m,align:v,clipRect:E,error:d.evaluated.type===Ne.error?d.evaluated.error:void 0,image:f?{type:"icon",size:y,clipIcon:b,image:Ul[f].img}:void 0})}else c.push({x:n.start-r,y:t.start-a,width:n.size,height:t.size,text:"",textWidth:0,border:p,style:g||null,align:void 0,clipRect:null,error:void 0})}}const p=this.getters.getActiveSheetId();for(let e of this.getters.getMerges(p))if(!this.getters.isMergeHidden(p,e)&&Ps(e,t)){const t=this.getters.getCell(p,e.left,e.top),s=this.getters.getCellBorder(p,e.left,e.top),i=this.getters.getCellBorder(p,e.right,e.bottom),o=h[e.right].end-h[e.left].start;let n,u,g,f,m;if(g=t?this.getters.getCellStyle(t):null,t||i||s){n=t?this.getters.getCellText(t,l):"",u=t?this.getters.getTextWidth(t):null;const o=this.getters.getConditionalStyle(e.topLeft.col,e.topLeft.row);o&&(g=Object.assign({},g,o)),f=n?g&&g.align||Fh(t,l):null,m={bottom:i?i.bottom:null,left:s?s.left:null,right:i?i.right:null,top:s?s.top:null}}g=g||{},g.fillColor&&"#ffffff"!==g.fillColor||(g=Object.create(g),g.fillColor="#fff");const v=h[e.left].start-r,E=d[e.top].start-a,b=d[e.bottom].end-d[e.top].start,S=this.getters.getConditionalIcon(e.left,e.top),C=g.fontSize||T,y=ls[C],w=S?2*I+y:0,x=w+u;f=n&&(null==t?void 0:t.evaluated.type)===Ne.number&&x>o&&"center"!==f?"left":f;const R=S?[v+w,E,Math.max(0,o-w),b]:[v,E,o,b],L=S?[v,E,Math.min(w,o),b]:null;c.push({x:v,y:E,width:o,height:b,text:n,textWidth:u,border:m,style:g,align:f,clipRect:R,error:t&&t.evaluated.type===Ne.error?t.evaluated.error:void 0,image:S?{type:"icon",clipIcon:L,size:y,image:Ul[S].img}:void 0})}return c}}Dh.layers=[0,7],Dh.getters=["getColIndex","getRowIndex","getRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow"],Dh.modes=["normal"];const Ph=new ti;class Uh extends mh{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 i=e.value.split(",").map((e=>e.trim()));this.setRange(s,t,i)}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),i=(this.inputHasSingleRange[this.focusedInputId]?[this.getters.getSelectedZone()]:this.getters.getSelectedZones()).map(Ns).filter((e=>!s.includes(e))),o=this.activeSheets[this.focusedInputId],n=this.getters.getActiveSheetId(),r=this.getters.getSheetName(n);this.add(i.map((e=>n===o?e:`${us(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}=Jt(e);return null!==t.match(Qt)&&(!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()===Ch.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:Ph.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:Xt()}))))}setRange(e,t,s){const[,...i]=s;this.setContent(e,t,s[0]),this.insertNewRange(e,t+1,i),i.length&&this.focus(e,t+i.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 i=this.cleanInputs([t]).filter((e=>this.isRangeValid(e))).filter((t=>this.shouldBeHighlighted(this.activeSheets[e],t)));if(0===i.length)return[];const[o,...n]=i,r=[[o,s||Xt()]];for(const e of n)r.push([e,Xt()]);return r}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:s}=Jt(t),i=this.getters.getSheetIdByName(s),o=this.getters.getActiveSheet().id;return this.isRangeValid(t)&&(i===o||void 0===i&&o===e)}getIndex(e,t){const s=this.inputs[e].findIndex((e=>e.id===t));return s>=0?s:null}}Uh.modes=["normal"],Uh.layers=[1],Uh.getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];class Bh{constructor(){this.bus=new i.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 Vh(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?function(e,t,s){const i="left"===t?"right":"bottom";let o=e[t],n=e[i];for(let r of s.sort(((e,t)=>t-e)))e[t]>r&&(o--,n--),e[t]<=r&&e[i]>=r&&n--;if(!(o>n))return{...e,[t]:o,[i]:n}}(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?function(e,t,s,i,o){const n="left"===t?"columns":"rows",r="before"===i?s-1:s,a="left"===t?"right":"bottom",l="before"===i?e[a]>r:e[a]>=r;return e[t]<=r&&l?Ws(e,n,"RESIZE",o):r<e[t]?Ws(e,n,"MOVE",o):{...e}}(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}function zh(e,t){const s=e.definition;let i,o;return s.labelRange&&(i=Vh(_s(s.labelRange),t)),s.dataSets&&(o=s.dataSets.map(_s).map((e=>Vh(e,t))).filter(Ls).map(Ns)),{...e,definition:{...s,dataSets:o,labelRange:i?Ns(i):void 0}}}dl.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],zh),dl.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],zh),dl.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),dl.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})),dl.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const s=[];for(const i of e.target)for(const e of t.target)Ps(i,e)||s.push({...i});if(s.length)return{...e,target:s};return}));const Hh=[{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 i of e.target){const e=Vh(i,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 i=e[s];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(i))return"IGNORE_COMMAND";for(let t of e)i>=t&&i--}"ADD_COLUMNS_ROWS"===t.type&&(i>t.base||i===t.base&&"before"===t.position)&&(i+=t.quantity);return{...e,[s]:i}}(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)&&Us(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,i=s?"base":"elements";let o=s?[e[i]]:e[i];if("REMOVE_COLUMNS_ROWS"===t.type&&(o=o.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(Ls)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;o=o.map((s=>s>e?s+t.quantity:s))}if(o.length){let t=o;return s&&(t=o[0]),{...e,[i]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}}];function Zh(e,t){const s=dl.getTransformation(e.type,t.type);return s?s(e,t):function(e,t){for(const{match:s,fn:i}of Hh)if(s(e)){const s=i(e,t);if("SKIP_TRANSFORMATION"===s)continue;if("IGNORE_COMMAND"===s)return;return s}return e}(e,t)}function Gh(e,t){let s=[...e];for(const e of t)s=s.map((t=>Zh(t,e))).filter(Ls);return s}class Wh{constructor(e,t,s,i){this._commands=[],this._changes=[],this.id=e,this.clientId=t,this._commands=[...s],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class qh extends Error{}class jh extends Bh{constructor(e,t,s=O){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 ti,this.debouncedMove=i.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 Wh(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,this.on("unexpected-revision-id",this,(({revisionId:e})=>{throw new Error(`The spreadsheet could not be loaded. Revision ${e} is corrupted.`)}));for(const t of e)this.onMessageReceived(t);this.off("unexpected-revision-id",this),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 qh("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(Ls))}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 i=s?"CLIENT_MOVED":"CLIENT_JOINED",o=this.getClient();this.clients[this.clientId]={...o,position:e},this.transportService.sendMessage({type:i,version:1,client:{...o,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){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":if(e.serverRevisionId!==this.serverRevisionId)return void this.trigger("unexpected-revision-id",{revisionId:e.serverRevisionId});const{clientId:t,commands:s}=e,i=new Wh(e.nextRevisionId,t,s);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:Gh(s,t)})}break;case"SNAPSHOT_CREATED":{const t=new Wh(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}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter((({type:e})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const Xh=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];class Yh extends mh{constructor(){super(...arguments),this.availableColors=new Set(Xh),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(Xh));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 qh)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 i=this.colors[s.id];t.push({...s,position:e,color:i})}return t}drawGrid(e){const{viewport:t,ctx:s,thinLineWidth:i}=e,o=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:n,col:r}=e.position,a=this.getters.expandZone(o,{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*i,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 ${T+1}px ${R}`}}}Yh.getters=["getClientsToDisplay"],Yh.layers=[5],Yh.modes=["normal"];class Kh extends mh{allowDispatch(e){if("SORT_CELLS"===e.type){if(!Us(e.anchor[0],e.anchor[1],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)e.interactive?this.interactiveSortSelection(e.sheetId,e.anchor,e.zone,e.sortDirection):this.sortZone(e.sheetId,e.anchor,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 i=t.left;i<=t.right;i++)if(!this.getters.isInMerge(e,i,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=>Ps(e,t))),i=Hs(s[0]);let[o,n]=[i.width,i.height];return s.every((e=>{let[t,s]=[e.right-e.left+1,e.bottom-e.top+1];return t===o&&s===n}))?0:48}interactiveSortSelection(e,t,s,i){let o=Pe.Success,n=s.right>s.left;if(this.getters.doesIntersectMerge(e,s)){let t;n=!1;for(let i=s.top;i<=s.bottom;i++){t=[];for(let o=s.left;o<=s.right;o++){let s=this.getters.getMerge(e,o,i);s&&!t.includes(s.id.toString())&&t.push(s.id.toString())}if(t.length>=2){n=!0;break}}}if(n)o=this.dispatch("SORT_CELLS",{sheetId:e,anchor:t,zone:s,sortDirection:i});else{const n=this.getContiguousZone(e,s);Ds(n,s)?o=this.dispatch("SORT_CELLS",{sheetId:e,anchor:t,zone:s,sortDirection:i}):this.ui.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?"),(()=>{s=n,o=this.dispatch("SORT_CELLS",{sheetId:e,anchor:t,zone:s,sortDirection:i})}),(()=>{o=this.dispatch("SORT_CELLS",{sheetId:e,anchor:t,zone:s,sortDirection:i})}))}o.isCancelledBecause(48)&&(this.dispatch("SET_SELECTION",{anchor:t,zones:[s],anchorZone:s}),this.ui.notifyUser(a("Cannot sort. To sort, select only cells or only merges that have the same size.")))}expand(e,t){const{left:s,right:i,top:o,bottom:n}=this.getters.expandZone(e.id,t);return{left:Math.max(0,s),right:Math.min(e.cols.length-1,i),top:Math.max(0,o),bottom:Math.min(e.rows.length-1,n)}}checkExpandedValues(e,t){const s=this.expand(e,t),i=e.id;let o,n=[];if(this.getters.doesIntersectMerge(i,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(i,s,e);o=this.getters.getCell(i,t,r),n.push((null==o?void 0:o.formattedValue)||"")}}else{const t=zs(s,e,(e=>e.formattedValue),"");n=t.flat()}return n.some((e=>""!==e))}getContiguousZone(e,t){let s,{top:i,bottom:o,left:n,right:r}=t;const a=this.getters.getSheet(e);let l=!1;for(;!l;)l=!0,i>0&&(s=this.checkExpandedValues(a,{left:n-1,right:r+1,top:i-1,bottom:i-1}),s&&(l=!1,i--)),n>0&&(s=this.checkExpandedValues(a,{left:n-1,right:n-1,top:i-1,bottom:o+1}),s&&(l=!1,n--)),r<a.cols.length-1&&(s=this.checkExpandedValues(a,{left:r+1,right:r+1,top:i-1,bottom:o+1}),s&&(l=!1,r++)),o<a.rows.length-1&&(s=this.checkExpandedValues(a,{left:n-1,right:r+1,top:o+1,bottom:o+1}),s&&(l=!1,o++));return{left:n,right:r,top:i,bottom:o}}hasHeader(e,t,s,i){const{left:o,right:n,top:r,bottom:a}=t;if(a-r+1==1)return!1;let l=zs({left:o,right:n,top:r,bottom:r+2*i-1},e,(e=>e.evaluated.type),Ne.empty,s,i);return l[0][0]===Ne.empty&&(l=l.slice(1)),!l.some((e=>e[0]===Ne.empty))&&!!l.some((e=>e[1]!==Ne.empty&&e[0]!==e[1]))}sortCellsList(e,t){const s=e.map(((e,t)=>({index:t,val:e}))),i=s.filter((e=>!(null==e.val||""===e.val.evaluated.value))),o=s.filter((e=>null==e.val||""===e.val.evaluated.value)),n="descending"===t?-1:1,r=[Ne.number,Ne.error,Ne.text,Ne.boolean];return i.map((e=>{return{index:e.index,val:(t=e.val,{type:t.evaluated.type,value:t.evaluated.value})};var t})).sort(((e,t)=>{let s=r.indexOf(e.val.type)-r.indexOf(t.val.type);return 0===s&&(s=e.val.type===Ne.text||e.val.type===Ne.error?e.val.value.localeCompare(t.val.value):e.val.value-t.val.value),n*s})).concat(o)}sortZone(e,t,s,i){let o=1,n=1,r=t[0],a=Object.assign({},s);if(this.getters.doesIntersectMerge(e,a)){const[s,i]=t,a=this.getters.getMerge(e,s,i);o=a.right-a.left+1,n=a.bottom-a.top+1,r=a.topLeft.col}const l=this.getters.getSheet(e);this.hasHeader(l,a,o,n)&&(a.top+=n);const c=zs(a,l,(e=>e),void 0,o,n),h=c[r-a.left],d=this.sortCellsList(h,i).map((e=>e.index)),[u,p]=[c.length,c[0].length];for(let t=0;t<u;t++)for(let s=0;s<p;s++){let i=c[t][d[s]],r=a.left+t*o,l=a.top+s*n,h={sheetId:e,col:r,row:l,content:"",value:""};if(i){let t=i.content;if(i.isFormula()){const s=l-this.getters.getCellPosition(i.id).row,o=this.getters.createAdaptedRanges(i.dependencies.references,0,s,e);t=this.getters.buildFormulaContent(e,i.normalizedText,{...i.dependencies,references:o})}h.style=i.style,h.content=t,h.format=i.format,h.value=i.evaluated.value}this.dispatch("UPDATE_CELL",h)}}}Kh.getters=["getContiguousZone"];class Qh extends mh{constructor(){super(...arguments),this.showFormulas=!1}handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}Qh.modes=["normal"],Qh.getters=["shouldShowFormulas"];class Jh extends mh{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}allowDispatch(e){switch(e.type){case"AUTORESIZE_ROWS":case"AUTORESIZE_COLUMNS":case"DELETE_SHEET_CONFIRMATION":try{this.getters.getSheet(e.sheetId);break}catch(e){return 23}}return 0}handle(e){switch(e.type){case"RENAME_SHEET":e.interactive&&this.interactiveRenameSheet(e.sheetId,a("Rename Sheet"));break;case"DELETE_SHEET_CONFIRMATION":this.interactiveDeleteSheet(e.sheetId);break;case"ADD_MERGE":e.interactive&&this.interactiveMerge(e.sheetId,e.target);break;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||T;return ls[s]+2*I}(this.ctx,this.getters.getCellStyle(e))),t}getTextWidth(e){const t=this.getters.getCellText(e,this.getters.shouldShowFormulas());return gs(this.ctx,t,this.getters.getCellStyle(e))}getCellHeight(e){const t=this.getters.getCellStyle(e).fontSize||T;return ls[t]}getCellText(e,t=!1){return t&&(e.isFormula()||e.evaluated.type===Ne.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),i=Object.values(s.rows[t].cells).map((e=>this.getCellHeight(e)));return Math.max(0,...i)}interactiveRenameSheet(e,t){const s=this.getters.getSheetName(e);this.ui.editText(t,s,(t=>{if(!t)return;const s=this.dispatch("RENAME_SHEET",{sheetId:e,name:t}),i=this.getters.getSheetName(e);s.isSuccessful||i===t||this.interactiveRenameSheet(e,a("Please enter a valid sheet name"))}))}interactiveDeleteSheet(e){this.ui.askConfirmation(a("Are you sure you want to delete this sheet ?"),(()=>{this.dispatch("DELETE_SHEET",{sheetId:e})}))}interactiveMerge(e,t){const s=this.dispatch("ADD_MERGE",{sheetId:e,target:t});s.isSuccessful||s.isCancelledBecause(3)&&this.ui.askConfirmation(a("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),(()=>{this.dispatch("ADD_MERGE",{sheetId:e,target:t,force:!0})}))}}Jh.getters=["getCellWidth","getCellHeight","getTextWidth","getCellText"];class ed extends mh{constructor(){super(...arguments),this.viewports={},this.snappedViewports={},this.updateSnap=!1,this.clientWidth=1e3,this.clientHeight=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"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)}getViewportDimension(){return{width:this.clientWidth,height:this.clientHeight}}getActiveViewport(){const e=this.getters.getActiveSheetId();return this.getViewport(e)}getActiveSnappedViewport(){const e=this.getters.getActiveSheetId();return this.getSnappedViewport(e)}getGridDimension(e){const t=oi(e,"cols"),s=this.clientWidth-m,i=oi(e,"rows"),o=this.clientHeight-f,n=e.cols.find((e=>e.end>t.end-s))||e.cols[e.cols.length-1],r=e.rows.find((e=>e.end>i.end-o))||e.rows[e.rows.length-1];return{width:t.end+Math.max(E,Math.min(n.size,s-t.size)),height:i.end+Math.max(b+5,Math.min(r.size,o-i.size))}}getMaximumViewportOffset(e){const{width:t,height:s}=this.getters.getGridDimension(e);return{maxOffsetX:Math.max(0,t-this.clientWidth+m+1),maxOffsetY:Math.max(0,s-this.clientHeight+f+1)}}checkOffsetValidity(e,t){const s=this.getters.getActiveSheet(),{maxOffsetX:i,maxOffsetY:o}=this.getMaximumViewportOffset(s);return e<0||t<0||t>o||e>i?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:i}=this.getGridDimension(this.getters.getSheet(e));if(this.clientWidth-m+s>i){const e=this.clientWidth-m+s-i;t.offsetX=Math.max(0,s-e)}this.adjustViewportZoneX(e,t)}adjustViewportOffsetY(e,t){const{offsetY:s}=t,{height:i}=this.getGridDimension(this.getters.getSheet(e));if(this.clientHeight-f+s>i){const e=this.clientHeight-f+s-i;t.offsetY=Math.max(0,s-e)}this.adjustViewportZoneY(e,t)}resizeViewport(e,t){this.clientHeight=e,this.clientWidth=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])}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),i=s.cols;t.left=this.getters.getColIndex(t.offsetX+m,0,s);const o=this.clientWidth+t.offsetX-m;t.right=i.length-1;for(let e=t.left;e<i.length;e++)if(o<i[e].end){t.right=e;break}this.updateSnap=!0}adjustViewportZoneY(e,t){const s=this.getters.getSheet(e),i=s.rows;t.top=this.getters.getRowIndex(t.offsetY+f,0,s);const o=this.clientHeight+t.offsetY-f;t.bottom=i.length-1;for(let e=t.top;e<i.length;e++)if(o<i[e].end){t.bottom=e;break}this.updateSnap=!0}adjustViewportsPosition(e,t){const s=this.getters.getSheet(e),{cols:i,rows:o}=s,n=this.getSnappedViewport(e);t=t||this.getters.getSheetPosition(e);const[r,a]=si(s,...this.getters.getMainCell(e,t[0],t[1]));for(;i[r].end>n.offsetX+this.clientWidth-m&&n.offsetX<i[r].start;)n.offsetX=i[n.left].end,this.adjustViewportZoneX(e,n);for(;r<n.left;){const t=i.slice(0,n.left).reverse().findIndex((e=>!e.isHidden));n.offsetX=i[n.left-1-t].start,this.adjustViewportZoneX(e,n)}for(;o[a].end>n.offsetY+this.clientHeight-f&&n.offsetY<o[a].start;)n.offsetY=o[n.top].end,this.adjustViewportZoneY(e,n);for(;a<n.top;){const t=o.slice(0,n.top).reverse().findIndex((e=>!e.isHidden));n.offsetY=o[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),i=this.getViewport(e),o=Object.assign({},i);this.adjustViewportOffsetX(e,o),this.adjustViewportOffsetY(e,o),o.offsetX=t[o.left].start,o.offsetY=s[o.top].start,this.adjustViewportZone(e,o),this.snappedViewports[e]=o}}ed.getters=["getActiveViewport","getSnappedViewport","getActiveSnappedViewport","getViewportDimension","getGridDimension","getMaximumViewportOffset"],ed.modes=["normal"];const td=(new Re).add("sheet",ya).add("cell",ma).add("merge",Ca).add("borders",ga).add("conditional formatting",ba).add("figures",Sa).add("chart",va),sd=(new Re).add("selection",Ih).add("ui_sheet",Jh).add("ui_options",Qh).add("evaluation",Th).add("evaluation_cf",Ah).add("evaluation_chart",Mh).add("clipboard",Sh).add("edition",wh).add("highlight",kh).add("selectionInput",Uh).add("viewport",ed).add("grid renderer",Dh).add("autofill",Eh).add("find_and_replace",Oh).add("sort",Kh).add("automatic_sum",bh).add("format",Nh).add("selection_multiuser",Yh);class id{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 od extends i.core.EventBus{constructor(){super(...arguments),this.registry=new Re}add(e,t){this.registry.add(e,t);const s=i.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 nd extends i.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 rd(e){return Ra.get(e.type)(e)}function ad(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class ld{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:i,operation:o,after:n}=this.locateOperation(t);this.operations=[...i,o,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 ld(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 cd{constructor(e,t){this.id=e,this.data=t}transformed(e){return new cd(this.id,e(this.data))}}class hd{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new hd(function*(e,t){for(const s of e)if(yield s,s.operation.id===t)return}(this.operations,e))}stopBefore(e){return new hd(function*(e,t){for(const s of e){if(s.operation.id===t)return;yield s}}(this.operations,e))}startAfter(e){return new hd(function*(e,t){let s=!0;for(const i of e)s||(yield i),i.operation.id===t&&(s=!1)}(this.operations,e))}}class dd{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 hd(vs(this._execution(e),this._execution(e)))}revertedExecution(e){return new hd(vs(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){var s;const i=e.getLastOperationId()||(null===(s=this.previousBranch(e))||void 0===s?void 0:s.getLastOperationId());e.append(t),i&&this.insertPrevious(e,t,i)}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),i=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const o=e.fork(t.id);i&&this.branchingOperationIds.set(o,i),this.insertBranchAfter(e,o),this.transform(o,s)}redo(e){const t=this.nextBranch(e);if(!t)return;const s=this.nextBranch(t);this.removeBranchFromTree(t);const i=this.branchingOperationIds.get(t);i?this.branchingOperationIds.set(e,i):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 i=this.buildTransformation.without(s.data),o=t.fork(s.id);this.branchingOperationIds.set(o,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,o),o.transform(i);const n=this.nextBranch(o);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 i=this.branchingOperationIds.get(e),o=this.nextBranch(e);if(i&&o)if(e.getFirstOperationAmong(s,i)===i){const n=this.addToNextBranch(e,o,i,t,s);this.updateNextWith(o,n,s)}else{const e=this.buildTransformation.with(t.data);this.transform(o,e)}}addToNextBranch(e,t,s,i,o){let n=i;return o===s?(n=this.getTransformedOperation(e,s,i),t.prepend(n)):t.contains(o)?(n=this.getTransformedOperation(e,s,i),t.insert(n,o)):t.append(i),n}getTransformedOperation(e,t,s){const i=e.getOperation(t),o=this.buildTransformation.without(i.data);return s.transformed(o)}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:i,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!i||!o)return;const n=this.buildTransformation.with(o.data),r=e.fork(s);r.transform(n),i.cutAfter(s),i.appendBranch(r);const a=t.transformed(n);this.insertPrevious(i,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 i=e.getOperations();for(let o=i.length-1;o>=0;o--){const n=i[o];n.id===t&&(s=!1),s||(yield{operation:n,branch:e,isCancelled:!this.shouldExecute(e,n)})}const o=this.previousBranch(e);yield*o?this._revertedExecution(o):[]}*_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 ud{constructor(e,t,s,i,o){this.applyOperation=t,this.revertOperation=s,this.buildEmpty=i,this.buildTransformation=o,this.HEAD_BRANCH=new ld(this.buildTransformation),this.tree=new dd(o,this.HEAD_BRANCH);const n=new cd(e,i(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 cd(e,t),i=this.tree.getLastBranch();this.tree.insertOperationLast(i,s),this.HEAD_BRANCH=i,this.HEAD_OPERATION=s}insert(e,t,s){const i=new cd(e,t);this.revertTo(s),this.tree.insertOperationAfter(this.HEAD_BRANCH,i,s),this.fastForward()}undo(e,t,s){const{branch:i,operation:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(i,o),this.fastForward(),this.insert(t,this.buildEmpty(t),s)}redo(e,t,s){const{branch:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(i),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:i}of e)i||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:i}of e)i||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=s}}function pd(e,t,s){return new ud(e,(e=>{const i=e.commands.slice(),{changes:o}=t((()=>{for(const e of i)s(e)}));e.setChanges(o)}),(e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){gd(t.changes[e],"before")}}([e])),(e=>new Wh(e,"empty",[],[])),{with:e=>t=>new Wh(t.id,t.clientId,Gh(t.commands,e.commands)),without:e=>t=>new Wh(t.id,t.clientId,Gh(t.commands,e.commands.map(rd).flat()))})}function gd(e,t){let s=e.root,i=e.path[e.path.length-1];for(let t=0;t<e.path.slice(0,-1).length;t++){const i=e.path[t];if(void 0===s[i]){const o=e.path[t+1];s[i]=ad(o)}s=s[i]}void 0===e[t]?delete s[i]:s[i]=e[t]}class fd extends i.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 md{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",i="COL"===e.dimension?"columns":"rows";e.elements.sort(((e,t)=>t-e));const o=ms(e.elements);this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};let r=n,a="NONE";for(let e of o){const o=Math.min(...e),l=Math.max(...e);if(n.zone[t]<=o&&o<=n.zone[s]){const e=Math.min(n.zone[s],l)-o+1;a="RESIZE",r=this.createAdaptedRange(r,i,a,-e)}else if(n.zone[t]>=o&&n.zone[s]<=l)a="REMOVE",r=this.buildInvalidRange(_);else if(n.zone[t]<=l&&n.zone[s]>=l){const e=l-n.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,i,a,-e),r=this.createAdaptedRange(r,i,"MOVE",-(n.zone[t]-o))}else o<n.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,i,a,-(l-o+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",i="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((o=>{if(o.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(o.zone[t]<=e.base&&e.base<o.zone[s])return{changeType:"RESIZE",range:this.createAdaptedRange(o,i,"RESIZE",e.quantity)};if(e.base<o.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(o,i,"MOVE",e.quantity)}}else{if(o.zone[t]<e.base&&e.base<=o.zone[s])return{changeType:"RESIZE",range:this.createAdaptedRange(o,i,"RESIZE",e.quantity)};if(e.base<=o.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(o,i,"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(_),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||Os(s.range.zone)?s:{range:s.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,s,i){return{...e,zone:Ws(e.zone,t,s,i)}}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 i=t[1].colFixed;t[1].colFixed=t[0].colFixed,t[0].colFixed=i}if(e.bottom<e.top){let s=e.bottom;e.bottom=e.top,e.top=s;let i=t[1].rowFixed;t[1].rowFixed=t[0].rowFixed,t[0].rowFixed=i}}createAdaptedRanges(e,t,s,i){return e.map((e=>Os(e.zone)?(e={...e,sheetId:e.prefixSheet?e.sheetId:i,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,i,o,n=t,r=!1;if(!Qt.test(t))return this.buildInvalidRange(t);t.includes("!")&&(({xc:n,sheetName:s}=Jt(t)),s?(i=this.getters.getSheetIdByName(s),r=!0,i||(o=s)):o=s);const a=As(n);let l=n.split(":").map((e=>({colFixed:e.startsWith("$"),rowFixed:e.includes("$",1)})));return this.orderZone(a,l),{sheetId:i||e,zone:a,parts:l,invalidSheetName:o,prefixSheet:r}}getRangeString(e,t){if(!e)return _;if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return _;if(e.zone.left<0||e.zone.top<0)return _;let s=e.sheetId!==t||e.invalidSheetName||e.prefixSheet,i="";if(s&&(i=e.invalidSheetName?e.invalidSheetName:us(this.getters.getSheetName(e.sheetId))),s&&!i)return _;let o=Array(9);return o[0]=e.parts&&e.parts[0].colFixed?"$":"",o[1]=es(e.zone.left),o[2]=e.parts&&e.parts[0].rowFixed?"$":"",o[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)&&(o[4]=":",o[5]=e.parts[1].colFixed?"$":"",o[6]=es(e.zone.right),o[7]=e.parts[1].rowFixed?"$":"",o[8]=String(e.zone.bottom+1)),`${s?i+"!":""}${o.join("")}`}buildInvalidRange(e){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:e}}}md.getters=["getRangeString","getRangeFromSheetXC","createAdaptedRanges"];class vd{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,...i]=e;let o=s,n=i[i.length-1];for(let e=0;e<=i.length-2;e++){const t=i[e];if(void 0===o[t]){const s=i[e+1];o[t]=ad(s)}o=o[t]}o[n]!==t&&(this.changes.push({root:s,path:i,before:o[n],after:t}),void 0===t?delete o[n]:o[n]=t)}}const Ed={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},bd={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},Sd={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"},Cd="http://schemas.openxmlformats.org/drawingml/2006/main",Id="http://schemas.openxmlformats.org/drawingml/2006/chart",yd={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"},wd="http://schemas.openxmlformats.org/officeDocument/2006/relationships",xd=.75,Td=.1425,Rd=164,Ld={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}]},Md=["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 Ad(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function _d(e){return Math.round(xd*e*window.devicePixelRatio*100)/100}function Od(e){return Math.round(Td*e*100)/100}function Nd(e,t){let s={};e.style&&(s=t.styles[e.style]);let i={};e.border&&(i=t.borders[e.border]);const o={font:{size:(null==s?void 0:s.fontSize)||T,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:e.format,border:i||{},verticalAlignment:"center",horizontalAlignment:null==s?void 0:s.align};return o.font.strike=!!(null==s?void 0:s.strikethrough)||void 0,o.font.underline=!!(null==s?void 0:s.underline)||void 0,o.font.bold=!!(null==s?void 0:s.bold)||void 0,o.font.italic=!!(null==s?void 0:s.italic)||void 0,o}function kd(e,t){const{id:s}=$d(t.font,e.fonts),{id:i}=$d(t.fill,e.fills),{id:o}=$d(t.border,e.borders),n=function(e,t){if(!e)return 0;let s=Ed[e];if(!s){const{id:i}=$d(e,t);s=i+Rd}return s}(t.numFmt,e.numFmts),r={fontId:s,fillId:i,borderId:o,numFmtId:n,verticalAlignment:t.verticalAlignment,horizontalAlignment:t.horizontalAlignment},{id:a}=$d(r,e.styles);return a}function Fd(e,t,s){let i,o=e.find((e=>e.path===t));return o?(i=`rId${(o.rels.length+1).toString()}`,o.rels.push({...s,id:i})):(i="rId1",e.push({path:t,rels:[{...s,id:i}]})),i}function $d(e,t){for(let[s,i]of Object.entries(t))if(JSON.stringify(i)===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 Dd=[];function Pd(e){const t=Dd.findIndex((t=>t===e));return-1===t?(Dd.push(e),Dd.length):t+1}function Ud(e){return Math.round(914400*e/96)}class Bd{constructor(e){this.xmlString=e}toString(){return this.xmlString}}function Vd(e,t,s){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:s}}function zd(e){return String(e).replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;")}function Hd(e){return new Bd(e.map((([e,t])=>`${e}="${zd(t)}"`)).join(" "))}function Zd(e){const t=(new DOMParser).parseFromString(e.toString(),"text/xml"),s=t.querySelector("parsererror");if(s){const t=s.innerHTML,i=parseInt(t.split(":")[0],10),o=e.toString().trim().split("\n"),n=o.slice(Math.max(i-3,0),Math.min(i+2,o.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${n}`)}return t}function Gd(e,t){return qd`
1044
+ `;class ph 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()}mounted(){this.focusInput()}async willUnmount(){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}}}}ph.template=dh,ph.style=uh;const gh=new Re;gh.add("ConditionalFormatting",{title:a("Conditional formatting"),Body:lh}),gh.add("ChartPanel",{title:a("Chart"),Body:Lc}),gh.add("FindAndReplace",{title:a("Find and Replace"),Body:ph});const fh=new Re;class mh extends ua{constructor(e,t,s,i){super(t,s,i),this.getters=e,this.ui=i}drawGrid(e,t){}}mh.layers=[];class vh{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:i}=wa.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:s,tooltip:i,origin:{col:e.data.col,row:e.data.row}}}}class Eh extends mh{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:ps(e.col,0,this.getters.getSheet(t).cols.length),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:ps(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 i=t.left;i<=t.right;i++){const o=[];for(let e=t.top;e<=t.bottom;e++)o.push(ss(i,e));const n=this.createGenerator(o);for(let t=s.top;t<=s.bottom;t++)this.computeNewCell(n,i,t,e)}break;case 0:for(let i=t.left;i<=t.right;i++){const o=[];for(let e=t.bottom;e>=t.top;e--)o.push(ss(i,e));const n=this.createGenerator(o);for(let t=s.bottom;t>=s.top;t--)this.computeNewCell(n,i,t,e)}break;case 2:for(let i=t.top;i<=t.bottom;i++){const o=[];for(let e=t.right;e>=t.left;e--)o.push(ss(e,i));const n=this.createGenerator(o);for(let t=s.right;t>=s.left;t--)this.computeNewCell(n,t,i,e)}break;case 3:for(let i=t.top;i<=t.bottom;i++){const o=[];for(let e=t.left;e<=t.right;e++)o.push(ss(e,i));const n=this.createGenerator(o);for(let t=s.left;t<=s.right;t++)this.computeNewCell(n,t,i,e)}}if(e){const e=$s(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(Us(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,i=e.bottom;if(s>0){let e=this.getters.getCell(t,s-1,i);for(;e&&!e.isEmpty();)i+=1,e=this.getters.getCell(t,s-1,i)}if(i===e.bottom&&(s=e.right,s<=this.getters.getActiveSheet().cols.length)){let e=this.getters.getCell(t,s+1,i);for(;e&&!e.isEmpty();)i+=1,e=this.getters.getCell(t,s+1,i)}i!==e.bottom&&(this.select(e.left,i-1),this.autofill(!0))}computeNewCell(e,t,s,i){const{cellData:o,tooltip:n,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=o;this.tooltip=n,i&&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=xa.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=[],i=this.getters.getActiveSheetId();for(let t of e){const[e,o]=ts(t),n=this.getters.getCell(i,e,o);s.push({col:e,row:o,cell:n,sheetId:i})}const o=s.map((e=>e.cell));for(let e of s){let s={type:"COPY_MODIFIER"};if(e&&e.cell){s=this.getRule(e.cell,o)||s}const{sheetId:i,col:n,row:r}=e,a=this.getters.getCellBorder(i,n,r)||void 0;t.push({data:{...e,border:a},rule:s})}return new vh(t,this.getters,this.direction)}saveZone(e,t,s,i){this.autofillZone={top:e,bottom:t,left:s,right:i}}getDirection(e,t){const s=this.getters.getSelectedZone(),i={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(i).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(i).find((e=>e.number>0?1:0)).value;const o=i.up.number>0?"up":"down",n=i.left.number>0?"left":"right";return Math.abs(i[o].number)>=Math.abs(i[n].number)?i[o].value:i[n].value}autoFillMerge(e,t,s,i){const o=this.getters.getActiveSheet();if(this.getters.isInMerge(o.id,s,i)&&!this.getters.isInMerge(o.id,e,t)){const e=this.getters.getMerge(o.id,s,i);e&&this.dispatch("REMOVE_MERGE",{sheetId:o.id,target:[e]})}const n=this.getters.getMerge(o.id,e,t);(null==n?void 0:n.topLeft.col)===e&&(null==n?void 0:n.topLeft.row)===t&&this.dispatch("ADD_MERGE",{sheetId:o.id,target:[{top:i,bottom:i+n.bottom-n.top,left:s,right:s+n.right-n.left}]})}drawGrid(e){if(!this.autofillZone)return;const{viewport:t,ctx:s,thinLineWidth:i}=e,[o,n,r,a]=this.getters.getRect(this.autofillZone,t);r>0&&a>0&&(s.strokeStyle="black",s.lineWidth=i,s.setLineDash([3]),s.strokeRect(o,n,r,a),s.setLineDash([]))}}Eh.layers=[6],Eh.getters=["getAutofillTooltip"],Eh.modes=["normal"];class bh extends mh{handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:s}=this.getters.getSelection();for(const i of t){const t=this.getAutomaticSums(e,i,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),i=this.sumDimensions(e,t,s).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return s.has("ROW")&&s.has("COL")&&i.push(this.sumTotal(t)),i}sumAdjacentData(e,t,s){const[i,o]=Us(s[0],s[1],t)?s:[t.left,t.top],n=this.findAdjacentData(e,i,o);return n?this.getters.isSingleCellOrMerge(e,t)||Zs($s(n,t))?[{position:[i,o],zone:n}]:this.sumDimensions(e,$s(n,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,s){const i=this.getters.getSheet(e),o=this.findSuitableZoneToSum(i,...this.getters.getMainCell(e,t,s));if(o)return this.getters.expandZone(e,o)}findSuitableZoneToSum(e,t,s){const i=this.getters.getCell(e.id,t,s-1),o=this.getters.getCell(e.id,t-1,s);if(this.isNumber(o)&&!this.isNumber(i))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 i={top:0,bottom:s-1,left:t,right:t},o=this.reduceZoneStart(e,i,i.bottom);return{...i,top:o}}findHorizontalZone(e,t,s){const i={top:s,bottom:s,left:0,right:t-1},o=this.reduceZoneStart(e,i,i.right);return{...i,left:o}}reduceZoneStart(e,t,s){const i=Hs(t,e,(e=>e),void 0).flat(),o=fs(s,-1,-1),n=o.filter((e=>{var t;return i[e]&&!(null===(t=i[e])||void 0===t?void 0:t.isAutoSummable)})),r=Math.max(...n),a=ms(o.filter((e=>this.isNumber(i[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)===Ne.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(A))}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 Zs(t)?(s.add(1===zs(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)},Gs(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)},Gs(s).map((t=>({position:t,zone:{...e,top:t[1],bottom:t[1]}})))}dispatchCellUpdates(e,t){for(const s of t){const[t,i]=s.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,content:`=SUM(${this.getters.zoneToXC(e,s.zone)})`})}}nextEmptyRow(e,t){let s=t.bottom+1;const{left:i,right:o}=t;for(;!this.getters.isEmpty(e,{bottom:s,top:s,left:i,right:o});)s++;return{...t,top:s,bottom:s}}nextEmptyCol(e,t){let s=t.right+1;const{top:i,bottom:o}=t;for(;!this.getters.isEmpty(e,{left:s,right:s,top:i,bottom:o});)s++;return{...t,left:s,right:s}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}bh.getters=["getAutomaticSums"],bh.modes=["normal","headless"];class Sh extends mh{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),i=this.getClipboardState(t,"CUT");return this.isPasteAllowed(i,s,!1)}case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),i=this.getClipboardState(t,"CUT");return this.isPasteAllowed(i,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 i=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);if(this._isPaintingFormat=!1,e.interactive)this.interactivePaste(this.state,e.target,e);else{const t=this.state.cells.length,s=this.state.cells[0].length;this.paste(this.state,e.target,i),this.selectPastedZone(s,t,e.target),this.status="invisible"}break;case"DELETE_CELL":{const{cut:t,paste:s}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Os(t[0])){for(const[t,s]of Gs(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:s,sheetId:this.getters.getActiveSheetId()});break}const i=this.getClipboardState(t,"CUT");e.interactive?this.interactivePaste(i,s,e):this.paste(i,s);break}case"INSERT_CELL":{const{cut:t,paste:s}=this.getInsertCellsTargets(e.zone,e.shiftDimension),i=this.getClipboardState(t,"CUT");e.interactive?this.interactivePaste(i,s,e):this.paste(i,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:De(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 i;return i="COL"===t?{...e,left:e.right+1,right:s.cols.length-1}:{...e,top:e.bottom+1,bottom:s.rows.length-1},{cut:[i],paste:[e]}}getInsertCellsTargets(e,t){const s=this.getters.getActiveSheet();let i,o;return"COL"===t?(i={...e,right:s.cols.length-1},o={...e,left:e.right+1,right:e.right+1}):(i={...e,bottom:s.rows.length-1},o={...e,top:e.bottom+1,bottom:s.rows.length-1}),{cut:[i],paste:[o]}}removeMergeIfTopLeft(e){const{sheetId:t,col:s,row:i}=e,[o,n]=this.getters.getMainCell(t,s,i);if(n===i&&o===s){const e=this.getters.getMerge(t,s,i);e&&this.dispatch("REMOVE_MERGE",{sheetId:t,target:[e]})}}pasteMergeIfExist(e,t){let{sheetId:s,col:i,row:o}=e;const[n,r]=this.getters.getMainCell(s,i,o);if(n===i&&r===o){const e=this.getters.getMerge(s,i,o);if(!e)return;({sheetId:s,col:i,row:o}=t),this.dispatch("ADD_MERGE",{sheetId:s,force:!0,target:[{left:i,top:o,right:i+e.right-e.left,bottom:o+e.bottom-e.top}]})}}getPasteZones(e,t){if(!t.length||!t[0].length)return e;const s=[],i=t.length,o=t[0].length,n=e[e.length-1],r=n.left,a=n.top,l=Math.max(1,Math.floor((n.right+1-r)/o)),c=Math.max(1,Math.floor((n.bottom+1-a)/i));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)s.push({left:r,top:a,right:r-1+e*o,bottom:a-1+t*i});return s}getClipboardState(e,t){const s=new Set(e.map((e=>e.top))),i=new Set(e.map((e=>e.bottom)));let o=1===s.size&&1===i.size?e:[e[e.length-1]];o=o.map((e=>({...e})));const n=[],r=[],a=this.getters.getActiveSheetId(),{top:l,bottom:c}=o[0];for(let e=l;e<=c;e++){const t=[];n.push(t);for(let s of o)for(let i=s.left;i<=s.right;i++){const s=this.getters.getCell(a,i,e),o=this.getters.getCellBorder(a,i,e)||void 0;t.push({cell:s,border:o,position:{col:i,row:e,sheetId:a}});const n=this.getters.getMerge(a,i,e);n&&n.top===e&&n.left===i&&r.push(n)}}return{cells:n,operation:t,sheetId:a,zones:o,merges:r}}pasteFromClipboard(e,t){this.status="invisible";const s=t.replace(/\r/g,"").split("\n").map((e=>e.split("\t"))),{left:i,top:o}=e[0],n=Math.max.apply(Math,s.map((e=>e.length))),r=s.length,a=this.getters.getActiveSheet();this.addMissingDimensions(a,n,r,i,o);for(let e=0;e<s.length;e++)for(let t=0;t<s[e].length;t++)this.dispatch("UPDATE_CELL",{row:o+e,col:i+t,content:s[e][t],sheetId:a.id});const l={left:i,top:o,right:i+n-1,bottom:o+r-1};this.dispatch("SET_SELECTION",{anchor:[i,o],zones:[l],anchorZone:l})}isPasteAllowed(e,t,s){const i=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(i,s))return 2;return 0}paste(e,t,s){if("CUT"===e.operation&&this.clearClippedZones(e),t.length>1)for(const i of t)for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++)this.pasteZone(e,t,o,s);else{const i=e.cells.length,o=e.cells[0].length,n=t[0],r=Math.max(1,Math.floor((n.right+1-n.left)/o)),a=Math.max(1,Math.floor((n.bottom+1-n.top)/i));for(let t=0;t<r;t++)for(let r=0;r<a;r++)this.pasteZone(e,n.left+t*o,n.top+r*i,s)}"CUT"===e.operation&&(this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:e.merges}),this.state=void 0)}selectPastedZone(e,t,s){const i=s[0],o=i.left,n=i.top,r=Math.max(1,Math.floor((i.right+1-i.left)/e)),a=Math.max(1,Math.floor((i.bottom+1-i.top)/t));if(t>1||e>1){const s={left:o,top:n,right:o+r*e-1,bottom:n+a*t-1},[i,l]=this.getters.getSelection().anchor,c=ps(i,o,o+r*e-1),h=ps(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,i){const o=e.cells.length,n=e.cells[0].length,r="onlyValue"!==i&&this.state&&this.state===e,a=this.getters.getActiveSheet();this.addMissingDimensions(a,n,o,t,s);for(let l=0;l<o;l++){const o=e.cells[l];for(let c=0;c<n;c++){const n=o[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,i),r&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:n.position,target:h,operation:e.operation})}}}addMissingDimensions(e,t,s,i,o){const{cols:n,rows:r,id:a}=e,l=s+o-r.length;l>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:r.length-1,sheetId:a,quantity:l,position:"after"});const c=t+i-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,i,o){const{sheetId:n,col:r,row:a}=t,l=this.getters.getCell(n,r,a);if("onlyValue"!==o&&this.dispatch("SET_BORDER",{sheetId:n,col:r,row:a,border:e.border}),e.cell){if("onlyFormat"===o)return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.cell.format});if("onlyValue"===o){const s=Zr(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,o=a-e.position.row;l=this.getUpdatedContent(n,e.cell,t,o,i,s)}this.dispatch("UPDATE_CELL",{...t,content:l,style:e.cell.style||null,format:e.cell.format})}else l&&("onlyValue"===o?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===o?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,s,i,o,n){if("CUT"===n){const n=[];for(const r of t.dependencies.references)this.isZoneOverlapClippedZone(o,r.zone)?n.push(...this.getters.createAdaptedRanges([r],s,i,e)):n.push(r);const r={...t.dependencies,references:n};return this.getters.buildFormulaContent(e,t.normalizedText,r)}const r=this.getters.createAdaptedRanges(t.dependencies.references,s,i,e),a={...t.dependencies,references:r};return this.getters.buildFormulaContent(e,t.normalizedText,a)}isZoneOverlapClippedZone(e,t){return e.some((e=>Ps(t,e)))}interactivePaste(e,t,s){const i=this.isPasteAllowed(e,t,!1);0!==i?(19===i&&this.ui.notifyUser(a("This operation is not allowed with multiple selections.")),2===i&&this.ui.notifyUser(a("This operation is not possible due to a merge. Please remove the merges first than try again."))):this.dispatch(s.type,{...s,interactive:!1})}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:i}=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*i;for(const e of this.state.zones){const[i,o,n,r]=this.getters.getRect(e,t);n>0&&r>0&&s.strokeRect(i,o,n,r)}}}}var Ch;Sh.layers=[2],Sh.getters=["getClipboardContent","isPaintingFormat"],Sh.modes=["normal"],function(e){e[e.idle=0]="idle",e[e.selecting=1]="selecting",e[e.readyToExpand=2]="readyToExpand",e[e.expanding=3]="expanding"}(Ch||(Ch={}));class Ih extends mh{constructor(e,t,s,i){super(e,t,s,i),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=Ch.idle,this.sheetsData={},this.activeSheet=null,this.moveClient=i.moveClient}allowDispatch(e){switch(e.type){case"SET_SELECTION":if(-1===e.zones.findIndex((t=>Ds(t,e.anchorZone))))return 16;break;case"ALTER_SELECTION":if(e.delta){const{left:t,right:s,top:i,bottom:o}=this.getSelectedZone(),n=this.getters.getActiveSheet(),r=ii(n,"cols",fs(t,s+1)),a=ii(n,"rows",fs(i,o+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:i,row:o}=this.getNextAvailablePosition(e.deltaX,e.deltaY);if(o<0||o>s.length-1||i<0||i>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":const t=this.isMoveElementAllowed(e);return 2===t&&this.ui.notifyUser(a("Merged cells are preventing this operation. Unmerge those cells and try again.")),t}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=si(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(...si(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=Ch.selecting;break;case"PREPARE_SELECTION_EXPANSION":this.mode=Ch.readyToExpand;break;case"START_SELECTION_EXPANSION":this.mode=Ch.expanding;break;case"STOP_SELECTION":this.mode=Ch.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]:si(this.getters.getSheet(e),0,0)}}getAggregate(){let e=0,t=0;for(let s of this.selection.zones)for(let i=s.top;i<=s.bottom;i++){const o=this.getters.getRow(this.getters.getActiveSheetId(),i);if(void 0!==o)for(let i=s.left;i<=s.right;i++){const s=o.cells[i];(null==s?void 0:s.evaluated.type)===Ne.number&&(t++,e+=s.evaluated.value)}}return t<2?null:se(e)}getSelectionMode(){return this.mode}isSelected(e){return!!this.getters.getSelectedZones().find((t=>Ds(t,e)))}getVisibleFigures(e){const t=[],s=this.getters.getFigures(e),{offsetX:i,offsetY:o}=this.getters.getSnappedViewport(e),{width:n,height:r}=this.getters.getViewportDimension();for(let e of s)e.x>=i+n||e.x+e.width<=i||e.y>=o+r||e.y+e.height<=o||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 i="COL"===e?"left":"top",o="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[o]-e[i]+1},((t,s)=>e[i]+s));s=s.concat(t)}return[...new Set(s)].sort()}selectColumn(e,t,s){const i=this.getters.getActiveSheet().rows.length-1;let o={left:e,right:e,top:0,bottom:i};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;o=$s(o,{left:e,right:e,top:l,bottom:i}),r=this.updateSelectionZones(o),a=[e,t]}else r=t?n.concat(o):[o],a=[e,l];this.dispatch("SET_SELECTION",{zones:r,anchor:a,strict:!0,anchorZone:o})}selectRow(e,t,s){const i=this.getters.getActiveSheet().cols.length-1;let o={top:e,bottom:e,left:0,right:i};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;o=$s(o,{left:l,right:i,top:t,bottom:t}),r=this.updateSelectionZones(o),a=[e,t]}else r=t?n.concat(o):[o],a=[l,e];this.dispatch("SET_SELECTION",{zones:r,anchor:a,strict:!0,anchorZone:o})}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});let i=this.getters.expandZone(s.id,{left:e,right:e,top:t,bottom:t});this.mode===Ch.expanding?this.selection.zones.push(i):this.selection.zones=[i],this.selection.zones=qs(this.selection.zones),this.selection.anchorZone=i,this.selection.anchor=[e,t],this.activeCol=e,this.activeRow=t}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:i,id:o}=this.getActiveSheet(),n={col:t,row:s};return this.getNextAvailableHeader(e,i,t,n,(e=>this.getters.isInSameMerge(o,t,s,e,s)))}getNextAvailableRow(e,t,s){const{rows:i,id:o}=this.getActiveSheet(),n={col:t,row:s};return this.getNextAvailableHeader(e,i,s,n,(e=>this.getters.isInSameMerge(o,t,s,t,e)))}getNextAvailableHeader(e,t,s,i,o){var n,r,a;const l=this.getters.getActiveSheetId(),{col:c,row:h}=i;if(0===e)return s;let d=s+e;if(this.getters.isInMerge(l,c,h)){for(;o(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,i,o):s:d}movePosition(e,t){const{col:s,row:i}=this.getNextAvailablePosition(e,t);this.selectCell(s,i)}setSelection(e,t,s,i=!1){this.selectCell(...e);const o=this.getters.getActiveSheetId();let n;t=qs(t),n=i?{zones:t,anchorZone:s,anchor:e}:{anchor:e,zones:t.map((e=>this.getters.expandZone(o,e))),anchorZone:this.getters.expandZone(o,s)},this.selection=this.clipSelection(o,n)}getReferencePosition(){const e=this.getters.getActiveSheet(),t=this.selection,{left:s,right:i,top:o,bottom:n}=t.anchorZone,[r,a]=t.anchor;return{col:e.cols[r].isHidden&&ii(e,"cols",fs(s,i+1))||r,row:e.rows[a].isHidden&&ii(e,"rows",fs(o,n+1))||a}}moveSelection(e,t){const s=this.selection;let i=[];const[o,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:i,bottom:o}=this.getters.expandZone(d.id,e);return{left:Math.max(0,t),right:Math.min(d.cols.length-1,s),top:Math.max(0,i),bottom:Math.min(d.rows.length-1,o)}},{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?js(h):h,h&&!Ds(h,s.anchorZone))return i=this.updateSelectionZones(h),void this.dispatch("SET_SELECTION",{zones:i,anchor:[o,n],anchorZone:h})}h=u($s({top:n,bottom:n,left:o,right:o},js({top:this.getNextAvailableRow(t,p,l),left:this.getNextAvailableCol(e,r,g),bottom:this.getNextAvailableRow(t,p,c),right:this.getNextAvailableCol(e,a,g)}))),Ds(h,s.anchorZone)||(i=this.updateSelectionZones(h),this.dispatch("SET_SELECTION",{zones:i,anchor:[o,n],anchorZone:h}))}addCellToSelection(e,t){const s=this.selection,[i,o]=s.anchor,n={left:Math.min(i,e),top:Math.min(o,t),right:Math.max(i,e),bottom:Math.max(o,t)},r=this.updateSelectionZones(n);this.dispatch("SET_SELECTION",{zones:r,anchor:[i,o],anchorZone:n})}ensureSelectionValidity(){const{anchor:e,zones:t,anchorZone:s}=this.clipSelection(this.getActiveSheetId(),this.selection);this.setSelection(e,t,s);const i=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of i)delete this.sheetsData[e];for(const e in this.sheetsData){const{anchor:t,zones:s,anchorZone:i}=this.clipSelection(e,this.sheetsData[e].selection);this.sheetsData[e]={selection:{anchor:t,zones:s,anchorZone:i},activeCol:t[0],activeRow:t[1]}}}clipSelection(e,t){const s=this.getters.getSheet(e),i=s.cols.length-1,o=s.rows.length-1,n=t.zones.map((e=>({left:ps(e.left,0,i),right:ps(e.right,0,i),top:ps(e.top,0,o),bottom:ps(e.bottom,0,o)})));return{anchor:[ps(t.anchor[0],0,i),ps(t.anchor[1],0,o)],zones:n,anchorZone:{left:ps(t.anchorZone.left,0,i),right:ps(t.anchorZone.right,0,i),top:ps(t.anchorZone.top,0,o),bottom:ps(t.anchorZone.bottom,0,o)}}}onColumnsRemoved(e){const t=Fs(this.getSelectedZone(),"left",e.elements);this.setSelection([t.left,t.top],[t],t,!0),this.ensureSelectionValidity()}onRowsRemoved(e){const t=Fs(this.getSelectedZone(),"top",e.elements);this.setSelection([t.left,t.top],[t],t,!0),this.ensureSelectionValidity()}onAddElements(e){const t=ks(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,i=t.findIndex((e=>Ds(e,s)));return i>=0&&(t[i]=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,i=e.elements[0],o=e.elements[t-1],n=e.base<i,r=n&&s?t:0,a=n&&!s?t:0,l=this.getters.getSheet(e.sheetId);this.dispatch("CUT",{target:[{left:s?i+r:0,right:s?o+r:l.cols.length-1,top:s?0:i+a,bottom:s?l.rows.length-1:o+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],i=e.elements[e.elements.length-1],o=e.sheetId,n=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;return n(o,s-1,s)||n(o,i,i+1)||n(o,e.base-1,e.base)?2:0}drawGrid(e){if("inactive"!==this.getters.getEditionMode())return;const{viewport:t,ctx:s,thinLineWidth:i}=e,o=this.getSelectedZones();s.fillStyle="#f3f7fe";const n=1===o.length&&o[0].left===o[0].right&&o[0].top===o[0].bottom;s.fillStyle=n?"#f3f7fe":"#e9f0ff",s.strokeStyle=p,s.lineWidth=1.5*i,s.globalCompositeOperation="multiply";for(const e of o){const[i,o,n,r]=this.getters.getRect(e,t);s.fillRect(i,o,n,r),s.strokeRect(i,o,n,r)}s.globalCompositeOperation="source-over";const r=this.getters.getActiveSheetId(),[a,l]=this.getPosition();let c;s.strokeStyle=p,s.lineWidth=3*i,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)}}Ih.layers=[5],Ih.modes=["normal"],Ih.getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getAggregate","getSelectedFigureId","getVisibleFigures","getSelection","getPosition","getSheetPosition","getSelectionMode","isSelected","getElementsFromSelection"];const yh=a("The cell you are trying to edit has been deleted.");class wh extends mh{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()===Ch.expanding?this.insertSelectedRange():this.replaceAllSelectedRanges();break;case"SET_SELECTION":e.strict?this.getters.getSelectionMode()===Ch.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=>"SYMBOL"===e.type)).find((t=>{let s=t.value;const{xc:i,sheetName:o}=Jt(s),n=o||this.getters.getSheetName(this.sheet),r=this.getters.getActiveSheetId();return Ds(this.getters.expandZone(r,_s(i)),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.notifyUser(yh))}}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.notifyUser(yh);const{top:t,left:s}=Fs({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.notifyUser(yh);const{top:t,left:s}=Fs({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}=ks({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[i,o]=this.getters.getPosition();this.col=i,this.row=o,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,i]=this.getters.getMainCell(t,this.col,this.row);let o=this.currentContent;if(!(this.initialContent!==o))return;if(o){const t=this.getters.getCell(e,s,i);if(o.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&&(o+=new Array(s).fill(")").join(""))}else(null==t?void 0:t.isLink())&&(o=ys(o,t.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheet,col:s,row:i,content:o})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheet,content:"",col:s,row:i});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 i=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(i||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?Br(e):[],this.currentTokens.length>100&&s&&this.ui.notifyUser(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 i=this.getters.zoneToXC(s,e,t);if(this.getters.getEditionSheet()!==this.getters.getActiveSheetId()){i=`${us(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${i}`}return i}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),i=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:s,selection:{start:i,end:i}})}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=[],t={};for(let s of this.currentTokens.filter((e=>"SYMBOL"===e.type))){let i=s.value;const{xc:o,sheetName:n}=Jt(i);if(Qt.test(o)){const s=(n?`${n}!`:`${this.getters.getSheetName(this.getters.getEditionSheet())}!`)+o.replace(/\$/g,"");e.push(s);const i=this.colorIndexByRange[s];void 0!==i&&(t[s]=i)}}this.colorIndexByRange=t;let s=Object.values(t),i=0;return e.map((e=>{if(void 0===this.colorIndexByRange[e]){for(;s.includes(i);)i++;s.push(i),this.colorIndexByRange[e]=i}return[e,Wt[this.colorIndexByRange[e]%Wt.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,i=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(i.type);){if("SPACE"!==i.type||s<1)return!1;s--,i=this.currentTokens[s]}for(s=t+1,i=this.currentTokens[s];i&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(i.type);){if("SPACE"!==i.type)return!1;s++,i=this.currentTokens[s]}s++,i=this.currentTokens[s]}return!0}return!1}}wh.getters=["getEditionMode","isSelectingForComposer","getCurrentContent","getEditionSheet","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights"],wh.modes=["normal"];const xh=ir.mapping;class Th extends mh{constructor(e,t,s,i){super(e,t,s,i),this.isUpToDate=new Set,this.evalContext=i.evalContext,i.dataSources.on("data-loaded",this,(()=>{this.dispatch("EVALUATE_CELLS",{sheetId:this.getters.getActiveSheetId()})}))}handle(e){switch(ke.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()){let s=Vr(e);const i=Dr(s),o=this.getFormulaParameters((()=>{})),n=[];for(let e of s.dependencies.references)n.push(this.getters.getRangeFromSheetXC(t,e));return i({...s.dependencies,references:n},t,...o)}getRangeFormattedValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[[]]:Hs(e.zone,t,(e=>this.getters.getCellText(e,this.getters.shouldShowFormulas())),"")}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[[]]:Hs(e.zone,t,(e=>e.evaluated.value))}evaluate(e){const t=this.getters.getCells(e),s=this.getFormulaParameters(o),i={};for(let s of Object.values(t))o(s,e);function o(e,t){if(!e.isFormula())return;const o=e.id;if(o in i)null===i[o]&&e.assignError("#CYCLE",a("Circular reference"));else{i[o]=null;try{if(s[2].__originCellXC=()=>{const e=s[2].getters.getCellPosition(o);return ss(e.col,e.row)},e.assignValue(e.compiledFormula(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 i=s[2].__lastFnCalled||"";t.assignError("#ERROR",e.message.replace("[[FUNCTION_NAME]]",i))}}(t,e)}i[o]=!0}}}getFormulaParameters(e){const t=Object.assign(Object.create(xh),this.evalContext,{getters:this.getters}),s=this.getters.getEvaluationSheets();function i(t,s){if(e(t,s),t.evaluated.type===Ne.error)throw new Error(a("This formula depends on invalid values"));return t.evaluated.value}function o(e){const o=s[e.sheetId];if(!Os(e.zone))throw new Error(a("Invalid reference"));const n={top:0,bottom:o.rows.length-1,left:0,right:o.cols.length-1},r=[],l=function(e,t){if(Ps(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 o=[];for(let n=l.top;n<=l.bottom;n++){const r=t.getters.getCell(e.sheetId,s,n);o.push(r?i(r,e.sheetId):void 0)}r.push(o)}return r}return[function(e,o,n,r,l,c){const h=o[e];if(r)return t.getters.getRangeString(h,n);if(!Os(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){var t;let o;const n=s[e.sheetId];if(!n)throw new Error(a("Invalid sheet name"));return o=null===(t=n.rows[e.zone.top])||void 0===t?void 0:t.cells[e.zone.left],!o||o.isEmpty()?null:i(o,e.sheetId)}(h)},function(e,t,s){return o(t[e])},t]}evaluateAllSheets(){for(const e of this.getters.getVisibleSheets())this.evaluate(e),this.isUpToDate.add(e)}}Th.getters=["evaluateFormula","getRangeFormattedValues","getRangeValues"],Th.modes=["normal"];const Rh=["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 Lh{constructor(){this.graphColorIndex=0}next(){return Rh[this.graphColorIndex++%Rh.length]}}class Mh extends mh{constructor(){super(...arguments),this.chartRuntime={},this.outOfDate=new Set}handle(e){if(ke.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 i={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?(i.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2}}],yAxes:[{position:e.verticalAxisPosition,ticks:{beginAtZero:!0}}]},"bar"===e.type&&e.stackedBar&&(i.options.scales.xAxes[0].stacked=!0,i.options.scales.yAxes[0].stacked=!0)):i.options.tooltips={callbacks:{title:function(e,t){return t.datasets[e[0].datasetIndex].label}}},i}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).flat(1));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=fs(0,this.getData(e.dataSets[0],e.sheetId).length).map((e=>e.toString()))}const s=this.getDefaultConfiguration(e,t),i=new Lh,o=[];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++)o.push(i.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=`${ac.Series} ${parseInt(t)+1}`}else r=r=`${ac.Series} ${parseInt(t)+1}`;const a="pie"!==e.type?i.next():"#FFFFFF",l={label:r,data:n.dataRange?this.getData(n,e.sheetId):[],lineTension:0,borderColor:a,backgroundColor:a};"pie"===e.type&&(l.backgroundColor=o),s.data.datasets.push(l)}return s}getData(e,t){if(e.dataRange){const t=e.labelCell?[Ns(e.labelCell.zone)]:[],s=Bs([Ns(e.dataRange.zone)],t)[0];if(void 0===s)return[];const i=this.getters.getRangeFromSheetXC(e.dataRange.sheetId,s);return this.getters.getRangeValues(i).flat(1)}return[]}}Mh.getters=["getChartRuntime"],Mh.modes=["normal"];class Ah extends mh{constructor(){super(...arguments),this.isStale=!0,this.computedStyles={},this.computedIcons={},this.rulePredicate={CellIsRule:(e,t)=>{if(e&&e.evaluated.type===Ne.error)return!1;const s=t.values.map(Gr);switch(t.operator){case"IsEmpty":return!Ls(e)||""===e.evaluated.value.toString().trim();case"IsNotEmpty":return Ls(e)&&""!==e.evaluated.value.toString().trim();case"BeginsWith":return!(!e&&""===s[0])&&(Ls(e)&&(null==e?void 0:e.evaluated.value.toString().startsWith(s[0].toString())));case"EndsWith":return!(!e&&""===s[0])&&(Ls(e)&&e.evaluated.value.toString().endsWith(s[0].toString()));case"Between":return Ls(e)&&e.evaluated.value>=s[0]&&e.evaluated.value<=s[1];case"NotBetween":return!(Ls(e)&&e.evaluated.value>=s[0]&&e.evaluated.value<=s[1]);case"ContainsText":return Ls(e)&&e.evaluated.value.toString().indexOf(s[0].toString())>-1;case"NotContains":return!Ls(e)||!e.evaluated.value||-1==e.evaluated.value.toString().indexOf(s[0].toString());case"GreaterThan":return Ls(e)&&e.evaluated.value>s[0];case"GreaterThanOrEqual":return Ls(e)&&e.evaluated.value>=s[0];case"LessThan":return Ls(e)&&e.evaluated.value<s[0];case"LessThanOrEqual":return Ls(e)&&e.evaluated.value<=s[0];case"NotEqual":return!(!Ls(e)&&""===s[0])&&(Ls(e)&&e.evaluated.value!==s[0]);case"Equal":return!e&&""===s[0]||Ls(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(),i=this.getters.getRulesByCell(s,e.originCol,e.originRow);for(const t of i)this.adaptRules(s,t,[ss(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 i=this.getters.getActiveSheetId(),o=this.computedStyles[i];return o&&(null===(s=o[e])||void 0===s?void 0:s[t])}getConditionalIcon(e,t){var s;const i=this.getters.getActiveSheetId(),o=this.computedIcons[i];return o&&(null===(s=o[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 i of this.getters.getConditionalFormats(t))try{switch(i.rule.type){case"ColorScaleRule":for(let e of i.ranges)this.applyColorScale(e,i.rule);break;case"IconSetRule":for(let e of i.ranges)this.applyIcon(e,i.rule);break;default:for(let o of i.ranges){const n=_s(o);for(let o=n.top;o<=n.bottom;o++)for(let r=n.left;r<=n.right;r++){const n=this.rulePredicate[i.rule.type];let a=this.getters.getCell(t,r,o);n&&n(a,i.rule)&&(s[r]||(s[r]=[]),s[r][o]=Object.assign((null===(e=s[r])||void 0===e?void 0:e[o])||{},i.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 i=this.getters.evaluateFormula(`=min(${e})`);return i+(this.getters.evaluateFormula(`=max(${e})`)-i)*Number(t.value)/100;case"percentile":return this.getters.evaluateFormula(`=PERCENTILE(${e},${Number(t.value)/100})`);case"formula":const o=t.value&&this.getters.evaluateFormula(t.value);return o instanceof Promise?null:o;default:return null}}applyIcon(e,t){const s=this.parsePoint(e,t.lowerInflectionPoint),i=this.parsePoint(e,t.upperInflectionPoint);if(null===s||null===i||s>i)return;const o=_s(e),n=this.getters.getActiveSheetId(),r=this.computedIcons[n],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=o.top;e<=o.bottom;e++)for(let l=o.left;l<=o.right;l++){const o=this.getters.getCell(n,l,e);if((null==o?void 0:o.evaluated.type)!==Ne.number)continue;const c=this.computeIcon(o.evaluated.value,i,t.upperInflectionPoint.operator,s,t.lowerInflectionPoint.operator,a);r[l]||(r[l]=[]),r[l][e]=c}}computeIcon(e,t,s,i,o,n){return"ge"===s&&e>=t||"gt"===s&&e>t?n[0]:"ge"===o&&e>=i||"gt"===o&&e>i?n[1]:n[2]}applyColorScale(e,t){var s;const i=this.parsePoint(e,t.minimum,"min"),o=t.midpoint?this.parsePoint(e,t.midpoint):null,n=this.parsePoint(e,t.maximum,"max");if(null===i||null===n||i>=n||o&&(i>=o||o>=n))return;const r=_s(e),a=this.getters.getActiveSheetId(),l=this.computedStyles[a],c=[];t.midpoint&&o?(c.push({minValue:i,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,o,t.minimum.color,t.midpoint.color)}),c.push({minValue:o,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(o,n,t.midpoint.color,t.maximum.color)})):c.push({minValue:i,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,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)===Ne.number){const a=ps(r.evaluated.value,i,n);let h;h=2===c.length&&o?a<=o?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="#"+qt(h)}}}computeColorDiffUnits(e,t,s,i){const o=t-e;return[((s>>16)%256-(i>>16)%256)/o,((s>>8)%256-(i>>8)%256)/o,(s%256-i%256)/o]}colorCell(e,t,s,i){const[o,n,r]=i;return Math.round((s>>16)%256-o*(e-t))<<16|Math.round((s>>8)%256-n*(e-t))<<8|Math.round(s%256-r*(e-t))}adaptRules(e,t,s,i){if(0===s.length&&0===i.length)return;const o=this.getters.getConditionalFormats(e),n=o.findIndex((e=>e.id===t.id));let r=[];n>-1&&(r=o[n].ranges),r=r.concat(s);const a=Bs(r,i);this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:t.id,rule:t.rule,stopIfTrue:t.stopIfTrue},target:a.map(_s),sheetId:e})}pasteCf(e,t,s){const i=ss(t.col,t.row);for(let o of this.getters.getConditionalFormats(e.sheetId))for(let n of o.ranges)if(Us(e.col,e.row,_s(n))){const n=o,r=[];"CUT"===s&&r.push(ss(e.col,e.row)),e.sheetId===t.sheetId?this.adaptRules(e.sheetId,n,[i],r):(this.adaptRules(t.sheetId,n,[i],[]),this.adaptRules(e.sheetId,n,[],r))}}}Ah.getters=["getConditionalStyle","getConditionalIcon"],Ah.modes=["normal"];var _h;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(_h||(_h={}));class Oh extends mh{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(_h.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(_h.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(_h.current)}updateRegex(){let e=hs(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),i={col:t.col,row:t.row,selected:!1};s.push(i)}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],i=this.getters.getActiveSheetId(),o=this.getters.getCell(i,s.col,s.row),n=this.toReplace(o,i);if(o&&n){const t=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),i=n.toString().replace(t,e);this.dispatch("UPDATE_CELL",{sheetId:this.getters.getActiveSheetId(),col:s.col,row:s.row,content:i}),this.searchMatches.splice(this.selectedMatchIndex,1),this.selectNextCell(_h.current)}else this.selectNextCell(_h.next)}replaceAll(e,t){const s=this.searchMatches.length;for(let i=0;i<s;i++)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,i=this.getters.getActiveSheetId();for(const e of this.searchMatches){const o=this.getters.getMerge(i,e.col,e.row),n=o?o.left:e.col,r=o?o.right:e.col,a=o?o.top:e.row,l=o?o.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)))}}}Oh.layers=[3],Oh.getters=["getSearchMatches","getCurrentSelectedMatchIndex"];class Nh extends mh{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,s){const i=this.searchNumberFormat(e,t);if(void 0!==i){const o=this.changeDecimalFormat(i,s);this.dispatch("SET_FORMATTING",{sheetId:e,target:t,format:o})}}searchNumberFormat(e,t){var s;for(let i of t)for(let t=i.top;t<=i.bottom;t++)for(let o=i.left;o<=i.right;o++){const i=this.getters.getCell(e,o,t);if((null==i?void 0:i.evaluated.type)===Ne.number&&!(null===(s=i.format)||void 0===s?void 0:s.match(A)))return i.format||this.setDefaultNumberFormat(i.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),i=e.split(";");let o=[];for(let e of i){const t=e.indexOf("."),i=e.toUpperCase().indexOf("E");let n;const r=i>-1?e.slice(0,i):e,a=t>-1?r.slice(t).match(/0/g).length:0,l=r.lastIndexOf("0");l>-1?s>0?n=a<oe?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,o.push(n)}return o.join(";")}}Nh.modes=["normal"];class kh extends mh{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[i,o]of e){const{xc:e,sheetName:n}=Jt(i),r=n?this.getters.getSheetIdByName(n):t;if(r){let i=_s(e);const{height:n,width:a}=zs(i);i=n*a==1?this.getters.expandZone(t,_s(e)):i,s.push({zone:i,color:o,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:i}=e,o=this.getters.getActiveSheetId(),n=3*i;t.lineWidth=n;for(let e of this.getHighlights().filter(((e,t)=>this.getHighlights().findIndex((t=>Ds(t.zone,e.zone)&&t.sheet===o))===t))){const[i,o,r,a]=this.getters.getRect(e.zone,s);r>0&&a>0&&(t.strokeStyle=e.color,t.strokeRect(i+n/2,o+n/2,r-n,a-n),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(i+n,o+n,r-2*n,a-2*n))}}}function Fh(e,t){return e.isFormula()&&t?"left":e.defaultAlign}function $h(e,t){let s=0,i=e.length-1;for(;s<=i;){const o=Math.floor((s+i)/2),n=e[o];if(t<n.start)i=o-1;else if(t>n.end)s=o+1;else{if(!n.isHidden)return o;s+=1}}return-1}kh.modes=["normal"],kh.layers=[1],kh.getters=["getHighlights"];class Dh extends mh{constructor(){super(...arguments),this.boxes=[]}getColIndex(e,t,s){if(e<m)return-1;const i=(s||this.getters.getActiveSheet()).cols;return $h(i,e-m+i[t].start+1)}getRowIndex(e,t,s){if(e<f)return-1;const i=(s||this.getters.getActiveSheet()).rows;return $h(i,e-f+i[t].start+1)}getRect(e,t){const{left:s,top:i,right:o,bottom:n}=e;let{offsetY:r,offsetX:a}=t;a-=m,r-=f;const{cols:l,rows:c}=this.getters.getActiveSheet(),h=Math.max(l[s].start-a,m),d=l[o].end-a-h,u=Math.max(c[i].start-r,f);return[h,u,d,c[n].end-r-u]}isVisibleInViewport(e,t,s){const{right:i,left:o,top:n,bottom:r}=s;return t<=r&&t>=n&&e>=o&&e<=i}getEdgeScrollCol(e){let t=!1,s=0,i=0;const{width:o}=this.getters.getViewportDimension(),{width:n}=this.getters.getGridDimension(this.getters.getActiveSheet()),{left:r,offsetX:a}=this.getters.getActiveSnappedViewport();return e<m&&r>0?(t=!0,s=-1,i=rs(m-e)):e>o&&a<n-o&&(t=!0,s=1,i=rs(e-o)),{canEdgeScroll:t,direction:s,delay:i}}getEdgeScrollRow(e){let t=!1,s=0,i=0;const{height:o}=this.getters.getViewportDimension(),{height:n}=this.getters.getGridDimension(this.getters.getActiveSheet()),{top:r,offsetY:a}=this.getters.getActiveSnappedViewport();return e<f&&r>0?(t=!0,s=-1,i=rs(f-e)):e>o&&a<n-o&&(t=!0,s=1,i=rs(e-o)),{canEdgeScroll:t,direction:s,delay:i}}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,viewport:s,thinLineWidth:i}=e;let{offsetX:o,offsetY:n,top:r,left:a,bottom:l,right:c}=s;const{width:h,height:d}=this.getters.getViewportDimension(),{cols:u,rows:p,id:g}=this.getters.getActiveSheet();if(t.fillStyle="white",t.fillRect(0,0,h,d),o-=m,n-=f,!this.getters.getGridLinesVisibility(g))return;t.lineWidth=2*i,t.strokeStyle="#E2E3E3",t.beginPath();const v=Math.min(d,p[l].end-n);for(let e=a;e<=c;e++){if(u[e].isHidden)continue;const s=u[e].end-o;t.moveTo(s,0),t.lineTo(s,v)}const E=Math.min(h,u[c].end-o);for(let e=r;e<=l;e++){if(p[e].isHidden)continue;const s=p[e].end-n;t.moveTo(0,s),t.lineTo(E,s)}t.stroke()}drawCellBackground(e){const{ctx:t,thinLineWidth:s}=e;t.lineWidth=.3*s;const i=.1*s;t.strokeStyle="#111";const o=this.getters.getGridLinesVisibility(this.getters.getActiveSheetId());for(let e of this.boxes){let s=e.style;s&&s.fillColor&&"#ffffff"!==s.fillColor&&(t.fillStyle=s.fillColor,t.fillRect(e.x,e.y,e.width,e.height),o&&t.strokeRect(e.x+i,e.y+i,e.width-2*i,e.height-2*i)),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:o,width:n,height:r}=e;t.left&&i(t.left,s,o,s,o+r),t.top&&i(t.top,s,o,s+n,o),t.right&&i(t.right,s+n,o,s+n,o+r),t.bottom&&i(t.bottom,s,o+r,s+n,o+r)}}function i([e,i],o,n,r,a){t.strokeStyle=i,t.lineWidth=("thin"===e?2:3)*s,t.beginPath(),t.moveTo(o,n),t.lineTo(r,a),t.stroke()}}drawTexts(e){const{ctx:t,thinLineWidth:s}=e;let i;t.textBaseline="middle";for(let e of this.boxes)if(e.text){const o=e.style||{},n=e.align,r=o.italic?"italic ":"",a=o.bold?"bold":x,l=o.fontSize||T,c=ls[l],h=`${r}${a} ${c}px ${R}`;let d;h!==i&&(i=h,t.font=h),t.fillStyle=o.textColor||"#000";let u=e.y+e.height/2+1;d="left"===n?e.x+(e.image?e.image.size+2*I: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.text,Math.round(d),Math.round(u)),(o.strikethrough||o.underline)&&("right"===n?d-=e.textWidth:"center"===n&&(d-=e.textWidth/2),o.strikethrough&&t.fillRect(d,u,e.textWidth,2.6*s),o.underline&&(u=e.y+e.height/2+1+c/2,t.fillRect(d,u,e.textWidth,1.3*s))),e.clipRect&&t.restore()}}async drawIcon(e){const{ctx:t}=e;for(let e of this.boxes)if(e.image){let s=e.x,i=e.y;const o=e.image.image,n=e.image.size,r=(e.height-n)/2;e.image.clipIcon&&(t.save(),t.beginPath(),t.rect(...e.image.clipIcon),t.clip()),t.drawImage(o,s+I,i+r,n,n),e.image.clipIcon&&t.restore()}}drawHeaders(e){const{ctx:t,viewport:s,thinLineWidth:i}=e;let{offsetX:o,offsetY:n,left:r,top:a,right:l,bottom:p}=s;const{width:g,height:v}=this.getters.getViewportDimension();o-=m,n-=f;const E=this.getters.getSelectedZones(),{cols:b,rows:S}=this.getters.getActiveSheet(),C=this.getters.getActiveCols(),I=this.getters.getActiveRows();t.fillStyle=c,t.font=`400 11px ${R}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=i,t.strokeStyle="#333",t.fillRect(0,0,g,f),t.fillRect(0,0,m,v),t.fillStyle=h;for(let e of E){const s=Math.max(m,b[e.left].start-o),i=Math.max(m,b[e.right].end-o),r=Math.max(f,S[e.top].start-n),a=Math.max(f,S[e.bottom].end-n);t.fillStyle=C.has(e.left)?d:h,t.fillRect(s,0,i-s,f),t.fillStyle=I.has(e.top)?d:h,t.fillRect(0,r,m,a-r)}t.beginPath(),t.moveTo(m,0),t.lineTo(m,v),t.moveTo(0,f),t.lineTo(g,f),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(let e=r;e<=l;e++){const s=b[e];s.isHidden||(t.fillStyle=C.has(e)?"#fff":u,t.fillText(s.name,(s.start+s.end)/2-o,13),t.moveTo(s.end-o,0),t.lineTo(s.end-o,f))}for(let e=a;e<=p;e++){const s=S[e];s.isHidden||(t.fillStyle=I.has(e)?"#fff":u,t.fillText(s.name,24,(s.start+s.end)/2-n),t.moveTo(0,s.end-n),t.lineTo(m,s.end-n))}t.stroke()}hasContent(e,t){const s=this.getters.getActiveSheetId(),i=this.getters.getCell(s,e,t);return i&&!i.isEmpty()||this.getters.isInMerge(s,e,t)}getGridBoxes(e){const{viewport:t}=e;let{right:s,left:i,top:o,bottom:n,offsetX:r,offsetY:a}=t;r-=m,a-=f;const l=this.getters.shouldShowFormulas(),c=[],{cols:h,rows:d,id:u}=this.getters.getActiveSheet();for(let e=o;e<=n;e++){const t=d[e];if(!t.isHidden)for(let o=i;o<=s;o++){const n=h[o];if(n.isHidden)continue;let d=t.cells[o];const p=this.getters.getCellBorder(u,o,e),g=this.getters.getConditionalStyle(o,e),f=this.getters.getConditionalIcon(o,e);if(!this.getters.isInMerge(u,o,e))if(d){const u=this.getters.getCellText(d,l);let m=this.getters.getCellStyle(d);g&&(m=Object.assign({},m,g));let v=u?m&&m.align||Fh(d,l):void 0,E=null,b=null;const S=this.getters.getTextWidth(d),C=m.fontSize||T,y=ls[C],w=f?y+2*I:0,x=w+S>h[o].size||ls[C]>t.size;if(x&&d.evaluated.type===Ne.number&&(v="center"!==v?"left":v),f){const e=n.end-n.start;E=[n.start-r+w,t.start-a,Math.max(0,e-w),t.size],b=[n.start-r,t.start-a,Math.min(w,e),t.size]}else if(x){let l,c;switch(v){case"left":for(l=o;l<s&&!this.hasContent(l+1,e);)l++;c=h[l].end-n.start,(c<S||ls[C]>t.size)&&(E=[n.start-r,t.start-a,c,t.size]);break;case"right":for(l=o;l>i&&!this.hasContent(l-1,e);)l--;c=n.end-h[l].start,(c<S||ls[C]>t.size)&&(E=[h[l].start-r,t.start-a,c,t.size]);break;case"center":let d=o;for(;d>i&&!this.hasContent(d-1,e);)d--;let u=o;for(;u<s&&!this.hasContent(u+1,e);)u++;const p=Math.min(d,o),g=Math.max(u,o);c=h[g].end-h[p].start,(c<S||p===o||g===o||ls[C]>t.size)&&(E=[h[p].start-r,t.start-a,c,t.size])}}c.push({x:n.start-r,y:t.start-a,width:n.size,height:t.size,text:u,textWidth:S,border:p,style:m,align:v,clipRect:E,error:d.evaluated.type===Ne.error?d.evaluated.error:void 0,image:f?{type:"icon",size:y,clipIcon:b,image:Ul[f].img}:void 0})}else c.push({x:n.start-r,y:t.start-a,width:n.size,height:t.size,text:"",textWidth:0,border:p,style:g||null,align:void 0,clipRect:null,error:void 0})}}const p=this.getters.getActiveSheetId();for(let e of this.getters.getMerges(p))if(!this.getters.isMergeHidden(p,e)&&Ps(e,t)){const t=this.getters.getCell(p,e.left,e.top),s=this.getters.getCellBorder(p,e.left,e.top),i=this.getters.getCellBorder(p,e.right,e.bottom),o=h[e.right].end-h[e.left].start;let n,u,g,f,m;if(g=t?this.getters.getCellStyle(t):null,t||i||s){n=t?this.getters.getCellText(t,l):"",u=t?this.getters.getTextWidth(t):null;const o=this.getters.getConditionalStyle(e.topLeft.col,e.topLeft.row);o&&(g=Object.assign({},g,o)),f=n?g&&g.align||Fh(t,l):null,m={bottom:i?i.bottom:null,left:s?s.left:null,right:i?i.right:null,top:s?s.top:null}}g=g||{},g.fillColor&&"#ffffff"!==g.fillColor||(g=Object.create(g),g.fillColor="#fff");const v=h[e.left].start-r,E=d[e.top].start-a,b=d[e.bottom].end-d[e.top].start,S=this.getters.getConditionalIcon(e.left,e.top),C=g.fontSize||T,y=ls[C],w=S?2*I+y:0,x=w+u;f=n&&(null==t?void 0:t.evaluated.type)===Ne.number&&x>o&&"center"!==f?"left":f;const R=S?[v+w,E,Math.max(0,o-w),b]:[v,E,o,b],L=S?[v,E,Math.min(w,o),b]:null;c.push({x:v,y:E,width:o,height:b,text:n,textWidth:u,border:m,style:g,align:f,clipRect:R,error:t&&t.evaluated.type===Ne.error?t.evaluated.error:void 0,image:S?{type:"icon",clipIcon:L,size:y,image:Ul[S].img}:void 0})}return c}}Dh.layers=[0,7],Dh.getters=["getColIndex","getRowIndex","getRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow"],Dh.modes=["normal"];const Ph=new ti;class Uh extends mh{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 i=e.value.split(",").map((e=>e.trim()));this.setRange(s,t,i)}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),i=(this.inputHasSingleRange[this.focusedInputId]?[this.getters.getSelectedZone()]:this.getters.getSelectedZones()).map(Ns).filter((e=>!s.includes(e))),o=this.activeSheets[this.focusedInputId],n=this.getters.getActiveSheetId(),r=this.getters.getSheetName(n);this.add(i.map((e=>n===o?e:`${us(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}=Jt(e);return null!==t.match(Qt)&&(!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()===Ch.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:Ph.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:Xt()}))))}setRange(e,t,s){const[,...i]=s;this.setContent(e,t,s[0]),this.insertNewRange(e,t+1,i),i.length&&this.focus(e,t+i.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 i=this.cleanInputs([t]).filter((e=>this.isRangeValid(e))).filter((t=>this.shouldBeHighlighted(this.activeSheets[e],t)));if(0===i.length)return[];const[o,...n]=i,r=[[o,s||Xt()]];for(const e of n)r.push([e,Xt()]);return r}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:s}=Jt(t),i=this.getters.getSheetIdByName(s),o=this.getters.getActiveSheet().id;return this.isRangeValid(t)&&(i===o||void 0===i&&o===e)}getIndex(e,t){const s=this.inputs[e].findIndex((e=>e.id===t));return s>=0?s:null}}Uh.modes=["normal"],Uh.layers=[1],Uh.getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];class Bh{constructor(){this.bus=new i.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 Vh(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?function(e,t,s){const i="left"===t?"right":"bottom";let o=e[t],n=e[i];for(let r of s.sort(((e,t)=>t-e)))e[t]>r&&(o--,n--),e[t]<=r&&e[i]>=r&&n--;if(!(o>n))return{...e,[t]:o,[i]:n}}(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?function(e,t,s,i,o){const n="left"===t?"columns":"rows",r="before"===i?s-1:s,a="left"===t?"right":"bottom",l="before"===i?e[a]>r:e[a]>=r;return e[t]<=r&&l?Ws(e,n,"RESIZE",o):r<e[t]?Ws(e,n,"MOVE",o):{...e}}(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}function Hh(e,t){const s=e.definition;let i,o;return s.labelRange&&(i=Vh(_s(s.labelRange),t)),s.dataSets&&(o=s.dataSets.map(_s).map((e=>Vh(e,t))).filter(Ls).map(Ns)),{...e,definition:{...s,dataSets:o,labelRange:i?Ns(i):void 0}}}dl.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],Hh),dl.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],Hh),dl.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),dl.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})),dl.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const s=[];for(const i of e.target)for(const e of t.target)Ps(i,e)||s.push({...i});if(s.length)return{...e,target:s};return}));const zh=[{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 i of e.target){const e=Vh(i,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 i=e[s];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(i))return"IGNORE_COMMAND";for(let t of e)i>=t&&i--}"ADD_COLUMNS_ROWS"===t.type&&(i>t.base||i===t.base&&"before"===t.position)&&(i+=t.quantity);return{...e,[s]:i}}(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)&&Us(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,i=s?"base":"elements";let o=s?[e[i]]:e[i];if("REMOVE_COLUMNS_ROWS"===t.type&&(o=o.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(Ls)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;o=o.map((s=>s>e?s+t.quantity:s))}if(o.length){let t=o;return s&&(t=o[0]),{...e,[i]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}}];function Zh(e,t){const s=dl.getTransformation(e.type,t.type);return s?s(e,t):function(e,t){for(const{match:s,fn:i}of zh)if(s(e)){const s=i(e,t);if("SKIP_TRANSFORMATION"===s)continue;if("IGNORE_COMMAND"===s)return;return s}return e}(e,t)}function Gh(e,t){let s=[...e];for(const e of t)s=s.map((t=>Zh(t,e))).filter(Ls);return s}class Wh{constructor(e,t,s,i){this._commands=[],this._changes=[],this.id=e,this.clientId=t,this._commands=[...s],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class qh extends Error{}class jh extends Bh{constructor(e,t,s=O){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 ti,this.debouncedMove=i.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 Wh(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,this.on("unexpected-revision-id",this,(({revisionId:e})=>{throw new Error(`The spreadsheet could not be loaded. Revision ${e} is corrupted.`)}));for(const t of e)this.onMessageReceived(t);this.off("unexpected-revision-id",this),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 qh("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(Ls))}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 i=s?"CLIENT_MOVED":"CLIENT_JOINED",o=this.getClient();this.clients[this.clientId]={...o,position:e},this.transportService.sendMessage({type:i,version:1,client:{...o,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){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":if(e.serverRevisionId!==this.serverRevisionId)return void this.trigger("unexpected-revision-id",{revisionId:e.serverRevisionId});const{clientId:t,commands:s}=e,i=new Wh(e.nextRevisionId,t,s);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:Gh(s,t)})}break;case"SNAPSHOT_CREATED":{const t=new Wh(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}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter((({type:e})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const Xh=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];class Yh extends mh{constructor(){super(...arguments),this.availableColors=new Set(Xh),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(Xh));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 qh)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 i=this.colors[s.id];t.push({...s,position:e,color:i})}return t}drawGrid(e){const{viewport:t,ctx:s,thinLineWidth:i}=e,o=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:n,col:r}=e.position,a=this.getters.expandZone(o,{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*i,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 ${T+1}px ${R}`}}}Yh.getters=["getClientsToDisplay"],Yh.layers=[5],Yh.modes=["normal"];class Kh extends mh{allowDispatch(e){if("SORT_CELLS"===e.type){if(!Us(e.anchor[0],e.anchor[1],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)e.interactive?this.interactiveSortSelection(e.sheetId,e.anchor,e.zone,e.sortDirection):this.sortZone(e.sheetId,e.anchor,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 i=t.left;i<=t.right;i++)if(!this.getters.isInMerge(e,i,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=>Ps(e,t))),i=zs(s[0]);let[o,n]=[i.width,i.height];return s.every((e=>{let[t,s]=[e.right-e.left+1,e.bottom-e.top+1];return t===o&&s===n}))?0:48}interactiveSortSelection(e,t,s,i){let o=Pe.Success,n=s.right>s.left;if(this.getters.doesIntersectMerge(e,s)){let t;n=!1;for(let i=s.top;i<=s.bottom;i++){t=[];for(let o=s.left;o<=s.right;o++){let s=this.getters.getMerge(e,o,i);s&&!t.includes(s.id.toString())&&t.push(s.id.toString())}if(t.length>=2){n=!0;break}}}if(n)o=this.dispatch("SORT_CELLS",{sheetId:e,anchor:t,zone:s,sortDirection:i});else{const n=this.getContiguousZone(e,s);Ds(n,s)?o=this.dispatch("SORT_CELLS",{sheetId:e,anchor:t,zone:s,sortDirection:i}):this.ui.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?"),(()=>{s=n,o=this.dispatch("SORT_CELLS",{sheetId:e,anchor:t,zone:s,sortDirection:i})}),(()=>{o=this.dispatch("SORT_CELLS",{sheetId:e,anchor:t,zone:s,sortDirection:i})}))}o.isCancelledBecause(48)&&(this.dispatch("SET_SELECTION",{anchor:t,zones:[s],anchorZone:s}),this.ui.notifyUser(a("Cannot sort. To sort, select only cells or only merges that have the same size.")))}expand(e,t){const{left:s,right:i,top:o,bottom:n}=this.getters.expandZone(e.id,t);return{left:Math.max(0,s),right:Math.min(e.cols.length-1,i),top:Math.max(0,o),bottom:Math.min(e.rows.length-1,n)}}checkExpandedValues(e,t){const s=this.expand(e,t),i=e.id;let o,n=[];if(this.getters.doesIntersectMerge(i,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(i,s,e);o=this.getters.getCell(i,t,r),n.push((null==o?void 0:o.formattedValue)||"")}}else{const t=Hs(s,e,(e=>e.formattedValue),"");n=t.flat()}return n.some((e=>""!==e))}getContiguousZone(e,t){let s,{top:i,bottom:o,left:n,right:r}=t;const a=this.getters.getSheet(e);let l=!1;for(;!l;)l=!0,i>0&&(s=this.checkExpandedValues(a,{left:n-1,right:r+1,top:i-1,bottom:i-1}),s&&(l=!1,i--)),n>0&&(s=this.checkExpandedValues(a,{left:n-1,right:n-1,top:i-1,bottom:o+1}),s&&(l=!1,n--)),r<a.cols.length-1&&(s=this.checkExpandedValues(a,{left:r+1,right:r+1,top:i-1,bottom:o+1}),s&&(l=!1,r++)),o<a.rows.length-1&&(s=this.checkExpandedValues(a,{left:n-1,right:r+1,top:o+1,bottom:o+1}),s&&(l=!1,o++));return{left:n,right:r,top:i,bottom:o}}hasHeader(e,t,s,i){const{left:o,right:n,top:r,bottom:a}=t;if(a-r+1==1)return!1;let l=Hs({left:o,right:n,top:r,bottom:r+2*i-1},e,(e=>e.evaluated.type),Ne.empty,s,i);return l[0][0]===Ne.empty&&(l=l.slice(1)),!l.some((e=>e[0]===Ne.empty))&&!!l.some((e=>e[1]!==Ne.empty&&e[0]!==e[1]))}sortCellsList(e,t){const s=e.map(((e,t)=>({index:t,val:e}))),i=s.filter((e=>!(null==e.val||""===e.val.evaluated.value))),o=s.filter((e=>null==e.val||""===e.val.evaluated.value)),n="descending"===t?-1:1,r=[Ne.number,Ne.error,Ne.text,Ne.boolean];return i.map((e=>{return{index:e.index,val:(t=e.val,{type:t.evaluated.type,value:t.evaluated.value})};var t})).sort(((e,t)=>{let s=r.indexOf(e.val.type)-r.indexOf(t.val.type);return 0===s&&(s=e.val.type===Ne.text||e.val.type===Ne.error?e.val.value.localeCompare(t.val.value):e.val.value-t.val.value),n*s})).concat(o)}sortZone(e,t,s,i){let o=1,n=1,r=t[0],a=Object.assign({},s);if(this.getters.doesIntersectMerge(e,a)){const[s,i]=t,a=this.getters.getMerge(e,s,i);o=a.right-a.left+1,n=a.bottom-a.top+1,r=a.topLeft.col}const l=this.getters.getSheet(e);this.hasHeader(l,a,o,n)&&(a.top+=n);const c=Hs(a,l,(e=>e),void 0,o,n),h=c[r-a.left],d=this.sortCellsList(h,i).map((e=>e.index)),[u,p]=[c.length,c[0].length];for(let t=0;t<u;t++)for(let s=0;s<p;s++){let i=c[t][d[s]],r=a.left+t*o,l=a.top+s*n,h={sheetId:e,col:r,row:l,content:"",value:""};if(i){let t=i.content;if(i.isFormula()){const s=l-this.getters.getCellPosition(i.id).row,o=this.getters.createAdaptedRanges(i.dependencies.references,0,s,e);t=this.getters.buildFormulaContent(e,i.normalizedText,{...i.dependencies,references:o})}h.style=i.style,h.content=t,h.format=i.format,h.value=i.evaluated.value}this.dispatch("UPDATE_CELL",h)}}}Kh.getters=["getContiguousZone"];class Qh extends mh{constructor(){super(...arguments),this.showFormulas=!1}handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}Qh.modes=["normal"],Qh.getters=["shouldShowFormulas"];class Jh extends mh{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}allowDispatch(e){switch(e.type){case"AUTORESIZE_ROWS":case"AUTORESIZE_COLUMNS":case"DELETE_SHEET_CONFIRMATION":try{this.getters.getSheet(e.sheetId);break}catch(e){return 23}}return 0}handle(e){switch(e.type){case"RENAME_SHEET":e.interactive&&this.interactiveRenameSheet(e.sheetId,a("Rename Sheet"));break;case"DELETE_SHEET_CONFIRMATION":this.interactiveDeleteSheet(e.sheetId);break;case"ADD_MERGE":e.interactive&&this.interactiveMerge(e.sheetId,e.target);break;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||T;return ls[s]+2*I}(this.ctx,this.getters.getCellStyle(e))),t}getTextWidth(e){const t=this.getters.getCellText(e,this.getters.shouldShowFormulas());return gs(this.ctx,t,this.getters.getCellStyle(e))}getCellHeight(e){const t=this.getters.getCellStyle(e).fontSize||T;return ls[t]}getCellText(e,t=!1){return t&&(e.isFormula()||e.evaluated.type===Ne.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),i=Object.values(s.rows[t].cells).map((e=>this.getCellHeight(e)));return Math.max(0,...i)}interactiveRenameSheet(e,t){const s=this.getters.getSheetName(e);this.ui.editText(t,s,(t=>{if(!t)return;const s=this.dispatch("RENAME_SHEET",{sheetId:e,name:t}),i=this.getters.getSheetName(e);s.isSuccessful||i===t||this.interactiveRenameSheet(e,a("Please enter a valid sheet name"))}))}interactiveDeleteSheet(e){this.ui.askConfirmation(a("Are you sure you want to delete this sheet ?"),(()=>{this.dispatch("DELETE_SHEET",{sheetId:e})}))}interactiveMerge(e,t){const s=this.dispatch("ADD_MERGE",{sheetId:e,target:t});s.isSuccessful||s.isCancelledBecause(3)&&this.ui.askConfirmation(a("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),(()=>{this.dispatch("ADD_MERGE",{sheetId:e,target:t,force:!0})}))}}Jh.getters=["getCellWidth","getCellHeight","getTextWidth","getCellText"];class ed extends mh{constructor(){super(...arguments),this.viewports={},this.snappedViewports={},this.updateSnap=!1,this.clientWidth=1e3,this.clientHeight=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"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)}getViewportDimension(){return{width:this.clientWidth,height:this.clientHeight}}getActiveViewport(){const e=this.getters.getActiveSheetId();return this.getViewport(e)}getActiveSnappedViewport(){const e=this.getters.getActiveSheetId();return this.getSnappedViewport(e)}getGridDimension(e){const t=oi(e,"cols"),s=this.clientWidth-m,i=oi(e,"rows"),o=this.clientHeight-f,n=e.cols.find((e=>e.end>t.end-s))||e.cols[e.cols.length-1],r=e.rows.find((e=>e.end>i.end-o))||e.rows[e.rows.length-1];return{width:t.end+Math.max(E,Math.min(n.size,s-t.size)),height:i.end+Math.max(b+5,Math.min(r.size,o-i.size))}}getMaximumViewportOffset(e){const{width:t,height:s}=this.getters.getGridDimension(e);return{maxOffsetX:Math.max(0,t-this.clientWidth+m+1),maxOffsetY:Math.max(0,s-this.clientHeight+f+1)}}checkOffsetValidity(e,t){const s=this.getters.getActiveSheet(),{maxOffsetX:i,maxOffsetY:o}=this.getMaximumViewportOffset(s);return e<0||t<0||t>o||e>i?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:i}=this.getGridDimension(this.getters.getSheet(e));if(this.clientWidth-m+s>i){const e=this.clientWidth-m+s-i;t.offsetX=Math.max(0,s-e)}this.adjustViewportZoneX(e,t)}adjustViewportOffsetY(e,t){const{offsetY:s}=t,{height:i}=this.getGridDimension(this.getters.getSheet(e));if(this.clientHeight-f+s>i){const e=this.clientHeight-f+s-i;t.offsetY=Math.max(0,s-e)}this.adjustViewportZoneY(e,t)}resizeViewport(e,t){this.clientHeight=e,this.clientWidth=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])}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),i=s.cols;t.left=this.getters.getColIndex(t.offsetX+m,0,s);const o=this.clientWidth+t.offsetX-m;t.right=i.length-1;for(let e=t.left;e<i.length;e++)if(o<i[e].end){t.right=e;break}this.updateSnap=!0}adjustViewportZoneY(e,t){const s=this.getters.getSheet(e),i=s.rows;t.top=this.getters.getRowIndex(t.offsetY+f,0,s);const o=this.clientHeight+t.offsetY-f;t.bottom=i.length-1;for(let e=t.top;e<i.length;e++)if(o<i[e].end){t.bottom=e;break}this.updateSnap=!0}adjustViewportsPosition(e,t){const s=this.getters.getSheet(e),{cols:i,rows:o}=s,n=this.getSnappedViewport(e);t=t||this.getters.getSheetPosition(e);const[r,a]=si(s,...this.getters.getMainCell(e,t[0],t[1]));for(;i[r].end>n.offsetX+this.clientWidth-m&&n.offsetX<i[r].start;)n.offsetX=i[n.left].end,this.adjustViewportZoneX(e,n);for(;r<n.left;){const t=i.slice(0,n.left).reverse().findIndex((e=>!e.isHidden));n.offsetX=i[n.left-1-t].start,this.adjustViewportZoneX(e,n)}for(;o[a].end>n.offsetY+this.clientHeight-f&&n.offsetY<o[a].start;)n.offsetY=o[n.top].end,this.adjustViewportZoneY(e,n);for(;a<n.top;){const t=o.slice(0,n.top).reverse().findIndex((e=>!e.isHidden));n.offsetY=o[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),i=this.getViewport(e),o=Object.assign({},i);this.adjustViewportOffsetX(e,o),this.adjustViewportOffsetY(e,o),o.offsetX=t[o.left].start,o.offsetY=s[o.top].start,this.adjustViewportZone(e,o),this.snappedViewports[e]=o}}ed.getters=["getActiveViewport","getSnappedViewport","getActiveSnappedViewport","getViewportDimension","getGridDimension","getMaximumViewportOffset"],ed.modes=["normal"];const td=(new Re).add("sheet",ya).add("cell",ma).add("merge",Ca).add("borders",ga).add("conditional formatting",ba).add("figures",Sa).add("chart",va),sd=(new Re).add("selection",Ih).add("ui_sheet",Jh).add("ui_options",Qh).add("evaluation",Th).add("evaluation_cf",Ah).add("evaluation_chart",Mh).add("clipboard",Sh).add("edition",wh).add("highlight",kh).add("selectionInput",Uh).add("viewport",ed).add("grid renderer",Dh).add("autofill",Eh).add("find_and_replace",Oh).add("sort",Kh).add("automatic_sum",bh).add("format",Nh).add("selection_multiuser",Yh);class id{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 od extends i.core.EventBus{constructor(){super(...arguments),this.registry=new Re}add(e,t){this.registry.add(e,t);const s=i.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 nd extends i.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 rd(e){return Ra.get(e.type)(e)}function ad(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class ld{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:i,operation:o,after:n}=this.locateOperation(t);this.operations=[...i,o,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 ld(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 cd{constructor(e,t){this.id=e,this.data=t}transformed(e){return new cd(this.id,e(this.data))}}class hd{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new hd(function*(e,t){for(const s of e)if(yield s,s.operation.id===t)return}(this.operations,e))}stopBefore(e){return new hd(function*(e,t){for(const s of e){if(s.operation.id===t)return;yield s}}(this.operations,e))}startAfter(e){return new hd(function*(e,t){let s=!0;for(const i of e)s||(yield i),i.operation.id===t&&(s=!1)}(this.operations,e))}}class dd{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 hd(vs(this._execution(e),this._execution(e)))}revertedExecution(e){return new hd(vs(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){var s;const i=e.getLastOperationId()||(null===(s=this.previousBranch(e))||void 0===s?void 0:s.getLastOperationId());e.append(t),i&&this.insertPrevious(e,t,i)}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),i=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const o=e.fork(t.id);i&&this.branchingOperationIds.set(o,i),this.insertBranchAfter(e,o),this.transform(o,s)}redo(e){const t=this.nextBranch(e);if(!t)return;const s=this.nextBranch(t);this.removeBranchFromTree(t);const i=this.branchingOperationIds.get(t);i?this.branchingOperationIds.set(e,i):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 i=this.buildTransformation.without(s.data),o=t.fork(s.id);this.branchingOperationIds.set(o,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,o),o.transform(i);const n=this.nextBranch(o);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 i=this.branchingOperationIds.get(e),o=this.nextBranch(e);if(i&&o)if(e.getFirstOperationAmong(s,i)===i){const n=this.addToNextBranch(e,o,i,t,s);this.updateNextWith(o,n,s)}else{const e=this.buildTransformation.with(t.data);this.transform(o,e)}}addToNextBranch(e,t,s,i,o){let n=i;return o===s?(n=this.getTransformedOperation(e,s,i),t.prepend(n)):t.contains(o)?(n=this.getTransformedOperation(e,s,i),t.insert(n,o)):t.append(i),n}getTransformedOperation(e,t,s){const i=e.getOperation(t),o=this.buildTransformation.without(i.data);return s.transformed(o)}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:i,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!i||!o)return;const n=this.buildTransformation.with(o.data),r=e.fork(s);r.transform(n),i.cutAfter(s),i.appendBranch(r);const a=t.transformed(n);this.insertPrevious(i,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 i=e.getOperations();for(let o=i.length-1;o>=0;o--){const n=i[o];n.id===t&&(s=!1),s||(yield{operation:n,branch:e,isCancelled:!this.shouldExecute(e,n)})}const o=this.previousBranch(e);yield*o?this._revertedExecution(o):[]}*_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 ud{constructor(e,t,s,i,o){this.applyOperation=t,this.revertOperation=s,this.buildEmpty=i,this.buildTransformation=o,this.HEAD_BRANCH=new ld(this.buildTransformation),this.tree=new dd(o,this.HEAD_BRANCH);const n=new cd(e,i(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 cd(e,t),i=this.tree.getLastBranch();this.tree.insertOperationLast(i,s),this.HEAD_BRANCH=i,this.HEAD_OPERATION=s}insert(e,t,s){const i=new cd(e,t);this.revertTo(s),this.tree.insertOperationAfter(this.HEAD_BRANCH,i,s),this.fastForward()}undo(e,t,s){const{branch:i,operation:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(i,o),this.fastForward(),this.insert(t,this.buildEmpty(t),s)}redo(e,t,s){const{branch:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(i),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:i}of e)i||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:i}of e)i||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=s}}function pd(e,t,s){return new ud(e,(e=>{const i=e.commands.slice(),{changes:o}=t((()=>{for(const e of i)s(e)}));e.setChanges(o)}),(e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){gd(t.changes[e],"before")}}([e])),(e=>new Wh(e,"empty",[],[])),{with:e=>t=>new Wh(t.id,t.clientId,Gh(t.commands,e.commands)),without:e=>t=>new Wh(t.id,t.clientId,Gh(t.commands,e.commands.map(rd).flat()))})}function gd(e,t){let s=e.root,i=e.path[e.path.length-1];for(let t=0;t<e.path.slice(0,-1).length;t++){const i=e.path[t];if(void 0===s[i]){const o=e.path[t+1];s[i]=ad(o)}s=s[i]}void 0===e[t]?delete s[i]:s[i]=e[t]}class fd extends i.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 md{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",i="COL"===e.dimension?"columns":"rows";e.elements.sort(((e,t)=>t-e));const o=ms(e.elements);this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};let r=n,a="NONE";for(let e of o){const o=Math.min(...e),l=Math.max(...e);if(n.zone[t]<=o&&o<=n.zone[s]){const e=Math.min(n.zone[s],l)-o+1;a="RESIZE",r=this.createAdaptedRange(r,i,a,-e)}else if(n.zone[t]>=o&&n.zone[s]<=l)a="REMOVE",r=this.buildInvalidRange(_);else if(n.zone[t]<=l&&n.zone[s]>=l){const e=l-n.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,i,a,-e),r=this.createAdaptedRange(r,i,"MOVE",-(n.zone[t]-o))}else o<n.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,i,a,-(l-o+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",i="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((o=>{if(o.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(o.zone[t]<=e.base&&e.base<o.zone[s])return{changeType:"RESIZE",range:this.createAdaptedRange(o,i,"RESIZE",e.quantity)};if(e.base<o.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(o,i,"MOVE",e.quantity)}}else{if(o.zone[t]<e.base&&e.base<=o.zone[s])return{changeType:"RESIZE",range:this.createAdaptedRange(o,i,"RESIZE",e.quantity)};if(e.base<=o.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(o,i,"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(_),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||Os(s.range.zone)?s:{range:s.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,s,i){return{...e,zone:Ws(e.zone,t,s,i)}}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 i=t[1].colFixed;t[1].colFixed=t[0].colFixed,t[0].colFixed=i}if(e.bottom<e.top){let s=e.bottom;e.bottom=e.top,e.top=s;let i=t[1].rowFixed;t[1].rowFixed=t[0].rowFixed,t[0].rowFixed=i}}createAdaptedRanges(e,t,s,i){return e.map((e=>Os(e.zone)?(e={...e,sheetId:e.prefixSheet?e.sheetId:i,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,i,o,n=t,r=!1;if(!Qt.test(t))return this.buildInvalidRange(t);t.includes("!")&&(({xc:n,sheetName:s}=Jt(t)),s?(i=this.getters.getSheetIdByName(s),r=!0,i||(o=s)):o=s);const a=As(n);let l=n.split(":").map((e=>({colFixed:e.startsWith("$"),rowFixed:e.includes("$",1)})));return this.orderZone(a,l),{sheetId:i||e,zone:a,parts:l,invalidSheetName:o,prefixSheet:r}}getRangeString(e,t){if(!e)return _;if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return _;if(e.zone.left<0||e.zone.top<0)return _;let s=e.sheetId!==t||e.invalidSheetName||e.prefixSheet,i="";if(s&&(i=e.invalidSheetName?e.invalidSheetName:us(this.getters.getSheetName(e.sheetId))),s&&!i)return _;let o=Array(9);return o[0]=e.parts&&e.parts[0].colFixed?"$":"",o[1]=es(e.zone.left),o[2]=e.parts&&e.parts[0].rowFixed?"$":"",o[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)&&(o[4]=":",o[5]=e.parts[1].colFixed?"$":"",o[6]=es(e.zone.right),o[7]=e.parts[1].rowFixed?"$":"",o[8]=String(e.zone.bottom+1)),`${s?i+"!":""}${o.join("")}`}buildInvalidRange(e){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:e}}}md.getters=["getRangeString","getRangeFromSheetXC","createAdaptedRanges"];class vd{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,...i]=e;let o=s,n=i[i.length-1];for(let e=0;e<=i.length-2;e++){const t=i[e];if(void 0===o[t]){const s=i[e+1];o[t]=ad(s)}o=o[t]}o[n]!==t&&(this.changes.push({root:s,path:i,before:o[n],after:t}),void 0===t?delete o[n]:o[n]=t)}}const Ed={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},bd={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},Sd={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"},Cd="http://schemas.openxmlformats.org/drawingml/2006/main",Id="http://schemas.openxmlformats.org/drawingml/2006/chart",yd={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"},wd="http://schemas.openxmlformats.org/officeDocument/2006/relationships",xd=.75,Td=.1425,Rd=164,Ld={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}]},Md=["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 Ad(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function _d(e){return Math.round(xd*e*window.devicePixelRatio*100)/100}function Od(e){return Math.round(Td*e*100)/100}function Nd(e,t){let s={};e.style&&(s=t.styles[e.style]);let i={};e.border&&(i=t.borders[e.border]);const o={font:{size:(null==s?void 0:s.fontSize)||T,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:e.format,border:i||{},verticalAlignment:"center",horizontalAlignment:null==s?void 0:s.align};return o.font.strike=!!(null==s?void 0:s.strikethrough)||void 0,o.font.underline=!!(null==s?void 0:s.underline)||void 0,o.font.bold=!!(null==s?void 0:s.bold)||void 0,o.font.italic=!!(null==s?void 0:s.italic)||void 0,o}function kd(e,t){const{id:s}=$d(t.font,e.fonts),{id:i}=$d(t.fill,e.fills),{id:o}=$d(t.border,e.borders),n=function(e,t){if(!e)return 0;let s=Ed[e];if(!s){const{id:i}=$d(e,t);s=i+Rd}return s}(t.numFmt,e.numFmts),r={fontId:s,fillId:i,borderId:o,numFmtId:n,verticalAlignment:t.verticalAlignment,horizontalAlignment:t.horizontalAlignment},{id:a}=$d(r,e.styles);return a}function Fd(e,t,s){let i,o=e.find((e=>e.path===t));return o?(i=`rId${(o.rels.length+1).toString()}`,o.rels.push({...s,id:i})):(i="rId1",e.push({path:t,rels:[{...s,id:i}]})),i}function $d(e,t){for(let[s,i]of Object.entries(t))if(JSON.stringify(i)===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 Dd=[];function Pd(e){const t=Dd.findIndex((t=>t===e));return-1===t?(Dd.push(e),Dd.length):t+1}function Ud(e){return Math.round(914400*e/96)}class Bd{constructor(e){this.xmlString=e}toString(){return this.xmlString}}function Vd(e,t,s){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:s}}function Hd(e){return String(e).replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;")}function zd(e){return new Bd(e.map((([e,t])=>`${e}="${Hd(t)}"`)).join(" "))}function Zd(e){const t=(new DOMParser).parseFromString(e.toString(),"text/xml"),s=t.querySelector("parsererror");if(s){const t=s.innerHTML,i=parseInt(t.split(":")[0],10),o=e.toString().trim().split("\n"),n=o.slice(Math.max(i-3,0),Math.min(i+2,o.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${n}`)}return t}function Gd(e,t){return qd`
1045
1045
  <Override ContentType="${t}" PartName="${e}" />
1046
- `}function Wd(e){return new Bd(e.join("\n"))}function qd(e,...t){let s=[e[0]];for(let i=0;i<t.length;i++){const o=t[i]instanceof Bd?t[i]:zd(t[i]);s.push(o+e[i+1])}return new Bd(s.join(""))}const jd=17781237,Xd=88853993;function Yd(e){const t=[["xmlns:r",wd],["xmlns:a",Cd],["xmlns:c",Id]],s=Kd({backgroundColor:Yt(e.data.backgroundColor),line:{color:"000000"}});let i=qd``;e.data.title&&(i=qd`
1046
+ `}function Wd(e){return new Bd(e.join("\n"))}function qd(e,...t){let s=[e[0]];for(let i=0;i<t.length;i++){const o=t[i]instanceof Bd?t[i]:Hd(t[i]);s.push(o+e[i+1])}return new Bd(s.join(""))}const jd=17781237,Xd=88853993;function Yd(e){const t=[["xmlns:r",wd],["xmlns:a",Cd],["xmlns:c",Id]],s=Kd({backgroundColor:Yt(e.data.backgroundColor),line:{color:"000000"}});let i=qd``;e.data.title&&(i=qd`
1047
1047
  <c:title>
1048
1048
  ${Jd(e.data.title)}
1049
1049
  <c:overlay val="0" />
@@ -1099,7 +1099,7 @@
1099
1099
  </c:lineChart>
1100
1100
  ${su("b","c:catAx",jd,Xd)}
1101
1101
  ${su(i,"c:valAx",Xd,jd)}
1102
- `}(e.data);break;case"pie":o=function(e,{holeSize:t}={holeSize:50}){const s=new Lh,i=Math.max(...e.dataSets.map((e=>{const t=_s(e.range),{height:s,width:i}=Hs(t);return s*i}))),o=fs(0,i).map((()=>Yt(s.next()))),n=[];for(const[t,s]of Object.entries(e.dataSets).reverse()){const i=_s(s.range),{height:r,width:a}=Hs(i),l=[];for(const e of fs(0,r*a)){const t=Kd({backgroundColor:o[e],line:{color:"FFFFFF",width:1.5}});l.push(qd`
1102
+ `}(e.data);break;case"pie":o=function(e,{holeSize:t}={holeSize:50}){const s=new Lh,i=Math.max(...e.dataSets.map((e=>{const t=_s(e.range),{height:s,width:i}=zs(t);return s*i}))),o=fs(0,i).map((()=>Yt(s.next()))),n=[];for(const[t,s]of Object.entries(e.dataSets).reverse()){const i=_s(s.range),{height:r,width:a}=zs(i),l=[];for(const e of fs(0,r*a)){const t=Kd({backgroundColor:o[e],line:{color:"FFFFFF",width:1.5}});l.push(qd`
1103
1103
  <c:dPt>
1104
1104
  <c:idx val="${e}"/>
1105
1105
  ${t}
@@ -1124,7 +1124,7 @@
1124
1124
  ${Wd(n)}
1125
1125
  </c:doughnutChart>
1126
1126
  `}(e.data,{holeSize:0})}let n="t";switch(e.data.legendPosition){case"bottom":n="b";break;case"left":n="l";break;case"right":n="r";break;case"top":n="t"}const r=qd`
1127
- <c:chartSpace ${Hd(t)}>
1127
+ <c:chartSpace ${zd(t)}>
1128
1128
  <c:roundedCorners val="0" />
1129
1129
  <!-- <manualLayout/> to manually position the chart in the figure container -->
1130
1130
  ${s}
@@ -1150,7 +1150,7 @@
1150
1150
  <c:spPr>
1151
1151
  ${e.backgroundColor?Qd(e.backgroundColor):""}
1152
1152
  ${e.line?function(e){const t=[["cmpd","sng"]];e.width&&t.push(["w",Ud(e.width)]);const s=e.style?qd`<a:prstDash val="${e.style}"/>`:"";return qd`
1153
- <a:ln ${Hd(t)}>
1153
+ <a:ln ${zd(t)}>
1154
1154
  ${Qd(e.color)}
1155
1155
  ${s}
1156
1156
  </a:ln>
@@ -1185,7 +1185,7 @@
1185
1185
  <a:lstStyle/>
1186
1186
  <a:p>
1187
1187
  <a:pPr lvl="0">
1188
- <a:defRPr ${Hd([["b",t?"1":"0"],["i",s?"1":"0"],["sz",100*e]])}>
1188
+ <a:defRPr ${zd([["b",t?"1":"0"],["i",s?"1":"0"],["sz",100*e]])}>
1189
1189
  ${Qd("000000")}
1190
1190
  <a:latin typeface="+mn-lt"/>
1191
1191
  </a:defRPr>
@@ -1239,24 +1239,24 @@
1239
1239
  ${n}
1240
1240
  </f>
1241
1241
  ${s}
1242
- `,{attrs:i,node:o}}{const t=e.value;if(t){const e=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n"}}(t);i.push(["t",e]),o=qd`<v>${t}</v>`}return{attrs:i,node:o}}}function ru(e,t){let s=e;const i=[];if(["TRUE","FALSE"].includes(s.trim()))s="TRUE"===s?"1":"0",i.push(["t","b"]);else if(!Q(s)){const{id:o}=$d(e,t);s=o.toString(),i.push(["t","s"])}return{attrs:i,node:qd`<v>${s}</v>`}}function au(e){let t;"="===e[0]&&(e=e.slice(1));try{t=Lr(e)}catch(t){return e}return t=Mr(t,"STRING",lu),t=Mr(t,"FUNCALL",(e=>(e=function(e){const t=e.value.toUpperCase(),s=e.args,i=Ld[t];if(i){const o=ir.content[t].args.filter((e=>!e.optional)),n=o.length-e.args.length;if(n)for(let t=e.args.length;t<o.length;t++){const e=i[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:Md.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})),e))),t?Ar(t):e}function lu(e){const t=e.value.replace(new RegExp('"',"g"),""),s=Z(t);if(s){let i=[];return(t.match(V)||t.match(z))&&i.push("yyyy-mm-dd"),t.match(H)&&i.push("hh:mm:ss"),{...e,value:`"${q({value:s.value,format:i.join(" ")})}"`}}return{...e,value:e.value.replace(/\\"/g,'""')}}function cu(e,t){const s=[];for(const i of t)switch(i.rule.type){case"CellIsRule":s.push(hu(i,i.rule,e));break;case"ColorScaleRule":s.push(du(i,i.rule));break;case"IconSetRule":s.push(uu(i,i.rule));break;default:console.warn(`Conditional formatting ${i.rule.type} not implemented`)}return s}function hu(e,t,s){const i=pu(e),o=Ad(t.operator);i.push(...function(e){const t=Ad(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",o]);const n=function(e,t){const s=e[0].split(":")[0],i=t.values;switch(t.operator){case"ContainsText":return[`NOT(ISERROR(SEARCH("${i[0]}",${s})))`];case"NotContains":return[`ISERROR(SEARCH("${i[0]}",${s}))`];case"BeginsWith":return[`LEFT(${s},LEN("${i[0]}"))="${i[0]}"`];case"EndsWith":return[`RIGHT(${s},LEN("${i[0]}"))="${i[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[i[0]];case"Between":case"NotBetween":return[i[0],i[1]]}}(e.ranges,t).map((e=>qd`<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}=$d(r,s);return i.push(["dxfId",a]),qd`
1242
+ `,{attrs:i,node:o}}{const t=e.value;if(t){const e=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n"}}(t);i.push(["t",e]),o=qd`<v>${t}</v>`}return{attrs:i,node:o}}}function ru(e,t){let s=e;const i=[];if(["TRUE","FALSE"].includes(s.trim()))s="TRUE"===s?"1":"0",i.push(["t","b"]);else if(!Q(s)){const{id:o}=$d(e,t);s=o.toString(),i.push(["t","s"])}return{attrs:i,node:qd`<v>${s}</v>`}}function au(e){let t;"="===e[0]&&(e=e.slice(1));try{t=Lr(e)}catch(t){return e}return t=Mr(t,"STRING",lu),t=Mr(t,"FUNCALL",(e=>(e=function(e){const t=e.value.toUpperCase(),s=e.args,i=Ld[t];if(i){const o=ir.content[t].args.filter((e=>!e.optional)),n=o.length-e.args.length;if(n)for(let t=e.args.length;t<o.length;t++){const e=i[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:Md.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})),e))),t?Ar(t):e}function lu(e){const t=e.value.replace(new RegExp('"',"g"),""),s=Z(t);if(s){let i=[];return(t.match(V)||t.match(H))&&i.push("yyyy-mm-dd"),t.match(z)&&i.push("hh:mm:ss"),{...e,value:`"${q({value:s.value,format:i.join(" ")})}"`}}return{...e,value:e.value.replace(/\\"/g,'""')}}function cu(e,t){const s=[];for(const i of t)switch(i.rule.type){case"CellIsRule":s.push(hu(i,i.rule,e));break;case"ColorScaleRule":s.push(du(i,i.rule));break;case"IconSetRule":s.push(uu(i,i.rule));break;default:console.warn(`Conditional formatting ${i.rule.type} not implemented`)}return s}function hu(e,t,s){const i=pu(e),o=Ad(t.operator);i.push(...function(e){const t=Ad(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",o]);const n=function(e,t){const s=e[0].split(":")[0],i=t.values;switch(t.operator){case"ContainsText":return[`NOT(ISERROR(SEARCH("${i[0]}",${s})))`];case"NotContains":return[`ISERROR(SEARCH("${i[0]}",${s}))`];case"BeginsWith":return[`LEFT(${s},LEN("${i[0]}"))="${i[0]}"`];case"EndsWith":return[`RIGHT(${s},LEN("${i[0]}"))="${i[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[i[0]];case"Between":case"NotBetween":return[i[0],i[1]]}}(e.ranges,t).map((e=>qd`<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}=$d(r,s);return i.push(["dxfId",a]),qd`
1243
1243
  <conditionalFormatting sqref="${e.ranges.join(" ")}">
1244
- <cfRule ${Hd(i)}>
1244
+ <cfRule ${zd(i)}>
1245
1245
  ${Wd(n)}
1246
1246
  </cfRule>
1247
1247
  </conditionalFormatting>
1248
- `}function du(e,t){const s=pu(e);s.push(["type","colorScale"]);const i=[];for(const o of e.ranges){const e=[],n=[];let r=!0;for(let s of["minimum","midpoint","maximum"]){const i=t[s];i&&("formula"!==i.type?(e.push(fu(i,s)),n.push([["rgb",qt(i.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=>qd`<cfvo ${Hd(e)}/>`)),l=n.map((e=>qd`<color ${Hd(e)}/>`));i.push(qd`
1248
+ `}function du(e,t){const s=pu(e);s.push(["type","colorScale"]);const i=[];for(const o of e.ranges){const e=[],n=[];let r=!0;for(let s of["minimum","midpoint","maximum"]){const i=t[s];i&&("formula"!==i.type?(e.push(fu(i,s)),n.push([["rgb",qt(i.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=>qd`<cfvo ${zd(e)}/>`)),l=n.map((e=>qd`<color ${zd(e)}/>`));i.push(qd`
1249
1249
  <conditionalFormatting sqref="${o}">
1250
- <cfRule ${Hd(s)}>
1250
+ <cfRule ${zd(s)}>
1251
1251
  <colorScale>
1252
1252
  ${Wd(a)}
1253
1253
  ${Wd(l)}
1254
1254
  </colorScale>
1255
1255
  </cfRule>
1256
1256
  </conditionalFormatting>
1257
- `)}return Wd(i)}function uu(e,t){const s=pu(e);s.push(["type","iconSet"]);const i=[];for(const o of e.ranges){const e=[[["type","percent"],["val",0]]];let n=!0;for(let s of["lowerInflectionPoint","upperInflectionPoint"]){if("formula"===t[s].type){n=!1;continue}const i=t[s];e.push([...fu(i,s),["gte","ge"===i.operator?"1":"0"]])}if(!n){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const r=e.map((e=>qd`<cfvo ${Hd(e)} />`));i.push(qd`
1257
+ `)}return Wd(i)}function uu(e,t){const s=pu(e);s.push(["type","iconSet"]);const i=[];for(const o of e.ranges){const e=[[["type","percent"],["val",0]]];let n=!0;for(let s of["lowerInflectionPoint","upperInflectionPoint"]){if("formula"===t[s].type){n=!1;continue}const i=t[s];e.push([...fu(i,s),["gte","ge"===i.operator?"1":"0"]])}if(!n){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const r=e.map((e=>qd`<cfvo ${zd(e)} />`));i.push(qd`
1258
1258
  <conditionalFormatting sqref="${o}">
1259
- <cfRule ${Hd(s)}>
1259
+ <cfRule ${zd(s)}>
1260
1260
  <iconSet iconSet="${gu(t.icons)}">
1261
1261
  ${Wd(r)}
1262
1262
  </iconSet>
@@ -1278,7 +1278,7 @@
1278
1278
  </xdr:to>
1279
1279
  <xdr:graphicFrame>
1280
1280
  <xdr:nvGraphicFramePr>
1281
- <xdr:cNvPr ${Hd(l)} />
1281
+ <xdr:cNvPr ${zd(l)} />
1282
1282
  <xdr:cNvGraphicFramePr />
1283
1283
  </xdr:nvGraphicFramePr>
1284
1284
  <xdr:xfrm>
@@ -1294,7 +1294,7 @@
1294
1294
  <xdr:clientData fLocksWithSheet="0"/>
1295
1295
  </xdr:twoCellAnchor>
1296
1296
  `)}return Zd(qd`
1297
- <xdr:wsDr ${Hd(i)}>
1297
+ <xdr:wsDr ${zd(i)}>
1298
1298
  ${Wd(o)}
1299
1299
  </xdr:wsDr>
1300
1300
  `)}function vu(e,t){const{x:s,y:i,height:o,width:n}=e,r=Object.values(t.cols),a=Object.values(t.rows),{index:l,offset:c}=Eu(r,s),{index:h,offset:d}=Eu(r,s+n),{index:u,offset:p}=Eu(a,i),{index:g,offset:f}=Eu(a,i+o);return{from:{col:l,colOff:c,row:u,rowOff:p},to:{col:h,colOff:d,row:g,rowOff:f}}}function Eu(e,t){let s=0;for(const[i,o]of Object.entries(e)){if(s<=t&&t<s+o.size)return{index:parseInt(i),offset:Ud(t-s+w)};s+=o.size}return{index:e.length-1,offset:Ud(t-s+w)}}function bu(e){return 0===Object.values(e).filter(Ls).length?qd``:qd`
@@ -1307,18 +1307,18 @@
1307
1307
  ${e.color?qd`<color rgb="${Yt(e.color)}" />`:""}
1308
1308
  ${e.name?qd`<name val="${e.name}" />`:""}
1309
1309
  </font>
1310
- `}function Su(e){return e?Hd([["style",e[0]],["color",Yt(e[1])]]):qd``}function Cu(e){if(!Object.values(e).length)return qd``;const t=[];for(let[s,i]of Object.entries(e)){const e=[["min",parseInt(s)+1],["max",parseInt(s)+1],["width",Od(i.size||E)],["customWidth",1],["hidden",i.isHidden?1:0]];t.push(qd`
1311
- <col ${Hd(e)}/>
1310
+ `}function Su(e){return e?zd([["style",e[0]],["color",Yt(e[1])]]):qd``}function Cu(e){if(!Object.values(e).length)return qd``;const t=[];for(let[s,i]of Object.entries(e)){const e=[["min",parseInt(s)+1],["max",parseInt(s)+1],["width",Od(i.size||E)],["customWidth",1],["hidden",i.isHidden?1:0]];t.push(qd`
1311
+ <col ${zd(e)}/>
1312
1312
  `)}return qd`
1313
1313
  <cols>
1314
1314
  ${Wd(t)}
1315
1315
  </cols>
1316
1316
  `}function Iu(e,t,s){const i=[];for(let o=0;o<s.rowNumber;o++){const n=[["r",o+1]],r=s.rows[o]||{};n.push(["ht",_d(r.size||b)],["customHeight",1],["hidden",r.isHidden?1:0]);const a=[];for(let i=0;i<s.colNumber;i++){const n=ss(i,o),r=s.cells[n];if(r){const s=[["r",n]],i=kd(e,Nd(r,t));s.push(["s",i]);let o=[],l=qd``;if(r.isFormula)({attrs:o,node:l}=nu(r));else if(r.content&&Is(r.content)){const{label:t}=ws(r.content);({attrs:o,node:l}=ru(t,e.sharedStrings))}else r.content&&""!==r.content&&({attrs:o,node:l}=ru(r.content,e.sharedStrings));s.push(...o),a.push(qd`
1317
- <c ${Hd(s)}>
1317
+ <c ${zd(s)}>
1318
1318
  ${l}
1319
1319
  </c>
1320
1320
  `)}}a.length&&i.push(qd`
1321
- <row ${Hd(n)}>
1321
+ <row ${zd(n)}>
1322
1322
  ${Wd(a)}
1323
1323
  </row>
1324
1324
  `)}return qd`
@@ -1338,16 +1338,16 @@
1338
1338
  ${Wd(t)}
1339
1339
  </mergeCells>
1340
1340
  `}return qd``}function xu(e){const t=[],s={relsFiles:[],sharedStrings:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,verticalAlignment:"center"}],fonts:[{size:T,family:2,color:"000000",name:"Calibri"}],fills:[{reservedAttribute:"none"},{reservedAttribute:"gray125"}],borders:[{}],numFmts:[],dxfs:[]};return t.push(function(e,t){const s=[["xmlns",Sd.workbook],["xmlns:r",wd]],i=[];for(const[s,o]of Object.entries(e.sheets)){const e=[["name",o.name],["sheetId",parseInt(s)+1],["r:id",`rId${parseInt(s)+1}`]];i.push(qd`
1341
- <sheet ${Hd(e)} />
1341
+ <sheet ${zd(e)} />
1342
1342
  `),Fd(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",target:`worksheets/sheet${s}.xml`})}const o=qd`
1343
- <workbook ${Hd(s)}>
1343
+ <workbook ${zd(s)}>
1344
1344
  <sheets>
1345
1345
  ${Wd(i)}
1346
1346
  </sheets>
1347
1347
  </workbook>
1348
1348
  `;return Vd(Zd(o),"xl/workbook.xml","workbook")}(e,s)),t.push(...function(e,t){const s=[];for(const[i,o]of Object.entries(e.sheets)){const n=[["xmlns",Sd.worksheet],["xmlns:r",wd]],r=[["defaultRowHeight",_d(b)],["defaultColWidth",Od(E)]];let a=qd``;const l=o.charts;if(l.length){const e=[];for(const o of l){const n=Pd(o.id),r=Fd(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../charts/chart${n}.xml`,type:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart"});e.push(r),s.push(Vd(Yd(o),`xl/charts/chart${n}.xml`,"chart"))}const n=Fd(t.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:`../drawings/drawing${i}.xml`,type:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing"});s.push(Vd(mu(e,o,l),`xl/drawings/drawing${i}.xml`,"drawing")),a=qd`<drawing r:id="${n}" />`}const c=qd`
1349
- <worksheet ${Hd(n)}>
1350
- <sheetFormatPr ${Hd(r)} />
1349
+ <worksheet ${zd(n)}>
1350
+ <sheetFormatPr ${zd(r)} />
1351
1351
  ${Cu(o.cols)}
1352
1352
  ${Iu(t,e,o)}
1353
1353
  ${wu(o.merges)}
@@ -1356,9 +1356,9 @@
1356
1356
  ${a}
1357
1357
  </worksheet>
1358
1358
  `;s.push(Vd(Zd(c),`xl/worksheets/sheet${i}.xml`,"sheet"))}return Fd(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",target:"sharedStrings.xml"}),Fd(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",target:"styles.xml"}),s}(e,s)),t.push(function(e){const t=qd`
1359
- <styleSheet ${Hd([["xmlns",Sd.styleSheet],["xmlns:r",wd]])}>
1359
+ <styleSheet ${zd([["xmlns",Sd.styleSheet],["xmlns:r",wd]])}>
1360
1360
  ${function(e){const t=[];for(let[s,i]of Object.entries(e)){const e=[["numFmtId",parseInt(s)+Rd],["formatCode",i]];t.push(qd`
1361
- <numFmt ${Hd(e)}/>
1361
+ <numFmt ${zd(e)}/>
1362
1362
  `)}return qd`
1363
1363
  <numFmts count="${e.length}">
1364
1364
  ${Wd(t)}
@@ -1399,8 +1399,8 @@
1399
1399
  </borders>
1400
1400
  `}(e.borders)}
1401
1401
  ${function(e){const t=[];for(let s of e){const e=[["numFmtId",s.numFmtId],["fillId",s.fillId],["fontId",s.fontId],["borderId",s.borderId]],i=[];s.verticalAlignment&&i.push(["vertical",s.verticalAlignment]),s.horizontalAlignment&&i.push(["horizontal",s.horizontalAlignment]),t.push(qd`
1402
- <xf ${Hd(e)}>
1403
- ${i?qd`<alignment ${Hd(i)} />`:""}
1402
+ <xf ${zd(e)}>
1403
+ ${i?qd`<alignment ${zd(i)} />`:""}
1404
1404
  </xf>
1405
1405
  `)}return qd`
1406
1406
  <cellXfs count="${e.length}">
@@ -1425,11 +1425,11 @@
1425
1425
  `}(e.dxfs)}
1426
1426
  </styleSheet>
1427
1427
  `;var s;return Vd(Zd(t),"xl/styles.xml","styles")}(s)),t.push(function(e){const t=[["xmlns",Sd.sst],["count",e.length],["uniqueCount",e.length]],s=e.map((e=>qd`<si><t>${e}</t></si>`)),i=qd`
1428
- <sst ${Hd(t)}>
1428
+ <sst ${zd(t)}>
1429
1429
  ${Wd(s)}
1430
1430
  </sst>
1431
1431
  `;return Vd(Zd(i),"xl/sharedStrings.xml","sharedStrings")}(s.sharedStrings)),t.push(...function(e){const t=[];for(const s of e){const e=[];for(const t of s.rels){const s=[["Id",t.id],["Target",t.target],["Type",t.type]];t.targetMode&&s.push(["TargetMode",t.targetMode]),e.push(qd`
1432
- <Relationship ${Hd(s)} />
1432
+ <Relationship ${zd(s)} />
1433
1433
  `)}const i=qd`
1434
1434
  <Relationships xmlns="${Sd.Relationships}">
1435
1435
  ${Wd(e)}
@@ -1442,7 +1442,7 @@
1442
1442
  </Types>
1443
1443
  `;return Vd(Zd(s),"[Content_Types].xml")}(t)),t.push(function(){const e=[["Id","rId1"],["Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"],["Target","xl/workbook.xml"]],t=qd`
1444
1444
  <Relationships xmlns="${Sd.Relationships}">
1445
- <Relationship ${Hd(e)} />
1445
+ <Relationship ${zd(e)} />
1446
1446
  </Relationships>
1447
1447
  `;return Vd(Zd(t),"_rels/.rels")}()),{name:"my_spreadsheet.xlsx",files:t}}var Tu;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing",e[e.Interactive=4]="Interactive"}(Tu||(Tu={}));class Ru extends i.core.EventBus{constructor(e={},t={},s=[],i=new ti){super(),this.corePlugins=[],this.uiPlugins=[],this.dataSources=new od,this.isReplayingCommand=!1,this.renderers=[],this.status=0,this.dispatch=(e,t)=>{const s={type:e,...t};let i=s.interactive?4:this.status;if(this.config.isReadonly&&(o=s,!Fe.has(o.type)))return new Pe(52);var o;if(!this.session.canApplyOptimisticUpdate())return new Pe(49);switch(i){case 0:const t=this.checkDispatchAllowed(s);if(!t.isSuccessful)return t;this.status=1;const{changes:i,commands:o}=this.state.recordChanges((()=>{De(s)&&this.state.addCommand(s),this.dispatchToHandlers(this.handlers,s),this.finalize()}));this.session.save(o,i),this.status=0,"headless"!==this.config.mode&&this.trigger("update");break;case 1:if(De(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 4:De(s)&&this.state.addCommand(s),this.dispatchToHandlers(this.handlers,s);break;case 3:throw new Error(a("Cannot dispatch commands in the finalize state"));case 2:if(De(s))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,s)}return Pe.Success},this.dispatchFromCorePlugin=(e,t)=>{const s={type:e,...t},i=this.status;this.status=2;const o=this.isReplayingCommand?[this.range,...this.corePlugins]:this.handlers;return this.dispatchToHandlers(o,s),this.status=i,Pe.Success},Ms.model=this,s=la(e,s);const o=ra(e);this.state=new vd,this.uuidGenerator=i,this.config=this.setupConfig(t),this.session=this.setupSession(o.revisionId),this.config.moveClient=this.session.move.bind(this.session),this.history=new fd(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 md(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 td.getAll())this.setupCorePlugin(e,o);for(let e of sd.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 Ms.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);s.import(t);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)}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 jh(pd(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 id;return{mode:e.mode||"normal",openSidePanel:e.openSidePanel||(()=>{}),notifyUser:e.notifyUser||(()=>{}),askConfirmation:e.askConfirmation||(()=>{}),editText:e.editText||(()=>{}),evalContext:e.evalContext||{},transportService:s,client:t,moveClient:()=>{},isHeadless:"headless"===e.mode||!1,isReadonly:e.isReadonly||!1,snapshotRequested:!1,dataSources:this.dataSources}}checkDispatchAllowed(e){const t=this.handlers.map((t=>t.allowDispatch(e)));return new Pe(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=da();for(let t of this.handlers)t instanceof pa&&t.export(e);return e.revisionId=this.session.getRevisionId()||O,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={...da(),sheets:[(t=na,s="Sheet1",{...ha(t,s),charts:[]})]};var t,s;for(let t of this.handlers)t instanceof pa&&t.exportForExcel(e);return e=JSON.parse(JSON.stringify(e)),xu(e)}}const{useComponent:Lu,useState:Mu,onPatched:Au,onMounted:_u}=t.hooks;function Ou(e){const t=Mu({x:0,y:0}),s=Lu(),i=function(){const e=Mu({x:0,y:0});let t=document.querySelector(".o-spreadsheet");function s(){if(t||(t=document.querySelector(".o-spreadsheet")),t){const{top:s,left:i}=t.getBoundingClientRect();e.x=i,e.y=s}}return _u(s),Au(s),e}();function o(){const o=(null==e?void 0:e.el)||s.el,{top:n,left:r}=o.getBoundingClientRect(),a=r-i.x,l=n-i.y;a===t.x&&l===t.y||(t.x=a,t.y=l)}return _u(o),Au(o),t}const{Portal:Nu}=t.misc,{xml:ku}=t.tags,Fu=ku`
1448
1448
  <Portal target="'.o-spreadsheet'">
@@ -1491,7 +1491,7 @@
1491
1491
  depth="props.depth + 1"
1492
1492
  t-ref="subMenuRef"
1493
1493
  t-on-close="subMenu.isOpen=false"/>
1494
- </Popover>`,zu=Pu`
1494
+ </Popover>`,Hu=Pu`
1495
1495
  .o-menu {
1496
1496
  background-color: white;
1497
1497
  padding: 8px 0px;
@@ -1539,7 +1539,7 @@
1539
1539
  margin-bottom: ${5}px;
1540
1540
  }
1541
1541
  }
1542
- `;class Hu extends t.Component{constructor(){super(...arguments),this.position=Ou(Bu("menu")),this.subMenuRef=Bu("subMenuRef"),Uu(window,"click",this.onClick),Uu(window,"contextmenu",this.onContextMenu),this.subMenu=t.useState({isOpen:!1,position:null,scrollOffset:0,menuItems:[]})}get subMenuPosition(){const e=Object.assign({},this.subMenu.position);return e.y-=this.subMenu.scrollOffset||0,e}get menuHeight(){return this.menuComponentHeight(this.props.menuItems)}get subMenuHeight(){return this.menuComponentHeight(this.subMenu.menuItems)}get popover(){const e=1===this.props.depth;return{marginTop:95,flipHorizontalOffset:y*(this.props.depth-1),flipVerticalOffset:e?0:24}}async activateMenu(e){const t=await e.action(this.env);this.close(),this.trigger("menu-clicked",t)}close(){this.subMenu.isOpen=!1,this.trigger("close")}subMenuVerticalPosition(e){const t=this.props.menuItems.slice(0,e);return this.menuComponentHeight(t)+this.position.y}onClick(e){this.el&&Mc(this.el,e)||this.close()}onContextMenu(e){this.el&&Mc(this.el,e)||(this.subMenu.isOpen=!1)}menuComponentHeight(e){const t=e.filter((e=>e.separator));return 24*e.length+11*t.length}getName(e){return nl.getName(e,this.env)}getShortCut(e){return nl.getShortCut(e)}isRoot(e){return!e.action}isEnabled(e){return!!e.isEnabled(this.env)&&(!this.env.getters.isReadonly()||e.isReadonlyAllowed)}closeSubMenus(){this.subMenuRef.comp&&this.subMenuRef.comp.closeSubMenus(),this.subMenu.isOpen=!1}onScroll(e){this.subMenu.scrollOffset=e.target.scrollTop}openSubMenu(e,t){this.closeSubMenus();const s=this.subMenuVerticalPosition(t);this.subMenu.position={x:this.position.x+y,y:s-(this.subMenu.scrollOffset||0)},this.subMenu.menuItems=nl.getChildren(e,this.env).filter((e=>!e.isVisible||e.isVisible(this.env))),this.subMenu.isOpen=!0}onClickMenu(e,t){this.isEnabled(e)&&(this.isRoot(e)?this.openSubMenu(e,t):this.activateMenu(e))}onMouseOver(e,t){e.isEnabled(this.env)&&(this.isRoot(e)?this.openSubMenu(e,t):this.subMenu.isOpen=!1)}}Hu.template=Vu,Hu.components={Menu:Hu,Popover:$u},Hu.style=zu,Hu.defaultProps={depth:1};const{xml:Zu,css:Gu}=t.tags,{useState:Wu}=t.hooks,qu=Zu`
1542
+ `;class zu extends t.Component{constructor(){super(...arguments),this.position=Ou(Bu("menu")),this.subMenuRef=Bu("subMenuRef"),Uu(window,"click",this.onClick),Uu(window,"contextmenu",this.onContextMenu),this.subMenu=t.useState({isOpen:!1,position:null,scrollOffset:0,menuItems:[]})}get subMenuPosition(){const e=Object.assign({},this.subMenu.position);return e.y-=this.subMenu.scrollOffset||0,e}get menuHeight(){return this.menuComponentHeight(this.props.menuItems)}get subMenuHeight(){return this.menuComponentHeight(this.subMenu.menuItems)}get popover(){const e=1===this.props.depth;return{marginTop:95,flipHorizontalOffset:y*(this.props.depth-1),flipVerticalOffset:e?0:24}}async activateMenu(e){const t=await e.action(this.env);this.close(),this.trigger("menu-clicked",t)}close(){this.subMenu.isOpen=!1,this.trigger("close")}subMenuVerticalPosition(e){const t=this.props.menuItems.slice(0,e);return this.menuComponentHeight(t)+this.position.y}onClick(e){this.el&&Mc(this.el,e)||this.close()}onContextMenu(e){this.el&&Mc(this.el,e)||(this.subMenu.isOpen=!1)}menuComponentHeight(e){const t=e.filter((e=>e.separator));return 24*e.length+11*t.length}getName(e){return nl.getName(e,this.env)}getShortCut(e){return nl.getShortCut(e)}isRoot(e){return!e.action}isEnabled(e){return!!e.isEnabled(this.env)&&(!this.env.getters.isReadonly()||e.isReadonlyAllowed)}closeSubMenus(){this.subMenuRef.comp&&this.subMenuRef.comp.closeSubMenus(),this.subMenu.isOpen=!1}onScroll(e){this.subMenu.scrollOffset=e.target.scrollTop}openSubMenu(e,t){this.closeSubMenus();const s=this.subMenuVerticalPosition(t);this.subMenu.position={x:this.position.x+y,y:s-(this.subMenu.scrollOffset||0)},this.subMenu.menuItems=nl.getChildren(e,this.env).filter((e=>!e.isVisible||e.isVisible(this.env))),this.subMenu.isOpen=!0}onClickMenu(e,t){this.isEnabled(e)&&(this.isRoot(e)?this.openSubMenu(e,t):this.activateMenu(e))}onMouseOver(e,t){e.isEnabled(this.env)&&(this.isRoot(e)?this.openSubMenu(e,t):this.subMenu.isOpen=!1)}}zu.template=Vu,zu.components={Menu:zu,Popover:$u},zu.style=Hu,zu.defaultProps={depth:1};const{xml:Zu,css:Gu}=t.tags,{useState:Wu}=t.hooks,qu=Zu`
1543
1543
  <div class="o-spreadsheet-bottom-bar">
1544
1544
  <div class="o-sheet-item o-add-sheet" t-att-class="{'disabled': getters.isReadonly()}" t-on-click="addSheet">${'<svg class="o-icon"><path fill="#000000" d="M8,0 L10,0 L10,8 L18,8 L18,10 L10,10 L10,18 L8,18 L8,10 L0,10 L0,8 L8,8"/></svg>'}</div>
1545
1545
  <div class="o-sheet-item o-list-sheets" t-on-click="listSheets">${Ll}</div>
@@ -1644,7 +1644,7 @@
1644
1644
  opacity: 0;
1645
1645
  }
1646
1646
  }
1647
- `;class Xu extends t.Component{constructor(){super(...arguments),this.position=Ou(),this.getters=this.env.getters,this.menuState=Wu({isOpen:!1,position:null,menuItems:[]})}mounted(){this.focusSheet()}patched(){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(),i=this.getters.getNextSheetName(this.env._t("Sheet"));this.env.dispatch("CREATE_SHEET",{sheetId:s,position:t,name:i}),this.env.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:s})}listSheets(e){const t=new _a,s=this.getters.getActiveSheetId();let i=0;for(let e of this.getters.getSheets())t.add(e.id,{name:e.name,sequence:i,isReadonlyAllowed:!0,action:t=>t.dispatch("ACTIVATE_SHEET",{sheetIdFrom:s,sheetIdTo:e.id})}),i++;const o=e.currentTarget,{left:n}=o.getBoundingClientRect();this.openContextMenu(n,t)}activateSheet(e){this.env.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:e})}onDblClick(e){this.env.dispatch("RENAME_SHEET",{interactive:!0,sheetId: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,cl)}}onContextMenu(e,t){this.getters.getActiveSheetId()!==e&&this.activateSheet(e);const s=t.currentTarget,{left:i}=s.getBoundingClientRect();this.openContextMenu(i,cl)}}function Yu(e,t){const s=o=>{t(o),window.removeEventListener("mouseup",s),window.removeEventListener("dragstart",i),window.removeEventListener("mousemove",e),window.removeEventListener("wheel",e)};function i(e){e.preventDefault()}window.addEventListener("mouseup",s),window.addEventListener("dragstart",i),window.addEventListener("mousemove",e),window.addEventListener("wheel",e)}function Ku(e,t,s,i){const o=e.getBoundingClientRect();let n,r=null;const a=e=>{if(n=e,r)return;const i=n.clientX-o.left,l=n.clientY-o.top,c=t.getters.getEdgeScrollCol(i),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(i,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:i}=t.getters.getActiveSheet(),o=i[e+c.direction].start;t.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o,offsetY:s}),r=setTimeout((()=>{r=null,a(n)}),Math.round(c.delay))}if(h.canEdgeScroll){const{top:e,offsetX:s}=t.getters.getActiveSnappedViewport(),{rows:i}=t.getters.getActiveSheet(),o=i[e+h.direction].start;t.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s,offsetY:o}),r=setTimeout((()=>{r=null,a(n)}),Math.round(h.delay))}};Yu(a,(()=>{clearTimeout(r),i()}))}Xu.template=qu,Xu.style=ju,Xu.components={Menu:Hu};const{xml:Qu,css:Ju}=t.tags,{useState:ep}=t.hooks,tp=Qu`
1647
+ `;class Xu extends t.Component{constructor(){super(...arguments),this.position=Ou(),this.getters=this.env.getters,this.menuState=Wu({isOpen:!1,position:null,menuItems:[]})}mounted(){this.focusSheet()}patched(){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(),i=this.getters.getNextSheetName(this.env._t("Sheet"));this.env.dispatch("CREATE_SHEET",{sheetId:s,position:t,name:i}),this.env.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:s})}listSheets(e){const t=new _a,s=this.getters.getActiveSheetId();let i=0;for(let e of this.getters.getSheets())t.add(e.id,{name:e.name,sequence:i,isReadonlyAllowed:!0,action:t=>t.dispatch("ACTIVATE_SHEET",{sheetIdFrom:s,sheetIdTo:e.id})}),i++;const o=e.currentTarget,{left:n}=o.getBoundingClientRect();this.openContextMenu(n,t)}activateSheet(e){this.env.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:e})}onDblClick(e){this.env.dispatch("RENAME_SHEET",{interactive:!0,sheetId: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,cl)}}onContextMenu(e,t){this.getters.getActiveSheetId()!==e&&this.activateSheet(e);const s=t.currentTarget,{left:i}=s.getBoundingClientRect();this.openContextMenu(i,cl)}}function Yu(e,t){const s=o=>{t(o),window.removeEventListener("mouseup",s),window.removeEventListener("dragstart",i),window.removeEventListener("mousemove",e),window.removeEventListener("wheel",e)};function i(e){e.preventDefault()}window.addEventListener("mouseup",s),window.addEventListener("dragstart",i),window.addEventListener("mousemove",e),window.addEventListener("wheel",e)}function Ku(e,t,s,i){const o=e.getBoundingClientRect();let n,r=null;const a=e=>{if(n=e,r)return;const i=n.clientX-o.left,l=n.clientY-o.top,c=t.getters.getEdgeScrollCol(i),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(i,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:i}=t.getters.getActiveSheet(),o=i[e+c.direction].start;t.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o,offsetY:s}),r=setTimeout((()=>{r=null,a(n)}),Math.round(c.delay))}if(h.canEdgeScroll){const{top:e,offsetX:s}=t.getters.getActiveSnappedViewport(),{rows:i}=t.getters.getActiveSheet(),o=i[e+h.direction].start;t.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s,offsetY:o}),r=setTimeout((()=>{r=null,a(n)}),Math.round(h.delay))}};Yu(a,(()=>{clearTimeout(r),i()}))}Xu.template=qu,Xu.style=ju,Xu.components={Menu:zu};const{xml:Qu,css:Ju}=t.tags,{useState:ep}=t.hooks,tp=Qu`
1648
1648
  <div class="o-autofill" t-on-mousedown="onMouseDown" t-att-style="style" t-on-dblclick="onDblClick">
1649
1649
  <div class="o-autofill-handler" t-att-style="styleHandler"/>
1650
1650
  <t t-set="tooltip" t-value="getTooltip()"/>
@@ -1734,7 +1734,7 @@
1734
1734
  }
1735
1735
  }
1736
1736
  }
1737
- `;class mp extends t.Component{constructor(){super(...arguments),this.state=t.useState({values:[],selectedIndex:0})}mounted(){this.filter(this.props.search)}willUpdateProps(e){return e.search!==this.props.search&&this.filter(e.search),super.willUpdateProps(e)}async filter(e){let t=pp.get(this.props.provider)();t=this.props.filter?this.props.filter(e,t):t.filter((t=>t.text.toUpperCase().startsWith(e.toUpperCase()))).sort(((e,t)=>e.text<t.text?-1:e.text>t.text?1:0)),this.state.values=t.slice(0,10),this.state.selectedIndex=0}fillValue(e){this.state.selectedIndex=e,this.trigger("completed",{text:this.getValueToFill()})}moveDown(){this.state.selectedIndex=(this.state.selectedIndex+1)%this.state.values.length}moveUp(){this.state.selectedIndex--,this.state.selectedIndex<0&&(this.state.selectedIndex=this.state.values.length-1)}getValueToFill(){if(this.state.values.length)return this.state.values[this.state.selectedIndex].text}}mp.template=gp,mp.style=fp;class vp{constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let s=window.getSelection();this.removeSelection();let i=document.createRange();if(e==t&&0===e)i.setStart(this.el,0),i.setEnd(this.el,0),s.addRange(i);else{(e<0||t>this.el.textContent.length)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${this.el.textContent.length}`),e<0&&(e=0),t>this.el.textContent.length&&(t=this.el.textContent.length),e>this.el.textContent.length&&(e=this.el.textContent.length));let o=this.findChildAtCharacterIndex(e),n=this.findChildAtCharacterIndex(t);i.setStart(o.node,o.offset),s.addRange(i),s.extend(n.node,n.offset)}}findChildAtCharacterIndex(e){let t,s,i=this.iterateChildren(this.el),o=e;do{t=i.next(),t.done||t.value.hasChildNodes()||(t.value.textContent&&t.value.textContent.length<o?o-=t.value.textContent.length:i.return(t.value),s=t.value)}while(!t.done);return t.value?{node:t.value,offset:o}:{node:s,offset:o}}*iterateChildren(e){if(yield e,e.hasChildNodes())for(let t of e.childNodes)yield*this.iterateChildren(t)}setText(e){if(0!==e.length)for(const t of e){const e=document.createElement("span");e.innerText=t.value,t.color&&(e.style.color=t.color),t.class&&e.classList.add(t.class),this.el.appendChild(e)}}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){let{startElement:e,endElement:t,startSelectionOffset:s,endSelectionOffset:i}=this.getStartAndEndSelection();return{start:this.findSizeBeforeElement(e)+s,end:this.findSizeBeforeElement(t)+i}}findSizeBeforeElement(e){let t=this.iterateChildren(this.el),s=0,i=t.next();for(;!i.done&&i.value!==e;)i.value.hasChildNodes()||i.value.textContent&&(s+=i.value.textContent.length),i=t.next();return s}getStartAndEndSelection(){const e=document.getSelection();return{startElement:e.anchorNode||this.el,startSelectionOffset:e.anchorOffset,endElement:e.focusNode||this.el,endSelectionOffset:e.focusOffset}}}const Ep=a("ABOUT"),bp=a("optional"),Sp=a("by default"),Cp=a("repeatable"),{xml:Ip,css:yp}=t.tags,{useState:wp}=t.hooks,xp=Ip`
1737
+ `;class mp extends t.Component{constructor(){super(...arguments),this.state=t.useState({values:[],selectedIndex:0})}mounted(){this.filter(this.props.search)}willUpdateProps(e){return e.search!==this.props.search&&this.filter(e.search),super.willUpdateProps(e)}async filter(e){let t=pp.get(this.props.provider)();t=this.props.filter?this.props.filter(e,t):t.filter((t=>t.text.toUpperCase().startsWith(e.toUpperCase()))).sort(((e,t)=>e.text<t.text?-1:e.text>t.text?1:0)),this.state.values=t.slice(0,10),this.state.selectedIndex=0}fillValue(e){this.state.selectedIndex=e,this.trigger("completed",{text:this.getValueToFill()})}moveDown(){this.state.selectedIndex=(this.state.selectedIndex+1)%this.state.values.length}moveUp(){this.state.selectedIndex--,this.state.selectedIndex<0&&(this.state.selectedIndex=this.state.values.length-1)}getValueToFill(){if(this.state.values.length)return this.state.values[this.state.selectedIndex].text}}mp.template=gp,mp.style=fp;class vp{constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let s=window.getSelection();this.removeSelection();let i=document.createRange();if(e==t&&0===e)i.setStart(this.el,0),i.setEnd(this.el,0),s.addRange(i);else{(e<0||t>this.el.textContent.length)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${this.el.textContent.length}`),e<0&&(e=0),t>this.el.textContent.length&&(t=this.el.textContent.length),e>this.el.textContent.length&&(e=this.el.textContent.length));let o=this.findChildAtCharacterIndex(e),n=this.findChildAtCharacterIndex(t);i.setStart(o.node,o.offset),s.addRange(i),s.extend(n.node,n.offset)}}findChildAtCharacterIndex(e){let t,s,i=this.iterateChildren(this.el),o=e;do{t=i.next(),t.done||t.value.hasChildNodes()||(t.value.textContent&&t.value.textContent.length<o?o-=t.value.textContent.length:i.return(t.value),s=t.value)}while(!t.done);return t.value?{node:t.value,offset:o}:{node:s,offset:o}}*iterateChildren(e){if(yield e,e.hasChildNodes())for(let t of e.childNodes)yield*this.iterateChildren(t)}setText(e){if(0!==e.length)for(const t of e){const e=document.createElement("span");e.innerText=t.value,t.color&&(e.style.color=t.color),t.class&&e.classList.add(t.class),this.el.appendChild(e)}}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){let{startElement:e,endElement:t,startSelectionOffset:s,endSelectionOffset:i}=this.getStartAndEndSelection();return{start:this.findSelectionIndex(e,s),end:this.findSelectionIndex(t,i)}}findSelectionIndex(e,t){let s=this.iterateChildren(this.el),i=0,o=s.next();for(;!o.done&&o.value!==e;)o.value.hasChildNodes()||o.value.textContent&&(i+=o.value.textContent.length),o=s.next();if(o.value===e)if(o.value.hasChildNodes()){const e=[...o.value.childNodes].slice(0,t);for(const t of e)t.textContent&&(i+=t.textContent.length)}else i+=t;return i}getStartAndEndSelection(){const e=document.getSelection();return{startElement:e.anchorNode||this.el,startSelectionOffset:e.anchorOffset,endElement:e.focusNode||this.el,endSelectionOffset:e.focusOffset}}}const Ep=a("ABOUT"),bp=a("optional"),Sp=a("by default"),Cp=a("repeatable"),{xml:Ip,css:yp}=t.tags,{useState:wp}=t.hooks,xp=Ip`
1738
1738
  <div class="o-formula-assistant-container"
1739
1739
  t-att-style="props.borderStyle"
1740
1740
  t-att-class="{
@@ -1912,7 +1912,7 @@
1912
1912
  .o-topbar-toolbar .o-composer-container:focus-within {
1913
1913
  border: 1px solid ${p};
1914
1914
  }
1915
- `;class Bp extends t.Component{constructor(){super(...arguments),this.composerRef=Mp("o_composer"),this.autoCompleteRef=Mp("o_autocomplete_provider"),this.getters=this.env.getters,this.dispatch=this.env.dispatch,this.composerState=Lp({positionStart:0,positionEnd:0}),this.autoCompleteState=Lp({showProvider:!1,provider:"functions",search:""}),this.functionDescriptionState=Lp({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 vp(this.composerRef.el)}get assistantStyle(){if(this.props.delimitation&&this.props.rect){const[e,t,,s]=this.props.rect;let i="";return t>this.props.delimitation.height-(t+s)&&(i+="\n top: -8px;\n transform: translate(0, -100%);\n "),e+300>this.props.delimitation.width&&(i+="right:0px;"),i+="width:300px;"}return"width:300px;"}mounted(){Ms.composer=this;const e=this.composerRef.el;this.contentHelper.updateEl(e),this.processContent()}willUnmount(){delete Ms.composer,this.trigger("composer-unmounted")}patched(){this.isKeyStillDown||this.processContent()}processArrowKeys(e){if(this.getters.isSelectingForComposer())return void(this.functionDescriptionState.showDescription=!1);if("cellFocus"===this.props.focus&&!this.autoCompleteState.showProvider)return;e.stopPropagation();const t=this.autoCompleteRef.comp;["ArrowUp","ArrowDown"].includes(e.key)&&this.autoCompleteState.showProvider&&t&&(e.preventDefault(),"ArrowUp"===e.key?t.moveUp():t.moveDown())}processTabKey(e){e.preventDefault(),e.stopPropagation();const t=this.autoCompleteRef.comp;if(this.autoCompleteState.showProvider&&t){const e=t.getValueToFill();if(e)return void this.autoComplete(e)}else this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const s=e.shiftKey?-1:1;this.dispatch("MOVE_POSITION",{deltaX:s,deltaY:0})}processEnterKey(e){e.preventDefault(),e.stopPropagation(),this.isKeyStillDown=!1;const t=this.autoCompleteRef.comp;if(this.autoCompleteState.showProvider&&t){const e=t.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();const{start:s,end:i}=this.contentHelper.getCurrentSelection();this.getters.isSelectingForComposer()||(this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:s,end:i}),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:i,end:o}=this.contentHelper.getCurrentSelection();i===t&&o===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.trigger("composer-content-focused",{selection:e}),this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",e),this.processTokenAtCursor()}onBlur(){this.isKeyStillDown=!1}onCompleted(e){this.autoComplete(e.detail.text)}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:i}=this.getters.getComposerSelection();for(const o of e){switch(o.type){case"OPERATOR":case"NUMBER":case"FUNCTION":case"COMMA":case"STRING":s.push({value:o.value,color:Dp[o.type]||"#000"});break;case"SYMBOL":let e=o.value;const{xc:i,sheetName:n}=Jt(e);Qt.test(i)?s.push({value:o.value,color:this.rangeColor(i,n)||"#000"}):["TRUE","FALSE"].includes(e.toUpperCase())?s.push({value:o.value,color:Fp}):s.push({value:o.value,color:"#000"});break;case"LEFT_PAREN":case"RIGHT_PAREN":t&&["LEFT_PAREN","RIGHT_PAREN"].includes(t.type)&&t.parenIndex&&t.parenIndex===o.parenIndex?s.push({value:o.value,color:"pink"}):s.push({value:o.value,color:Dp[o.type]||"#000"});break;default:s.push({value:o.value,color:"#000"})}"waitingForRangeSelection"===this.getters.getEditionMode()&&i===o.end&&(s[s.length-1].class=$p)}return s}rangeColor(e,t){if("inactive"===this.getters.getEditionMode())return;const s=this.getters.getHighlights(),i=t?this.getters.getSheetIdByName(t):this.getters.getEditionSheet(),o=s.find((t=>{if(t.sheet!==i)return!1;let s=_s(e);const{height:o,width:n}=Hs(s);return s=o*n==1?this.getters.expandZone(i,_s(e)):s,t.sheet===i&&Ds(s,t.zone)}));return o&&o.color?o.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}=Jt(e.value);if("FUNCTION"===e.type||"SYMBOL"===e.type&&!Qt.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(),i=Op[s],o=t.argPosition;this.functionDescriptionState.functionName=s,this.functionDescriptionState.functionDescription=i,this.functionDescriptionState.argToFocus=i.getArgToFocus(o+1)-1,this.functionDescriptionState.showDescription=!0}}}}autoComplete(e){if(e){const t=this.getters.getTokenAtCursor();if(t){let s=t.end,i=t.end;["SYMBOL","FUNCTION"].includes(t.type)&&(s=t.start);const o=this.getters.getCurrentTokens();if(this.autoCompleteState.provider&&o.length){e+="(";const s=o.map((e=>e.start)).indexOf(t.start);if(s+1<o.length){"LEFT_PAREN"===o[s+1].type&&i++}}this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:s,end:i})}this.dispatch("REPLACE_COMPOSER_CURSOR_SELECTION",{text:e})}this.processTokenAtCursor()}}Bp.template=Pp,Bp.style=Up,Bp.components={TextValueProvider:mp,FunctionDescriptionProvider:Rp},Bp.defaultProps={inputStyle:"",focus:"inactive"};const{useState:Vp}=t.hooks,{xml:zp,css:Hp}=t.tags,Zp=zp`
1915
+ `;class Bp extends t.Component{constructor(){super(...arguments),this.composerRef=Mp("o_composer"),this.autoCompleteRef=Mp("o_autocomplete_provider"),this.getters=this.env.getters,this.dispatch=this.env.dispatch,this.composerState=Lp({positionStart:0,positionEnd:0}),this.autoCompleteState=Lp({showProvider:!1,provider:"functions",search:""}),this.functionDescriptionState=Lp({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 vp(this.composerRef.el)}get assistantStyle(){if(this.props.delimitation&&this.props.rect){const[e,t,,s]=this.props.rect;let i="";return t>this.props.delimitation.height-(t+s)&&(i+="\n top: -8px;\n transform: translate(0, -100%);\n "),e+300>this.props.delimitation.width&&(i+="right:0px;"),i+="width:300px;"}return"width:300px;"}mounted(){Ms.composer=this;const e=this.composerRef.el;this.contentHelper.updateEl(e),this.processContent()}willUnmount(){delete Ms.composer,this.trigger("composer-unmounted")}patched(){this.isKeyStillDown||this.processContent()}processArrowKeys(e){if(this.getters.isSelectingForComposer())return void(this.functionDescriptionState.showDescription=!1);if("cellFocus"===this.props.focus&&!this.autoCompleteState.showProvider)return;e.stopPropagation();const t=this.autoCompleteRef.comp;["ArrowUp","ArrowDown"].includes(e.key)&&this.autoCompleteState.showProvider&&t&&(e.preventDefault(),"ArrowUp"===e.key?t.moveUp():t.moveDown())}processTabKey(e){e.preventDefault(),e.stopPropagation();const t=this.autoCompleteRef.comp;if(this.autoCompleteState.showProvider&&t){const e=t.getValueToFill();if(e)return void this.autoComplete(e)}else this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const s=e.shiftKey?-1:1;this.dispatch("MOVE_POSITION",{deltaX:s,deltaY:0})}processEnterKey(e){e.preventDefault(),e.stopPropagation(),this.isKeyStillDown=!1;const t=this.autoCompleteRef.comp;if(this.autoCompleteState.showProvider&&t){const e=t.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();const{start:s,end:i}=this.contentHelper.getCurrentSelection();this.getters.isSelectingForComposer()||(this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:s,end:i}),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:i,end:o}=this.contentHelper.getCurrentSelection();i===t&&o===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.trigger("composer-content-focused",{selection:e}),this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",e),this.processTokenAtCursor()}onBlur(){this.isKeyStillDown=!1}onCompleted(e){this.autoComplete(e.detail.text)}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:i}=this.getters.getComposerSelection();for(const o of e){switch(o.type){case"OPERATOR":case"NUMBER":case"FUNCTION":case"COMMA":case"STRING":s.push({value:o.value,color:Dp[o.type]||"#000"});break;case"SYMBOL":let e=o.value;const{xc:i,sheetName:n}=Jt(e);Qt.test(i)?s.push({value:o.value,color:this.rangeColor(i,n)||"#000"}):["TRUE","FALSE"].includes(e.toUpperCase())?s.push({value:o.value,color:Fp}):s.push({value:o.value,color:"#000"});break;case"LEFT_PAREN":case"RIGHT_PAREN":t&&["LEFT_PAREN","RIGHT_PAREN"].includes(t.type)&&t.parenIndex&&t.parenIndex===o.parenIndex?s.push({value:o.value,color:"pink"}):s.push({value:o.value,color:Dp[o.type]||"#000"});break;default:s.push({value:o.value,color:"#000"})}"waitingForRangeSelection"===this.getters.getEditionMode()&&i===o.end&&(s[s.length-1].class=$p)}return s}rangeColor(e,t){if("inactive"===this.getters.getEditionMode())return;const s=this.getters.getHighlights(),i=t?this.getters.getSheetIdByName(t):this.getters.getEditionSheet(),o=s.find((t=>{if(t.sheet!==i)return!1;let s=_s(e);const{height:o,width:n}=zs(s);return s=o*n==1?this.getters.expandZone(i,_s(e)):s,t.sheet===i&&Ds(s,t.zone)}));return o&&o.color?o.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}=Jt(e.value);if("FUNCTION"===e.type||"SYMBOL"===e.type&&!Qt.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(),i=Op[s],o=t.argPosition;this.functionDescriptionState.functionName=s,this.functionDescriptionState.functionDescription=i,this.functionDescriptionState.argToFocus=i.getArgToFocus(o+1)-1,this.functionDescriptionState.showDescription=!0}}}}autoComplete(e){if(e){const t=this.getters.getTokenAtCursor();if(t){let s=t.end,i=t.end;["SYMBOL","FUNCTION"].includes(t.type)&&(s=t.start);const o=this.getters.getCurrentTokens();if(this.autoCompleteState.provider&&o.length){e+="(";const s=o.map((e=>e.start)).indexOf(t.start);if(s+1<o.length){"LEFT_PAREN"===o[s+1].type&&i++}}this.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:s,end:i})}this.dispatch("REPLACE_COMPOSER_CURSOR_SELECTION",{text:e})}this.processTokenAtCursor()}}Bp.template=Pp,Bp.style=Up,Bp.components={TextValueProvider:mp,FunctionDescriptionProvider:Rp},Bp.defaultProps={inputStyle:"",focus:"inactive"};const{useState:Vp}=t.hooks,{xml:Hp,css:zp}=t.tags,Zp=Hp`
1916
1916
  <div class="o-grid-composer" t-att-style="containerStyle">
1917
1917
  <Composer
1918
1918
  focus = "props.focus"
@@ -1922,7 +1922,7 @@
1922
1922
  t-on-keydown = "onKeydown"
1923
1923
  />
1924
1924
  </div>
1925
- `,Gp=Hp`
1925
+ `,Gp=zp`
1926
1926
  .o-grid-composer {
1927
1927
  z-index: 5;
1928
1928
  box-sizing: border-box;
@@ -1973,7 +1973,7 @@
1973
1973
  }
1974
1974
  }
1975
1975
  }
1976
- `;class og extends t.Component{constructor(){super(...arguments),this.menuState=Qp({isOpen:!1,position:null,menuItems:[]}),this.canvas=tg("graphContainer"),this.state={background:g},this.position=Ou()}get canvasStyle(){return`background-color: ${this.state.background}`}mounted(){const e=this.props.figure,t=this.env.getters.getChartRuntime(e.id);t&&this.createChart(t)}patched(){var e,t,s;const i=this.props.figure,o=this.env.getters.getChartRuntime(i.id);o?(o.type!==this.chart.config.type?(this.chart&&this.chart.destroy(),this.createChart(o)):o.data&&o.data.datasets?(this.chart.data=o.data,(null===(e=o.options)||void 0===e?void 0:e.title)&&(this.chart.config.options.title=o.options.title)):this.chart.data.datasets=void 0,this.chart.config.options.legend=null===(t=o.options)||void 0===t?void 0:t.legend,this.chart.config.options.scales=null===(s=o.options)||void 0===s?void 0:s.scales,this.chart.update({duration:0})):this.chart&&this.chart.destroy();const n=this.env.getters.getChartDefinition(i.id);n&&(this.state.background=n.background)}createChart(e){const t=this.canvas.el.getContext("2d");this.chart=new window.Chart(t,e);const s=this.env.getters.getChartDefinition(this.props.figure.id);s&&(this.state.background=s.background)}showMenu(e){const t=new _a;t.add("edit",{name:a("Edit"),sequence:1,action:()=>this.env.openSidePanel("ChartPanel",{figure:this.props.figure}),isVisible:()=>!!this.env.getters.getChartDefinition(this.props.figure.id)}),t.add("delete",{name:a("Delete"),sequence:10,action:()=>{this.env.dispatch("DELETE_FIGURE",{sheetId:this.env.getters.getActiveSheetId(),id:this.props.figure.id}),this.props.sidePanelIsOpen&&this.env.toggleSidePanel("ChartPanel",{figure:this.props.figure}),this.trigger("figure-deleted")}}),t.add("refresh",{name:a("Refresh"),sequence:11,action:()=>{this.env.dispatch("REFRESH_CHART",{id:this.props.figure.id})}}),this.openContextMenu(e.currentTarget,t)}openContextMenu(e,t){const s=e.offsetLeft,i=e.offsetTop;this.menuState.isOpen=!0,this.menuState.menuItems=t.getAll().filter((e=>e.isVisible(this.env))),this.menuState.position={x:this.position.x+s-y,y:this.position.y+i}}}og.template=sg,og.style=ig,og.components={Menu:Hu};const{xml:ng,css:rg}=i.tags,{useState:ag}=i,lg=ng`<div>
1976
+ `;class og extends t.Component{constructor(){super(...arguments),this.menuState=Qp({isOpen:!1,position:null,menuItems:[]}),this.canvas=tg("graphContainer"),this.state={background:g},this.position=Ou()}get canvasStyle(){return`background-color: ${this.state.background}`}mounted(){const e=this.props.figure,t=this.env.getters.getChartRuntime(e.id);t&&this.createChart(t)}patched(){var e,t,s;const i=this.props.figure,o=this.env.getters.getChartRuntime(i.id);o?(o.type!==this.chart.config.type?(this.chart&&this.chart.destroy(),this.createChart(o)):o.data&&o.data.datasets?(this.chart.data=o.data,(null===(e=o.options)||void 0===e?void 0:e.title)&&(this.chart.config.options.title=o.options.title)):this.chart.data.datasets=void 0,this.chart.config.options.legend=null===(t=o.options)||void 0===t?void 0:t.legend,this.chart.config.options.scales=null===(s=o.options)||void 0===s?void 0:s.scales,this.chart.update({duration:0})):this.chart&&this.chart.destroy();const n=this.env.getters.getChartDefinition(i.id);n&&(this.state.background=n.background)}createChart(e){const t=this.canvas.el.getContext("2d");this.chart=new window.Chart(t,e);const s=this.env.getters.getChartDefinition(this.props.figure.id);s&&(this.state.background=s.background)}showMenu(e){const t=new _a;t.add("edit",{name:a("Edit"),sequence:1,action:()=>this.env.openSidePanel("ChartPanel",{figure:this.props.figure}),isVisible:()=>!!this.env.getters.getChartDefinition(this.props.figure.id)}),t.add("delete",{name:a("Delete"),sequence:10,action:()=>{this.env.dispatch("DELETE_FIGURE",{sheetId:this.env.getters.getActiveSheetId(),id:this.props.figure.id}),this.props.sidePanelIsOpen&&this.env.toggleSidePanel("ChartPanel",{figure:this.props.figure}),this.trigger("figure-deleted")}}),t.add("refresh",{name:a("Refresh"),sequence:11,action:()=>{this.env.dispatch("REFRESH_CHART",{id:this.props.figure.id})}}),this.openContextMenu(e.currentTarget,t)}openContextMenu(e,t){const s=e.offsetLeft,i=e.offsetTop;this.menuState.isOpen=!0,this.menuState.menuItems=t.getAll().filter((e=>e.isVisible(this.env))),this.menuState.position={x:this.position.x+s-y,y:this.position.y+i}}}og.template=sg,og.style=ig,og.components={Menu:zu};const{xml:ng,css:rg}=i.tags,{useState:ag}=i,lg=ng`<div>
1977
1977
  <t t-foreach="getVisibleFigures()" t-as="info" t-key="info.id">
1978
1978
  <div class="o-figure-wrapper"
1979
1979
  t-att-style="getStyle(info)"
@@ -2212,7 +2212,7 @@
2212
2212
  cursor: pointer;
2213
2213
  color: #000;
2214
2214
  }
2215
- `;class Lg 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(),i=this.getters.getCell(s,e,t);if(null==i?void 0:i.isLink())return i;throw new Error(`LinkDisplay Component can only be used with link cells. ${ss(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(),[i,o]=this.getters.getMainCell(e,t,s),n=this.cell.style,r=(null==n?void 0:n.textColor)===M||null==n?void 0:n.textColor;this.env.dispatch("UPDATE_CELL",{col:i,row:o,sheetId:e,content:this.cell.link.label,style:{...n,textColor:r,underline:void 0}})}}Lg.template=Tg,Lg.components={Menu:Hu},Lg.style=Rg;const{xml:Mg,css:Ag}=t.tags,{useRef:_g}=t.hooks,Og=Mg`
2215
+ `;class Lg 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(),i=this.getters.getCell(s,e,t);if(null==i?void 0:i.isLink())return i;throw new Error(`LinkDisplay Component can only be used with link cells. ${ss(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(),[i,o]=this.getters.getMainCell(e,t,s),n=this.cell.style,r=(null==n?void 0:n.textColor)===M||null==n?void 0:n.textColor;this.env.dispatch("UPDATE_CELL",{col:i,row:o,sheetId:e,content:this.cell.link.label,style:{...n,textColor:r,underline:void 0}})}}Lg.template=Tg,Lg.components={Menu:zu},Lg.style=Rg;const{xml:Mg,css:Ag}=t.tags,{useRef:_g}=t.hooks,Og=Mg`
2216
2216
  <div class="o-link-editor" t-on-click.stop="menu.isOpen=false" t-on-keydown.stop="onKeyDown">
2217
2217
  <div class="o-section">
2218
2218
  <div t-esc="env._t('${vc}')" class="o-section-title"/>
@@ -2312,7 +2312,7 @@
2312
2312
  }
2313
2313
  }
2314
2314
  }
2315
- `;class kg extends t.Component{constructor(){super(...arguments),this.menuItems=al.getAll(),this.getters=this.env.getters,this.state=t.useState(this.defaultState),this.menu=t.useState({isOpen:!1}),this.position=Ou(),this.urlInput=_g("urlInput")}mounted(){var e;null===(e=this.urlInput.el)||void 0===e||e.focus()}get defaultState(){const{col:e,row:t}=this.props.cellPosition,s=this.getters.getActiveSheetId(),i=this.getters.getCell(s,e,t);return(null==i?void 0:i.isLink())?{link:{url:i.link.url,label:i.formattedValue},urlRepresentation:i.urlRepresentation,isUrlEditable:i.isUrlEditable}:{link:{url:"",label:(null==i?void 0:i.formattedValue)||""},isUrlEditable:!0,urlRepresentation:""}}get menuPosition(){return{x:this.position.x+320-12-2,y:this.position.y+100}}onSpecialLink(e){const{detail:t}=e;this.state.link.url=t.link.url,this.state.link.label=t.link.label,this.state.isUrlEditable=t.isUrlEditable,this.state.urlRepresentation=t.urlRepresentation}openMenu(){this.menu.isOpen=!0}removeLink(){this.state.link.url="",this.state.urlRepresentation="",this.state.isUrlEditable=!0}save(){const{col:e,row:t}=this.props.cellPosition,s=this.state.link.label||this.state.link.url;this.env.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:this.getters.getActiveSheetId(),content:ys(s,this.state.link.url)}),this.trigger("link-editor-closed")}cancel(){this.trigger("link-editor-closed")}onKeyDown(e){switch(e.key){case"Enter":this.state.link.url&&this.save();break;case"Escape":this.cancel()}}}kg.template=Og,kg.components={Menu:Hu},kg.style=Ng;const{xml:Fg,css:$g}=t.tags,{useState:Dg}=t.hooks;class Pg extends t.Component{constructor(){super(...arguments),this.PADDING=0,this.MAX_SIZE_MARGIN=0,this.MIN_ELEMENT_SIZE=0,this.lastSelectedElementIndex=null,this.getters=this.env.getters,this.dispatch=this.env.dispatch,this.state=Dg({resizerIsActive:!1,isResizing:!1,isMoving:!1,isSelecting:!1,waitingForMove:!1,activeElement:0,draggerLinePosition:0,draggerShadowPosition:0,draggerShadowThickness:0,delta:0,base:0})}_computeHandleDisplay(e){const t=this._getEvOffset(e),s=this._getElementIndex(t);if(s<0)return;const i=this._getElement(s),o=this._getStateOffset();t-(i.start-o)<this.PADDING&&s!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=i.start-o-this._getHeaderSize(),this.state.activeElement=this._getPreviousVisibleElement(s)):i.end-o-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=i.end-o-this._getHeaderSize(),this.state.activeElement=s):this.state.resizerIsActive=!1}_computeGrabDisplay(e){const t=this._getElementIndex(this._getEvOffset(e)),s=this._getActiveElements(),i=this._getSelectedZoneStart(),o=this._getSelectedZoneEnd();s.has(i)&&i<=t&&t<=o?this.state.waitingForMove=!0:this.state.waitingForMove=!1}onMouseMove(e){this.state.isResizing||this.state.isMoving||this.state.isSelecting||(this._computeHandleDisplay(e),this._computeGrabDisplay(e))}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(){this._fitElementSize(this.state.activeElement),this.state.isResizing=!1}onMouseDown(e){this.state.isResizing=!0,this.state.delta=0;const t=this._getClientPosition(e),s=this.state.draggerLinePosition,i=this._getElement(this.state.activeElement).size,o=s-i+this.MIN_ELEMENT_SIZE,n=this._getMaxSize();Yu((e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=s+this.state.delta,this.state.draggerLinePosition<o&&(this.state.draggerLinePosition=o,this.state.delta=this.MIN_ELEMENT_SIZE-i),this.state.draggerLinePosition>n&&(this.state.draggerLinePosition=n,this.state.delta=n-s)}),(e=>{this.state.isResizing=!1,0!==this.state.delta&&this._updateSize()}))}select(e){if(e.button>0)return;const t=this._getElementIndex(this._getEvOffset(e));t<0||(!0!==this.state.waitingForMove?this.startSelection(e,t):this.startMovement(e))}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;const t=this._getElement(this._getSelectedZoneStart()),s=this._getElement(this._getSelectedZoneEnd()),i=this._getClientPosition(e),o=t.start-this._getStateOffset()-this._getHeaderSize();this.state.draggerLinePosition=o,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=o,this.state.draggerShadowThickness=s.end-t.start;this.dragOverlayBeyondTheViewport(e,((e,s)=>{if(e>=0){const n=this._getElement(e),r=this._getStateOffset()+this._getHeaderSize();e<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=n.start-r,this.state.base=e):this._getSelectedZoneEnd()<e?(this.state.draggerLinePosition=n.end-r,this.state.base=e+1):(this.state.draggerLinePosition=t.start-r,this.state.base=this._getSelectedZoneStart());const a=this._getClientPosition(s)-i;this.state.draggerShadowPosition=Math.max(o+a,0)}}),(e=>{this.state.isMoving=!1,this.state.base!==this._getSelectedZoneStart()&&this._moveElements(),this._computeGrabDisplay(e)}))}startSelection(e,t){this.state.isSelecting=!0,this.dispatch(e.ctrlKey?"START_SELECTION_EXPANSION":"START_SELECTION"),e.shiftKey?this._increaseSelection(t):this._selectElement(t,e.ctrlKey),this.lastSelectedElementIndex=t;this.dragOverlayBeyondTheViewport(e,((e,t)=>{e!==this.lastSelectedElementIndex&&-1!==e&&(this._increaseSelection(e),this.lastSelectedElementIndex=e)}),(()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this.dispatch(e.ctrlKey?"PREPARE_SELECTION_EXPANSION":"STOP_SELECTION"),this._computeGrabDisplay(e)}))}dragOverlayBeyondTheViewport(e,t,s){let i,o=null;const n=this._getClientPosition(e),r=this._getEvOffset(e),a=e=>{if(i=e,o)return;const s=this._getClientPosition(i)-n+r,l=this._getEdgeScroll(s),{first:c,last:h}=this._getBoundaries();let d;d=l.canEdgeScroll?l.direction>0?h:c-1:this._getElementIndex(s),t(d,i),l.canEdgeScroll&&(this._adjustViewport(l.direction),o=setTimeout((()=>{o=null,a(i)}),Math.round(l.delay)))};Yu(a,(e=>{clearTimeout(o),s(e)}))}onMouseUp(e){this.lastSelectedElementIndex=null}onContextMenu(e){e.preventDefault();const t=this._getElementIndex(this._getEvOffset(e));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);const s=this._getType(),{x:i,y:o}=this._getXY(e);this.trigger("open-contextmenu",{type:s,x:i,y:o})}}class Ug extends Pg{constructor(){super(...arguments),this.PADDING=15,this.MAX_SIZE_MARGIN=90,this.MIN_ELEMENT_SIZE=5}_getEvOffset(e){return e.offsetX+m}_getStateOffset(){return this.getters.getActiveSnappedViewport().offsetX-m}_getViewportOffset(){return this.getters.getActiveSnappedViewport().left}_getClientPosition(e){return e.clientX}_getElementIndex(e){return this.getters.getColIndex(e,this.getters.getActiveSnappedViewport().left)}_getSelectedZoneStart(){return this.getters.getSelectedZone().left}_getSelectedZoneEnd(){return this.getters.getSelectedZone().right}_getEdgeScroll(e){return this.getters.getEdgeScrollCol(e)}_getBoundaries(){const{left:e,right:t}=this.getters.getActiveSnappedViewport();return{first:e,last:t}}_getElement(e){return this.getters.getCol(this.getters.getActiveSheetId(),e)}_getBottomRightValue(e){return e.end}_getHeaderSize(){return m}_getMaxSize(){return this.el.clientWidth}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElement(e).size,s=this.getters.getActiveCols();this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"COL",sheetId:this.getters.getActiveSheetId(),elements:s.has(e)?[...s]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),s=this._getSelectedZoneEnd();for(let i=t;i<=s;i++)e.push(i);this.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.getters.getActiveSheetId(),dimension:"COL",base:this.state.base,elements:e})}_selectElement(e,t){this.dispatch("SELECT_COLUMN",{index:e,createRange:t})}_increaseSelection(e){this.dispatch("SELECT_COLUMN",{index:e,updateRange:!0})}_adjustViewport(e){const{left:t,offsetY:s}=this.getters.getActiveSnappedViewport(),{cols:i}=this.getters.getActiveSheet(),o=i[t+e].start;this.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o,offsetY:s})}_fitElementSize(e){const t=this.getters.getActiveCols();this.dispatch("AUTORESIZE_COLUMNS",{sheetId:this.getters.getActiveSheetId(),cols:t.has(e)?[...t]:[e]})}_getType(){return"COL"}_getActiveElements(){return this.getters.getActiveCols()}_getXY(e){return{x:e.offsetX+m,y:e.offsetY}}_getPreviousVisibleElement(e){return e-1-this.getters.getActiveSheet().cols.slice(0,e).reverse().findIndex((e=>!e.isHidden))}unhide(e){this.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.getters.getActiveSheetId(),elements:e,dimension:"COL"})}unhideStyleValue(e){const t=this.getters.getCol(this.getters.getActiveSheetId(),e),s=this._getStateOffset();return t.start-s-this._getHeaderSize()}}Ug.template=Fg`
2315
+ `;class kg extends t.Component{constructor(){super(...arguments),this.menuItems=al.getAll(),this.getters=this.env.getters,this.state=t.useState(this.defaultState),this.menu=t.useState({isOpen:!1}),this.position=Ou(),this.urlInput=_g("urlInput")}mounted(){var e;null===(e=this.urlInput.el)||void 0===e||e.focus()}get defaultState(){const{col:e,row:t}=this.props.cellPosition,s=this.getters.getActiveSheetId(),i=this.getters.getCell(s,e,t);return(null==i?void 0:i.isLink())?{link:{url:i.link.url,label:i.formattedValue},urlRepresentation:i.urlRepresentation,isUrlEditable:i.isUrlEditable}:{link:{url:"",label:(null==i?void 0:i.formattedValue)||""},isUrlEditable:!0,urlRepresentation:""}}get menuPosition(){return{x:this.position.x+320-12-2,y:this.position.y+100}}onSpecialLink(e){const{detail:t}=e;this.state.link.url=t.link.url,this.state.link.label=t.link.label,this.state.isUrlEditable=t.isUrlEditable,this.state.urlRepresentation=t.urlRepresentation}openMenu(){this.menu.isOpen=!0}removeLink(){this.state.link.url="",this.state.urlRepresentation="",this.state.isUrlEditable=!0}save(){const{col:e,row:t}=this.props.cellPosition,s=this.state.link.label||this.state.link.url;this.env.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:this.getters.getActiveSheetId(),content:ys(s,this.state.link.url)}),this.trigger("link-editor-closed")}cancel(){this.trigger("link-editor-closed")}onKeyDown(e){switch(e.key){case"Enter":this.state.link.url&&this.save();break;case"Escape":this.cancel()}}}kg.template=Og,kg.components={Menu:zu},kg.style=Ng;const{xml:Fg,css:$g}=t.tags,{useState:Dg}=t.hooks;class Pg extends t.Component{constructor(){super(...arguments),this.PADDING=0,this.MAX_SIZE_MARGIN=0,this.MIN_ELEMENT_SIZE=0,this.lastSelectedElementIndex=null,this.getters=this.env.getters,this.dispatch=this.env.dispatch,this.state=Dg({resizerIsActive:!1,isResizing:!1,isMoving:!1,isSelecting:!1,waitingForMove:!1,activeElement:0,draggerLinePosition:0,draggerShadowPosition:0,draggerShadowThickness:0,delta:0,base:0})}_computeHandleDisplay(e){const t=this._getEvOffset(e),s=this._getElementIndex(t);if(s<0)return;const i=this._getElement(s),o=this._getStateOffset();t-(i.start-o)<this.PADDING&&s!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=i.start-o-this._getHeaderSize(),this.state.activeElement=this._getPreviousVisibleElement(s)):i.end-o-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=i.end-o-this._getHeaderSize(),this.state.activeElement=s):this.state.resizerIsActive=!1}_computeGrabDisplay(e){const t=this._getElementIndex(this._getEvOffset(e)),s=this._getActiveElements(),i=this._getSelectedZoneStart(),o=this._getSelectedZoneEnd();s.has(i)&&i<=t&&t<=o?this.state.waitingForMove=!0:this.state.waitingForMove=!1}onMouseMove(e){this.state.isResizing||this.state.isMoving||this.state.isSelecting||(this._computeHandleDisplay(e),this._computeGrabDisplay(e))}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(){this._fitElementSize(this.state.activeElement),this.state.isResizing=!1}onMouseDown(e){this.state.isResizing=!0,this.state.delta=0;const t=this._getClientPosition(e),s=this.state.draggerLinePosition,i=this._getElement(this.state.activeElement).size,o=s-i+this.MIN_ELEMENT_SIZE,n=this._getMaxSize();Yu((e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=s+this.state.delta,this.state.draggerLinePosition<o&&(this.state.draggerLinePosition=o,this.state.delta=this.MIN_ELEMENT_SIZE-i),this.state.draggerLinePosition>n&&(this.state.draggerLinePosition=n,this.state.delta=n-s)}),(e=>{this.state.isResizing=!1,0!==this.state.delta&&this._updateSize()}))}select(e){if(e.button>0)return;const t=this._getElementIndex(this._getEvOffset(e));t<0||(!0!==this.state.waitingForMove?this.startSelection(e,t):this.startMovement(e))}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;const t=this._getElement(this._getSelectedZoneStart()),s=this._getElement(this._getSelectedZoneEnd()),i=this._getClientPosition(e),o=t.start-this._getStateOffset()-this._getHeaderSize();this.state.draggerLinePosition=o,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=o,this.state.draggerShadowThickness=s.end-t.start;this.dragOverlayBeyondTheViewport(e,((e,s)=>{if(e>=0){const n=this._getElement(e),r=this._getStateOffset()+this._getHeaderSize();e<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=n.start-r,this.state.base=e):this._getSelectedZoneEnd()<e?(this.state.draggerLinePosition=n.end-r,this.state.base=e+1):(this.state.draggerLinePosition=t.start-r,this.state.base=this._getSelectedZoneStart());const a=this._getClientPosition(s)-i;this.state.draggerShadowPosition=Math.max(o+a,0)}}),(e=>{this.state.isMoving=!1,this.state.base!==this._getSelectedZoneStart()&&this._moveElements(),this._computeGrabDisplay(e)}))}startSelection(e,t){this.state.isSelecting=!0,this.dispatch(e.ctrlKey?"START_SELECTION_EXPANSION":"START_SELECTION"),e.shiftKey?this._increaseSelection(t):this._selectElement(t,e.ctrlKey),this.lastSelectedElementIndex=t;this.dragOverlayBeyondTheViewport(e,((e,t)=>{e!==this.lastSelectedElementIndex&&-1!==e&&(this._increaseSelection(e),this.lastSelectedElementIndex=e)}),(()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this.dispatch(e.ctrlKey?"PREPARE_SELECTION_EXPANSION":"STOP_SELECTION"),this._computeGrabDisplay(e)}))}dragOverlayBeyondTheViewport(e,t,s){let i,o=null;const n=this._getClientPosition(e),r=this._getEvOffset(e),a=e=>{if(i=e,o)return;const s=this._getClientPosition(i)-n+r,l=this._getEdgeScroll(s),{first:c,last:h}=this._getBoundaries();let d;d=l.canEdgeScroll?l.direction>0?h:c-1:this._getElementIndex(s),t(d,i),l.canEdgeScroll&&(this._adjustViewport(l.direction),o=setTimeout((()=>{o=null,a(i)}),Math.round(l.delay)))};Yu(a,(e=>{clearTimeout(o),s(e)}))}onMouseUp(e){this.lastSelectedElementIndex=null}onContextMenu(e){e.preventDefault();const t=this._getElementIndex(this._getEvOffset(e));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);const s=this._getType(),{x:i,y:o}=this._getXY(e);this.trigger("open-contextmenu",{type:s,x:i,y:o})}}class Ug extends Pg{constructor(){super(...arguments),this.PADDING=15,this.MAX_SIZE_MARGIN=90,this.MIN_ELEMENT_SIZE=5}_getEvOffset(e){return e.offsetX+m}_getStateOffset(){return this.getters.getActiveSnappedViewport().offsetX-m}_getViewportOffset(){return this.getters.getActiveSnappedViewport().left}_getClientPosition(e){return e.clientX}_getElementIndex(e){return this.getters.getColIndex(e,this.getters.getActiveSnappedViewport().left)}_getSelectedZoneStart(){return this.getters.getSelectedZone().left}_getSelectedZoneEnd(){return this.getters.getSelectedZone().right}_getEdgeScroll(e){return this.getters.getEdgeScrollCol(e)}_getBoundaries(){const{left:e,right:t}=this.getters.getActiveSnappedViewport();return{first:e,last:t}}_getElement(e){return this.getters.getCol(this.getters.getActiveSheetId(),e)}_getBottomRightValue(e){return e.end}_getHeaderSize(){return m}_getMaxSize(){return this.el.clientWidth}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElement(e).size,s=this.getters.getActiveCols();this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"COL",sheetId:this.getters.getActiveSheetId(),elements:s.has(e)?[...s]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),s=this._getSelectedZoneEnd();for(let i=t;i<=s;i++)e.push(i);this.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.getters.getActiveSheetId(),dimension:"COL",base:this.state.base,elements:e})}_selectElement(e,t){this.dispatch("SELECT_COLUMN",{index:e,createRange:t})}_increaseSelection(e){this.dispatch("SELECT_COLUMN",{index:e,updateRange:!0})}_adjustViewport(e){const{left:t,offsetY:s}=this.getters.getActiveSnappedViewport(),{cols:i}=this.getters.getActiveSheet(),o=i[t+e].start;this.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o,offsetY:s})}_fitElementSize(e){const t=this.getters.getActiveCols();this.dispatch("AUTORESIZE_COLUMNS",{sheetId:this.getters.getActiveSheetId(),cols:t.has(e)?[...t]:[e]})}_getType(){return"COL"}_getActiveElements(){return this.getters.getActiveCols()}_getXY(e){return{x:e.offsetX+m,y:e.offsetY}}_getPreviousVisibleElement(e){return e-1-this.getters.getActiveSheet().cols.slice(0,e).reverse().findIndex((e=>!e.isHidden))}unhide(e){this.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.getters.getActiveSheetId(),elements:e,dimension:"COL"})}unhideStyleValue(e){const t=this.getters.getCol(this.getters.getActiveSheetId(),e),s=this._getStateOffset();return t.start-s-this._getHeaderSize()}}Ug.template=Fg`
2316
2316
  <div class="o-col-resizer" t-on-mousemove.self="onMouseMove" t-on-mouseleave="onMouseLeave" t-on-mousedown.self.prevent="select"
2317
2317
  t-on-mouseup.self="onMouseUp" t-on-contextmenu.self="onContextMenu" t-att-class="{'o-grab': state.waitingForMove, 'o-dragging': state.isMoving, }">
2318
2318
  <div t-if="state.isMoving" class="dragging-col-line" t-attf-style="left:{{state.draggerLinePosition}}px;"/>
@@ -2494,7 +2494,7 @@
2494
2494
  height: ${f}px;
2495
2495
  }
2496
2496
  }
2497
- `,Vg.components={ColResizer:Ug,RowResizer:Bg};class zg{constructor(e,t){this.el=e,this.direction=t}get scroll(){return"horizontal"===this.direction?this.el.scrollLeft:this.el.scrollTop}set scroll(e){"horizontal"===this.direction?this.el.scrollLeft=e:this.el.scrollTop=e}}const{xml:Hg,css:Zg}=t.tags,{useRef:Gg,onMounted:Wg,onWillUnmount:qg,useState:jg}=t.hooks,Xg={ROW:ll,COL:rl,CELL:nl};function Yg(e,t){const s=jg({}),{browser:i,getters:o}=e,{Date:n,setInterval:r,clearInterval:a}=i,l=Gg("canvas");let c,h=0,d=0,u=0;function p(){const[e,i]=function(){const e=t();return[o.getColIndex(h,e.left),o.getRowIndex(d,e.top)]}(),r=n.now()-u;if(e===s.col&&i===s.row||(s.col=void 0,s.row=void 0),400<r&&r<600){if(e<0||i<0)return;s.col=e,s.row=i}}function g(e){h=e.offsetX,d=e.offsetY,u=n.now()}return Wg((()=>{l.el.addEventListener("mousemove",g),c=r(p,200)})),qg((()=>{l.el.removeEventListener("mousemove",g),a(c)})),s}const Kg=Hg`
2497
+ `,Vg.components={ColResizer:Ug,RowResizer:Bg};class Hg{constructor(e,t){this.el=e,this.direction=t}get scroll(){return"horizontal"===this.direction?this.el.scrollLeft:this.el.scrollTop}set scroll(e){"horizontal"===this.direction?this.el.scrollLeft=e:this.el.scrollTop=e}}const{xml:zg,css:Zg}=t.tags,{useRef:Gg,onMounted:Wg,onWillUnmount:qg,useState:jg}=t.hooks,Xg={ROW:ll,COL:rl,CELL:nl};function Yg(e,t){const s=jg({}),{browser:i,getters:o}=e,{Date:n,setInterval:r,clearInterval:a}=i,l=Gg("canvas");let c,h=0,d=0,u=0;function p(){const[e,i]=function(){const e=t();return[o.getColIndex(h,e.left),o.getRowIndex(d,e.top)]}(),r=n.now()-u;if(e===s.col&&i===s.row||(s.col=void 0,s.row=void 0),400<r&&r<600){if(e<0||i<0)return;s.col=e,s.row=i}}function g(e){h=e.offsetX,d=e.offsetY,u=n.now()}return Wg((()=>{l.el.addEventListener("mousemove",g),c=r(p,200)})),qg((()=>{l.el.removeEventListener("mousemove",g),a(c)})),s}const Kg=zg`
2498
2498
  <div class="o-grid" t-on-click="focus" t-on-keydown="onKeydown" t-on-wheel="onMouseWheel">
2499
2499
  <t t-if="getters.getEditionMode() !== 'inactive'">
2500
2500
  <GridComposer
@@ -2606,7 +2606,7 @@
2606
2606
  }
2607
2607
  }
2608
2608
  }
2609
- `;class Jg extends t.Component{constructor(){super(...arguments),this.menuState=jg({isOpen:!1,position:null,menuItems:[]}),this.vScrollbarRef=Gg("vscrollbar"),this.hScrollbarRef=Gg("hscrollbar"),this.canvas=Gg("canvas"),this.hiddenInput=Gg("hiddenInput"),this.getters=this.env.getters,this.dispatch=this.env.dispatch,this.currentSheet=this.getters.getActiveSheetId(),this.clickedCol=0,this.clickedRow=0,this.hoveredCell=Yg(this.env,(()=>this.getters.getActiveSnappedViewport())),this.keyDownMapping={ENTER:()=>{const e=this.getters.getActiveCell();!e||e.isEmpty()?this.trigger("composer-cell-focused"):this.trigger("composer-content-focused")},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.trigger("composer-cell-focused"):this.trigger("composer-content-focused")},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(),i=this.getters.getAutomaticSums(t,s,this.getters.getPosition());if(this.getters.isSingleCellOrMerge(t,s)||this.getters.isEmpty(t,s)&&i.length<=1){const s=(null===(e=i[0])||void 0===e?void 0:e.zone)?this.getters.zoneToXC(t,i[0].zone):"",o=`=SUM(${s})`;this.trigger("composer-cell-focused",{content:o,selection:{start:5,end:5+s.length}})}else this.dispatch("SUM_SELECTION")},"CTRL+HOME":()=>{const e=this.getters.getActiveSheet(),[t,s]=si(e,0,0);this.dispatch("SELECT_CELL",{col:t,row:s})},"CTRL+END":()=>{const e=this.getters.getActiveSheet(),t=ii(e,"cols",fs(0,e.cols.length).reverse()),s=ii(e,"rows",fs(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")}},this.vScrollbar=new zg(this.vScrollbarRef.el,"vertical"),this.hScrollbar=new zg(this.hScrollbarRef.el,"horizontal"),function(e,t){const s=Gg("canvas");let i=null,o=null;function n(e){1===e.touches.length&&(i=e.touches[0].clientX,o=e.touches[0].clientY)}function r(){i=null,o=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(i-n,o-r),i=n,o=r}Wg((()=>{s.el.addEventListener("touchstart",n),s.el.addEventListener("touchend",r),s.el.addEventListener("touchmove",a)})),qg((()=>{s.el.removeEventListener("touchstart",n),s.el.removeEventListener("touchend",r),s.el.removeEventListener("touchmove",a)}))}(this.moveCanvas.bind(this),(()=>this.vScrollbar.scroll>0)),this.props.exposeFocus((()=>this.focus()))}get errorTooltip(){const{col:e,row:t}=this.hoveredCell;if(void 0===e||void 0===t)return{isOpen:!1};const s=this.getters.getActiveSheetId(),[i,o]=this.getters.getMainCell(s,e,t),n=this.getters.getCell(s,i,o);if(n&&n.evaluated.type===Ne.error){const s=this.getters.getActiveSnappedViewport(),[i,o,r]=this.getters.getRect({left:e,top:t,right:e,bottom:t},s);return{isOpen:!0,position:{x:i+r,y:o+v},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,i=this.getters.getActiveSnappedViewport(),o=this.getters.getCell(e,t,s);return this.getters.isVisibleInViewport(t,s,i)&&!!o&&o.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(),[i,o,n,r]=this.getters.getRect({left:e,top:t,right:e,bottom:t},s);return{position:{x:i,y:o+r+v},cellWidth:n,cellHeight:r}}mounted(){this.vScrollbar.el=this.vScrollbarRef.el,this.hScrollbar.el=this.hScrollbarRef.el,this.focus(),this.resizeGrid(),this.drawGrid()}patched(){this.resizeGrid(),this.drawGrid()}focus(){this.getters.isSelectingForComposer()||this.getters.getSelectedFigureId()||this.hiddenInput.el.focus()}resizeGrid(){const e=this.el.clientHeight-S,t=this.el.clientWidth-S,{height:s,width:i}=this.getters.getViewportDimension();e==s&&t===i||this.dispatch("RESIZE_VIEWPORT",{height:e,width:t})}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:i}=this.getters.getActiveSnappedViewport();return{left:t.cols[e.right].end-4+m-s,top:t.rows[e.bottom].end-4+f-i}}drawGrid(){const{offsetX:e,offsetY:t}=this.getters.getActiveViewport();this.hScrollbar.scroll=e,this.vScrollbar.scroll=t,this.checkSheetChanges();const s=this.canvas.el,i=window.devicePixelRatio||1,o=s.getContext("2d",{alpha:!1}),n=.4*i,r={ctx:o,viewport:this.getters.getActiveViewport(),dpr:i,thinLineWidth:n},{width:a,height:l}=this.getters.getViewportDimension();s.style.width=`${a}px`,s.style.height=`${l}px`,s.width=a*i,s.height=l*i,s.setAttribute("style",`width:${a}px;height:${l}px;`),o.translate(-.5,-.5),o.scale(i,i),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,i;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===(i=e.position)||void 0===i?void 0:i.row}`}onMouseWheel(e){if(e.ctrlKey)return;function t(t){return t*(0===e.deltaMode?1:b)}const s=e.shiftKey?e.deltaY:e.deltaX,i=e.shiftKey?e.deltaX:e.deltaY;this.moveCanvas(t(s),t(i))}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:i,top:o}=this.getters.getActiveSnappedViewport();return[this.getters.getColIndex(t,i),this.getters.getRowIndex(s,o)]}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 i=this.getters.getActiveSheetId(),[o,n]=this.getters.getMainCell(i,t,s),r=this.getters.getCell(i,o,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 i=this.getters.getEdgeScrollCol(t),o=this.getters.getEdgeScrollRow(s),{left:n,right:r,top:f,bottom:m}=this.getters.getActiveSnappedViewport();let v,E;if(i.canEdgeScroll?v=i.direction>0?r:n-1:(v=this.getters.getColIndex(t,n),v=-1===v?l:v),o.canEdgeScroll?E=o.direction>0?m:f-1:(E=this.getters.getRowIndex(s,f),E=-1===E?c:E),h=i.canEdgeScroll||o.canEdgeScroll,u=Math.min(i.canEdgeScroll?i.delay:is,o.canEdgeScroll?o.delay:is),v===l&&E===c||(l=v,c=E,this.dispatch("ALTER_SELECTION",{cell:[v,E]})),h){const e=p.cols[n+i.direction].start,t=p.rows[f+o.direction].start;this.dispatch("SET_VIEWPORT_OFFSET",{offsetX:e,offsetY:t}),d=setTimeout((()=>{d=null,g(a)}),Math.round(u))}};Yu(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.trigger("composer-cell-focused"):this.trigger("composer-content-focused")}}closeLinkEditor(){this.trigger("link-editor-closed")}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(),i=this.getters.getActiveSnappedViewport(),o=this.getters.getActiveSheet(),[n,r]=function(e,t,s){let i,o;const{left:n,right:r,top:a,bottom:l}=e,{left:c,right:h,top:d,bottom:u}=t;return i=c!=n?c:h!=r?h:s.left,o=d!=a?d:u!=l?u:s.top,[i,o]}(e,s,i),{left:a,right:l,top:c,bottom:h,offsetX:d,offsetY:u}=i,p=n<a||n>l-1?o.cols[a+t[0]].start:d,g=r<c||r>h-1?o.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.trigger("composer-cell-focused",{content: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:i}=t;let o="CELL";this.dispatch("STOP_EDITION"),this.getters.getActiveCols().has(s)?o="COL":this.getters.getActiveRows().has(i)&&(o="ROW");const[n,r,a,l]=this.getters.getRect(t,this.getters.getActiveSnappedViewport());this.toggleContextMenu(o,n+a,r+l)}onCanvasContextMenu(e){e.preventDefault();const[t,s]=this.getCartesianCoordinates(e);if(t<0||s<0)return;const i=this.getters.getSelectedZones();let o="CELL";Us(t,s,i[i.length-1])?this.getters.getActiveCols().has(t)?o="COL":this.getters.getActiveRows().has(s)&&(o="ROW"):(this.dispatch("STOP_EDITION"),this.dispatch("SELECT_CELL",{col:t,row:s})),this.toggleContextMenu(o,e.offsetX,e.offsetY)}onOverlayContextMenu(e){const t=e.detail.type,s=e.detail.x,i=e.detail.y;this.toggleContextMenu(t,s,i)}toggleContextMenu(e,t,s){this.closeLinkEditor(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:s+v},this.menuState.menuItems=Xg[e].getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}closeMenu(){this.menuState.isOpen=!1,this.focus()}}Jg.template=Kg,Jg.style=Qg,Jg.components={GridComposer:Wp,Overlay:Vg,Menu:Hu,Autofill:ip,FiguresContainer:hg,ClientTag:cp,Highlight:yg,ErrorToolTip:Kp,LinkDisplay:Lg,LinkEditor:kg,Popover:$u};const{xml:ef,css:tf}=t.tags,{useState:sf}=t.hooks,of=ef`
2609
+ `;class Jg extends t.Component{constructor(){super(...arguments),this.menuState=jg({isOpen:!1,position:null,menuItems:[]}),this.vScrollbarRef=Gg("vscrollbar"),this.hScrollbarRef=Gg("hscrollbar"),this.canvas=Gg("canvas"),this.hiddenInput=Gg("hiddenInput"),this.getters=this.env.getters,this.dispatch=this.env.dispatch,this.currentSheet=this.getters.getActiveSheetId(),this.clickedCol=0,this.clickedRow=0,this.hoveredCell=Yg(this.env,(()=>this.getters.getActiveSnappedViewport())),this.keyDownMapping={ENTER:()=>{const e=this.getters.getActiveCell();!e||e.isEmpty()?this.trigger("composer-cell-focused"):this.trigger("composer-content-focused")},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.trigger("composer-cell-focused"):this.trigger("composer-content-focused")},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(),i=this.getters.getAutomaticSums(t,s,this.getters.getPosition());if(this.getters.isSingleCellOrMerge(t,s)||this.getters.isEmpty(t,s)&&i.length<=1){const s=(null===(e=i[0])||void 0===e?void 0:e.zone)?this.getters.zoneToXC(t,i[0].zone):"",o=`=SUM(${s})`;this.trigger("composer-cell-focused",{content:o,selection:{start:5,end:5+s.length}})}else this.dispatch("SUM_SELECTION")},"CTRL+HOME":()=>{const e=this.getters.getActiveSheet(),[t,s]=si(e,0,0);this.dispatch("SELECT_CELL",{col:t,row:s})},"CTRL+END":()=>{const e=this.getters.getActiveSheet(),t=ii(e,"cols",fs(0,e.cols.length).reverse()),s=ii(e,"rows",fs(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")}},this.vScrollbar=new Hg(this.vScrollbarRef.el,"vertical"),this.hScrollbar=new Hg(this.hScrollbarRef.el,"horizontal"),function(e,t){const s=Gg("canvas");let i=null,o=null;function n(e){1===e.touches.length&&(i=e.touches[0].clientX,o=e.touches[0].clientY)}function r(){i=null,o=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(i-n,o-r),i=n,o=r}Wg((()=>{s.el.addEventListener("touchstart",n),s.el.addEventListener("touchend",r),s.el.addEventListener("touchmove",a)})),qg((()=>{s.el.removeEventListener("touchstart",n),s.el.removeEventListener("touchend",r),s.el.removeEventListener("touchmove",a)}))}(this.moveCanvas.bind(this),(()=>this.vScrollbar.scroll>0)),this.props.exposeFocus((()=>this.focus()))}get errorTooltip(){const{col:e,row:t}=this.hoveredCell;if(void 0===e||void 0===t)return{isOpen:!1};const s=this.getters.getActiveSheetId(),[i,o]=this.getters.getMainCell(s,e,t),n=this.getters.getCell(s,i,o);if(n&&n.evaluated.type===Ne.error){const s=this.getters.getActiveSnappedViewport(),[i,o,r]=this.getters.getRect({left:e,top:t,right:e,bottom:t},s);return{isOpen:!0,position:{x:i+r,y:o+v},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,i=this.getters.getActiveSnappedViewport(),o=this.getters.getCell(e,t,s);return this.getters.isVisibleInViewport(t,s,i)&&!!o&&o.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(),[i,o,n,r]=this.getters.getRect({left:e,top:t,right:e,bottom:t},s);return{position:{x:i,y:o+r+v},cellWidth:n,cellHeight:r}}mounted(){this.vScrollbar.el=this.vScrollbarRef.el,this.hScrollbar.el=this.hScrollbarRef.el,this.focus(),this.resizeGrid(),this.drawGrid()}patched(){this.resizeGrid(),this.drawGrid()}focus(){this.getters.isSelectingForComposer()||this.getters.getSelectedFigureId()||this.hiddenInput.el.focus()}resizeGrid(){const e=this.el.clientHeight-S,t=this.el.clientWidth-S,{height:s,width:i}=this.getters.getViewportDimension();e==s&&t===i||this.dispatch("RESIZE_VIEWPORT",{height:e,width:t})}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:i}=this.getters.getActiveSnappedViewport();return{left:t.cols[e.right].end-4+m-s,top:t.rows[e.bottom].end-4+f-i}}drawGrid(){const{offsetX:e,offsetY:t}=this.getters.getActiveViewport();this.hScrollbar.scroll=e,this.vScrollbar.scroll=t,this.checkSheetChanges();const s=this.canvas.el,i=window.devicePixelRatio||1,o=s.getContext("2d",{alpha:!1}),n=.4*i,r={ctx:o,viewport:this.getters.getActiveViewport(),dpr:i,thinLineWidth:n},{width:a,height:l}=this.getters.getViewportDimension();s.style.width=`${a}px`,s.style.height=`${l}px`,s.width=a*i,s.height=l*i,s.setAttribute("style",`width:${a}px;height:${l}px;`),o.translate(-.5,-.5),o.scale(i,i),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,i;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===(i=e.position)||void 0===i?void 0:i.row}`}onMouseWheel(e){if(e.ctrlKey)return;function t(t){return t*(0===e.deltaMode?1:b)}const s=e.shiftKey?e.deltaY:e.deltaX,i=e.shiftKey?e.deltaX:e.deltaY;this.moveCanvas(t(s),t(i))}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:i,top:o}=this.getters.getActiveSnappedViewport();return[this.getters.getColIndex(t,i),this.getters.getRowIndex(s,o)]}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 i=this.getters.getActiveSheetId(),[o,n]=this.getters.getMainCell(i,t,s),r=this.getters.getCell(i,o,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 i=this.getters.getEdgeScrollCol(t),o=this.getters.getEdgeScrollRow(s),{left:n,right:r,top:f,bottom:m}=this.getters.getActiveSnappedViewport();let v,E;if(i.canEdgeScroll?v=i.direction>0?r:n-1:(v=this.getters.getColIndex(t,n),v=-1===v?l:v),o.canEdgeScroll?E=o.direction>0?m:f-1:(E=this.getters.getRowIndex(s,f),E=-1===E?c:E),h=i.canEdgeScroll||o.canEdgeScroll,u=Math.min(i.canEdgeScroll?i.delay:is,o.canEdgeScroll?o.delay:is),v===l&&E===c||(l=v,c=E,this.dispatch("ALTER_SELECTION",{cell:[v,E]})),h){const e=p.cols[n+i.direction].start,t=p.rows[f+o.direction].start;this.dispatch("SET_VIEWPORT_OFFSET",{offsetX:e,offsetY:t}),d=setTimeout((()=>{d=null,g(a)}),Math.round(u))}};Yu(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.trigger("composer-cell-focused"):this.trigger("composer-content-focused")}}closeLinkEditor(){this.trigger("link-editor-closed")}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(),i=this.getters.getActiveSnappedViewport(),o=this.getters.getActiveSheet(),[n,r]=function(e,t,s){let i,o;const{left:n,right:r,top:a,bottom:l}=e,{left:c,right:h,top:d,bottom:u}=t;return i=c!=n?c:h!=r?h:s.left,o=d!=a?d:u!=l?u:s.top,[i,o]}(e,s,i),{left:a,right:l,top:c,bottom:h,offsetX:d,offsetY:u}=i,p=n<a||n>l-1?o.cols[a+t[0]].start:d,g=r<c||r>h-1?o.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.trigger("composer-cell-focused",{content: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:i}=t;let o="CELL";this.dispatch("STOP_EDITION"),this.getters.getActiveCols().has(s)?o="COL":this.getters.getActiveRows().has(i)&&(o="ROW");const[n,r,a,l]=this.getters.getRect(t,this.getters.getActiveSnappedViewport());this.toggleContextMenu(o,n+a,r+l)}onCanvasContextMenu(e){e.preventDefault();const[t,s]=this.getCartesianCoordinates(e);if(t<0||s<0)return;const i=this.getters.getSelectedZones();let o="CELL";Us(t,s,i[i.length-1])?this.getters.getActiveCols().has(t)?o="COL":this.getters.getActiveRows().has(s)&&(o="ROW"):(this.dispatch("STOP_EDITION"),this.dispatch("SELECT_CELL",{col:t,row:s})),this.toggleContextMenu(o,e.offsetX,e.offsetY)}onOverlayContextMenu(e){const t=e.detail.type,s=e.detail.x,i=e.detail.y;this.toggleContextMenu(t,s,i)}toggleContextMenu(e,t,s){this.closeLinkEditor(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:s+v},this.menuState.menuItems=Xg[e].getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}closeMenu(){this.menuState.isOpen=!1,this.focus()}}Jg.template=Kg,Jg.style=Qg,Jg.components={GridComposer:Wp,Overlay:Vg,Menu:zu,Autofill:ip,FiguresContainer:hg,ClientTag:cp,Highlight:yg,ErrorToolTip:Kp,LinkDisplay:Lg,LinkEditor:kg,Popover:$u};const{xml:ef,css:tf}=t.tags,{useState:sf}=t.hooks,of=ef`
2610
2610
  <div class="o-sidePanel" >
2611
2611
  <div class="o-sidePanelHeader">
2612
2612
  <div class="o-sidePanelTitle" t-esc="getTitle()"/>
@@ -3016,7 +3016,7 @@
3016
3016
  }
3017
3017
  }
3018
3018
  }
3019
- `,Mf.components={ColorPicker:ml,Menu:Hu,Composer:Bp};const{useExternalListener:Af,useSubEnv:_f,useRef:Of}=t.hooks,{xml:Nf,css:kf}=t.tags,Ff=Nf`
3019
+ `,Mf.components={ColorPicker:ml,Menu:zu,Composer:Bp};const{useExternalListener:Af,useSubEnv:_f,useRef:Of}=t.hooks,{xml:Nf,css:kf}=t.tags,Ff=Nf`
3020
3020
  <div class="o-spreadsheet" t-on-save-requested="save" t-on-keydown="onKeydown">
3021
3021
  <TopBar
3022
3022
  t-on-click="focusGrid"
@@ -3072,4 +3072,4 @@
3072
3072
  height: ${15}px;
3073
3073
  vertical-align: sub;
3074
3074
  }
3075
- `;class Df extends t.Component{constructor(e,s={}){super(e,s),this.model=new Ru(this.props.data,{notifyUser:e=>this.trigger("notify-user",{content:e}),askConfirmation:(e,t,s)=>this.trigger("ask-confirmation",{content:e,confirm:t,cancel:s}),editText:(e,t,s)=>this.trigger("edit-text",{title:e,placeholder:t,callback:s}),openSidePanel:(e,t={})=>this.openSidePanel(e,t),evalContext:{env:this.env},transportService:this.props.transportService,client:this.props.client,isReadonly:this.props.isReadonly,snapshotRequested:this.props.snapshotRequested},this.props.stateUpdateMessages),this.grid=Of("grid"),this.sidePanel=t.useState({isOpen:!1,panelProps:{}}),this.linkEditor=t.useState({isOpen:!1}),this.composer=t.useState({topBarFocus:"inactive",gridFocusMode:"inactive"}),this.clipBoardString="",this.keyDownMapping={"CTRL+H":()=>this.toggleSidePanel("FindAndReplace",{}),"CTRL+F":()=>this.toggleSidePanel("FindAndReplace",{})},_f({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:Df._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()}),Af(window,"resize",this.render),Af(document.body,"cut",this.copy.bind(this,!0)),Af(document.body,"copy",this.copy.bind(this,!1)),Af(document.body,"paste",this.paste),Af(document.body,"keyup",this.onKeyup.bind(this)),Af(window,"beforeunload",this.leaveCollaborativeSession.bind(this)),this.activateFirstSheet()}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}mounted(){this.model.on("update",this,this.render),this.model.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.props.client&&this.model.joinSession(this.props.client)}willUnmount(){this.leaveCollaborativeSession()}async willUpdateProps(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()}copy(e,t){if(!this.grid.el.contains(document.activeElement))return;if("inactive"!==this.model.getters.getEditionMode())return;const s=e?"CUT":"COPY",i=this.model.getters.getSelectedZones();this.model.dispatch(s,{target:i});const o=this.model.getters.getClipboardContent();this.clipBoardString=o,t.clipboardData.setData("text/plain",o),t.preventDefault()}paste(e){if(!this.grid.el.contains(document.activeElement))return;const t=e.clipboardData;if(t.types.indexOf("text/plain")>-1){const e=t.getData("text/plain"),s=this.model.getters.getSelectedZones();this.clipBoardString===e?this.model.dispatch("PASTE",{target:s,interactive:!0}):this.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:s,text:e})}}save(){this.trigger("save-content",{data:this.model.exportData()})}onKeyup(e){"Control"===e.key&&this.model.getters.getSelectionMode()!==Ch.expanding&&this.model.dispatch("STOP_SELECTION")}onKeydown(e){"Control"!==e.key||e.repeat||this.model.dispatch(this.model.getters.getSelectionMode()===Ch.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(e.detail||{}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}onGridComposerContentFocused(e){this.model.getters.isReadonly()||(this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent(e.detail||{}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}onGridComposerCellFocused(e){this.model.getters.isReadonly()||(this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent(e.detail||{}),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})}}Df.template=Ff,Df.style=$f,Df.components={TopBar:Mf,Grid:Jg,BottomBar:Xu,SidePanel:rf,LinkEditor:kg},Df._t=e=>e;const Pf={},Uf={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:f,HEADER_WIDTH:m,TOPBAR_HEIGHT:v,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:E,DEFAULT_CELL_HEIGHT:b,SCROLLBAR_WIDTH:S},Bf={autofillModifiersRegistry:wa,autofillRulesRegistry:xa,cellMenuRegistry:nl,colMenuRegistry:rl,linkMenuRegistry:al,functionRegistry:ir,uiPluginRegistry:sd,corePluginRegistry:td,rowMenuRegistry:ll,sidePanelRegistry:gh,sheetMenuRegistry:cl,topbarMenuRegistry:hl,topbarComponentRegistry:fh,otRegistry:dl,inverseCommandRegistry:Ra,cellRegistry:Hr},Vf={LinkCell:Qr},zf={args:Ae,toBoolean:pe,toNumber:ce,toString:de,toXC:ss,toZone:_s,toCartesian:ts,numberToLetters:es,createFullMenuItem:Aa,UuidGenerator:ti,formatDecimal:ne,computeTextWidth:gs,isMarkdownLink:Is,parseMarkdownLink:ws,markdownLink:ys,createEmptyWorkbookData:da};e.CorePlugin=pa,e.DATETIME_FORMAT=A,e.DataSource=nd,e.DispatchResult=Pe,e.Model=Ru,e.Revision=Wh,e.SPREADSHEET_DIMENSIONS=Uf,e.Spreadsheet=Df,e.UIPlugin=mh,e.__DEBUG__=Ms,e.__info__=Pf,e.astToFormula=Ar,e.cellTypes=Vf,e.convertAstNodes=Mr,e.coreTypes=$e,e.functionCache=$r,e.helpers=zf,e.invalidateEvaluationCommands=ke,e.normalize=Vr,e.parse=Lr,e.readonlyAllowedCommands=Fe,e.registries=Bf,e.setTranslationMethod=function(e){o=e},Object.defineProperty(e,"__esModule",{value:!0}),Pf.version="15.0.3",Pf.date="2023-03-23T11:34:07.983Z",Pf.hash="f51b30b"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
3075
+ `;class Df extends t.Component{constructor(e,s={}){super(e,s),this.model=new Ru(this.props.data,{notifyUser:e=>this.trigger("notify-user",{content:e}),askConfirmation:(e,t,s)=>this.trigger("ask-confirmation",{content:e,confirm:t,cancel:s}),editText:(e,t,s)=>this.trigger("edit-text",{title:e,placeholder:t,callback:s}),openSidePanel:(e,t={})=>this.openSidePanel(e,t),evalContext:{env:this.env},transportService:this.props.transportService,client:this.props.client,isReadonly:this.props.isReadonly,snapshotRequested:this.props.snapshotRequested},this.props.stateUpdateMessages),this.grid=Of("grid"),this.sidePanel=t.useState({isOpen:!1,panelProps:{}}),this.linkEditor=t.useState({isOpen:!1}),this.composer=t.useState({topBarFocus:"inactive",gridFocusMode:"inactive"}),this.clipBoardString="",this.keyDownMapping={"CTRL+H":()=>this.toggleSidePanel("FindAndReplace",{}),"CTRL+F":()=>this.toggleSidePanel("FindAndReplace",{})},_f({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:Df._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()}),Af(window,"resize",this.render),Af(document.body,"cut",this.copy.bind(this,!0)),Af(document.body,"copy",this.copy.bind(this,!1)),Af(document.body,"paste",this.paste),Af(document.body,"keyup",this.onKeyup.bind(this)),Af(window,"beforeunload",this.leaveCollaborativeSession.bind(this)),this.activateFirstSheet()}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}mounted(){this.model.on("update",this,this.render),this.model.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.props.client&&this.model.joinSession(this.props.client)}willUnmount(){this.leaveCollaborativeSession()}async willUpdateProps(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()}copy(e,t){if(!this.grid.el.contains(document.activeElement))return;if("inactive"!==this.model.getters.getEditionMode())return;const s=e?"CUT":"COPY",i=this.model.getters.getSelectedZones();this.model.dispatch(s,{target:i});const o=this.model.getters.getClipboardContent();this.clipBoardString=o,t.clipboardData.setData("text/plain",o),t.preventDefault()}paste(e){if(!this.grid.el.contains(document.activeElement))return;const t=e.clipboardData;if(t.types.indexOf("text/plain")>-1){const e=t.getData("text/plain"),s=this.model.getters.getSelectedZones();this.clipBoardString===e?this.model.dispatch("PASTE",{target:s,interactive:!0}):this.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:s,text:e})}}save(){this.trigger("save-content",{data:this.model.exportData()})}onKeyup(e){"Control"===e.key&&this.model.getters.getSelectionMode()!==Ch.expanding&&this.model.dispatch("STOP_SELECTION")}onKeydown(e){"Control"!==e.key||e.repeat||this.model.dispatch(this.model.getters.getSelectionMode()===Ch.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(e.detail||{}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}onGridComposerContentFocused(e){this.model.getters.isReadonly()||(this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent(e.detail||{}),this.env.dispatch("UNFOCUS_SELECTION_INPUT"))}onGridComposerCellFocused(e){this.model.getters.isReadonly()||(this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent(e.detail||{}),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})}}Df.template=Ff,Df.style=$f,Df.components={TopBar:Mf,Grid:Jg,BottomBar:Xu,SidePanel:rf,LinkEditor:kg},Df._t=e=>e;const Pf={},Uf={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:f,HEADER_WIDTH:m,TOPBAR_HEIGHT:v,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:E,DEFAULT_CELL_HEIGHT:b,SCROLLBAR_WIDTH:S},Bf={autofillModifiersRegistry:wa,autofillRulesRegistry:xa,cellMenuRegistry:nl,colMenuRegistry:rl,linkMenuRegistry:al,functionRegistry:ir,uiPluginRegistry:sd,corePluginRegistry:td,rowMenuRegistry:ll,sidePanelRegistry:gh,sheetMenuRegistry:cl,topbarMenuRegistry:hl,topbarComponentRegistry:fh,otRegistry:dl,inverseCommandRegistry:Ra,cellRegistry:zr},Vf={LinkCell:Qr},Hf={args:Ae,toBoolean:pe,toNumber:ce,toString:de,toXC:ss,toZone:_s,toCartesian:ts,numberToLetters:es,createFullMenuItem:Aa,UuidGenerator:ti,formatDecimal:ne,computeTextWidth:gs,isMarkdownLink:Is,parseMarkdownLink:ws,markdownLink:ys,createEmptyWorkbookData:da};e.CorePlugin=pa,e.DATETIME_FORMAT=A,e.DataSource=nd,e.DispatchResult=Pe,e.Model=Ru,e.Revision=Wh,e.SPREADSHEET_DIMENSIONS=Uf,e.Spreadsheet=Df,e.UIPlugin=mh,e.__DEBUG__=Ms,e.__info__=Pf,e.astToFormula=Ar,e.cellTypes=Vf,e.convertAstNodes=Mr,e.coreTypes=$e,e.functionCache=$r,e.helpers=Hf,e.invalidateEvaluationCommands=ke,e.normalize=Vr,e.parse=Lr,e.readonlyAllowedCommands=Fe,e.registries=Bf,e.setTranslationMethod=function(e){o=e},Object.defineProperty(e,"__esModule",{value:!0}),Pf.version="15.0.5",Pf.date="2023-04-21T07:27:19.753Z",Pf.hash="ef69cc7"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);