@odoo/o-spreadsheet 16.2.28 → 16.2.29

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";let i=e=>e;function o(e,...t){if(1===t.length&&"object"==typeof t[0]){const i=t[0];e=e.replace(/\%\(?([^\)]+)\)s/g,((e,t)=>i[t]))}else t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));return e}const n=function(e,...t){return o(i(e),...t)},s=function(e,...t){return new r(e,t)};class r extends String{constructor(e,t){super(e),this.values=t}valueOf(){const e=super.valueOf();return o(i(e),...this.values)}toString(){return this.valueOf()}}var a,l;!function(e){e.NotAvailable="#N/A",e.InvalidReference="#REF",e.BadExpression="#BAD_EXPR",e.CircularDependency="#CYCLE",e.UnknownFunction="#NAME?",e.GenericError="#ERROR"}(a||(a={})),function(e){e[e.silent=0]="silent",e[e.error=1]="error"}(l||(l={}));class c extends Error{constructor(e,t,i=l.error){super(t),this.errorType=e,this.logLevel=i}}class h extends c{constructor(e){super(a.BadExpression,e)}}class d extends c{constructor(){super(a.CircularDependency,s("Circular reference"))}}class u extends c{constructor(){super(a.InvalidReference,s("Invalid reference"))}}class g extends c{constructor(e){super(a.NotAvailable,e||s("Data not available"),e?l.error:l.silent)}}class p extends c{constructor(e){super(a.UnknownFunction,s('Unknown function: "%s"',e))}}const m=.5,f="#f5f5f5",v="#F8F9FA",b="#E8EAED",C="#595959",S="#666666",E="#3266ca",w="#FFFFFF",y="#CACACA",x=11982760,I="#01666b",R="#188038",T="#E6F4EA",A="#CEEAD6",M="#E0E2E4",O=["#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"],N=26,_=48,F=96,D=23,k=15,L=18,P=14,U=4,V=4,z=3,B=V,H=17,$=250,W=1,G="400",q=10,Z="'Roboto', arial",j=["thin","#000"],Y=["thin",R],X=/[ymdhs:]/,K=a.InvalidReference,Q="START_REVISION",J=20,ee="??",te="difference",ie="#00A04A",oe="#DC6965",ne=.4,se=["'","*","?","/","\\","[","]"],re=/'|\*|\?|\/|\\|\[|\]/,ae="|",le=s("Invalid expression");var ce;!function(e){e[e.Grid=0]="Grid",e[e.Highlight=5]="Highlight",e[e.Figure=10]="Figure",e[e.ScrollBar=15]="ScrollBar",e[e.GridPopover=19]="GridPopover",e[e.GridComposer=20]="GridComposer",e[e.Dropdown=21]="Dropdown",e[e.IconPicker=25]="IconPicker",e[e.TopBarComposer=30]="TopBarComposer",e[e.Popover=35]="Popover",e[e.ChartAnchor=1e3]="ChartAnchor"}(ce||(ce={}));const he="\n",de=[6,7,8,9,10,11,12,14,18,24,36];class ue{constructor(e,t,i,o=0,n=0,s=0){this.jsDate=new Date(Date.UTC(e,t,i,o,n,s,0))}static fromTimestamp(e){const t=new Date(e);return new ue(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())}static now(){const e=new Date;return new ue(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds())}toString(){return this.jsDate.toString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}getDate(){return this.jsDate.getUTCDate()}getDay(){return this.jsDate.getUTCDay()}getHours(){return this.jsDate.getUTCHours()}getMinutes(){return this.jsDate.getUTCMinutes()}getSeconds(){return this.jsDate.getUTCSeconds()}setFullYear(e){this.jsDate.setFullYear(e)}setDate(e){this.jsDate.setUTCDate(e)}setHours(e){this.jsDate.setUTCHours(e)}setMinutes(e){this.jsDate.setUTCMinutes(e)}setSeconds(e){this.jsDate.setUTCSeconds(e)}}const ge=new ue(1899,11,30),pe=864e5,me=2e3,fe=ue.now().getFullYear(),ve=ue.fromTimestamp(0).getTime()-ge.getTime(),be=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,Ce=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,Se=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/,Ee={};function we(e){if(e in Ee)return Ee[e];const t=function(e){let t;e=e.trim();const i=e.match(Se);if(i){if(t=function(e){if(e=e.trim(),Se.test(e)){const t=/AM/i.test(e),i=/PM/i.test(e),o=(t||i?e.substring(0,e.length-2).trim():e).split(/:/),n=o.length>=2,s=3===o.length;let r=Number(o[0]),a=n?Number(o[1]):0,l=s?Number(o[2]):0,c=s?"hh:mm:ss":"hh:mm";if(t||i)c+=" a";else if(!n)return null;r>=12&&t?r-=12:r<12&&i&&(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 ue(1899,11,30,r,a,l)}}return null}(i[0]),null===t)return null;e=e.replace(i[0],"").trim()}let o;const n=e.match(be),s=e.match(Ce);if(n||s){let t;if(n?(t=n[0],o=ye(t,"mdy")):(t=s[0],o=ye(t,"ymd")),null===o)return null;e=e.replace(t,"").trim()}if(""!==e||!o&&!t)return null;if(o&&t)return{value:o.value+t.value,format:o.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new ue(o.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,o.jsDate.getMonth()+t.jsDate.getMonth()-11,o.jsDate.getDate()+t.jsDate.getDate()-30,o.jsDate.getHours()+t.jsDate.getHours(),o.jsDate.getMinutes()+t.jsDate.getMinutes(),o.jsDate.getSeconds()+t.jsDate.getSeconds())};return o||t}(e);return Ee[e]=t,t}function ye(e,t){const i="mdy"===t;if(i||"ymd"===t){const t=e.split(/\/|-|\s/),o=i?0:1,n=i?1:2,s=i?2:0,r=Number(t[o]),a=Number(t[n]),l=2===t[o].length&&r<10||2===t[n].length&&a<10,c=t[s]?function(e){const t=Number(e);switch(e.length){case 1:return me+t;case 2:return me+(me+t>fe+10?-100:0)+t;case 3:case 4:return t}return 0}(t[s]):fe,h=new ue(c,r-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==r-1||h.getDate()!==a)return null;const u=h.getTime()-ge.getTime();let g=l?`mm${d}dd`:`m${d}d`;return t[s]&&(g=i?g+d+"yyyy":"yyyy"+d+g),{value:Math.round(u/pe),format:g,jsDate:h}}return null}function xe(e){const t=Math.trunc(e);let i=ue.fromTimestamp(t*pe-ve),o=e-t;o=o<0?1+o:o;const n=Math.round(24*o),s=Math.round(24*(o-n/24)*60),r=Math.round(24*(o-n/24-s/24/60)*60*60);return i.setHours(n),i.setMinutes(s),i.setSeconds(r),i}function Ie(e){const t=e.getTime()-ge.getTime();return Math.round(t/pe)}function Re(e){return new ue(e.getFullYear(),e.getMonth()+1,0).getDate()}function Te(e){return Re(e)===e.getDate()}function Ae(e,t,i){const o=e.getFullYear(),n=e.getMonth(),s=e.getDate(),r=new ue(o,n+t,1);return i&&s===Re(e)||s>Re(r)?r.setDate(Re(r)):r.setDate(s),r}function Me(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function Oe(e,t,i){if(e===t)return 0;if(e>t){const i=t;t=e,e=i}const o=xe(e),n=xe(t);let s=o.getDate(),r=n.getDate();const a=o.getMonth(),l=n.getMonth(),c=o.getFullYear(),h=n.getFullYear();let d=0,u=0;switch(i){case 0:31===s&&(s=30),30===s&&31===r&&(r=30),1===a&&s===(Me(c)?29:28)&&(s=30,1===l&&r===(Me(h)?29:28)&&(r=30)),d=c+(30*a+s)/360,u=h+(30*l+r)/360;break;case 1:let i=365;const o=c===h;if(!o&&!(c+1===h)||!o&&a<l||!o&&a===l&&s<r){let e=0,t=0;for(let i=c;i<=h;i++)e++,t+=Me(i)?366:365;i=t/e}else o?Me(c)&&(i=366):(Me(c)&&a<2&&(i=366),Me(h)&&(l>1||1===l&&29===r)&&(i=366));d=e/i,u=t/i;break;case 2:d=e/360,u=t/360;break;case 3:d=e/365,u=t/365;break;case 4:31===s&&(s=30),31===r&&(r=30),d=c+(30*a+s)/360,u=h+(30*l+r)/360}return u-d}function Ne(e){return'"'===e[0]&&(e=e.slice(1)),'"'===e[e.length-1]&&"\\"!==e[e.length-2]?e.slice(0,e.length-1):e}function _e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Fe(e){const t=Array.isArray(e)?[]:{};switch(typeof e){case"object":if(null===e)return e;if(function(e){return"clone"in e&&e.clone instanceof Function}(e))return e.clone();if(!(function(e){return"object"==typeof e&&(null==e?void 0:e.constructor)===Object}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");for(const i in e)t[i]=Fe(e[i]);return t;case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function De(e){return e.startsWith("'")&&(e=e.slice(1,-1).replace(/''/g,"'")),e}function ke(e){var t;return(null===(t=e.match(/\w/g))||void 0===t?void 0:t.length)!==e.length&&(e=`'${e}'`),e}function Le(e,t,i){return e<t?t:e>i?i:e}function Pe(e,t=1){return t*(e+V)-V}function Ue(e,t,i){const o=Be(i);if(Ve[o]||(Ve[o]={}),void 0===Ve[o][t]){e.save(),e.font=o;const i=e.measureText(t).width;e.restore(),Ve[o][t]=i}return Ve[o][t]}const Ve={};function ze(e){return Math.round(96*e/72)}function Be(e){return`${e.italic?"italic ":""}${e.bold?"bold":G} ${He(e)}px ${Z}`}function He(e){return ze((null==e?void 0:e.fontSize)||q)}function $e(e,t,i=1){if(t<=e&&i>0)return[];if(0===i)throw new Error("range() step must not be zero");const o=Math.ceil(Math.abs((t-e)/i)),n=Array(o);for(let t=0;t<o;t++)n[t]=e+t*i;return n}function We(e){return e.reduce(((e,t,i,o)=>{if(1===Math.abs(t-o[i-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*Ge(e,t){t.next();for(const i of e){const e=t.next();yield{...i,next:e.done?void 0:e.value}}}function qe(e){return null!==we(e)}const Ze=/^\[(.+)\]\((.+)\)$/,je=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function Ye(e){return Ze.test(e)}function Xe(e){return je.test(e)}function Ke(e,t){return`[${e}](${t})`}function Qe(e){const t=e.match(Ze)||[],i=t[1],o=t[2];if(!i||!o)throw new Error(`Could not parse markdown link ${e}.`);return{label:i,url:o}}const Je="o-spreadsheet://";function et(e){return e.startsWith(Je)}function tt(e){return`${Je}${e}`}function it(e){if(e.startsWith(Je))return e.substr(Je.length);throw new Error(`${e} is not a valid sheet link`)}function ot(e){return void 0!==e}function nt(e){return void 0===e||Object.values(e).every((e=>"object"==typeof e?nt(e):!e))}function st(e,t){for(let[i,o]of Object.entries(t))if(ht(o,e))return parseInt(i,10);const i=Object.keys(t),o=0===i.length?0:Math.max(...i.map((e=>parseInt(e,10))));return t[o+1]=e,o+1}function rt(e){let t="";for(let i=0,o=e.length;i<o;i++)t+=e[i];return t}function at(e){let t,i=!1;const o=()=>(i||(t=e instanceof Function?e():e,i=!0),t);return o.map=e=>at((()=>e(o()))),o}function lt(e,t){let i=e.slice(t).find((e=>e));return i||(i=e.slice(0,t).reverse().find((e=>e))),i||""}function ct(e,t){return"after"===e?t+1:t}function ht(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;if(typeof e!=typeof t)return!1;if("object"!=typeof e)return e===t;const i=new Set;Object.keys(e).forEach((e=>i.add(e))),Object.keys(t).forEach((e=>i.add(e)));for(let o of i){if(typeof e[o]!=typeof e[o])return!1;if("object"==typeof e[o]){if(!ht(e[o],t[o]))return!1}else if(e[o]!==t[o])return!1}return!0}function dt(e,t){return t.every((t=>e.includes(t)))}function ut(e){const t={...e};return Object.keys(t).forEach((e=>!t[e]&&delete t[e])),t}function gt(e){return e?e.toLowerCase():""}const pt=[" ","\t","\f","\v",String.fromCharCode(parseInt("00a0",16)),String.fromCharCode(parseInt("1680",16)),String.fromCharCode(parseInt("2000",16)),String.fromCharCode(parseInt("200a",16)),String.fromCharCode(parseInt("2028",16)),String.fromCharCode(parseInt("2029",16)),String.fromCharCode(parseInt("202f",16)),String.fromCharCode(parseInt("205f",16)),String.fromCharCode(parseInt("3000",16)),String.fromCharCode(parseInt("feff",16))],mt=new RegExp(pt.join("|"),"g"),ft=/\r\n|\r|\n/g;function vt(e){return e?e=(e=e.replace(mt," ")).replace(ft,he):""}const bt=/rgba?\(|\s+|\)/gi,Ct=/^#([A-F\d]{2}){3,4}$/g,St=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function Et(e){return wt(e.toString(16).padStart(6,"0"))}function wt(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(bt,"").split(",");let i=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");i=Math.round(255*(e||1))}const o=t.map((e=>parseInt(e,10)));255!==i&&o.push(i);return"#"+rt(o.map((e=>e.toString(16).padStart(2,"0")))).toUpperCase()}(e):(t=e.replace("#","").toUpperCase(),3!==t.length&&4!==t.length||(t=t.split("").reduce(((e,t)=>e+t+t),"")),t=`#${t}`),!t.match(Ct))throw new Error(`invalid color input: ${e}`);return t}function yt(e){try{return wt(e),!0}catch(e){return!1}}const xt=e=>e>=0&&e<=255;function It(e,t,i,o=1){if(!xt(e)||!xt(t)||!xt(i)||o<0||o>1)throw new Error(`Invalid RGBA values ${[e,t,i,o]}`);return{a:o,b:i,g:t,r:e}}function Rt(e){let{r:t,g:i,b:o}=At(e);t/=255,i/=255,o/=255;const n=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*n(t)+.7152*n(i)+.0722*n(o)}function Tt(e){let t=e.r.toString(16),i=e.g.toString(16),o=e.b.toString(16),n=Math.round(255*e.a).toString(16);return 1==t.length&&(t="0"+t),1==i.length&&(i="0"+i),1==o.length&&(o="0"+o),1==n.length&&(n="0"+n),"ff"===n&&(n=""),("#"+t+i+o+n).toUpperCase()}function At(e){let t,i,o,n;if(7===(e=wt(e)).length)t=parseInt(e[1]+e[2],16),i=parseInt(e[3]+e[4],16),o=parseInt(e[5]+e[6],16),n=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),i=parseInt(e[3]+e[4],16),o=parseInt(e[5]+e[6],16),n=parseInt(e[7]+e[8],16)}return n=+(n/255).toFixed(3),{a:n,r:t,g:i,b:o}}function Mt(e){(e={...e}).s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,i=t*(1-Math.abs(e.h/60%2-1)),o=e.l-t/2,n=0,s=0,r=0;return 0<=e.h&&e.h<60?(n=t,s=i,r=0):60<=e.h&&e.h<120?(n=i,s=t,r=0):120<=e.h&&e.h<180?(n=0,s=t,r=i):180<=e.h&&e.h<240?(n=0,s=i,r=t):240<=e.h&&e.h<300?(n=i,s=0,r=t):300<=e.h&&e.h<360&&(n=t,s=0,r=i),n=Math.round(255*(n+o)),s=Math.round(255*(s+o)),r=Math.round(255*(r+o)),{a:e.a,r:n,g:s,b:r}}function Ot(e){const t=e.r/255,i=e.g/255,o=e.b/255;let n=Math.min(t,i,o),s=Math.max(t,i,o),r=s-n,a=0,l=0,c=0;return a=0==r?0:s==t?(i-o)/r%6:s==i?(o-t)/r+2:(t-i)/r+4,a=Math.round(60*a),a<0&&(a+=360),c=(s+n)/2,l=0==r?0:r/(1-Math.abs(2*c-1)),l=+(100*l).toFixed(1),c=+(100*c).toFixed(1),{a:e.a,h:a,s:l,l:c}}const Nt=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),_t=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),Ft=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),Dt=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),kt=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),Lt=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),Pt=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[Nt.source,/(\$?[A-Z]{1,3})?\$?[0-9]{1,7}\s*:\s*(\$?[A-Z]{1,3})?\$?[0-9]{1,7}\s*/i.source,/\$?[A-Z]{1,3}(\$?[0-9]{1,7})?\s*:\s*\$?[A-Z]{1,3}(\$?[0-9]{1,7})?\s*/i.source].join("|")+")"+/$/.source,"i");function Ut(e){return kt.test(e)}function Vt(e){return Lt.test(e)}function zt(e){return Ft.test(e)}function Bt(e){return Dt.test(e)}function Ht(e){return _t.test(e)}function $t(e){const t=e.split("!"),i=t.pop();return{sheetName:De(t.join("!"))||void 0,xc:i}}function Wt(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Wt(Math.floor(e/26)-1)+Wt(e%26)}function Gt(e){let t=0;const i=e.length;for(let o=0;o<i;o++){t+=(e.charCodeAt(o)-65+(o<i-1?1:0))*26**(i-o-1)}return t}function qt(e){const t=(e=e.toUpperCase().trim()).match(Nt);if(null!==t){const[i,o,n]=t;if(i===e){return{col:Gt(o),row:parseInt(n,10)-1}}}throw new Error(`Invalid cell description: ${e}`)}function Zt(e,t,i={colFixed:!1,rowFixed:!1}){return(i.colFixed?"$":"")+Wt(e)+(i.rowFixed?"$":"")+String(t+1)}const jt=140,Yt=20,Xt=.035;function Kt(e){return Yt+(jt-Yt)*Math.exp(-Xt*(e-1))}const Qt=/(^-?\d+(\.?\d*(e\d+)?)?|^-?\.\d+)(?!\w|!)/,Jt="(\\s*(\\d+(,\\d{3,})*(\\.\\d*)?)|(\\.\\d+))(e(\\+|-)?\\d+)?(\\s*%)?",ei="(\\s*-)?",ti="(\\s*[\\$€])?",ii="^(("+[ei+ti+Jt,ei+Jt+ti,ti+ei+Jt].join(")|(")+"))$",oi=new RegExp(ii,"i");function ni(e){return!!e&&oi.test(e.trim())}const si=/[,\$€]+/g;function ri(e){e=e.replace(si,"");let t=Number(e);return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}function ai(e,t,i){const o=[...e].sort(((e,t)=>e-t));let n=(o.length+(i?-1:1))*t;if(i||n--,Number.isInteger(n))return o[n];const s=Math.ceil(n),r=Math.floor(n);return o[s]*(n-r)+o[r]*(s-n)}const li=20,ci=11,hi=/(\d+?)(?=(\d{3})+(?!\d)|$)/g,di=/0/g,ui={0:s("January"),1:s("February"),2:s("March"),3:s("April"),4:s("May"),5:s("June"),6:s("July"),7:s("August"),8:s("September"),9:s("October"),10:s("November"),11:s("December")},gi={0:s("Sunday"),1:s("Monday"),2:s("Tuesday"),3:s("Wednesday"),4:s("Thursday"),5:s("Friday"),6:s("Saturday")},pi={};function mi(e){let t=pi[e];return void 0===t&&(t=function(e){if(""===e)throw new Error("A format cannot be empty");let t=0,i=[];for(;t<e.length;){let o;if("["===e.charAt(t)){if("$"!==e.charAt(t+1))throw new Error(`Currency formats have to be prefixed by a $: ${e}`);if(o=e.substring(t+1).indexOf("]")+t+2,0===o)throw new Error(`Invalid currency brackets format: ${e}`);const n=e.substring(t+2,o-1);if(n.includes("["))throw new Error(`Invalid currency format: ${e}`);i.push({type:"STRING",format:n})}else{const n=e.substring(t).indexOf("[");o=n>-1?n+t:e.length;const s=e.substring(t,o);s.match(X)?i.push({type:"DATE",format:s}):i.push({type:"NUMBER",format:_i(s)})}t=o}return i}(e),pi[e]=t),t}function fi(e,t){switch(typeof e){case"string":return e;case"boolean":return e?"TRUE":"FALSE";case"number":t||(t=Ri(e));return function(e,t){if("DATE"===t[0].type)return yi(e,t[0].format);let i=e<0?"-":"";for(let o of t)switch(o.type){case"NUMBER":i+=vi(Math.abs(e),o.format);break;case"STRING":i+=o.format}return i}(e,mi(t));case"object":return"0"}}function vi(e,t){t.isPercent&&(e*=100),e/=t.magnitude;let i=0;void 0!==t.decimalPart&&(i=t.decimalPart.length);const{integerDigits:o,decimalDigits:n}=Ci(e,i);let s=function(e,t,i){var o;const n="0"===e?"":e;let s=n;const r=t.length-n.length;if(r>0){const e=(t.substring(0,r).match(di)||[]).length;s="0".repeat(e)+s}i&&(s=(null===(o=s.match(hi))||void 0===o?void 0:o.join(","))||s);return s}(o,t.integerPart,t.thousandsSeparator);return void 0!==t.decimalPart&&(s+="."+function(e,t){let i=e;if(t.length-e.length>0){const o=(t.substring(e.length,t.length+1).match(di)||[]).length;i+="0".repeat(o)}return i}(n||"",t.decimalPart)),t.isPercent&&(s+="%"),s}const bi=[];function Ci(e,t=li){const i=e.toString();if(i.includes("e"))return function(e,t=li){let i=bi[t];i||(i=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),bi[t]=i);const[o,n]=i.format(e).split(".");return{integerDigits:o,decimalDigits:n}}(e,t);if(Number.isInteger(e))return{integerDigits:i,decimalDigits:void 0};const o=i.indexOf(".");let n=i.substring(0,o),s=i.substring(o+1);if(0===t)return Number(s[0])>=5&&(n=(Number(n)+1).toString()),{integerDigits:n,decimalDigits:void 0};if(s.length>t){const{integerDigits:e,decimalDigits:i}=function(e,t){var i;let o="0",n=e,s=e.slice(0,t);const r=t;if(Number(e[r])<5)return{integerDigits:o,decimalDigits:s};const a=(null===(i=s.match(Ei))||void 0===i?void 0:i[0])||"",l=(Number(s)+1).toString(),c=s.slice(a.length),h=l.length>c.length;h&&!a?(o="1",n=void 0):n=h?a.slice(0,-1)+l:a+l;return{integerDigits:o,decimalDigits:n}}(s,t);s=i,"0"!==e&&(n=(Number(n)+Number(e)).toString())}return{integerDigits:n,decimalDigits:Si(s||"")}}function Si(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const Ei=/^0+/;function wi(e){try{return yi(1,e),!0}catch(e){return!1}}function yi(e,t){const i=xe(e),o=t.indexOf("h");let n="",s="";return o>0?(n=xi(i,t.substring(0,o-1)),s=Ii(i,t.substring(o))):0===o?s=Ii(i,t):o<0&&(n=xi(i,t)),n+(n&&s?" ":"")+s}function xi(e,t){var i;const o=null===(i=t.match(/\/|-|\s/))||void 0===i?void 0:i[0];return(o?t.split(o):[t]).map((i=>{switch(i){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return gi[e.getDay()].slice(0,3);case"dddd":return gi[e.getDay()];case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return ui[e.getMonth()].slice(0,3);case"mmmm":return ui[e.getMonth()];case"mmmmm":return ui[e.getMonth()].slice(0,1);case"yy":const i=String(e.getFullYear()).replace("-","").padStart(2,"0");return i.slice(i.length-2);case"yyyy":return e.getFullYear();default:throw new Error(`invalid format: ${t}`)}})).join(o)}function Ii(e,t){let i=t.split(/:|\s/);const o=e.getHours(),n="a"===i[i.length-1];let s=o,r="";return n&&(s=0===s?12:s>12?s-12:s,r=o>=12?" PM":" AM",i.pop()),i.map((i=>{switch(i){case"hhhh":return Math.floor((e.getTime()-ge.getTime())/36e5).toString();case"hh":return s.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}function Ri(e){let{integerDigits:t,decimalDigits:i}=Ci(e);if(!i)return"0";const o=t.replace("-","").length;if(o+2>ci)return"0";const n=ci-o-1;return({decimalDigits:i}=Ci(e,Math.min(n,i.length))),i?"0."+"0".repeat(i.length):"0"}function Ti(e){if(qe(e)){return we(e).format}if(!ni(e))return;const t=e.includes(".")?"0.00":"0",i=e.match(/[\$€]/);if(i){const o=e.match(/[\d]/),n="[$"+i.values().next().value+"]";return o.index<i.index?"#,##"+t+n:n+"#,##"+t}return e.includes("%")?t+"%":void 0}function Ai(e,t,i){return Di(mi(e||"#,##0").map((e=>"NUMBER"===e.type?[{...e,format:{...e.format,magnitude:t,decimalPart:void 0}},{type:"STRING",format:i}]:e)).flat())}function Mi(e,t){const i=mi(e).map((e=>"NUMBER"===e.type?{...e,format:Oi(e.format,t)}:e)),o=Di(i);return pi[o]=i,o}function Oi(e,t){var i;const o={...e},n=Math.sign(t),s=(null===(i=o.decimalPart)||void 0===i?void 0:i.length)||0,r=Math.min(Math.max(0,s+n),li);return o.decimalPart="0".repeat(r),""===o.decimalPart&&delete o.decimalPart,o}const Ni=/,*?$/;function _i(e){var t;if(function(e){return Boolean(e.replace(Fi,""))}(e=e.trim()))throw new Error(`Invalid number format: ${e}`);const i=e.includes("%"),o=(null===(t=e.match(Ni))||void 0===t?void 0:t[0])||"",n=o?1e3**o.length:1;let s=e.slice(0,e.length-(o.length||0));const r=s.includes(",");if(s.match(/\..*,/))throw new Error("A format can't contain ',' symbol in the decimal part");s=s.replace("%","").replace(",","");const a=s.match(/[\%|,]/);if(a)throw new Error(`A format can only contain a single '${a[0]}' symbol`);const[l,c]=s.split(".");if(c&&c.length>20)throw new Error("A format can't contain more than 20 decimal places");return void 0!==c?{integerPart:l,isPercent:i,thousandsSeparator:r,decimalPart:c,magnitude:n}:{integerPart:l,isPercent:i,thousandsSeparator:r,magnitude:n}}const Fi=/[,#0.%]/g;function Di(e){let t="";for(let i of e){let e;switch(i.type){case"NUMBER":const t=i.format;e=t.integerPart,t.thousandsSeparator&&(e=e.slice(0,-3)+","+e.slice(-3)),void 0!==t.decimalPart&&(e+="."+t.decimalPart),t.isPercent&&(e+="%"),t.magnitude&&(e+=",".repeat(Math.log10(t.magnitude)/3));break;case"STRING":e=`[$${i.format}]`;break;case"DATE":e=i.format}t+=e}return t}class ki{constructor(e,t){this.getSheetSize=t,this.prefixSheet=!1,this._zone=e.zone,this.parts=e.parts,this.prefixSheet=e.prefixSheet,this.invalidXc=e.invalidXc,this.sheetId=e.sheetId,this.invalidSheetName=e.invalidSheetName}static fromRange(e,t){return e instanceof ki?e:new ki(e,t.getSheetSize)}get unboundedZone(){return this._zone}get zone(){const{left:e,top:t,bottom:i,right:o}=this._zone;if(void 0!==o&&void 0!==i)return this._zone;if(void 0===i&&void 0!==o)return{right:o,top:t,left:e,bottom:this.getSheetSize(this.sheetId).numberOfRows-1};if(void 0===o&&void 0!==i)return{bottom:i,left:e,top:t,right:this.getSheetSize(this.sheetId).numberOfCols-1};throw new Error(s("Bad zone format"))}static getRangeParts(e,t){const i=e.split(":").map((e=>{const t=Vt(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}})),o=void 0===t.bottom,n=void 0===t.right;return o&&(i[0].rowFixed=i[0].rowFixed||i[1].rowFixed,i[1].rowFixed=i[0].rowFixed||i[1].rowFixed),n&&(i[0].colFixed=i[0].colFixed||i[1].colFixed,i[1].colFixed=i[0].colFixed||i[1].colFixed),i}get isFullCol(){return void 0===this._zone.bottom}get isFullRow(){return void 0===this._zone.right}get rangeData(){return{_zone:this._zone,_sheetId:this.sheetId}}orderZone(){var e,t,i,o,n,s,r,a;const l={...this._zone};let c=this.parts;if(void 0!==l.right&&l.right<l.left){let n=l.right;l.right=l.left,l.left=n,c=[{colFixed:(null===(e=c[1])||void 0===e?void 0:e.colFixed)||!1,rowFixed:(null===(t=c[0])||void 0===t?void 0:t.rowFixed)||!1},{colFixed:(null===(i=c[0])||void 0===i?void 0:i.colFixed)||!1,rowFixed:(null===(o=c[1])||void 0===o?void 0:o.rowFixed)||!1}]}if(void 0!==l.bottom&&l.bottom<l.top){let e=l.bottom;l.bottom=l.top,l.top=e,c=[{colFixed:(null===(n=c[0])||void 0===n?void 0:n.colFixed)||!1,rowFixed:(null===(s=c[1])||void 0===s?void 0:s.rowFixed)||!1},{colFixed:(null===(r=c[1])||void 0===r?void 0:r.colFixed)||!1,rowFixed:(null===(a=c[0])||void 0===a?void 0:a.rowFixed)||!1}]}return this.clone({zone:l,parts:c})}clone(e){return new ki({zone:(null==e?void 0:e.zone)?e.zone:{...this._zone},sheetId:(null==e?void 0:e.sheetId)?e.sheetId:this.sheetId,invalidSheetName:e&&"invalidSheetName"in e?e.invalidSheetName:this.invalidSheetName,invalidXc:e&&"invalidXc"in e?e.invalidXc:this.invalidXc,parts:(null==e?void 0:e.parts)?e.parts:this.parts.map((e=>({rowFixed:e.rowFixed,colFixed:e.colFixed}))),prefixSheet:(null==e?void 0:e.prefixSheet)?e.prefixSheet:this.prefixSheet},this.getSheetSize)}}function Li(e,t,i){const o=i.sheetId===e?t:i.sheetId;return i.clone({sheetId:o})}function Pi(e,t,i){return i?e.getRangeFromSheetXC(t,i):void 0}function Ui(e,t,i){const o=[];return t.forEach((t=>{const n=function(e,t){e=e.toLocaleLowerCase();let i=0,o=0,n=(t=t.toLocaleLowerCase()).length,s=0;for(let r=0;r<n;r++)t[r]===e[s]?(s++,o+=100+o-r/200):o=0,i+=o;return s===e.length?i:0}(e,i(t));n>0&&o.push({score:n,elem:t})})),o.sort(((e,t)=>t.score-e.score)),o.map((e=>e.elem))}function Vi(e){const t=[];for(let i=0;i<e;i++){const e={cells:{}};t.push(e)}return t}class zi{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 Bi(e){const t=function(e){const t=(e=e.split("!").pop()).replace(/\$/g,"").split(":").map((e=>e.trim()));let i,o,n,s,r=!1,a=!1,l=!1;const c=t[0],h=t[1]&&t[1];if(Ut(c))n=s=Gt(c),i=o=0,r=!0;else if(Vt(c))i=o=parseInt(c,10)-1,n=s=0,a=!0;else{const e=qt(c);n=s=e.col,i=o=e.row,l=!0}if(2===t.length)if(Ut(h))s=Gt(h),r=!0;else if(Vt(h))o=parseInt(h,10)-1,a=!0;else{const e=qt(h);s=e.col,o=e.row,i=r?o:i,n=a?s:n,l=!0}if(r&&a)throw new Error("Wrong zone xc. The zone cannot be at the same time a full column and a full row");const d={top:i,left:n,bottom:r?void 0:o,right:a?void 0:s};return l=l&&(a||r),l&&(d.hasHeader=l),d}(e);if(void 0!==t.right&&t.right<t.left){const e=t.left;t.left=t.right,t.right=e}if(void 0!==t.bottom&&t.bottom<t.top){const e=t.top;t.top=t.bottom,t.bottom=e}return t}function Hi(e){const t=Bi(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function $i(e){const{bottom:t,top:i,left:o,right:n}=e;return!(void 0!==t&&isNaN(t)||isNaN(i)||isNaN(o)||void 0!==n&&isNaN(n))&&((void 0===e.bottom||e.bottom>=e.top&&e.bottom>=0)&&(void 0===e.right||e.right>=e.left&&e.right>=0)&&e.top>=0&&e.left>=0)}function Wi(e){const{top:t,bottom:i,left:o,right:n}=e,r="hasHeader"in e&&e.hasHeader,a=t===i&&o===n;if(void 0===i&&void 0!==n)return 0!==t||r?`${Zt(o,t)}:${Wt(n)}`:`${Wt(o)}:${Wt(n)}`;if(void 0===n&&void 0!==i)return 0!==o||r?`${Zt(o,t)}:${i+1}`:`${t+1}:${i+1}`;if(void 0!==i&&void 0!==n)return a?Zt(o,t):`${Zt(o,t)}:${Zt(n,i)}`;throw new Error(s("Bad zone format"))}function Gi(e,t,i,o,n){const s="left"===t?"columns":"rows",r="before"===o?i-1:i,a=e["left"===t?"right":"bottom"];return e[t]<=r&&a&&a>r?ro(e,s,"RESIZE",n):r<e[t]?ro(e,s,"MOVE",n):{...e}}function qi(e,t,i,o,n){const s="left"===t?"columns":"rows",r="before"===o?i-1:i,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?ro(e,s,"RESIZE",n):r<e[t]?ro(e,s,"MOVE",n):{...e}}function Zi(e,t,i){const o="left"===t?"right":"bottom";let n=e[t],s=e[o];for(let r of i.sort(((e,t)=>t-e)))e[t]>r&&(n--,s--),e[t]<r&&e[o]>=r&&s--;return{...e,[t]:n,[o]:s}}function ji(e,t,i){const o="left"===t?"right":"bottom";let n=e[t],s=e[o];const r=e[o];for(let o of i.sort(((e,t)=>t-e)))e[t]>o&&(n--,void 0!==s&&s--),void 0!==r&&void 0!==s&&e[t]<=o&&r>=o&&s--;if(!(void 0!==s&&n>s))return{...e,[t]:n,[o]:s}}function Yi(...e){return{top:Math.min(...e.map((e=>e.top))),left:Math.min(...e.map((e=>e.left))),bottom:Math.max(...e.map((e=>e.bottom))),right:Math.max(...e.map((e=>e.right)))}}function Xi(e,t){if(Qi(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:Math.min(e.bottom,t.bottom),right:Math.min(e.right,t.right)}}function Ki(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function Qi(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function Ji(e,t,i){const{left:o,right:n,top:s,bottom:r}=i;return e>=o&&e<=n&&t>=s&&t<=r}function eo(e,t){return Ki(Yi(t,e),t)}function to(e,t){const i=e.map(Bi),o=t.map(Hi),n=Math.max(...i.concat(o).map((e=>e.bottom||0))),s=Math.max(...i.concat(o).map((e=>e.right||0))),r=i.map((e=>({...e,bottom:void 0===e.bottom?n+1:e.bottom,right:void 0===e.right?s+1:e.right}))),a=o.map((e=>({...e,bottom:void 0===e.bottom?n+1:e.bottom,right:void 0===e.right?s+1:e.right}))),l=function(e,t){const i=new Set(t.map((({col:e,row:t})=>`${e}-${t}`)));return e.filter((({col:e,row:t})=>!i.has(`${e}-${t}`)))}(r.map(so).flat(),a.map(so).flat()),c=function(e){if(0===e.length)return[];const[t,...i]=[...e].sort(((e,t)=>e.row-t.row)).sort(((e,t)=>e.col-t.col)),o=[];let n=co(t);for(const{col:e,row:t}of i)if(!Ji(e,t,n))if(e===n.left&&t===n.bottom+1){const e=n.bottom+1;n={...n,bottom:e}}else o.push(n),n=co({col:e,row:t});return[...o,n]}(l);return function(e){if(0===e.length)return[];if(e.some((e=>e.left!==e.right)))throw new Error("only columns can be merged");const t=[],i=io(e),o=(e,t)=>e.top===t.top&&e.bottom===t.bottom&&e.right+1===t.left;for(;i.length;){const e=i.reduce(((e,t)=>o(e,t)?Yi(e,t):e),i.shift());t.push(e)}return io(t)}(c).map((e=>({...e,bottom:e.bottom===n+1?void 0:e.bottom,right:e.right===s+1?void 0:e.right}))).map(Wi)}function io(e){const t=[...e].sort(((e,t)=>t.right-e.right)).sort(((e,t)=>t.bottom-e.bottom)).sort(((e,t)=>e.top-t.top)).sort(((e,t)=>e.left-t.left)).reverse(),i=[];for(;0!==t.length;){const e=t.shift();t.some((t=>eo(e,t)))||i.push(e)}return i.reverse()}function oo(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function no(e){const{numberOfCols:t,numberOfRows:i}=oo(e);return 1===t||1===i}function so(e){const t=[],[i,o]=[e.right,e.left].sort(((e,t)=>e-t)),[n,s]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of $e(i,o+1))for(const i of $e(n,s+1))t.push({col:e,row:i});return t}function ro(e,t,i,o){const n="both"===t?o[0]:"columns"===t?o:0,s="both"===t?o[1]:"rows"===t?o:0,r="hasHeader"in e&&e.hasHeader;let a;a=!function(e){return void 0===e.bottom}(e)||r?!(ho(e)&&!r)||"columns"!==t:"rows"!==t;const l={...e};return a&&"MOVE"===i&&(l.left+=n,l.top+=s),void 0!==l.right&&(l.right+=n),void 0!==l.bottom&&(l.bottom+=s),l}function ao(e,t){let i,o;const{left:n,right:s,top:r,bottom:a}=e,{left:l,right:c,top:h,bottom:d}=t;return i=l!=n?l:c!=s?c:l,o=h!=r?h:d!=a?d:h,{col:i,row:o}}function lo(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 co(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function ho(e){return void 0===e.right}function uo(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function go(...e){return e.length<2||1===to(e.map(Wi),[]).length}class po extends t.Component{constructor(){super(...arguments),this.canvas=t.useRef("graphContainer")}get background(){return this.chartRuntime.background}get canvasStyle(){return`background-color: ${this.background}`}get chartRuntime(){const e=this.env.model.getters.getChartRuntime(this.props.figure.id);if(!("chartJsConfig"in e))throw new Error("Unsupported chart runtime");return e}setup(){t.onMounted((()=>{const e=this.chartRuntime;this.createChart(e.chartJsConfig)}));let e=this.chartRuntime;t.onPatched((()=>{const t=this.chartRuntime;ht(e,t)||(this.updateChartJs(t),e=t)}))}createChart(e){const t=this.canvas.el.getContext("2d");this.chart=new window.Chart(t,e)}updateChartJs(e){var t,i,o,n,s;const r=e.chartJsConfig;r.data&&r.data.datasets?(this.chart.data=r.data,(null===(t=r.options)||void 0===t?void 0:t.title)&&(this.chart.config.options.title=r.options.title),r.options&&"valueLabel"in r.options&&(null===(i=r.options)||void 0===i?void 0:i.valueLabel)&&(this.chart.config.options.valueLabel=r.options.valueLabel)):this.chart.data.datasets=void 0,this.chart.config.options.tooltips=null===(o=r.options)||void 0===o?void 0:o.tooltips,this.chart.config.options.legend=null===(n=r.options)||void 0===n?void 0:n.legend,this.chart.config.options.scales=null===(s=r.options)||void 0===s?void 0:s.scales,this.chart.update({duration:0})}}po.template="o-spreadsheet-ChartJsComponent",po.props={figure:Object};const mo={};let fo=0;function vo(e,...t){const i="__sheet__"+fo++;return function(e,t){const i=document.createElement("style");i.textContent=function(e){const t=e.split(/(\{|\}|;)/).map((e=>e.trim())),i=[],o=[];let n=[];function s(e,t){const o=[];for(const n of i[e]){let r=t&&t+" "+n||n;r.includes("&")&&(r=n.replace(/&/g,t||"")),e<i.length-1&&(r=s(e+1,r)),o.push(r)}return o.join(", ")}function r(){n.length&&(o.push(s(0)+" {"),o.push(...n),o.push("}"),n=[])}for(;t.length;){let e=t.shift();"}"===e?(r(),i.pop()):("{"===t[0]&&(r(),i.push(e.split(/\s*,\s*/)),t.shift()),";"===t[0]&&n.push(" "+e+";"))}return o.join("\n")}(t),mo[e]=i}(i,String.raw(e,...t)),function(e){const t=mo[e];t.setAttribute("component",e),document.head.appendChild(t)}(i),i}function bo({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function Co(e){const t=So(e);return e?(e.fillColor&&(t.background=e.fillColor),t):t}function So(e){const t={};if(!e)return t;if(e.bold&&(t["font-weight"]="bold"),e.italic&&(t["font-style"]="italic"),e.strikethrough||e.underline){let i=e.strikethrough?"line-through":"";i=e.underline?i+" underline":i,t["text-decoration"]=i}return e.textColor&&(t.color=e.textColor),t}function Eo(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>`${e}:${t};`)).join(" ")}const wo=1.2;vo`
1
+ !function(e,t){"use strict";let i=e=>e;function o(e,...t){if(1===t.length&&"object"==typeof t[0]){const i=t[0];e=e.replace(/\%\(?([^\)]+)\)s/g,((e,t)=>i[t]))}else t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));return e}const n=function(e,...t){return o(i(e),...t)},s=function(e,...t){return new r(e,t)};class r extends String{constructor(e,t){super(e),this.values=t}valueOf(){const e=super.valueOf();return o(i(e),...this.values)}toString(){return this.valueOf()}}var a,l;!function(e){e.NotAvailable="#N/A",e.InvalidReference="#REF",e.BadExpression="#BAD_EXPR",e.CircularDependency="#CYCLE",e.UnknownFunction="#NAME?",e.GenericError="#ERROR"}(a||(a={})),function(e){e[e.silent=0]="silent",e[e.error=1]="error"}(l||(l={}));class c extends Error{constructor(e,t,i=l.error){super(t),this.errorType=e,this.logLevel=i}}class h extends c{constructor(e){super(a.BadExpression,e)}}class d extends c{constructor(){super(a.CircularDependency,s("Circular reference"))}}class u extends c{constructor(){super(a.InvalidReference,s("Invalid reference"))}}class g extends c{constructor(e){super(a.NotAvailable,e||s("Data not available"),e?l.error:l.silent)}}class p extends c{constructor(e){super(a.UnknownFunction,s('Unknown function: "%s"',e))}}const m=.5,f="#f5f5f5",v="#F8F9FA",b="#E8EAED",C="#595959",S="#666666",E="#3266ca",w="#FFFFFF",y="#CACACA",x=11982760,I="#01666b",R="#188038",T="#E6F4EA",A="#CEEAD6",M="#E0E2E4",O=["#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"],N=26,_=48,F=96,D=23,k=15,L=18,P=14,U=4,V=4,z=3,B=V,H=17,$=250,W=1,G="400",q=10,Z="'Roboto', arial",j=["thin","#000"],Y=["thin",R],X=/[ymdhs:]/,K=a.InvalidReference,Q="START_REVISION",J=20,ee="??",te="difference",ie="#00A04A",oe="#DC6965",ne=.4,se=["'","*","?","/","\\","[","]"],re=/'|\*|\?|\/|\\|\[|\]/,ae="|",le=s("Invalid expression");var ce;!function(e){e[e.Grid=0]="Grid",e[e.Highlight=5]="Highlight",e[e.Figure=10]="Figure",e[e.ScrollBar=15]="ScrollBar",e[e.GridPopover=19]="GridPopover",e[e.GridComposer=20]="GridComposer",e[e.Dropdown=21]="Dropdown",e[e.IconPicker=25]="IconPicker",e[e.TopBarComposer=30]="TopBarComposer",e[e.Popover=35]="Popover",e[e.ChartAnchor=1e3]="ChartAnchor"}(ce||(ce={}));const he="\n",de=[6,7,8,9,10,11,12,14,18,24,36];class ue{constructor(e,t,i,o=0,n=0,s=0){this.jsDate=new Date(Date.UTC(e,t,i,o,n,s,0))}static fromTimestamp(e){const t=new Date(e);return new ue(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())}static now(){const e=new Date;return new ue(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds())}toString(){return this.jsDate.toString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}getDate(){return this.jsDate.getUTCDate()}getDay(){return this.jsDate.getUTCDay()}getHours(){return this.jsDate.getUTCHours()}getMinutes(){return this.jsDate.getUTCMinutes()}getSeconds(){return this.jsDate.getUTCSeconds()}setFullYear(e){this.jsDate.setFullYear(e)}setDate(e){this.jsDate.setUTCDate(e)}setHours(e){this.jsDate.setUTCHours(e)}setMinutes(e){this.jsDate.setUTCMinutes(e)}setSeconds(e){this.jsDate.setUTCSeconds(e)}}const ge=new ue(1899,11,30),pe=864e5,me=2e3,fe=ue.now().getFullYear(),ve=ue.fromTimestamp(0).getTime()-ge.getTime(),be=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,Ce=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,Se=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/,Ee={};function we(e){if(e in Ee)return Ee[e];const t=function(e){let t;e=e.trim();const i=e.match(Se);if(i){if(t=function(e){if(e=e.trim(),Se.test(e)){const t=/AM/i.test(e),i=/PM/i.test(e),o=(t||i?e.substring(0,e.length-2).trim():e).split(/:/),n=o.length>=2,s=3===o.length;let r=Number(o[0]),a=n?Number(o[1]):0,l=s?Number(o[2]):0,c=s?"hh:mm:ss":"hh:mm";if(t||i)c+=" a";else if(!n)return null;r>=12&&t?r-=12:r<12&&i&&(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 ue(1899,11,30,r,a,l)}}return null}(i[0]),null===t)return null;e=e.replace(i[0],"").trim()}let o;const n=e.match(be),s=e.match(Ce);if(n||s){let t;if(n?(t=n[0],o=ye(t,"mdy")):(t=s[0],o=ye(t,"ymd")),null===o)return null;e=e.replace(t,"").trim()}if(""!==e||!o&&!t)return null;if(o&&t)return{value:o.value+t.value,format:o.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new ue(o.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,o.jsDate.getMonth()+t.jsDate.getMonth()-11,o.jsDate.getDate()+t.jsDate.getDate()-30,o.jsDate.getHours()+t.jsDate.getHours(),o.jsDate.getMinutes()+t.jsDate.getMinutes(),o.jsDate.getSeconds()+t.jsDate.getSeconds())};return o||t}(e);return Ee[e]=t,t}function ye(e,t){const i="mdy"===t;if(i||"ymd"===t){const t=e.split(/\/|-|\s/),o=i?0:1,n=i?1:2,s=i?2:0,r=Number(t[o]),a=Number(t[n]),l=2===t[o].length&&r<10||2===t[n].length&&a<10,c=t[s]?function(e){const t=Number(e);switch(e.length){case 1:return me+t;case 2:return me+(me+t>fe+10?-100:0)+t;case 3:case 4:return t}return 0}(t[s]):fe,h=new ue(c,r-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==r-1||h.getDate()!==a)return null;const u=h.getTime()-ge.getTime();let g=l?`mm${d}dd`:`m${d}d`;return t[s]&&(g=i?g+d+"yyyy":"yyyy"+d+g),{value:Math.round(u/pe),format:g,jsDate:h}}return null}function xe(e){const t=Math.trunc(e);let i=ue.fromTimestamp(t*pe-ve),o=e-t;o=o<0?1+o:o;const n=Math.round(24*o),s=Math.round(24*(o-n/24)*60),r=Math.round(24*(o-n/24-s/24/60)*60*60);return i.setHours(n),i.setMinutes(s),i.setSeconds(r),i}function Ie(e){const t=e.getTime()-ge.getTime();return Math.round(t/pe)}function Re(e){return new ue(e.getFullYear(),e.getMonth()+1,0).getDate()}function Te(e){return Re(e)===e.getDate()}function Ae(e,t,i){const o=e.getFullYear(),n=e.getMonth(),s=e.getDate(),r=new ue(o,n+t,1);return i&&s===Re(e)||s>Re(r)?r.setDate(Re(r)):r.setDate(s),r}function Me(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function Oe(e,t,i){if(e===t)return 0;if(e>t){const i=t;t=e,e=i}const o=xe(e),n=xe(t);let s=o.getDate(),r=n.getDate();const a=o.getMonth(),l=n.getMonth(),c=o.getFullYear(),h=n.getFullYear();let d=0,u=0;switch(i){case 0:31===s&&(s=30),30===s&&31===r&&(r=30),1===a&&s===(Me(c)?29:28)&&(s=30,1===l&&r===(Me(h)?29:28)&&(r=30)),d=c+(30*a+s)/360,u=h+(30*l+r)/360;break;case 1:let i=365;const o=c===h;if(!o&&!(c+1===h)||!o&&a<l||!o&&a===l&&s<r){let e=0,t=0;for(let i=c;i<=h;i++)e++,t+=Me(i)?366:365;i=t/e}else o?Me(c)&&(i=366):(Me(c)&&a<2&&(i=366),Me(h)&&(l>1||1===l&&29===r)&&(i=366));d=e/i,u=t/i;break;case 2:d=e/360,u=t/360;break;case 3:d=e/365,u=t/365;break;case 4:31===s&&(s=30),31===r&&(r=30),d=c+(30*a+s)/360,u=h+(30*l+r)/360}return u-d}function Ne(e){return'"'===e[0]&&(e=e.slice(1)),'"'===e[e.length-1]&&"\\"!==e[e.length-2]?e.slice(0,e.length-1):e}function _e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Fe(e){const t=Array.isArray(e)?[]:{};switch(typeof e){case"object":if(null===e)return e;if(function(e){return"clone"in e&&e.clone instanceof Function}(e))return e.clone();if(!(function(e){return"object"==typeof e&&(null==e?void 0:e.constructor)===Object}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");for(const i in e)t[i]=Fe(e[i]);return t;case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function De(e){return e.startsWith("'")&&(e=e.slice(1,-1).replace(/''/g,"'")),e}function ke(e){var t;return(null===(t=e.match(/\w/g))||void 0===t?void 0:t.length)!==e.length&&(e=`'${e}'`),e}function Le(e,t,i){return e<t?t:e>i?i:e}function Pe(e,t=1){return t*(e+V)-V}function Ue(e,t,i){const o=Be(i);if(Ve[o]||(Ve[o]={}),void 0===Ve[o][t]){e.save(),e.font=o;const i=e.measureText(t).width;e.restore(),Ve[o][t]=i}return Ve[o][t]}const Ve={};function ze(e){return Math.round(96*e/72)}function Be(e){return`${e.italic?"italic ":""}${e.bold?"bold":G} ${He(e)}px ${Z}`}function He(e){return ze((null==e?void 0:e.fontSize)||q)}function $e(e,t,i=1){if(t<=e&&i>0)return[];if(0===i)throw new Error("range() step must not be zero");const o=Math.ceil(Math.abs((t-e)/i)),n=Array(o);for(let t=0;t<o;t++)n[t]=e+t*i;return n}function We(e){return e.reduce(((e,t,i,o)=>{if(1===Math.abs(t-o[i-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*Ge(e,t){t.next();for(const i of e){const e=t.next();yield{...i,next:e.done?void 0:e.value}}}function qe(e){return null!==we(e)}const Ze=/^\[(.+)\]\((.+)\)$/,je=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function Ye(e){return Ze.test(e)}function Xe(e){return je.test(e)}function Ke(e,t){return`[${e}](${t})`}function Qe(e){const t=e.match(Ze)||[],i=t[1],o=t[2];if(!i||!o)throw new Error(`Could not parse markdown link ${e}.`);return{label:i,url:o}}const Je="o-spreadsheet://";function et(e){return e.startsWith(Je)}function tt(e){return`${Je}${e}`}function it(e){if(e.startsWith(Je))return e.substr(Je.length);throw new Error(`${e} is not a valid sheet link`)}function ot(e){return void 0!==e}function nt(e){return void 0===e||Object.values(e).every((e=>"object"==typeof e?nt(e):!e))}function st(e,t){for(let[i,o]of Object.entries(t))if(ht(o,e))return parseInt(i,10);const i=Object.keys(t),o=0===i.length?0:Math.max(...i.map((e=>parseInt(e,10))));return t[o+1]=e,o+1}function rt(e){let t="";for(let i=0,o=e.length;i<o;i++)t+=e[i];return t}function at(e){let t,i=!1;const o=()=>(i||(t=e instanceof Function?e():e,i=!0),t);return o.map=e=>at((()=>e(o()))),o}function lt(e,t){let i=e.slice(t).find((e=>e));return i||(i=e.slice(0,t).reverse().find((e=>e))),i||""}function ct(e,t){return"after"===e?t+1:t}function ht(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;if(typeof e!=typeof t)return!1;if("object"!=typeof e)return e===t;const i=new Set;Object.keys(e).forEach((e=>i.add(e))),Object.keys(t).forEach((e=>i.add(e)));for(let o of i){if(typeof e[o]!=typeof e[o])return!1;if("object"==typeof e[o]){if(!ht(e[o],t[o]))return!1}else if(e[o]!==t[o])return!1}return!0}function dt(e,t){return t.every((t=>e.includes(t)))}function ut(e){const t={...e};return Object.keys(t).forEach((e=>!t[e]&&delete t[e])),t}function gt(e){return e?e.toLowerCase():""}const pt=[" ","\t","\f","\v",String.fromCharCode(parseInt("00a0",16)),String.fromCharCode(parseInt("1680",16)),String.fromCharCode(parseInt("2000",16)),String.fromCharCode(parseInt("200a",16)),String.fromCharCode(parseInt("2028",16)),String.fromCharCode(parseInt("2029",16)),String.fromCharCode(parseInt("202f",16)),String.fromCharCode(parseInt("205f",16)),String.fromCharCode(parseInt("3000",16)),String.fromCharCode(parseInt("feff",16))],mt=new RegExp(pt.join("|"),"g"),ft=/\r\n|\r|\n/g;function vt(e){return e?e=(e=e.replace(mt," ")).replace(ft,he):""}const bt=/rgba?\(|\s+|\)/gi,Ct=/^#([A-F\d]{2}){3,4}$/g,St=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function Et(e){return wt(e.toString(16).padStart(6,"0"))}function wt(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(bt,"").split(",");let i=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");i=Math.round(255*(e||1))}const o=t.map((e=>parseInt(e,10)));255!==i&&o.push(i);return"#"+rt(o.map((e=>e.toString(16).padStart(2,"0")))).toUpperCase()}(e):(t=e.replace("#","").toUpperCase(),3!==t.length&&4!==t.length||(t=t.split("").reduce(((e,t)=>e+t+t),"")),t=`#${t}`),!t.match(Ct))throw new Error(`invalid color input: ${e}`);return t}function yt(e){try{return wt(e),!0}catch(e){return!1}}const xt=e=>e>=0&&e<=255;function It(e,t,i,o=1){if(!xt(e)||!xt(t)||!xt(i)||o<0||o>1)throw new Error(`Invalid RGBA values ${[e,t,i,o]}`);return{a:o,b:i,g:t,r:e}}function Rt(e){let{r:t,g:i,b:o}=At(e);t/=255,i/=255,o/=255;const n=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*n(t)+.7152*n(i)+.0722*n(o)}function Tt(e){let t=e.r.toString(16),i=e.g.toString(16),o=e.b.toString(16),n=Math.round(255*e.a).toString(16);return 1==t.length&&(t="0"+t),1==i.length&&(i="0"+i),1==o.length&&(o="0"+o),1==n.length&&(n="0"+n),"ff"===n&&(n=""),("#"+t+i+o+n).toUpperCase()}function At(e){let t,i,o,n;if(7===(e=wt(e)).length)t=parseInt(e[1]+e[2],16),i=parseInt(e[3]+e[4],16),o=parseInt(e[5]+e[6],16),n=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),i=parseInt(e[3]+e[4],16),o=parseInt(e[5]+e[6],16),n=parseInt(e[7]+e[8],16)}return n=+(n/255).toFixed(3),{a:n,r:t,g:i,b:o}}function Mt(e){(e={...e}).s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,i=t*(1-Math.abs(e.h/60%2-1)),o=e.l-t/2,n=0,s=0,r=0;return 0<=e.h&&e.h<60?(n=t,s=i,r=0):60<=e.h&&e.h<120?(n=i,s=t,r=0):120<=e.h&&e.h<180?(n=0,s=t,r=i):180<=e.h&&e.h<240?(n=0,s=i,r=t):240<=e.h&&e.h<300?(n=i,s=0,r=t):300<=e.h&&e.h<360&&(n=t,s=0,r=i),n=Math.round(255*(n+o)),s=Math.round(255*(s+o)),r=Math.round(255*(r+o)),{a:e.a,r:n,g:s,b:r}}function Ot(e){const t=e.r/255,i=e.g/255,o=e.b/255;let n=Math.min(t,i,o),s=Math.max(t,i,o),r=s-n,a=0,l=0,c=0;return a=0==r?0:s==t?(i-o)/r%6:s==i?(o-t)/r+2:(t-i)/r+4,a=Math.round(60*a),a<0&&(a+=360),c=(s+n)/2,l=0==r?0:r/(1-Math.abs(2*c-1)),l=+(100*l).toFixed(1),c=+(100*c).toFixed(1),{a:e.a,h:a,s:l,l:c}}const Nt=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),_t=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),Ft=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),Dt=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),kt=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),Lt=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),Pt=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[Nt.source,/(\$?[A-Z]{1,3})?\$?[0-9]{1,7}\s*:\s*(\$?[A-Z]{1,3})?\$?[0-9]{1,7}\s*/i.source,/\$?[A-Z]{1,3}(\$?[0-9]{1,7})?\s*:\s*\$?[A-Z]{1,3}(\$?[0-9]{1,7})?\s*/i.source].join("|")+")"+/$/.source,"i");function Ut(e){return kt.test(e)}function Vt(e){return Lt.test(e)}function zt(e){return Ft.test(e)}function Bt(e){return Dt.test(e)}function Ht(e){return _t.test(e)}function $t(e){const t=e.split("!"),i=t.pop();return{sheetName:De(t.join("!"))||void 0,xc:i}}function Wt(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Wt(Math.floor(e/26)-1)+Wt(e%26)}function Gt(e){let t=0;const i=e.length;for(let o=0;o<i;o++){t+=(e.charCodeAt(o)-65+(o<i-1?1:0))*26**(i-o-1)}return t}function qt(e){const t=(e=e.toUpperCase().trim()).match(Nt);if(null!==t){const[i,o,n]=t;if(i===e){return{col:Gt(o),row:parseInt(n,10)-1}}}throw new Error(`Invalid cell description: ${e}`)}function Zt(e,t,i={colFixed:!1,rowFixed:!1}){return(i.colFixed?"$":"")+Wt(e)+(i.rowFixed?"$":"")+String(t+1)}const jt=140,Yt=20,Xt=.035;function Kt(e){return Yt+(jt-Yt)*Math.exp(-Xt*(e-1))}const Qt=/(^-?\d+(\.?\d*(e\d+)?)?|^-?\.\d+)(?!\w|!)/,Jt="(\\s*(\\d+(,\\d{3,})*(\\.\\d*)?)|(\\.\\d+))(e(\\+|-)?\\d+)?(\\s*%)?",ei="(\\s*-)?",ti="(\\s*[\\$€])?",ii="^(("+[ei+ti+Jt,ei+Jt+ti,ti+ei+Jt].join(")|(")+"))$",oi=new RegExp(ii,"i");function ni(e){return!!e&&oi.test(e.trim())}const si=/[,\$€]+/g;function ri(e){e=e.replace(si,"");let t=Number(e);return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}function ai(e,t,i){const o=[...e].sort(((e,t)=>e-t));let n=(o.length+(i?-1:1))*t;if(i||n--,Number.isInteger(n))return o[n];const s=Math.ceil(n),r=Math.floor(n);return o[s]*(n-r)+o[r]*(s-n)}const li=20,ci=11,hi=/(\d+?)(?=(\d{3})+(?!\d)|$)/g,di=/0/g,ui={0:s("January"),1:s("February"),2:s("March"),3:s("April"),4:s("May"),5:s("June"),6:s("July"),7:s("August"),8:s("September"),9:s("October"),10:s("November"),11:s("December")},gi={0:s("Sunday"),1:s("Monday"),2:s("Tuesday"),3:s("Wednesday"),4:s("Thursday"),5:s("Friday"),6:s("Saturday")},pi={};function mi(e){let t=pi[e];return void 0===t&&(t=function(e){if(""===e)throw new Error("A format cannot be empty");let t=0,i=[];for(;t<e.length;){let o;if("["===e.charAt(t)){if("$"!==e.charAt(t+1))throw new Error(`Currency formats have to be prefixed by a $: ${e}`);if(o=e.substring(t+1).indexOf("]")+t+2,0===o)throw new Error(`Invalid currency brackets format: ${e}`);const n=e.substring(t+2,o-1);if(n.includes("["))throw new Error(`Invalid currency format: ${e}`);i.push({type:"STRING",format:n})}else{const n=e.substring(t).indexOf("[");o=n>-1?n+t:e.length;const s=e.substring(t,o);s.match(X)?i.push({type:"DATE",format:s}):i.push({type:"NUMBER",format:_i(s)})}t=o}return i}(e),pi[e]=t),t}function fi(e,t){switch(typeof e){case"string":return e;case"boolean":return e?"TRUE":"FALSE";case"number":t||(t=Ri(e));return function(e,t){if("DATE"===t[0].type)return yi(e,t[0].format);let i=e<0?"-":"";for(let o of t)switch(o.type){case"NUMBER":i+=vi(Math.abs(e),o.format);break;case"STRING":i+=o.format}return i}(e,mi(t));case"object":return"0"}}function vi(e,t){t.isPercent&&(e*=100),e/=t.magnitude;let i=0;void 0!==t.decimalPart&&(i=t.decimalPart.length);const{integerDigits:o,decimalDigits:n}=Ci(e,i);let s=function(e,t,i){var o;const n="0"===e?"":e;let s=n;const r=t.length-n.length;if(r>0){const e=(t.substring(0,r).match(di)||[]).length;s="0".repeat(e)+s}i&&(s=(null===(o=s.match(hi))||void 0===o?void 0:o.join(","))||s);return s}(o,t.integerPart,t.thousandsSeparator);return void 0!==t.decimalPart&&(s+="."+function(e,t){let i=e;if(t.length-e.length>0){const o=(t.substring(e.length,t.length+1).match(di)||[]).length;i+="0".repeat(o)}return i}(n||"",t.decimalPart)),t.isPercent&&(s+="%"),s}const bi=[];function Ci(e,t=li){const i=e.toString();if(i.includes("e"))return function(e,t=li){let i=bi[t];i||(i=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),bi[t]=i);const[o,n]=i.format(e).split(".");return{integerDigits:o,decimalDigits:n}}(e,t);if(Number.isInteger(e))return{integerDigits:i,decimalDigits:void 0};const o=i.indexOf(".");let n=i.substring(0,o),s=i.substring(o+1);if(0===t)return Number(s[0])>=5&&(n=(Number(n)+1).toString()),{integerDigits:n,decimalDigits:void 0};if(s.length>t){const{integerDigits:e,decimalDigits:i}=function(e,t){var i;let o="0",n=e,s=e.slice(0,t);const r=t;if(Number(e[r])<5)return{integerDigits:o,decimalDigits:s};const a=(null===(i=s.match(Ei))||void 0===i?void 0:i[0])||"",l=(Number(s)+1).toString(),c=s.slice(a.length),h=l.length>c.length;h&&!a?(o="1",n=void 0):n=h?a.slice(0,-1)+l:a+l;return{integerDigits:o,decimalDigits:n}}(s,t);s=i,"0"!==e&&(n=(Number(n)+Number(e)).toString())}return{integerDigits:n,decimalDigits:Si(s||"")}}function Si(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const Ei=/^0+/;function wi(e){try{return yi(1,e),!0}catch(e){return!1}}function yi(e,t){const i=xe(e),o=t.indexOf("h");let n="",s="";return o>0?(n=xi(i,t.substring(0,o-1)),s=Ii(i,t.substring(o))):0===o?s=Ii(i,t):o<0&&(n=xi(i,t)),n+(n&&s?" ":"")+s}function xi(e,t){var i;const o=null===(i=t.match(/\/|-|\s/))||void 0===i?void 0:i[0];return(o?t.split(o):[t]).map((i=>{switch(i){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return gi[e.getDay()].slice(0,3);case"dddd":return gi[e.getDay()];case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return ui[e.getMonth()].slice(0,3);case"mmmm":return ui[e.getMonth()];case"mmmmm":return ui[e.getMonth()].slice(0,1);case"yy":const i=String(e.getFullYear()).replace("-","").padStart(2,"0");return i.slice(i.length-2);case"yyyy":return e.getFullYear();default:throw new Error(`invalid format: ${t}`)}})).join(o)}function Ii(e,t){let i=t.split(/:|\s/);const o=e.getHours(),n="a"===i[i.length-1];let s=o,r="";return n&&(s=0===s?12:s>12?s-12:s,r=o>=12?" PM":" AM",i.pop()),i.map((i=>{switch(i){case"hhhh":return Math.floor((e.getTime()-ge.getTime())/36e5).toString();case"hh":return s.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}function Ri(e){let{integerDigits:t,decimalDigits:i}=Ci(e);if(!i)return"0";const o=t.replace("-","").length;if(o+2>ci)return"0";const n=ci-o-1;return({decimalDigits:i}=Ci(e,Math.min(n,i.length))),i?"0."+"0".repeat(i.length):"0"}function Ti(e){if(qe(e)){return we(e).format}if(!ni(e))return;const t=e.includes(".")?"0.00":"0",i=e.match(/[\$€]/);if(i){const o=e.match(/[\d]/),n="[$"+i.values().next().value+"]";return o.index<i.index?"#,##"+t+n:n+"#,##"+t}return e.includes("%")?t+"%":void 0}function Ai(e,t,i){const o=mi(e||"#,##0"),n=[];for(let e=0;e<o.length;e++){const s=o[e];if("NUMBER"!==s.type){n.push(s);continue}n.push({...s,format:{...s.format,magnitude:t,decimalPart:void 0}}),n.push({type:"STRING",format:i});const r=o[e+1];"STRING"===(null==r?void 0:r.type)&&["k","m","b"].includes(r.format)&&e++}return Di(n)}function Mi(e,t){const i=mi(e).map((e=>"NUMBER"===e.type?{...e,format:Oi(e.format,t)}:e)),o=Di(i);return pi[o]=i,o}function Oi(e,t){var i;const o={...e},n=Math.sign(t),s=(null===(i=o.decimalPart)||void 0===i?void 0:i.length)||0,r=Math.min(Math.max(0,s+n),li);return o.decimalPart="0".repeat(r),""===o.decimalPart&&delete o.decimalPart,o}const Ni=/,*?$/;function _i(e){var t;if(function(e){return Boolean(e.replace(Fi,""))}(e=e.trim()))throw new Error(`Invalid number format: ${e}`);const i=e.includes("%"),o=(null===(t=e.match(Ni))||void 0===t?void 0:t[0])||"",n=o?1e3**o.length:1;let s=e.slice(0,e.length-(o.length||0));const r=s.includes(",");if(s.match(/\..*,/))throw new Error("A format can't contain ',' symbol in the decimal part");s=s.replace("%","").replace(",","");const a=s.match(/[\%|,]/);if(a)throw new Error(`A format can only contain a single '${a[0]}' symbol`);const[l,c]=s.split(".");if(c&&c.length>20)throw new Error("A format can't contain more than 20 decimal places");return void 0!==c?{integerPart:l,isPercent:i,thousandsSeparator:r,decimalPart:c,magnitude:n}:{integerPart:l,isPercent:i,thousandsSeparator:r,magnitude:n}}const Fi=/[,#0.%]/g;function Di(e){let t="";for(let i of e){let e;switch(i.type){case"NUMBER":const t=i.format;e=t.integerPart,t.thousandsSeparator&&(e=e.slice(0,-3)+","+e.slice(-3)),void 0!==t.decimalPart&&(e+="."+t.decimalPart),t.isPercent&&(e+="%"),t.magnitude&&(e+=",".repeat(Math.log10(t.magnitude)/3));break;case"STRING":e=`[$${i.format}]`;break;case"DATE":e=i.format}t+=e}return t}class ki{constructor(e,t){this.getSheetSize=t,this.prefixSheet=!1,this._zone=e.zone,this.parts=e.parts,this.prefixSheet=e.prefixSheet,this.invalidXc=e.invalidXc,this.sheetId=e.sheetId,this.invalidSheetName=e.invalidSheetName}static fromRange(e,t){return e instanceof ki?e:new ki(e,t.getSheetSize)}get unboundedZone(){return this._zone}get zone(){const{left:e,top:t,bottom:i,right:o}=this._zone;if(void 0!==o&&void 0!==i)return this._zone;if(void 0===i&&void 0!==o)return{right:o,top:t,left:e,bottom:this.getSheetSize(this.sheetId).numberOfRows-1};if(void 0===o&&void 0!==i)return{bottom:i,left:e,top:t,right:this.getSheetSize(this.sheetId).numberOfCols-1};throw new Error(s("Bad zone format"))}static getRangeParts(e,t){const i=e.split(":").map((e=>{const t=Vt(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}})),o=void 0===t.bottom,n=void 0===t.right;return o&&(i[0].rowFixed=i[0].rowFixed||i[1].rowFixed,i[1].rowFixed=i[0].rowFixed||i[1].rowFixed),n&&(i[0].colFixed=i[0].colFixed||i[1].colFixed,i[1].colFixed=i[0].colFixed||i[1].colFixed),i}get isFullCol(){return void 0===this._zone.bottom}get isFullRow(){return void 0===this._zone.right}get rangeData(){return{_zone:this._zone,_sheetId:this.sheetId}}orderZone(){var e,t,i,o,n,s,r,a;const l={...this._zone};let c=this.parts;if(void 0!==l.right&&l.right<l.left){let n=l.right;l.right=l.left,l.left=n,c=[{colFixed:(null===(e=c[1])||void 0===e?void 0:e.colFixed)||!1,rowFixed:(null===(t=c[0])||void 0===t?void 0:t.rowFixed)||!1},{colFixed:(null===(i=c[0])||void 0===i?void 0:i.colFixed)||!1,rowFixed:(null===(o=c[1])||void 0===o?void 0:o.rowFixed)||!1}]}if(void 0!==l.bottom&&l.bottom<l.top){let e=l.bottom;l.bottom=l.top,l.top=e,c=[{colFixed:(null===(n=c[0])||void 0===n?void 0:n.colFixed)||!1,rowFixed:(null===(s=c[1])||void 0===s?void 0:s.rowFixed)||!1},{colFixed:(null===(r=c[1])||void 0===r?void 0:r.colFixed)||!1,rowFixed:(null===(a=c[0])||void 0===a?void 0:a.rowFixed)||!1}]}return this.clone({zone:l,parts:c})}clone(e){return new ki({zone:(null==e?void 0:e.zone)?e.zone:{...this._zone},sheetId:(null==e?void 0:e.sheetId)?e.sheetId:this.sheetId,invalidSheetName:e&&"invalidSheetName"in e?e.invalidSheetName:this.invalidSheetName,invalidXc:e&&"invalidXc"in e?e.invalidXc:this.invalidXc,parts:(null==e?void 0:e.parts)?e.parts:this.parts.map((e=>({rowFixed:e.rowFixed,colFixed:e.colFixed}))),prefixSheet:(null==e?void 0:e.prefixSheet)?e.prefixSheet:this.prefixSheet},this.getSheetSize)}}function Li(e,t,i){const o=i.sheetId===e?t:i.sheetId;return i.clone({sheetId:o})}function Pi(e,t,i){return i?e.getRangeFromSheetXC(t,i):void 0}function Ui(e,t,i){const o=[];return t.forEach((t=>{const n=function(e,t){e=e.toLocaleLowerCase();let i=0,o=0,n=(t=t.toLocaleLowerCase()).length,s=0;for(let r=0;r<n;r++)t[r]===e[s]?(s++,o+=100+o-r/200):o=0,i+=o;return s===e.length?i:0}(e,i(t));n>0&&o.push({score:n,elem:t})})),o.sort(((e,t)=>t.score-e.score)),o.map((e=>e.elem))}function Vi(e){const t=[];for(let i=0;i<e;i++){const e={cells:{}};t.push(e)}return t}class zi{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 Bi(e){const t=function(e){const t=(e=e.split("!").pop()).replace(/\$/g,"").split(":").map((e=>e.trim()));let i,o,n,s,r=!1,a=!1,l=!1;const c=t[0],h=t[1]&&t[1];if(Ut(c))n=s=Gt(c),i=o=0,r=!0;else if(Vt(c))i=o=parseInt(c,10)-1,n=s=0,a=!0;else{const e=qt(c);n=s=e.col,i=o=e.row,l=!0}if(2===t.length)if(Ut(h))s=Gt(h),r=!0;else if(Vt(h))o=parseInt(h,10)-1,a=!0;else{const e=qt(h);s=e.col,o=e.row,i=r?o:i,n=a?s:n,l=!0}if(r&&a)throw new Error("Wrong zone xc. The zone cannot be at the same time a full column and a full row");const d={top:i,left:n,bottom:r?void 0:o,right:a?void 0:s};return l=l&&(a||r),l&&(d.hasHeader=l),d}(e);if(void 0!==t.right&&t.right<t.left){const e=t.left;t.left=t.right,t.right=e}if(void 0!==t.bottom&&t.bottom<t.top){const e=t.top;t.top=t.bottom,t.bottom=e}return t}function Hi(e){const t=Bi(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function $i(e){const{bottom:t,top:i,left:o,right:n}=e;return!(void 0!==t&&isNaN(t)||isNaN(i)||isNaN(o)||void 0!==n&&isNaN(n))&&((void 0===e.bottom||e.bottom>=e.top&&e.bottom>=0)&&(void 0===e.right||e.right>=e.left&&e.right>=0)&&e.top>=0&&e.left>=0)}function Wi(e){const{top:t,bottom:i,left:o,right:n}=e,r="hasHeader"in e&&e.hasHeader,a=t===i&&o===n;if(void 0===i&&void 0!==n)return 0!==t||r?`${Zt(o,t)}:${Wt(n)}`:`${Wt(o)}:${Wt(n)}`;if(void 0===n&&void 0!==i)return 0!==o||r?`${Zt(o,t)}:${i+1}`:`${t+1}:${i+1}`;if(void 0!==i&&void 0!==n)return a?Zt(o,t):`${Zt(o,t)}:${Zt(n,i)}`;throw new Error(s("Bad zone format"))}function Gi(e,t,i,o,n){const s="left"===t?"columns":"rows",r="before"===o?i-1:i,a=e["left"===t?"right":"bottom"];return e[t]<=r&&a&&a>r?ro(e,s,"RESIZE",n):r<e[t]?ro(e,s,"MOVE",n):{...e}}function qi(e,t,i,o,n){const s="left"===t?"columns":"rows",r="before"===o?i-1:i,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?ro(e,s,"RESIZE",n):r<e[t]?ro(e,s,"MOVE",n):{...e}}function Zi(e,t,i){const o="left"===t?"right":"bottom";let n=e[t],s=e[o];for(let r of i.sort(((e,t)=>t-e)))e[t]>r&&(n--,s--),e[t]<r&&e[o]>=r&&s--;return{...e,[t]:n,[o]:s}}function ji(e,t,i){const o="left"===t?"right":"bottom";let n=e[t],s=e[o];const r=e[o];for(let o of i.sort(((e,t)=>t-e)))e[t]>o&&(n--,void 0!==s&&s--),void 0!==r&&void 0!==s&&e[t]<=o&&r>=o&&s--;if(!(void 0!==s&&n>s))return{...e,[t]:n,[o]:s}}function Yi(...e){return{top:Math.min(...e.map((e=>e.top))),left:Math.min(...e.map((e=>e.left))),bottom:Math.max(...e.map((e=>e.bottom))),right:Math.max(...e.map((e=>e.right)))}}function Xi(e,t){if(Qi(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:Math.min(e.bottom,t.bottom),right:Math.min(e.right,t.right)}}function Ki(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function Qi(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function Ji(e,t,i){const{left:o,right:n,top:s,bottom:r}=i;return e>=o&&e<=n&&t>=s&&t<=r}function eo(e,t){return Ki(Yi(t,e),t)}function to(e,t){const i=e.map(Bi),o=t.map(Hi),n=Math.max(...i.concat(o).map((e=>e.bottom||0))),s=Math.max(...i.concat(o).map((e=>e.right||0))),r=i.map((e=>({...e,bottom:void 0===e.bottom?n+1:e.bottom,right:void 0===e.right?s+1:e.right}))),a=o.map((e=>({...e,bottom:void 0===e.bottom?n+1:e.bottom,right:void 0===e.right?s+1:e.right}))),l=function(e,t){const i=new Set(t.map((({col:e,row:t})=>`${e}-${t}`)));return e.filter((({col:e,row:t})=>!i.has(`${e}-${t}`)))}(r.map(so).flat(),a.map(so).flat()),c=function(e){if(0===e.length)return[];const[t,...i]=[...e].sort(((e,t)=>e.row-t.row)).sort(((e,t)=>e.col-t.col)),o=[];let n=co(t);for(const{col:e,row:t}of i)if(!Ji(e,t,n))if(e===n.left&&t===n.bottom+1){const e=n.bottom+1;n={...n,bottom:e}}else o.push(n),n=co({col:e,row:t});return[...o,n]}(l);return function(e){if(0===e.length)return[];if(e.some((e=>e.left!==e.right)))throw new Error("only columns can be merged");const t=[],i=io(e),o=(e,t)=>e.top===t.top&&e.bottom===t.bottom&&e.right+1===t.left;for(;i.length;){const e=i.reduce(((e,t)=>o(e,t)?Yi(e,t):e),i.shift());t.push(e)}return io(t)}(c).map((e=>({...e,bottom:e.bottom===n+1?void 0:e.bottom,right:e.right===s+1?void 0:e.right}))).map(Wi)}function io(e){const t=[...e].sort(((e,t)=>t.right-e.right)).sort(((e,t)=>t.bottom-e.bottom)).sort(((e,t)=>e.top-t.top)).sort(((e,t)=>e.left-t.left)).reverse(),i=[];for(;0!==t.length;){const e=t.shift();t.some((t=>eo(e,t)))||i.push(e)}return i.reverse()}function oo(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function no(e){const{numberOfCols:t,numberOfRows:i}=oo(e);return 1===t||1===i}function so(e){const t=[],[i,o]=[e.right,e.left].sort(((e,t)=>e-t)),[n,s]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of $e(i,o+1))for(const i of $e(n,s+1))t.push({col:e,row:i});return t}function ro(e,t,i,o){const n="both"===t?o[0]:"columns"===t?o:0,s="both"===t?o[1]:"rows"===t?o:0,r="hasHeader"in e&&e.hasHeader;let a;a=!function(e){return void 0===e.bottom}(e)||r?!(ho(e)&&!r)||"columns"!==t:"rows"!==t;const l={...e};return a&&"MOVE"===i&&(l.left+=n,l.top+=s),void 0!==l.right&&(l.right+=n),void 0!==l.bottom&&(l.bottom+=s),l}function ao(e,t){let i,o;const{left:n,right:s,top:r,bottom:a}=e,{left:l,right:c,top:h,bottom:d}=t;return i=l!=n?l:c!=s?c:l,o=h!=r?h:d!=a?d:h,{col:i,row:o}}function lo(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 co(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function ho(e){return void 0===e.right}function uo(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function go(...e){return e.length<2||1===to(e.map(Wi),[]).length}class po extends t.Component{constructor(){super(...arguments),this.canvas=t.useRef("graphContainer")}get background(){return this.chartRuntime.background}get canvasStyle(){return`background-color: ${this.background}`}get chartRuntime(){const e=this.env.model.getters.getChartRuntime(this.props.figure.id);if(!("chartJsConfig"in e))throw new Error("Unsupported chart runtime");return e}setup(){t.onMounted((()=>{const e=this.chartRuntime;this.createChart(e.chartJsConfig)}));let e=this.chartRuntime;t.onPatched((()=>{const t=this.chartRuntime;ht(e,t)||(this.updateChartJs(t),e=t)}))}createChart(e){const t=this.canvas.el.getContext("2d");this.chart=new window.Chart(t,e)}updateChartJs(e){var t,i,o,n,s;const r=e.chartJsConfig;r.data&&r.data.datasets?(this.chart.data=r.data,(null===(t=r.options)||void 0===t?void 0:t.title)&&(this.chart.config.options.title=r.options.title),r.options&&"valueLabel"in r.options&&(null===(i=r.options)||void 0===i?void 0:i.valueLabel)&&(this.chart.config.options.valueLabel=r.options.valueLabel)):this.chart.data.datasets=void 0,this.chart.config.options.tooltips=null===(o=r.options)||void 0===o?void 0:o.tooltips,this.chart.config.options.legend=null===(n=r.options)||void 0===n?void 0:n.legend,this.chart.config.options.scales=null===(s=r.options)||void 0===s?void 0:s.scales,this.chart.update({duration:0})}}po.template="o-spreadsheet-ChartJsComponent",po.props={figure:Object};const mo={};let fo=0;function vo(e,...t){const i="__sheet__"+fo++;return function(e,t){const i=document.createElement("style");i.textContent=function(e){const t=e.split(/(\{|\}|;)/).map((e=>e.trim())),i=[],o=[];let n=[];function s(e,t){const o=[];for(const n of i[e]){let r=t&&t+" "+n||n;r.includes("&")&&(r=n.replace(/&/g,t||"")),e<i.length-1&&(r=s(e+1,r)),o.push(r)}return o.join(", ")}function r(){n.length&&(o.push(s(0)+" {"),o.push(...n),o.push("}"),n=[])}for(;t.length;){let e=t.shift();"}"===e?(r(),i.pop()):("{"===t[0]&&(r(),i.push(e.split(/\s*,\s*/)),t.shift()),";"===t[0]&&n.push(" "+e+";"))}return o.join("\n")}(t),mo[e]=i}(i,String.raw(e,...t)),function(e){const t=mo[e];t.setAttribute("component",e),document.head.appendChild(t)}(i),i}function bo({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function Co(e){const t=So(e);return e?(e.fillColor&&(t.background=e.fillColor),t):t}function So(e){const t={};if(!e)return t;if(e.bold&&(t["font-weight"]="bold"),e.italic&&(t["font-style"]="italic"),e.strikethrough||e.underline){let i=e.strikethrough?"line-through":"";i=e.underline?i+" underline":i,t["text-decoration"]=i}return e.textColor&&(t.color=e.textColor),t}function Eo(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>`${e}:${t};`)).join(" ")}const wo=1.2;vo`
2
2
  div.o-scorecard {
3
3
  font-family: ${Z};
4
4
  user-select: none;
@@ -50,7 +50,7 @@
50
50
  }
51
51
  }
52
52
  }
53
- `;class yo extends t.Component{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}get runtime(){return this.env.model.getters.getChartRuntime(this.props.figure.id)}get title(){return this.runtime.title}get keyValue(){return this.runtime.keyValue}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){const e=this.runtime.baselineDescr||"";return this.baseline&&e?" "+e:e}get baselineArrowDirection(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get primaryFontColor(){return this.runtime.fontColor}get secondaryFontColor(){return Rt(this.backgroundColor)>.3?"#525252":"#C8C8C8"}get figure(){return this.props.figure}get chartStyle(){return Eo({padding:`${this.chartPadding}px`,background:this.backgroundColor})}get chartContentStyle(){return Eo({height:`${this.getDrawableHeight()}px`})}get chartPadding(){return.02*this.props.figure.width}getTextStyles(){const e=.96*this.props.figure.width,t=this.getWidestElement(),i=t.getElementMaxFontSize(this.getDrawableHeight(),this);let o=function(e,t,i,o=.25){let n=1;if(i(n)>e)return n;if(i(t)<e)return t;let s=(n+t)/2,r=i(s),a=0;for(;Math.abs(r-e)>o&&a<20;)r>=e?t=(n+t)/2:n=(n+t)/2,s=(n+t)/2,r=i(s),a++;return s}(e,i,(e=>t.getElementWidth(e,this.ctx,this)))/i;const n=(new Io).getElementMaxFontSize(this.getDrawableHeight(),this)*o,s=(new xo).getElementMaxFontSize(this.getDrawableHeight(),this)*o;return{titleStyle:this.getTextStyle({fontSize:18,color:this.secondaryFontColor}),keyStyle:this.getTextStyle({fontSize:n,cellStyle:this.runtime.keyValueStyle,color:this.primaryFontColor}),baselineStyle:this.getTextStyle({fontSize:s}),baselineValueStyle:this.getTextStyle({fontSize:s,cellStyle:this.runtime.baselineStyle,color:this.runtime.baselineColor||this.secondaryFontColor}),baselineDescrStyle:this.getTextStyle({fontSize:.9*s,color:this.secondaryFontColor})}}getTextStyle(e){const t=So(e.cellStyle);return t["font-size"]=`${e.fontSize}px`,t.display="inline-block",!t.color&&e.color&&(t.color=e.color),Eo(t)}getDrawableHeight(){const e=2*this.chartPadding;let t=this.props.figure.height-e;return t-=this.title?18*wo:0,t}getWidestElement(){const e=new xo,t=new Io;return e.getElementWidth(.35,this.ctx,this)>t.getElementWidth(.65,this.ctx,this)?e:t}}yo.template="o-spreadsheet-ScorecardChart";class xo{getElementWidth(e,t,i){if(!i.runtime)return 0;const o=i.baseline,n="neutral"!==i.baselineArrowDirection?"A "+o:o;t.font=`${e}px ${Z}`;let s=t.measureText(n).width;return t.font=`${.9*e}px ${Z}`,s+=t.measureText(i.baselineDescr).width,s}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.35*e:0)/wo}}class Io{getElementWidth(e,t,i){if(!i.runtime)return 0;const o=i.keyValue||"";return t.font=`${e}px ${Z}`,t.measureText(o).width}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.65*e:e)/wo}}yo.props={figure:Object};class Ro{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)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}}function To(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const Ao=new Ro;function Mo(e,t){return{url:e=To(e),label:t||e,isExternal:!0,isUrlEditable:!0}}Ao.add("sheet_URL",{match:e=>et(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){const i=it(e);return t.tryGetSheetName(i)||s("Invalid sheet")},open(e,t){const i=it(e);t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:i})},sequence:0});const Oo={createLink:Mo,match:e=>Xe(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function No(e){return Ao.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((t=>t.match(e)))||Oo}function _o(e,t){return No(e.url).urlRepresentation(e.url,t)}function Fo(e,t){No(e.url).open(e.url,t)}function Do(e){if("string"==typeof e){if(Ye(e)){const{label:t,url:i}=Qe(e);return No(i).createLink(i,t)}return Xe(e)?Mo(e):void 0}}const ko=["number","string","boolean","undefined"];function Lo(e,t){if(!e())throw new Error(t)}const Po=e=>s("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function Uo(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(ni(e)||""===e)return ri(e);const t=we(e);if(t)return t.value;throw new Error(Po(e));default:return 0}}function Vo(e){if(""===e)throw new Error(Po(e));return Uo(e)}function zo(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}const Bo=function(e){const t=new Map,i=e.name?e.name+" (memoized)":"memoized";return{[i]:(...i)=>(t.has(i[0])||t.set(i[0],e(...i)),t.get(i[0]))}[i]}((function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}));function Ho(e){return"string"==typeof e?Bo(e):e}const $o=e=>s("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function Wo(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($o(e))}return!1;case"number":return!!e;default:return!1}}function Go(e){return xe(Uo(e))}function qo(e,t,i){for(let o of e)if(Array.isArray(o)){const e=o.length,i=o[0].length;for(let n=0;n<i;n++)for(let i=0;i<e;i++)t(o[i][n])}else i(o)}function Zo(e,t){qo(e,t,t)}function jo(e,t){qo(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(Vo(e))}))}function Yo(e,t,i,o){let n=o;for(let o of e)if(Array.isArray(o)){const e=o.length,i=o[0].length;for(let s=0;s<i;s++)for(let i=0;i<e;i++)n=t(n,o[i][s])}else n=i(n,o);return n}function Xo(e,t,i){return Yo(e,t,t,i)}function Ko(e,t,i){return Yo(e,((e,i)=>"number"==typeof i?t(e,i):e),((e,i)=>t(e,Vo(i))),i)}function Qo(e,t,i){return Yo(e,((e,i)=>null!=i?t(e,"number"==typeof i?i:"boolean"==typeof i?Uo(i):0):e),((e,i)=>t(e,Uo(i))),i)}function Jo(e,t){return function(e,t,i){for(let o of e)if(Array.isArray(o)){const e=o.length,i=o[0].length;for(let n=0;n<i;n++)for(let i=0;i<e;i++)if(!t(o[i][n]))return}else if(!i(o))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error($o(e));return Wo(e)}(e))))}function en(e,t){let i,o,n=e.substring(0,2);"<="===n||">="===n||"<>"===n?(i=n,o=e.substring(2)):(n=e.substring(0,1),"<"===n||">"===n||"="===n?(i=n,o=e.substring(1)):(i="=",o=e)),ni(o)?o=Uo(o):"TRUE"!==o&&"FALSE"!==o||(o=Wo(o));const s={operator:i,operand:o};return"string"==typeof o&&(t&&(o+="*"),s.regexp=function(e){let t="",i="";for(let o of e)"?"===o&&"~"!==i?t+=".":"*"===o&&"~"!==i?t+=".*":("*"!==o&&"?"!==o||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(o)&&(t+="\\"),t+=o),i=o;return new RegExp("^"+t+"$","i")}(o)),s}function tn(e,t){const{operator:i,operand:o}=t;if(void 0===e||void 0===o)return!1;if("number"==typeof o&&"="===i)return zo(e)===zo(o);if("<>"===i||"="===i){let n;return n=typeof e==typeof o&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===o),"="===i?n:!n}if(typeof e==typeof o)switch(i){case"<":return e<o;case">":return e>o;case"<=":return e<=o;case">=":return e>=o}return!1}function on(e,t,i=!1){const o=e.length;if(o%2==1)throw new Error(s("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const n=e[0].length,r=e[0][0].length;let a=[];for(let t=0;t<o-1;t+=2){const o=e[t];if(!Array.isArray(o)||o.length!==n||o[0].length!==r)throw new Error(s("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=zo(e[t+1]);a.push(en(l,i))}for(let i=0;i<n;i++)for(let n=0;n<r;n++){let s=!0;for(let t=0;t<o-1;t+=2){if(s=tn(e[t][i][n],a[t/2]),!s)break}s&&t(i,n)}}function nn(e,t){return Ho(e[0][t])}function sn(e,t){return Ho(e[t][0])}function rn(e,t,i,o,n,s){if(null==t)return-1;const r=typeof t;let a,l,c,h,d,u,g=0,p=n-1;for(;p-g>=0;){for(c=Math.floor((g+p)/2),h=c,d=s(e,h),u=typeof d;g<h&&r!==u;)h--,d=s(e,h),u=typeof d;u===r&&void 0!==d?("strict"===i&&d===t?(a=d,l=h):"nextSmaller"===i&&d<=t?(void 0===a||a<d||a===d&&"asc"===o&&l<h||a===d&&"desc"===o&&l>h)&&(a=d,l=h):"nextGreater"===i&&d>=t&&(void 0===a||a>d||a===d&&"asc"===o&&l<h||a===d&&"desc"===o&&l>h)&&(a=d,l=h),"asc"===o&&d>t||"desc"===o&&d<=t?p=h-1:g=c+1):g=c+1}return void 0!==l?l:-1}function an(e,t,i,o,n,s=!1){if(null==t)return-1;const r=s?(e,t)=>n(e,o-t-1):n;let a,l=-1;for(let n=0;n<o;n++){const c=r(e,n);if(c===t)return s?o-n-1:n;"nextSmaller"===i?(!a&&ln(t,c)>=0||ln(t,c)>=0&&ln(c,a)>0)&&(a=c,l=n):"nextGreater"===i&&(!a&&ln(t,c)<=0||ln(t,c)<=0&&ln(c,a)<0)&&(a=c,l=n)}return s?o-l-1:l}function ln(e,t){let i=ko.indexOf(typeof e)-ko.indexOf(typeof t);return 0===i&&("string"==typeof e&&"string"==typeof t?i=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?i=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(i=Number(e)-Number(t))),i}var cn,hn;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(cn||(cn={})),function(e){e.PlainText="text/plain",e.Html="text/html"}(hn||(hn={}));const dn=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),un=new Set([...dn,"DUPLICATE_SHEET","EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT"]),gn=new Set(["START","ACTIVATE_SHEET","COPY","PREPARE_SELECTION_INPUT_EXPANSION","STOP_SELECTION_INPUT","RESIZE_SHEETVIEW","SET_VIEWPORT_OFFSET","SELECT_SEARCH_NEXT_MATCH","SELECT_SEARCH_PREVIOUS_MATCH","UPDATE_SEARCH","CLEAR_SEARCH","EVALUATE_CELLS","SET_CURRENT_CONTENT","SET_FORMULA_VISIBILITY","OPEN_CELL_POPOVER","CLOSE_CELL_POPOVER","UPDATE_FILTER"]),pn=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","UNFREEZE_COLUMNS","UNFREEZE_ROWS","FREEZE_COLUMNS","FREEZE_ROWS","UNFREEZE_COLUMNS_ROWS","ADD_MERGE","REMOVE_MERGE","CREATE_SHEET","DELETE_SHEET","DUPLICATE_SHEET","MOVE_SHEET","RENAME_SHEET","HIDE_SHEET","SHOW_SHEET","MOVE_RANGES","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","CREATE_CHART","UPDATE_CHART","CREATE_FILTER_TABLE","REMOVE_FILTER_TABLE","CREATE_IMAGE"]);function mn(e){return pn.has(e.type)}class fn{constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new fn}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var vn,bn,Cn;function Sn(e,t){return wn(En(e||""),t)}function En(e){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);return ni(e)||qe(e)?Uo(e):function(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}(e)?"TRUE"===e.toUpperCase():e}function wn(e,t){const i=Do(e);return i?{...yn(En(i.label),t||Ti(i.label)),link:i}:yn(e,t)}function yn(e,t){try{for(const i of Tn){const o=i(e,t);if(o)return o}return function(e,t){return{type:cn.text,value:e,format:t,isAutoSummable:!0,defaultAlign:"left",formattedValue:fi(e,t)}}((e||"").toString(),t)}catch(t){return Rn((e||"").toString(),new c(a.GenericError,t.message||le))}}function xn(e,t){return{type:cn.number,value:e||0,format:t,isAutoSummable:!0,defaultAlign:"right",formattedValue:fi(e,t)}}e.CommandResult=void 0,(vn=e.CommandResult||(e.CommandResult={}))[vn.Success=0]="Success",vn[vn.CancelledForUnknownReason=1]="CancelledForUnknownReason",vn[vn.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",vn[vn.MergeIsDestructive=3]="MergeIsDestructive",vn[vn.CellIsMerged=4]="CellIsMerged",vn[vn.InvalidTarget=5]="InvalidTarget",vn[vn.EmptyUndoStack=6]="EmptyUndoStack",vn[vn.EmptyRedoStack=7]="EmptyRedoStack",vn[vn.NotEnoughElements=8]="NotEnoughElements",vn[vn.NotEnoughSheets=9]="NotEnoughSheets",vn[vn.MissingSheetName=10]="MissingSheetName",vn[vn.DuplicatedSheetName=11]="DuplicatedSheetName",vn[vn.DuplicatedSheetId=12]="DuplicatedSheetId",vn[vn.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",vn[vn.WrongSheetMove=14]="WrongSheetMove",vn[vn.WrongSheetPosition=15]="WrongSheetPosition",vn[vn.InvalidAnchorZone=16]="InvalidAnchorZone",vn[vn.SelectionOutOfBound=17]="SelectionOutOfBound",vn[vn.TargetOutOfSheet=18]="TargetOutOfSheet",vn[vn.WrongCutSelection=19]="WrongCutSelection",vn[vn.WrongPasteSelection=20]="WrongPasteSelection",vn[vn.WrongPasteOption=21]="WrongPasteOption",vn[vn.WrongFigurePasteOption=22]="WrongFigurePasteOption",vn[vn.EmptyClipboard=23]="EmptyClipboard",vn[vn.EmptyRange=24]="EmptyRange",vn[vn.InvalidRange=25]="InvalidRange",vn[vn.InvalidZones=26]="InvalidZones",vn[vn.InvalidSheetId=27]="InvalidSheetId",vn[vn.InvalidFigureId=28]="InvalidFigureId",vn[vn.InputAlreadyFocused=29]="InputAlreadyFocused",vn[vn.MaximumRangesReached=30]="MaximumRangesReached",vn[vn.InvalidChartDefinition=31]="InvalidChartDefinition",vn[vn.InvalidDataSet=32]="InvalidDataSet",vn[vn.InvalidLabelRange=33]="InvalidLabelRange",vn[vn.InvalidScorecardKeyValue=34]="InvalidScorecardKeyValue",vn[vn.InvalidScorecardBaseline=35]="InvalidScorecardBaseline",vn[vn.InvalidGaugeDataRange=36]="InvalidGaugeDataRange",vn[vn.EmptyGaugeRangeMin=37]="EmptyGaugeRangeMin",vn[vn.GaugeRangeMinNaN=38]="GaugeRangeMinNaN",vn[vn.EmptyGaugeRangeMax=39]="EmptyGaugeRangeMax",vn[vn.GaugeRangeMaxNaN=40]="GaugeRangeMaxNaN",vn[vn.GaugeRangeMinBiggerThanRangeMax=41]="GaugeRangeMinBiggerThanRangeMax",vn[vn.GaugeLowerInflectionPointNaN=42]="GaugeLowerInflectionPointNaN",vn[vn.GaugeUpperInflectionPointNaN=43]="GaugeUpperInflectionPointNaN",vn[vn.GaugeLowerBiggerThanUpper=44]="GaugeLowerBiggerThanUpper",vn[vn.InvalidAutofillSelection=45]="InvalidAutofillSelection",vn[vn.WrongComposerSelection=46]="WrongComposerSelection",vn[vn.MinBiggerThanMax=47]="MinBiggerThanMax",vn[vn.LowerBiggerThanUpper=48]="LowerBiggerThanUpper",vn[vn.MidBiggerThanMax=49]="MidBiggerThanMax",vn[vn.MinBiggerThanMid=50]="MinBiggerThanMid",vn[vn.FirstArgMissing=51]="FirstArgMissing",vn[vn.SecondArgMissing=52]="SecondArgMissing",vn[vn.MinNaN=53]="MinNaN",vn[vn.MidNaN=54]="MidNaN",vn[vn.MaxNaN=55]="MaxNaN",vn[vn.ValueUpperInflectionNaN=56]="ValueUpperInflectionNaN",vn[vn.ValueLowerInflectionNaN=57]="ValueLowerInflectionNaN",vn[vn.MinInvalidFormula=58]="MinInvalidFormula",vn[vn.MidInvalidFormula=59]="MidInvalidFormula",vn[vn.MaxInvalidFormula=60]="MaxInvalidFormula",vn[vn.ValueUpperInvalidFormula=61]="ValueUpperInvalidFormula",vn[vn.ValueLowerInvalidFormula=62]="ValueLowerInvalidFormula",vn[vn.InvalidSortZone=63]="InvalidSortZone",vn[vn.WaitingSessionConfirmation=64]="WaitingSessionConfirmation",vn[vn.MergeOverlap=65]="MergeOverlap",vn[vn.TooManyHiddenElements=66]="TooManyHiddenElements",vn[vn.Readonly=67]="Readonly",vn[vn.InvalidViewportSize=68]="InvalidViewportSize",vn[vn.InvalidScrollingDirection=69]="InvalidScrollingDirection",vn[vn.FigureDoesNotExist=70]="FigureDoesNotExist",vn[vn.InvalidConditionalFormatId=71]="InvalidConditionalFormatId",vn[vn.InvalidCellPopover=72]="InvalidCellPopover",vn[vn.EmptyTarget=73]="EmptyTarget",vn[vn.InvalidFreezeQuantity=74]="InvalidFreezeQuantity",vn[vn.FrozenPaneOverlap=75]="FrozenPaneOverlap",vn[vn.ValuesNotChanged=76]="ValuesNotChanged",vn[vn.InvalidFilterZone=77]="InvalidFilterZone",vn[vn.FilterOverlap=78]="FilterOverlap",vn[vn.FilterNotFound=79]="FilterNotFound",vn[vn.MergeInFilter=80]="MergeInFilter",vn[vn.NonContinuousTargets=81]="NonContinuousTargets",vn[vn.DuplicatedFigureId=82]="DuplicatedFigureId",vn[vn.InvalidSelectionStep=83]="InvalidSelectionStep",vn[vn.DuplicatedChartId=84]="DuplicatedChartId",vn[vn.ChartDoesNotExist=85]="ChartDoesNotExist",vn[vn.InvalidHeaderIndex=86]="InvalidHeaderIndex",vn[vn.InvalidQuantity=87]="InvalidQuantity",vn[vn.NoChanges=88]="NoChanges",function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(bn||(bn={})),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.Autofill=5]="Autofill",e[e.Selection=6]="Selection",e[e.Headers=7]="Headers"}(Cn||(Cn={}));const In={type:cn.empty,value:"",format:void 0,isAutoSummable:!0,defaultAlign:"left",formattedValue:""};function Rn(e,t){return{type:cn.error,value:t.errorType,error:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:t.errorType}}const Tn=[function(e,t){if(""===e)return function(e){return void 0===e?In:{type:cn.empty,value:"",format:e,isAutoSummable:!0,defaultAlign:"left",formattedValue:""}}(t)},function(e,t){if(t&&"number"==typeof e&&wi(t))return function(e,t){const i=fi(e,t);return{type:cn.number,value:e,format:t,isAutoSummable:!1,defaultAlign:"right",formattedValue:i}}(e,t)},function(e,t){return"number"==typeof e?xn(e,t):null===e?xn(0,t):void 0},function(e,t){if("boolean"==typeof e)return function(e,t){const i=e?"TRUE":"FALSE";return{type:cn.boolean,value:e,format:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:i}}(e,t)}],An=new Ro;An.add("ALPHANUMERIC_INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;const i=`${e.prefix}${e.current.toString().padStart(e.numberPostfixLength||0,"0")}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i},tooltip:{props:{content:i}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t)=>{var i;e.current+=e.increment;const o=e.current.toString(),n=fi(e.current,null===(i=t.cell)||void 0===i?void 0:i.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:n}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,i)=>{var o,n,s;const r=(null===(o=t.cell)||void 0===o?void 0:o.content)||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:Sn(null===(n=t.cell)||void 0===n?void 0:n.content,null===(s=t.cell)||void 0===s?void 0:s.format).formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,i,o)=>{e.current+=e.increment;let n=0,s=0;switch(o){case"up":n=0,s=-e.current;break;case"down":n=0,s=e.current;break;case"left":n=-e.current,s=0;break;case"right":n=e.current,s=0}const r=t.cell;if(!r||!r.isFormula)return{cellData:{}};const a=t.sheetId,l=i.createAdaptedRanges(r.dependencies,n,s,a),c=i.buildFormulaContent(a,r,l);return{cellData:{border:t.border,style:r.style,format:r.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});const Mn=new Ro,On=/(\d+)$/,Nn=/^(.*\D+)/,_n=/^(.*\D+)(\d+)$/;function Fn(e,t,i){let o=[],n=!1;for(let s of t){s===e&&(n=!0);const t=Sn(null==s?void 0:s.content);if(i(t))o.push(t);else{if(n)return o;o=[]}}return o}function Dn(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let i=e[0];for(let o=1;o<e.length;o++){const n=e[o];t.push(n-i),i=n}return t.reduce(((e,t)=>e+t),0)/t.length}(e)*e.length),t}Mn.add("simple_value_copy",{condition:(e,t)=>{var i;return 1===t.length&&!e.isFormula&&!(null===(i=e.format)||void 0===i?void 0:i.match(X))},generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&Sn(e.content).type===cn.text&&_n.test(e.content),generateRule:(e,t)=>{const i=parseInt(e.content.match(On)[0]),o=e.content.match(Nn)[0],n=e.content.length-o.length,s=Fn(e,t,(e=>e.type===cn.text&&_n.test(e.value))).filter((e=>o===e.value.toString().match(Nn)[0])).map((e=>parseInt(e.value.toString().match(On)[0]))),r=Dn(s);return{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:o,current:i,increment:r,numberPostfixLength:n}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&Sn(e.content).type===cn.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.isFormula&&Sn(e.content).type===cn.number,generateRule:(e,t)=>{const i=Dn(Fn(e,t,(e=>e.type===cn.number)).map((e=>Number(e.value)))),o=Sn(e.content);return{type:"INCREMENT_MODIFIER",increment:i,current:o.type===cn.number?o.value:0}},sequence:40});vo`
53
+ `;class yo extends t.Component{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}get runtime(){return this.env.model.getters.getChartRuntime(this.props.figure.id)}get title(){return this.runtime.title}get keyValue(){return this.runtime.keyValue}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){const e=this.runtime.baselineDescr||"";return this.baseline&&e?" "+e:e}get baselineArrowDirection(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get primaryFontColor(){return this.runtime.fontColor}get secondaryFontColor(){return Rt(this.backgroundColor)>.3?"#525252":"#C8C8C8"}get figure(){return this.props.figure}get chartStyle(){return Eo({padding:`${this.chartPadding}px`,background:this.backgroundColor})}get chartContentStyle(){return Eo({height:`${this.getDrawableHeight()}px`})}get chartPadding(){return.02*this.props.figure.width}getTextStyles(){const e=.96*this.props.figure.width,t=this.getWidestElement(),i=t.getElementMaxFontSize(this.getDrawableHeight(),this);let o=function(e,t,i,o=.25){let n=1;if(i(n)>e)return n;if(i(t)<e)return t;let s=(n+t)/2,r=i(s),a=0;for(;Math.abs(r-e)>o&&a<20;)r>=e?t=(n+t)/2:n=(n+t)/2,s=(n+t)/2,r=i(s),a++;return s}(e,i,(e=>t.getElementWidth(e,this.ctx,this)))/i;const n=(new Io).getElementMaxFontSize(this.getDrawableHeight(),this)*o,s=(new xo).getElementMaxFontSize(this.getDrawableHeight(),this)*o;return{titleStyle:this.getTextStyle({fontSize:18,color:this.secondaryFontColor}),keyStyle:this.getTextStyle({fontSize:n,cellStyle:this.runtime.keyValueStyle,color:this.primaryFontColor}),baselineStyle:this.getTextStyle({fontSize:s}),baselineValueStyle:this.getTextStyle({fontSize:s,cellStyle:this.runtime.baselineStyle,color:this.runtime.baselineColor||this.secondaryFontColor}),baselineDescrStyle:this.getTextStyle({fontSize:.9*s,color:this.secondaryFontColor})}}getTextStyle(e){const t=So(e.cellStyle);return t["font-size"]=`${e.fontSize}px`,t.display="inline-block",!t.color&&e.color&&(t.color=e.color),Eo(t)}getDrawableHeight(){const e=2*this.chartPadding;let t=this.props.figure.height-e;return t-=this.title?18*wo:0,t}getWidestElement(){const e=new xo,t=new Io;return e.getElementWidth(.35,this.ctx,this)>t.getElementWidth(.65,this.ctx,this)?e:t}}yo.template="o-spreadsheet-ScorecardChart";class xo{getElementWidth(e,t,i){if(!i.runtime)return 0;const o=i.baseline,n="neutral"!==i.baselineArrowDirection?"A "+o:o;t.font=`${e}px ${Z}`;let s=t.measureText(n).width;return t.font=`${.9*e}px ${Z}`,s+=t.measureText(i.baselineDescr).width,s}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.35*e:0)/wo}}class Io{getElementWidth(e,t,i){if(!i.runtime)return 0;const o=i.keyValue||"";return t.font=`${e}px ${Z}`,t.measureText(o).width}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.65*e:e)/wo}}yo.props={figure:Object};class Ro{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)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}}function To(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const Ao=new Ro;function Mo(e,t){return{url:e=To(e),label:t||e,isExternal:!0,isUrlEditable:!0}}Ao.add("sheet_URL",{match:e=>et(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){const i=it(e);return t.tryGetSheetName(i)||s("Invalid sheet")},open(e,t){const i=it(e);t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:i})},sequence:0});const Oo={createLink:Mo,match:e=>Xe(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function No(e){return Ao.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((t=>t.match(e)))||Oo}function _o(e,t){return No(e.url).urlRepresentation(e.url,t)}function Fo(e,t){No(e.url).open(e.url,t)}function Do(e){if("string"==typeof e){if(Ye(e)){const{label:t,url:i}=Qe(e);return No(i).createLink(i,t)}return Xe(e)?Mo(e):void 0}}const ko=["number","string","boolean","undefined"];function Lo(e,t){if(!e())throw new Error(t)}const Po=e=>s("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function Uo(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(ni(e)||""===e)return ri(e);const t=we(e);if(t)return t.value;throw new Error(Po(e));default:return 0}}function Vo(e){if(""===e)throw new Error(Po(e));return Uo(e)}function zo(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}const Bo=function(e){const t=new Map,i=e.name?e.name+" (memoized)":"memoized";return{[i]:(...i)=>(t.has(i[0])||t.set(i[0],e(...i)),t.get(i[0]))}[i]}((function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}));function Ho(e){return"string"==typeof e?Bo(e):e}const $o=e=>s("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function Wo(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($o(e))}return!1;case"number":return!!e;default:return!1}}function Go(e){return xe(Uo(e))}function qo(e,t,i){for(let o of e)if(Array.isArray(o)){const e=o.length,i=o[0].length;for(let n=0;n<i;n++)for(let i=0;i<e;i++)t(o[i][n])}else i(o)}function Zo(e,t){qo(e,t,t)}function jo(e,t){qo(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(Vo(e))}))}function Yo(e,t,i,o){let n=o;for(let o of e)if(Array.isArray(o)){const e=o.length,i=o[0].length;for(let s=0;s<i;s++)for(let i=0;i<e;i++)n=t(n,o[i][s])}else n=i(n,o);return n}function Xo(e,t,i){return Yo(e,t,t,i)}function Ko(e,t,i){return Yo(e,((e,i)=>"number"==typeof i?t(e,i):e),((e,i)=>t(e,Vo(i))),i)}function Qo(e,t,i){return Yo(e,((e,i)=>null!=i?t(e,"number"==typeof i?i:"boolean"==typeof i?Uo(i):0):e),((e,i)=>t(e,Uo(i))),i)}function Jo(e,t){return function(e,t,i){for(let o of e)if(Array.isArray(o)){const e=o.length,i=o[0].length;for(let n=0;n<i;n++)for(let i=0;i<e;i++)if(!t(o[i][n]))return}else if(!i(o))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error($o(e));return Wo(e)}(e))))}function en(e,t){let i,o,n=e.substring(0,2);"<="===n||">="===n||"<>"===n?(i=n,o=e.substring(2)):(n=e.substring(0,1),"<"===n||">"===n||"="===n?(i=n,o=e.substring(1)):(i="=",o=e)),ni(o)?o=Uo(o):"TRUE"!==o&&"FALSE"!==o||(o=Wo(o));const s={operator:i,operand:o};return"string"==typeof o&&(t&&(o+="*"),s.regexp=function(e){let t="",i="";for(let o of e)"?"===o&&"~"!==i?t+=".":"*"===o&&"~"!==i?t+=".*":("*"!==o&&"?"!==o||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(o)&&(t+="\\"),t+=o),i=o;return new RegExp("^"+t+"$","i")}(o)),s}function tn(e,t){const{operator:i,operand:o}=t;if(void 0===e||void 0===o)return!1;if("number"==typeof o&&"="===i)return zo(e)===zo(o);if("<>"===i||"="===i){let n;return n=typeof e==typeof o&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===o),"="===i?n:!n}if(typeof e==typeof o)switch(i){case"<":return e<o;case">":return e>o;case"<=":return e<=o;case">=":return e>=o}return!1}function on(e,t,i=!1){const o=e.length;if(o%2==1)throw new Error(s("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const n=e[0].length,r=e[0][0].length;let a=[];for(let t=0;t<o-1;t+=2){const o=e[t];if(!Array.isArray(o)||o.length!==n||o[0].length!==r)throw new Error(s("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=zo(e[t+1]);a.push(en(l,i))}for(let i=0;i<n;i++)for(let n=0;n<r;n++){let s=!0;for(let t=0;t<o-1;t+=2){if(s=tn(e[t][i][n],a[t/2]),!s)break}s&&t(i,n)}}function nn(e,t){return Ho(e[0][t])}function sn(e,t){return Ho(e[t][0])}function rn(e,t,i,o,n,s){if(null==t)return-1;const r=typeof t;let a,l,c,h,d,u,g=0,p=n-1;for(;p-g>=0;){for(c=Math.floor((g+p)/2),h=c,d=s(e,h),u=typeof d;g<h&&r!==u;)h--,d=s(e,h),u=typeof d;u===r&&void 0!==d?("strict"===i&&d===t?(a=d,l=h):"nextSmaller"===i&&d<=t?(void 0===a||a<d||a===d&&"asc"===o&&l<h||a===d&&"desc"===o&&l>h)&&(a=d,l=h):"nextGreater"===i&&d>=t&&(void 0===a||a>d||a===d&&"asc"===o&&l<h||a===d&&"desc"===o&&l>h)&&(a=d,l=h),"asc"===o&&d>t||"desc"===o&&d<=t?p=h-1:g=c+1):g=c+1}return void 0!==l?l:-1}function an(e,t,i,o,n,s=!1){if(null==t)return-1;const r=s?(e,t)=>n(e,o-t-1):n;let a,l=-1;for(let n=0;n<o;n++){const c=r(e,n);if(c===t)return s?o-n-1:n;"nextSmaller"===i?(!a&&ln(t,c)>=0||ln(t,c)>=0&&ln(c,a)>0)&&(a=c,l=n):"nextGreater"===i&&(!a&&ln(t,c)<=0||ln(t,c)<=0&&ln(c,a)<0)&&(a=c,l=n)}return s?o-l-1:l}function ln(e,t){let i=ko.indexOf(typeof e)-ko.indexOf(typeof t);return 0===i&&("string"==typeof e&&"string"==typeof t?i=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?i=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(i=Number(e)-Number(t))),i}var cn,hn;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(cn||(cn={})),function(e){e.PlainText="text/plain",e.Html="text/html"}(hn||(hn={}));const dn=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),un=new Set([...dn,"DUPLICATE_SHEET","EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT"]),gn=new Set(["START","ACTIVATE_SHEET","COPY","PREPARE_SELECTION_INPUT_EXPANSION","STOP_SELECTION_INPUT","RESIZE_SHEETVIEW","SET_VIEWPORT_OFFSET","SELECT_SEARCH_NEXT_MATCH","SELECT_SEARCH_PREVIOUS_MATCH","UPDATE_SEARCH","CLEAR_SEARCH","EVALUATE_CELLS","SET_CURRENT_CONTENT","SET_FORMULA_VISIBILITY","OPEN_CELL_POPOVER","CLOSE_CELL_POPOVER","UPDATE_FILTER"]),pn=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","UNFREEZE_COLUMNS","UNFREEZE_ROWS","FREEZE_COLUMNS","FREEZE_ROWS","UNFREEZE_COLUMNS_ROWS","ADD_MERGE","REMOVE_MERGE","CREATE_SHEET","DELETE_SHEET","DUPLICATE_SHEET","MOVE_SHEET","RENAME_SHEET","HIDE_SHEET","SHOW_SHEET","MOVE_RANGES","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","CREATE_CHART","UPDATE_CHART","CREATE_FILTER_TABLE","REMOVE_FILTER_TABLE","CREATE_IMAGE"]);function mn(e){return pn.has(e.type)}class fn{constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new fn}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var vn,bn,Cn;function Sn(e,t){return wn(En(e||""),t)}function En(e){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);return ni(e)||qe(e)?Uo(e):function(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}(e)?"TRUE"===e.toUpperCase():e}function wn(e,t){const i=Do(e);return i?{...yn(En(i.label),t||Ti(i.label)),link:i}:yn(e,t)}function yn(e,t){try{for(const i of Tn){const o=i(e,t);if(o)return o}return function(e,t){return{type:cn.text,value:e,format:t,isAutoSummable:!0,defaultAlign:"left",formattedValue:fi(e,t)}}((e||"").toString(),t)}catch(t){return Rn((e||"").toString(),new c(a.GenericError,t.message||le))}}function xn(e,t){return{type:cn.number,value:e||0,format:t,isAutoSummable:!0,defaultAlign:"right",formattedValue:fi(e,t)}}e.CommandResult=void 0,(vn=e.CommandResult||(e.CommandResult={}))[vn.Success=0]="Success",vn[vn.CancelledForUnknownReason=1]="CancelledForUnknownReason",vn[vn.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",vn[vn.MergeIsDestructive=3]="MergeIsDestructive",vn[vn.CellIsMerged=4]="CellIsMerged",vn[vn.InvalidTarget=5]="InvalidTarget",vn[vn.EmptyUndoStack=6]="EmptyUndoStack",vn[vn.EmptyRedoStack=7]="EmptyRedoStack",vn[vn.NotEnoughElements=8]="NotEnoughElements",vn[vn.NotEnoughSheets=9]="NotEnoughSheets",vn[vn.MissingSheetName=10]="MissingSheetName",vn[vn.DuplicatedSheetName=11]="DuplicatedSheetName",vn[vn.DuplicatedSheetId=12]="DuplicatedSheetId",vn[vn.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",vn[vn.WrongSheetMove=14]="WrongSheetMove",vn[vn.WrongSheetPosition=15]="WrongSheetPosition",vn[vn.InvalidAnchorZone=16]="InvalidAnchorZone",vn[vn.SelectionOutOfBound=17]="SelectionOutOfBound",vn[vn.TargetOutOfSheet=18]="TargetOutOfSheet",vn[vn.WrongCutSelection=19]="WrongCutSelection",vn[vn.WrongPasteSelection=20]="WrongPasteSelection",vn[vn.WrongPasteOption=21]="WrongPasteOption",vn[vn.WrongFigurePasteOption=22]="WrongFigurePasteOption",vn[vn.EmptyClipboard=23]="EmptyClipboard",vn[vn.EmptyRange=24]="EmptyRange",vn[vn.InvalidRange=25]="InvalidRange",vn[vn.InvalidZones=26]="InvalidZones",vn[vn.InvalidSheetId=27]="InvalidSheetId",vn[vn.InvalidFigureId=28]="InvalidFigureId",vn[vn.InputAlreadyFocused=29]="InputAlreadyFocused",vn[vn.MaximumRangesReached=30]="MaximumRangesReached",vn[vn.InvalidInputId=31]="InvalidInputId",vn[vn.InvalidChartDefinition=32]="InvalidChartDefinition",vn[vn.InvalidDataSet=33]="InvalidDataSet",vn[vn.InvalidLabelRange=34]="InvalidLabelRange",vn[vn.InvalidScorecardKeyValue=35]="InvalidScorecardKeyValue",vn[vn.InvalidScorecardBaseline=36]="InvalidScorecardBaseline",vn[vn.InvalidGaugeDataRange=37]="InvalidGaugeDataRange",vn[vn.EmptyGaugeRangeMin=38]="EmptyGaugeRangeMin",vn[vn.GaugeRangeMinNaN=39]="GaugeRangeMinNaN",vn[vn.EmptyGaugeRangeMax=40]="EmptyGaugeRangeMax",vn[vn.GaugeRangeMaxNaN=41]="GaugeRangeMaxNaN",vn[vn.GaugeRangeMinBiggerThanRangeMax=42]="GaugeRangeMinBiggerThanRangeMax",vn[vn.GaugeLowerInflectionPointNaN=43]="GaugeLowerInflectionPointNaN",vn[vn.GaugeUpperInflectionPointNaN=44]="GaugeUpperInflectionPointNaN",vn[vn.GaugeLowerBiggerThanUpper=45]="GaugeLowerBiggerThanUpper",vn[vn.InvalidAutofillSelection=46]="InvalidAutofillSelection",vn[vn.WrongComposerSelection=47]="WrongComposerSelection",vn[vn.MinBiggerThanMax=48]="MinBiggerThanMax",vn[vn.LowerBiggerThanUpper=49]="LowerBiggerThanUpper",vn[vn.MidBiggerThanMax=50]="MidBiggerThanMax",vn[vn.MinBiggerThanMid=51]="MinBiggerThanMid",vn[vn.FirstArgMissing=52]="FirstArgMissing",vn[vn.SecondArgMissing=53]="SecondArgMissing",vn[vn.MinNaN=54]="MinNaN",vn[vn.MidNaN=55]="MidNaN",vn[vn.MaxNaN=56]="MaxNaN",vn[vn.ValueUpperInflectionNaN=57]="ValueUpperInflectionNaN",vn[vn.ValueLowerInflectionNaN=58]="ValueLowerInflectionNaN",vn[vn.MinInvalidFormula=59]="MinInvalidFormula",vn[vn.MidInvalidFormula=60]="MidInvalidFormula",vn[vn.MaxInvalidFormula=61]="MaxInvalidFormula",vn[vn.ValueUpperInvalidFormula=62]="ValueUpperInvalidFormula",vn[vn.ValueLowerInvalidFormula=63]="ValueLowerInvalidFormula",vn[vn.InvalidSortZone=64]="InvalidSortZone",vn[vn.WaitingSessionConfirmation=65]="WaitingSessionConfirmation",vn[vn.MergeOverlap=66]="MergeOverlap",vn[vn.TooManyHiddenElements=67]="TooManyHiddenElements",vn[vn.Readonly=68]="Readonly",vn[vn.InvalidViewportSize=69]="InvalidViewportSize",vn[vn.InvalidScrollingDirection=70]="InvalidScrollingDirection",vn[vn.FigureDoesNotExist=71]="FigureDoesNotExist",vn[vn.InvalidConditionalFormatId=72]="InvalidConditionalFormatId",vn[vn.InvalidCellPopover=73]="InvalidCellPopover",vn[vn.EmptyTarget=74]="EmptyTarget",vn[vn.InvalidFreezeQuantity=75]="InvalidFreezeQuantity",vn[vn.FrozenPaneOverlap=76]="FrozenPaneOverlap",vn[vn.ValuesNotChanged=77]="ValuesNotChanged",vn[vn.InvalidFilterZone=78]="InvalidFilterZone",vn[vn.FilterOverlap=79]="FilterOverlap",vn[vn.FilterNotFound=80]="FilterNotFound",vn[vn.MergeInFilter=81]="MergeInFilter",vn[vn.NonContinuousTargets=82]="NonContinuousTargets",vn[vn.DuplicatedFigureId=83]="DuplicatedFigureId",vn[vn.InvalidSelectionStep=84]="InvalidSelectionStep",vn[vn.DuplicatedChartId=85]="DuplicatedChartId",vn[vn.ChartDoesNotExist=86]="ChartDoesNotExist",vn[vn.InvalidHeaderIndex=87]="InvalidHeaderIndex",vn[vn.InvalidQuantity=88]="InvalidQuantity",vn[vn.NoChanges=89]="NoChanges",function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(bn||(bn={})),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.Autofill=5]="Autofill",e[e.Selection=6]="Selection",e[e.Headers=7]="Headers"}(Cn||(Cn={}));const In={type:cn.empty,value:"",format:void 0,isAutoSummable:!0,defaultAlign:"left",formattedValue:""};function Rn(e,t){return{type:cn.error,value:t.errorType,error:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:t.errorType}}const Tn=[function(e,t){if(""===e)return function(e){return void 0===e?In:{type:cn.empty,value:"",format:e,isAutoSummable:!0,defaultAlign:"left",formattedValue:""}}(t)},function(e,t){if(t&&"number"==typeof e&&wi(t))return function(e,t){const i=fi(e,t);return{type:cn.number,value:e,format:t,isAutoSummable:!1,defaultAlign:"right",formattedValue:i}}(e,t)},function(e,t){return"number"==typeof e?xn(e,t):null===e?xn(0,t):void 0},function(e,t){if("boolean"==typeof e)return function(e,t){const i=e?"TRUE":"FALSE";return{type:cn.boolean,value:e,format:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:i}}(e,t)}],An=new Ro;An.add("ALPHANUMERIC_INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;const i=`${e.prefix}${e.current.toString().padStart(e.numberPostfixLength||0,"0")}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i},tooltip:{props:{content:i}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t)=>{var i;e.current+=e.increment;const o=e.current.toString(),n=fi(e.current,null===(i=t.cell)||void 0===i?void 0:i.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:n}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,i)=>{var o,n,s;const r=(null===(o=t.cell)||void 0===o?void 0:o.content)||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:Sn(null===(n=t.cell)||void 0===n?void 0:n.content,null===(s=t.cell)||void 0===s?void 0:s.format).formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,i,o)=>{e.current+=e.increment;let n=0,s=0;switch(o){case"up":n=0,s=-e.current;break;case"down":n=0,s=e.current;break;case"left":n=-e.current,s=0;break;case"right":n=e.current,s=0}const r=t.cell;if(!r||!r.isFormula)return{cellData:{}};const a=t.sheetId,l=i.createAdaptedRanges(r.dependencies,n,s,a),c=i.buildFormulaContent(a,r,l);return{cellData:{border:t.border,style:r.style,format:r.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});const Mn=new Ro,On=/(\d+)$/,Nn=/^(.*\D+)/,_n=/^(.*\D+)(\d+)$/;function Fn(e,t,i){let o=[],n=!1;for(let s of t){s===e&&(n=!0);const t=Sn(null==s?void 0:s.content);if(i(t))o.push(t);else{if(n)return o;o=[]}}return o}function Dn(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let i=e[0];for(let o=1;o<e.length;o++){const n=e[o];t.push(n-i),i=n}return t.reduce(((e,t)=>e+t),0)/t.length}(e)*e.length),t}Mn.add("simple_value_copy",{condition:(e,t)=>{var i;return 1===t.length&&!e.isFormula&&!(null===(i=e.format)||void 0===i?void 0:i.match(X))},generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&Sn(e.content).type===cn.text&&_n.test(e.content),generateRule:(e,t)=>{const i=parseInt(e.content.match(On)[0]),o=e.content.match(Nn)[0],n=e.content.length-o.length,s=Fn(e,t,(e=>e.type===cn.text&&_n.test(e.value))).filter((e=>o===e.value.toString().match(Nn)[0])).map((e=>parseInt(e.value.toString().match(On)[0]))),r=Dn(s);return{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:o,current:i,increment:r,numberPostfixLength:n}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&Sn(e.content).type===cn.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.isFormula&&Sn(e.content).type===cn.number,generateRule:(e,t)=>{const i=Dn(Fn(e,t,(e=>e.type===cn.number)).map((e=>Number(e.value)))),o=Sn(e.content);return{type:"INCREMENT_MODIFIER",increment:i,current:o.type===cn.number?o.value:0}},sequence:40});vo`
54
54
  .o-error-tooltip {
55
55
  font-size: 13px;
56
56
  background-color: white;
@@ -341,13 +341,13 @@
341
341
  }
342
342
  }
343
343
  }
344
- `;class hs extends t.Component{constructor(){super(...arguments),this.menuItems=cs.getMenuItems(),this.link=t.useState(this.defaultState),this.menu=t.useState({isOpen:!1}),this.linkEditorRef=t.useRef("linkEditor"),this.position=Yn(this.linkEditorRef),this.urlInput=t.useRef("urlInput")}setup(){t.onMounted((()=>{var e;return null===(e=this.urlInput.el)||void 0===e?void 0:e.focus()}))}get defaultState(){const{col:e,row:t}=this.props.cellPosition,i=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getEvaluatedCell({sheetId:i,col:e,row:t});return o.link?{url:o.link.url,label:o.formattedValue,isUrlEditable:o.link.isUrlEditable}:{label:o.formattedValue,url:"",isUrlEditable:!0}}get menuPosition(){return{x:this.position.x+320-12-2,y:this.position.y+100}}onSpecialLink(e){const{detail:t}=e,i=Do(t);i&&(this.link.url=i.url,this.link.label=i.label,this.link.isUrlEditable=i.isUrlEditable)}getUrlRepresentation(e){return _o(e,this.env.model.getters)}openMenu(){this.menu.isOpen=!0}removeLink(){this.link.url="",this.link.isUrlEditable=!0}save(){var e,t;const{col:i,row:o}=this.props.cellPosition,n=this.link.label||this.link.url;this.env.model.dispatch("UPDATE_CELL",{col:i,row:o,sheetId:this.env.model.getters.getActiveSheetId(),content:Ke(n,this.link.url)}),null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}cancel(){var e,t;null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}onKeyDown(e){switch(e.key){case"Enter":this.link.url&&this.save(),e.stopPropagation();break;case"Escape":this.cancel(),e.stopPropagation()}}}hs.template="o-spreadsheet-LinkEditor",hs.components={Menu:is};const ds={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:hs,cellCorner:"BottomLeft"})};hs.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const us=new Ro;function gs(e){return 8===(e=wt(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}us.add("ErrorToolTip",Ln).add("LinkCell",ns).add("LinkEditor",ds).add("FilterMenu",zn);class ps{constructor(e,t,i){this.title=e.title,this.sheetId=t,this.getters=i}static validateChartDefinition(e,t){throw new Error("This method should be implemented by sub class")}static transformDefinition(e,t){throw new Error("This method should be implemented by sub class")}static getDefinitionFromContextCreation(e){throw new Error("This method should be implemented by sub class")}}function ms(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?ji(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?Gi(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}function fs(e,t,i,o){let n=!1;const s=[];for(let o in i){let r=i[o];if(r.labelCell){const e=Cs(r.labelCell,t);r.labelCell!==e&&(n=!0,r={...r,labelCell:e})}const a=Cs(r.dataRange,t);void 0===a||e.getRangeString(a,a.sheetId)===K?(n=!0,r=void 0):a!==r.dataRange&&(n=!0,r={...r,dataRange:a}),s[o]=r}let r=o;const a=Cs(r,t);a!==r&&(n=!0,r=a);return{isStale:n,dataSets:s.filter(ot),labelRange:r}}function vs(e,t,i){return i.map((i=>({dataRange:Li(e,t,i.dataRange),labelCell:i.labelCell?Li(e,t,i.labelCell):void 0})))}function bs(e,t,i){return i?Li(e,t,i):void 0}function Cs(e,t){if(!e)return;const i=t(e);switch(i.changeType){case"NONE":return e;case"REMOVE":return;default:return i.range}}function Ss(e,t,i,o){const n=[];for(const s of t){const t=e.getRangeFromSheetXC(i,s),{unboundedZone:r,sheetId:a,invalidSheetName:l}=t;if(!l)if(r.left!==r.right&&r.top!==r.bottom){if(void 0===r.right)continue;for(let t=r.left;t<=r.right;t++){const i={...r,left:t,right:t};n.push(Es(e,a,i,o?{top:i.top,bottom:i.top,left:i.left,right:i.left}:void 0))}}else r.left===r.right&&r.top===r.bottom?o||n.push(Es(e,a,r,void 0)):n.push(Es(e,a,r,o?{top:r.top,bottom:r.top,left:r.left,right:r.left}:void 0))}return n}function Es(e,t,i,o){if(i.left!==i.right&&i.top!==i.bottom)throw new Error(`Zone should be a single column or row: ${Wi(i)}`);if(o){const n=Wi(i),s=Wi(o);return{labelCell:e.getRangeFromSheetXC(t,s),dataRange:e.getRangeFromSheetXC(t,n)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,Wi(i))}}function ws(e,t){var i;const o=null===(i=t.labelCell)||void 0===i?void 0:i.zone;let n=t.dataRange.zone;if(o){const{numberOfRows:e,numberOfCols:t}=oo(n);1===e?n={...n,left:n.left+1}:1===t&&(n={...n,top:n.top+1})}const s=t.dataRange.clone({zone:n});return{label:t.labelCell?e.getRangeString(t.labelCell,"forceSheetReference"):void 0,range:e.getRangeString(s,"forceSheetReference")}}function ys(e,t){let i;if(e.labelRange){const o=ms(Bi(e.labelRange),t);i=o?Wi(o):void 0}const o=e.dataSets.map(Bi).map((e=>ms(e,t))).filter(ot).map(Wi);return{...e,labelRange:i,dataSets:o}}const xs=["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 Is{constructor(){this.graphColorIndex=0}next(){return xs[this.graphColorIndex++%xs.length]}}function Rs(e){return e&&Rt(e)<.3?"#FFFFFF":"#000000"}function Ts(e){if(e.dataSets){const t=void 0!==e.dataSets.find((e=>!Pt.test(e)));if(t)return 32;if(e.dataSets.map(Bi).some((e=>e.top!==e.bottom&&ho(e))))return 32}return 0}function As(e){if(e.labelRange){if(!Pt.test(e.labelRange||""))return 33}return 0}function Ms(e,t,i){if(e){if("text"===i||(null==t?void 0:t.type)!==cn.number||e.type!==cn.number)return e.formattedValue;{let o=t.value-e.value;if("percentage"===i&&0!==o&&(o=o/e.value*100),"percentage"!==i&&e.format)return fi(o,e.format);const n=Math.abs(parseFloat(o.toFixed(2))).toLocaleString();return"percentage"===i?n+"%":n}}return""}function Os(e,t,i,o,n){if("text"===t||(null==e?void 0:e.type)!==cn.number||(null==i?void 0:i.type)!==cn.number)return;const s=i.value-e.value;return s>0?o:s<0?n:void 0}function Ns(e,t,i){if("text"===i||(null==e?void 0:e.type)!==cn.number||(null==t?void 0:t.type)!==cn.number)return"neutral";const o=t.value-e.value;return o>0?"up":o<0?"down":"neutral"}const _s={Errors:{25:s("The range is invalid"),51:s("The argument is missing. Please provide a value"),52:s("The second argument is missing. Please provide a value"),53:s("The minpoint must be a number"),54:s("The midpoint must be a number"),55:s("The maxpoint must be a number"),56:s("The first value must be a number"),57:s("The second value must be a number"),47:s("Minimum must be smaller then Maximum"),50:s("Minimum must be smaller then Midpoint"),49:s("Midpoint must be smaller then Maximum"),48:s("Lower inflection point must be smaller than upper inflection point"),58:s("Invalid Minpoint formula"),60:s("Invalid Maxpoint formula"),59:s("Invalid Midpoint formula"),61:s("Invalid upper inflection point formula"),62:s("Invalid lower inflection point formula"),24:s("A range needs to be defined"),Unexpected:s("The rule is invalid for an unknown reason")},ColorScale:s("Color scale"),IconSet:s("Icon set")},Fs={IsEmpty:s("Is empty"),IsNotEmpty:s("Is not empty"),ContainsText:s("Contains"),NotContains:s("Does not contain"),BeginsWith:s("Starts with"),EndsWith:s("Ends with"),Equal:s("Is equal to"),NotEqual:s("Is not equal to"),GreaterThan:s("Is greater than"),GreaterThanOrEqual:s("Is greater than or equal to"),LessThan:s("Is less than"),LessThanOrEqual:s("Is less than or equal to"),Between:s("Is between"),NotBetween:s("Is not between")},Ds={Series:s("Series"),Errors:{Unexpected:s("The chart definition is invalid for an unknown reason"),32:s("The dataset is invalid"),33:s("Labels are invalid"),34:s("The key value is invalid"),35:s("The baseline value is invalid"),36:s("The data range is invalid"),37:s("A minimum range limit value is needed"),38:s("The minimum range limit value must be a number"),39:s("A maximum range limit value is needed"),40:s("The maximum range limit value must be a number"),41:s("Minimum range limit must be smaller than maximum range limit"),42:s("The lower inflection point value must be a number"),43:s("The upper inflection point value must be a number")}},ks={Automatic:s("Automatic"),Number:s("Number"),Percent:s("Percent"),Currency:s("Currency"),CurrencyRounded:s("Currency rounded"),Date:s("Date"),Time:s("Time"),DateTime:s("Date time"),Duration:s("Duration"),CustomCurrency:s("Custom currency")},Ls={Custom:s("Custom")},Ps=s("Merged cells are preventing this operation. Unmerge those cells and try again.");function Us(e,t){if(t.dataRange){const i=t.labelCell?[Wi(t.labelCell.zone)]:[],o=to([Wi(t.dataRange.zone)],i)[0];if(void 0===o)return[];const n=e.getRangeFromSheetXC(t.dataRange.sheetId,o);return e.getRangeValues(n).map((e=>""===e?void 0:e))}return[]}function Vs(e,t){const i=$e(0,Math.max(e.length,...t.map((e=>{var t;return(null===(t=e.data)||void 0===t?void 0:t.length)||0})))).filter((i=>{const o=e[i],n=t.map((e=>{var t;return null===(t=e.data)||void 0===t?void 0:t[i]}));return o||n.some((e=>0===e||Boolean(e)))}));return{labels:i.map((t=>e[t]||"")),dataSetsValues:t.map((e=>({...e,data:i.map((t=>e.data[t]))})))}}function zs(e,t){const i=new Set(e),o={};i.forEach((e=>{o[e]=new Array(t.length).fill(0)}));for(const i of $e(0,e.length)){const s=e[i];for(const e of $e(0,t.length))o[s][e]+="number"==typeof(n=t[e].data[i])?n:0}var n;return{labels:Object.keys(o),dataSetsValues:t.map(((e,t)=>({...e,data:Object.values(o).map((e=>e[t]))})))}}function Bs(e){return e?e.length>J?e.substring(0,J)+"…":e:""}function Hs(e,t,i,o){return{type:e.type,options:{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:n(e.title),fontColor:i},legend:{onClick:void 0},tooltips:{callbacks:{label:function(e,t){var i,n,s,r,a;let l=null===(n=null===(i=t.datasets)||void 0===i?void 0:i[e.datasetIndex||0])||void 0===n?void 0:n.label;const c=""!==e.yLabel?e.yLabel:null===(a=null===(r=null===(s=t.datasets)||void 0===s?void 0:s[e.datasetIndex||0])||void 0===r?void 0:r.data)||void 0===a?void 0:a[e.index||0],h=o&&"number"==typeof c?fi(c,o):(null==c?void 0:c.toLocaleString())||"";return l?`${l}: ${h}`:h}}}},data:{labels:t.map(Bs),datasets:[]}}}function $s(e,t,i){let o={values:[],formattedValues:[]};if(i)i.invalidXc||i.invalidSheetName||(o={formattedValues:e.getRangeFormattedValues(i),values:e.getRangeValues(i).map((e=>String(e)))});else if(1===t.length)for(let i=0;i<Us(e,t[0]).length;i++)o.formattedValues.push(""),o.values.push("");else if(t[0]){o={formattedValues:$e(0,Us(e,t[0]).length).map((e=>e.toString())),values:o.formattedValues}}return o}function Ws(e,t){for(const i of t){const t=e.getRangeFormats(i.dataRange).find((e=>void 0!==e&&!wi(e)));if(t)return t}}function Gs(e,t){const i=[];for(const[o,n]of Object.entries(t)){let t;if(n.labelCell){const i=n.labelCell,s=i?e.getEvaluatedCell({sheetId:i.sheetId,col:i.zone.left,row:i.zone.top}):void 0;t=s&&i?Bs(s.formattedValue):t=`${Ds.Series} ${parseInt(o)+1}`}else t=t=`${Ds.Series} ${parseInt(o)+1}`;let s=n.dataRange?Us(e,n):[];i.push({data:s,label:t})}return i}function qs(e){return 0===e?"origin":e-1}class Zs extends ps{constructor(e,t,i){super(e,t,i),this.type="bar",this.dataSets=Ss(i,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Pi(i,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated}static transformDefinition(e,t){return ys(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,Ts,As)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,stacked:!1,aggregated:!1,legendPosition:"top",title:e.title||"",type:"bar",verticalAxisPosition:"left",labelRange:e.auxiliaryRange||void 0}}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}copyForSheetId(e){const t=vs(this.sheetId,e,this.dataSets),i=bs(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,i,e);return new Zs(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Zs(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,i){return{type:"bar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated}}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>ws(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:gs(this.background||w),fontColor:gs(Rs(this.background)),dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:o}=fs(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const n=this.getDefinitionWithSpecificDataSets(t,i);return new Zs(n,this.sheetId,this.getters)}}function js(e){return e.dataRange&&!Pt.test(e.dataRange)?36:0}function Ys(e,t){return t((t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):0),(t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):0))}function Xs(e){return e.sectionRule&&Number(e.sectionRule.rangeMin)>=Number(e.sectionRule.rangeMax)?41:0}function Ks(e,t){if(""===e)switch(t){case"rangeMin":return 37;case"rangeMax":return 39}return 0}function Qs(e,t){if(isNaN(e))switch(t){case"rangeMin":return 38;case"rangeMax":return 40;case"lowerInflectionPointValue":return 42;case"upperInflectionPointValue":return 43}return 0}class Js extends ps{constructor(e,t,i){super(e,t,i),this.type="gauge",this.dataRange=Pi(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,js,e.chainValidations(Ys(Ks,e.batchValidations),Ys(Qs,e.batchValidations),Xs),e.chainValidations((i=Qs,(0,e.batchValidations)((e=>e.sectionRule?i(e.sectionRule.lowerInflectionPoint.value,"lowerInflectionPointValue"):0),(e=>e.sectionRule?i(e.sectionRule.upperInflectionPoint.value,"upperInflectionPointValue"):0)))));var i}static transformDefinition(e,t){let i;return e.dataRange&&(i=ms(Bi(e.dataRange),t)),{...e,dataRange:i?Wi(i):void 0}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||"",type:"gauge",dataRange:e.range?e.range[0]:void 0,sectionRule:{colors:{lowerColor:"#cc0000",middleColor:"#f1c232",upperColor:"#6aa84f"},rangeMin:"0",rangeMax:"100",lowerInflectionPoint:{type:"percentage",value:"15"},upperInflectionPoint:{type:"percentage",value:"40"}}}}copyForSheetId(e){const t=bs(this.sheetId,e,this.dataRange),i=this.getDefinitionWithSpecificRanges(t,e);return new Js(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.dataRange,e);return new Js(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.dataRange)}getDefinitionWithSpecificRanges(e,t){return{background:this.background,sectionRule:this.sectionRule,title:this.title,type:"gauge",dataRange:e?this.getters.getRangeString(e,t||this.sheetId):void 0}}getDefinitionForExcel(){}getContextCreation(){return{background:this.background,title:this.title,range:this.dataRange?[this.getters.getRangeString(this.dataRange,this.sheetId)]:void 0}}updateRanges(e){const t=Cs(this.dataRange,e);if(this.dataRange===t)return this;const i=this.getDefinitionWithSpecificRanges(t);return new Js(i,this.sheetId,this.getters)}}const er={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},tr={inSeconds:function(e){return Math.floor(e/er.second)},inMinutes:function(e){return Math.floor(e/er.minute)},inHours:function(e){return Math.floor(e/er.hour)},inDays:function(e){return Math.floor(e/er.day)},inMonths:function(e){return Math.floor(e/er.month)},inYears:function(e){return Math.floor(e/er.year)}},ir=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function or(e,t){const i=function(e){const t=(e=(e=e.replace(/y/g,"Y")).replace(/d/g,"D")).indexOf("h");e=t>=0?e.slice(0,t).replace(/m/g,"M")+e.slice(t):e.replace(/m/g,"M");e.includes("a")||(e=e.replace(/h/g,"H"));return e}(t),o=function(e,t){const i=e.map((e=>{var t;return null===(t=we(e))||void 0===t?void 0:t.jsDate}));if(i.some((e=>void 0===e))||e.length<2)return;const o=i.map((e=>e.getTime())),n=Math.max(...o)-Math.min(...o),s=function(e){if(e.includes("s"))return"second";if(e.includes("m"))return"minute";if(e.includes("h")||e.includes("H"))return"hour";if(e.includes("D"))return"day";if(e.includes("M"))return"month";return"year"}(t);if(er.second>=er[s]&&tr.inSeconds(n)<180)return"second";if(er.minute>=er[s]&&tr.inMinutes(n)<180)return"minute";if(er.hour>=er[s]&&tr.inHours(n)<96)return"hour";if(er.day>=er[s]&&tr.inDays(n)<90)return"day";if(er.month>=er[s]&&tr.inMonths(n)<36)return"month";return"year"}(e,i),n={};return o&&(n[o]=i),{parser:i,displayFormats:n,unit:o}}class nr extends ps{constructor(e,t,i){super(e,t,i),this.type="line",this.dataSets=Ss(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Pi(this.getters,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.stacked=e.stacked,this.aggregated=e.aggregated,this.cumulative=e.cumulative}static validateChartDefinition(e,t){return e.checkValidations(t,Ts,As)}static transformDefinition(e,t){return ys(e,t)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,labelsAsText:!1,legendPosition:"top",title:e.title||"",type:"line",verticalAxisPosition:"left",labelRange:e.auxiliaryRange||void 0,stacked:!1,aggregated:!1,cumulative:!1}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,i){return{type:"line",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,stacked:this.stacked,aggregated:this.aggregated,cumulative:this.cumulative}}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:o}=fs(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const n=this.getDefinitionWithSpecificDataSets(t,i);return new nr(n,this.sheetId,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>ws(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:gs(this.background||w),fontColor:gs(Rs(this.background)),dataSets:e}}copyForSheetId(e){const t=vs(this.sheetId,e,this.dataSets),i=bs(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,i,e);return new nr(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new nr(t,e,this.getters)}}function sr(e,t){return ar(e,t)||lr(e,t)}function rr(e,t){return function(e,t){return!e.labelsAsText&&ar(e.labelRange,t)}(e,t)?"time":function(e,t){return!e.labelsAsText&&lr(e.labelRange,t)}(e,t)?"linear":"category"}function ar(e,t){if(!e||!lr(e,t))return!1;const i=t.getEvaluatedCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}).format;return Boolean(i&&ir.test(i))}function lr(e,t){if(!e)return!1;const i=t.getRangeValues(e);return!i.some((e=>isNaN(Number(e))&&e))&&!i.every((e=>!e))}class cr extends ps{constructor(e,t,i){super(e,t,i),this.type="pie",this.dataSets=Ss(i,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Pi(i,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated}static transformDefinition(e,t){return ys(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,Ts,As)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,legendPosition:"top",title:e.title||"",type:"pie",labelRange:e.auxiliaryRange||void 0,aggregated:!1}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,i){return{type:"pie",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,aggregated:this.aggregated}}copyForSheetId(e){const t=vs(this.sheetId,e,this.dataSets),i=bs(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,i,e);return new cr(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new cr(t,e,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>ws(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:gs(this.background||w),fontColor:gs(Rs(this.background)),verticalAxisPosition:"left",dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:o}=fs(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const n=this.getDefinitionWithSpecificDataSets(t,i);return new cr(n,this.sheetId,this.getters)}}function hr(e,t){const i=[],o=Math.max(...t.map((e=>e.data.length)));for(let t=0;t<=o;t++)i.push(e.next());return i}function dr(e){return e.keyValue&&!Pt.test(e.keyValue)?34:0}function ur(e){return e.baseline&&!Pt.test(e.baseline)?35:0}class gr extends ps{constructor(e,t,i){super(e,t,i),this.type="scorecard",this.keyValue=Pi(i,t,e.keyValue),this.baseline=Pi(i,t,e.baseline),this.baselineMode=e.baselineMode,this.baselineDescr=e.baselineDescr,this.background=e.background,this.baselineColorUp=e.baselineColorUp,this.baselineColorDown=e.baselineColorDown}static validateChartDefinition(e,t){return e.checkValidations(t,dr,ur)}static getDefinitionFromContextCreation(e){return{background:e.background,type:"scorecard",keyValue:e.range?e.range[0]:void 0,title:e.title||"",baselineMode:te,baselineColorUp:ie,baselineColorDown:oe,baseline:e.auxiliaryRange||""}}static transformDefinition(e,t){let i,o;return e.baseline&&(i=ms(Bi(e.baseline),t)),e.keyValue&&(o=ms(Bi(e.keyValue),t)),{...e,baseline:i?Wi(i):void 0,keyValue:o?Wi(o):void 0}}copyForSheetId(e){const t=bs(this.sheetId,e,this.baseline),i=bs(this.sheetId,e,this.keyValue),o=this.getDefinitionWithSpecificRanges(t,i,e);return new gr(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,e);return new gr(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue)}getContextCreation(){return{background:this.background,title:this.title,range:this.keyValue?[this.getters.getRangeString(this.keyValue,this.sheetId)]:void 0,auxiliaryRange:this.baseline?this.getters.getRangeString(this.baseline,this.sheetId):void 0}}getDefinitionWithSpecificRanges(e,t,i){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:"scorecard",background:this.background,baseline:e?this.getters.getRangeString(e,i||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,i||this.sheetId):void 0}}getDefinitionForExcel(){}updateRanges(e){const t=Cs(this.baseline,e),i=Cs(this.keyValue,e);if(this.baseline===t&&this.keyValue===i)return this;const o=this.getDefinitionWithSpecificRanges(t,i);return new gr(o,this.sheetId,this.getters)}}const pr=new Ro;pr.add("bar",{match:e=>"bar"===e,createChart:(e,t,i)=>new Zs(e,t,i),getChartRuntime:function(e,t){let i=$s(t,e.dataSets,e.labelRange).formattedValues,o=Gs(t,e.dataSets);({labels:i,dataSetsValues:o}=Vs(i,o)),e.aggregated&&({labels:i,dataSetsValues:o}=zs(i,o));const n=function(e,t,i){var o;const n=Rs(e.background),s=Hs(e,t,n,i),r={labels:{fontColor:n}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,s.options.legend={...null===(o=s.options)||void 0===o?void 0:o.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:n}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:n,beginAtZero:!0,callback:e=>i?fi(e,i):(null==e?void 0:e.toLocaleString())||e}}]},e.stacked&&(s.options.scales.xAxes[0].stacked=!0,s.options.scales.yAxes[0].stacked=!0),s}(e,i,Ws(t,e.dataSets)),s=new Is;for(let{label:e,data:t}of o){const i=s.next(),o={label:e,data:t,borderColor:i,backgroundColor:i};n.data.datasets.push(o)}return{chartJsConfig:n,background:e.background||w}},validateChartDefinition:(e,t)=>Zs.validateChartDefinition(e,t),transformDefinition:(e,t)=>Zs.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Zs.getDefinitionFromContextCreation(e),name:s("Bar"),sequence:10}),pr.add("line",{match:e=>"line"===e,createChart:(e,t,i)=>new nr(e,t,i),getChartRuntime:function(e,t){const i=rr(e,t),o=$s(t,e.dataSets,e.labelRange);let n="linear"===i?o.values:o.formattedValues,s=Gs(t,e.dataSets);({labels:n,dataSetsValues:s}=Vs(n,s)),"time"===i&&({labels:n,dataSetsValues:s}=function(e,t){if(0===e.length||e.every((e=>!e)))return{labels:e,dataSetsValues:t};const i=[...e],o=Fe(t);for(let e=0;e<i.length;e++)if(!i[e]){i[e]=lt(i,e);for(let t of o)t.data[e]=void 0}return{labels:i,dataSetsValues:o}}(n,s)),e.aggregated&&({labels:n,dataSetsValues:s}=zs(n,s));const r=Ws(t,e.dataSets),a=function(e,t,i){var o;const n=Rs(e.background),s=Hs(e,t,n,i),r={labels:{fontColor:n,generateLabels(e){const{data:t}=e,i=window.Chart.defaults.global.legend.labels.generateLabels(e);for(const[e,o]of i.entries())o.fillStyle=t.datasets[e].borderColor;return i}}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,s.options.legend={...null===(o=s.options)||void 0===o?void 0:o.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:n}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:n,beginAtZero:!0,callback:e=>i?fi(e,i):(null==e?void 0:e.toLocaleString())||e}}]},e.stacked&&(s.options.scales.yAxes[0].stacked=!0),s}(e,n,r),l=function(e,t){if(t)return e.getEvaluatedCell({sheetId:t.sheetId,col:t.zone.left,row:t.zone.top}).format}(t,e.labelRange);"time"===i?(a.options.scales.xAxes[0].type="time",a.options.scales.xAxes[0].time=or(n,l),a.options.scales.xAxes[0].ticks.maxTicksLimit=15):"linear"===i&&(a.options.scales.xAxes[0].type="linear",a.options.scales.xAxes[0].ticks.callback=e=>fi(e,l),a.options.tooltips.callbacks.title=e=>{var t;return fi((null===(t=e[0])||void 0===t?void 0:t.xLabel)||"",l)});const c=new Is;for(let[t,{label:o,data:r}]of s.entries()){["linear","time"].includes(i)&&(r=r.map(((e,t)=>({x:n[t]||void 0,y:e}))));const s=c.next();let l=At(s);if(e.stacked&&(l.a=ne),e.cumulative){let e=0;r=r.map((t=>isNaN(t)?t:(e+=parseFloat(t),e)))}const h={label:o,data:r,lineTension:0,borderColor:s,backgroundColor:Tt(l),pointBackgroundColor:s,fill:!!e.stacked&&qs(t)};a.data.datasets.push(h)}return{chartJsConfig:a,background:e.background||w}},validateChartDefinition:(e,t)=>nr.validateChartDefinition(e,t),transformDefinition:(e,t)=>nr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>nr.getDefinitionFromContextCreation(e),name:s("Line"),sequence:20}),pr.add("pie",{match:e=>"pie"===e,createChart:(e,t,i)=>new cr(e,t,i),getChartRuntime:function(e,t){let i=$s(t,e.dataSets,e.labelRange).formattedValues,o=Gs(t,e.dataSets);({labels:i,dataSetsValues:o}=Vs(i,o)),e.aggregated&&({labels:i,dataSetsValues:o}=zs(i,o));const n=function(e,t,i){var o;const n=Rs(e.background),s=Hs(e,t,n,i),r={labels:{fontColor:n}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,s.options.legend={...null===(o=s.options)||void 0===o?void 0:o.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.tooltips.callbacks.title=function(e,t){return t.datasets[e[0].datasetIndex].label},s}(e,i,Ws(t,e.dataSets)),s=new Is;for(let{label:e,data:t}of o){const i={label:e,data:t,borderColor:"#FFFFFF",backgroundColor:hr(s,o)};n.data.datasets.push(i)}return{chartJsConfig:n,background:e.background||w}},validateChartDefinition:(e,t)=>cr.validateChartDefinition(e,t),transformDefinition:(e,t)=>cr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>cr.getDefinitionFromContextCreation(e),name:s("Pie"),sequence:30}),pr.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,i)=>new gr(e,t,i),getChartRuntime:function(e,t){let i,o,s="",r="";if(e.keyValue){const o={sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top};i=t.getEvaluatedCell(o),s=String(i.value),r=i.formattedValue}const a=e.baseline;if(a){const i={sheetId:e.baseline.sheetId,col:e.baseline.zone.left,row:e.baseline.zone.top};o=t.getEvaluatedCell(i)}const{background:l,fontColor:c}=t.getStyleOfSingleCellChart(e.background,e.keyValue);return{title:n(e.title),keyValue:r||s,baselineDisplay:Ms(o,i,e.baselineMode),baselineArrow:Ns(o,i,e.baselineMode),baselineColor:Os(o,e.baselineMode,i,e.baselineColorUp,e.baselineColorDown),baselineDescr:e.baselineDescr?n(e.baselineDescr):"",fontColor:c,background:l,baselineStyle:"percentage"!==e.baselineMode&&a?t.getCellStyle({sheetId:a.sheetId,col:a.zone.left,row:a.zone.top}):void 0,keyValueStyle:e.keyValue?t.getCellStyle({sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top}):void 0}},validateChartDefinition:(e,t)=>gr.validateChartDefinition(e,t),transformDefinition:(e,t)=>gr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>gr.getDefinitionFromContextCreation(e),name:s("Scorecard"),sequence:40}),pr.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,i)=>new Js(e,t,i),getChartRuntime:function(e,t){const i=function(e){const t=Hs(e,[],Rs(e.background));return t.options.hover=void 0,t.options.events=[],t.options.layout={padding:{left:30,right:30,top:e.title?10:25,bottom:25}},t.options.needle={radiusPercentage:2,widthPercentage:3.2,lengthPercentage:80,color:"#000000"},t.options.valueLabel={display:!1,formatter:null,color:"#FFFFFF",backgroundColor:"#000000",fontSize:30,borderRadius:5,padding:{top:5,right:5,bottom:5,left:5},bottomMarginPercentage:5},t}(e),o=e.sectionRule.colors,n=e.sectionRule.lowerInflectionPoint,s=e.sectionRule.upperInflectionPoint,r=Number(n.value),a=Number(s.value),l=Number(e.sectionRule.rangeMin),c=Number(e.sectionRule.rangeMax),h=c-l,d=[];if(""!==n.value){const e="number"===n.type?r:l+h*r/100;d.push({value:Le(e,l,c),color:o.lowerColor})}if(""!==s.value){const e="number"===s.type?a:l+h*a/100;d.push({value:Le(e,l,c),color:o.middleColor})}const u=[],g=[];d.sort(((e,t)=>e.value-t.value)).map((e=>{u.push(e.value),g.push(e.color)})),u.push(c),g.push(o.upperColor);const p=e.dataRange,m=h/30;let f=l-m,v=null,b=!1;if(void 0!==p){const e=t.getEvaluatedCell({sheetId:p.sheetId,col:p.zone.left,row:p.zone.top});e.type===cn.number&&(f=Le(e.value,l-m,c+m),v=()=>t.getRangeFormattedValues(p)[0],b=!0)}return i.options.valueLabel.display=b,i.options.valueLabel.formatter=v,i.data.datasets.push({data:u,minValue:Number(e.sectionRule.rangeMin),value:f,backgroundColor:g}),{chartJsConfig:i,background:t.getStyleOfSingleCellChart(e.background,p).background}},validateChartDefinition:(e,t)=>Js.validateChartDefinition(e,t),transformDefinition:(e,t)=>Js.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Js.getDefinitionFromContextCreation(e),name:s("Gauge"),sequence:50});const mr=new Ro;mr.add("line",po),mr.add("bar",po),mr.add("pie",po),mr.add("gauge",po),mr.add("scorecard",yo);const fr=new Ro;vo`
344
+ `;class hs extends t.Component{constructor(){super(...arguments),this.menuItems=cs.getMenuItems(),this.link=t.useState(this.defaultState),this.menu=t.useState({isOpen:!1}),this.linkEditorRef=t.useRef("linkEditor"),this.position=Yn(this.linkEditorRef),this.urlInput=t.useRef("urlInput")}setup(){t.onMounted((()=>{var e;return null===(e=this.urlInput.el)||void 0===e?void 0:e.focus()}))}get defaultState(){const{col:e,row:t}=this.props.cellPosition,i=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getEvaluatedCell({sheetId:i,col:e,row:t});return o.link?{url:o.link.url,label:o.formattedValue,isUrlEditable:o.link.isUrlEditable}:{label:o.formattedValue,url:"",isUrlEditable:!0}}get menuPosition(){return{x:this.position.x+320-12-2,y:this.position.y+100}}onSpecialLink(e){const{detail:t}=e,i=Do(t);i&&(this.link.url=i.url,this.link.label=i.label,this.link.isUrlEditable=i.isUrlEditable)}getUrlRepresentation(e){return _o(e,this.env.model.getters)}openMenu(){this.menu.isOpen=!0}removeLink(){this.link.url="",this.link.isUrlEditable=!0}save(){var e,t;const{col:i,row:o}=this.props.cellPosition,n=this.link.label||this.link.url;this.env.model.dispatch("UPDATE_CELL",{col:i,row:o,sheetId:this.env.model.getters.getActiveSheetId(),content:Ke(n,this.link.url)}),null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}cancel(){var e,t;null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}onKeyDown(e){switch(e.key){case"Enter":this.link.url&&this.save(),e.stopPropagation();break;case"Escape":this.cancel(),e.stopPropagation()}}}hs.template="o-spreadsheet-LinkEditor",hs.components={Menu:is};const ds={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:hs,cellCorner:"BottomLeft"})};hs.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const us=new Ro;function gs(e){return 8===(e=wt(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}us.add("ErrorToolTip",Ln).add("LinkCell",ns).add("LinkEditor",ds).add("FilterMenu",zn);class ps{constructor(e,t,i){this.title=e.title,this.sheetId=t,this.getters=i}static validateChartDefinition(e,t){throw new Error("This method should be implemented by sub class")}static transformDefinition(e,t){throw new Error("This method should be implemented by sub class")}static getDefinitionFromContextCreation(e){throw new Error("This method should be implemented by sub class")}}function ms(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?ji(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?Gi(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}function fs(e,t,i,o){let n=!1;const s=[];for(let o in i){let r=i[o];if(r.labelCell){const e=Cs(r.labelCell,t);r.labelCell!==e&&(n=!0,r={...r,labelCell:e})}const a=Cs(r.dataRange,t);void 0===a||e.getRangeString(a,a.sheetId)===K?(n=!0,r=void 0):a!==r.dataRange&&(n=!0,r={...r,dataRange:a}),s[o]=r}let r=o;const a=Cs(r,t);a!==r&&(n=!0,r=a);return{isStale:n,dataSets:s.filter(ot),labelRange:r}}function vs(e,t,i){return i.map((i=>({dataRange:Li(e,t,i.dataRange),labelCell:i.labelCell?Li(e,t,i.labelCell):void 0})))}function bs(e,t,i){return i?Li(e,t,i):void 0}function Cs(e,t){if(!e)return;const i=t(e);switch(i.changeType){case"NONE":return e;case"REMOVE":return;default:return i.range}}function Ss(e,t,i,o){const n=[];for(const s of t){const t=e.getRangeFromSheetXC(i,s),{unboundedZone:r,sheetId:a,invalidSheetName:l}=t;if(!l)if(r.left!==r.right&&r.top!==r.bottom){if(void 0===r.right)continue;for(let t=r.left;t<=r.right;t++){const i={...r,left:t,right:t};n.push(Es(e,a,i,o?{top:i.top,bottom:i.top,left:i.left,right:i.left}:void 0))}}else r.left===r.right&&r.top===r.bottom?o||n.push(Es(e,a,r,void 0)):n.push(Es(e,a,r,o?{top:r.top,bottom:r.top,left:r.left,right:r.left}:void 0))}return n}function Es(e,t,i,o){if(i.left!==i.right&&i.top!==i.bottom)throw new Error(`Zone should be a single column or row: ${Wi(i)}`);if(o){const n=Wi(i),s=Wi(o);return{labelCell:e.getRangeFromSheetXC(t,s),dataRange:e.getRangeFromSheetXC(t,n)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,Wi(i))}}function ws(e,t){var i;const o=null===(i=t.labelCell)||void 0===i?void 0:i.zone;let n=t.dataRange.zone;if(o){const{numberOfRows:e,numberOfCols:t}=oo(n);1===e?n={...n,left:n.left+1}:1===t&&(n={...n,top:n.top+1})}const s=t.dataRange.clone({zone:n});return{label:t.labelCell?e.getRangeString(t.labelCell,"forceSheetReference"):void 0,range:e.getRangeString(s,"forceSheetReference")}}function ys(e,t){let i;if(e.labelRange){const o=ms(Bi(e.labelRange),t);i=o?Wi(o):void 0}const o=e.dataSets.map(Bi).map((e=>ms(e,t))).filter(ot).map(Wi);return{...e,labelRange:i,dataSets:o}}const xs=["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 Is{constructor(){this.graphColorIndex=0}next(){return xs[this.graphColorIndex++%xs.length]}}function Rs(e){return e&&Rt(e)<.3?"#FFFFFF":"#000000"}function Ts(e){if(e.dataSets){const t=void 0!==e.dataSets.find((e=>!Pt.test(e)));if(t)return 33;if(e.dataSets.map(Bi).some((e=>e.top!==e.bottom&&ho(e))))return 33}return 0}function As(e){if(e.labelRange){if(!Pt.test(e.labelRange||""))return 34}return 0}function Ms(e,t,i){if(e){if("text"===i||(null==t?void 0:t.type)!==cn.number||e.type!==cn.number)return e.formattedValue;{let o=t.value-e.value;if("percentage"===i&&0!==o&&(o=o/e.value*100),"percentage"!==i&&e.format)return fi(o,e.format);const n=Math.abs(parseFloat(o.toFixed(2))).toLocaleString();return"percentage"===i?n+"%":n}}return""}function Os(e,t,i,o,n){if("text"===t||(null==e?void 0:e.type)!==cn.number||(null==i?void 0:i.type)!==cn.number)return;const s=i.value-e.value;return s>0?o:s<0?n:void 0}function Ns(e,t,i){if("text"===i||(null==e?void 0:e.type)!==cn.number||(null==t?void 0:t.type)!==cn.number)return"neutral";const o=t.value-e.value;return o>0?"up":o<0?"down":"neutral"}const _s={Errors:{25:s("The range is invalid"),52:s("The argument is missing. Please provide a value"),53:s("The second argument is missing. Please provide a value"),54:s("The minpoint must be a number"),55:s("The midpoint must be a number"),56:s("The maxpoint must be a number"),57:s("The first value must be a number"),58:s("The second value must be a number"),48:s("Minimum must be smaller then Maximum"),51:s("Minimum must be smaller then Midpoint"),50:s("Midpoint must be smaller then Maximum"),49:s("Lower inflection point must be smaller than upper inflection point"),59:s("Invalid Minpoint formula"),61:s("Invalid Maxpoint formula"),60:s("Invalid Midpoint formula"),62:s("Invalid upper inflection point formula"),63:s("Invalid lower inflection point formula"),24:s("A range needs to be defined"),Unexpected:s("The rule is invalid for an unknown reason")},ColorScale:s("Color scale"),IconSet:s("Icon set")},Fs={IsEmpty:s("Is empty"),IsNotEmpty:s("Is not empty"),ContainsText:s("Contains"),NotContains:s("Does not contain"),BeginsWith:s("Starts with"),EndsWith:s("Ends with"),Equal:s("Is equal to"),NotEqual:s("Is not equal to"),GreaterThan:s("Is greater than"),GreaterThanOrEqual:s("Is greater than or equal to"),LessThan:s("Is less than"),LessThanOrEqual:s("Is less than or equal to"),Between:s("Is between"),NotBetween:s("Is not between")},Ds={Series:s("Series"),Errors:{Unexpected:s("The chart definition is invalid for an unknown reason"),33:s("The dataset is invalid"),34:s("Labels are invalid"),35:s("The key value is invalid"),36:s("The baseline value is invalid"),37:s("The data range is invalid"),38:s("A minimum range limit value is needed"),39:s("The minimum range limit value must be a number"),40:s("A maximum range limit value is needed"),41:s("The maximum range limit value must be a number"),42:s("Minimum range limit must be smaller than maximum range limit"),43:s("The lower inflection point value must be a number"),44:s("The upper inflection point value must be a number")}},ks={Automatic:s("Automatic"),Number:s("Number"),Percent:s("Percent"),Currency:s("Currency"),CurrencyRounded:s("Currency rounded"),Date:s("Date"),Time:s("Time"),DateTime:s("Date time"),Duration:s("Duration"),CustomCurrency:s("Custom currency")},Ls={Custom:s("Custom")},Ps=s("Merged cells are preventing this operation. Unmerge those cells and try again.");function Us(e,t){if(t.dataRange){const i=t.labelCell?[Wi(t.labelCell.zone)]:[],o=to([Wi(t.dataRange.zone)],i)[0];if(void 0===o)return[];const n=e.getRangeFromSheetXC(t.dataRange.sheetId,o);return e.getRangeValues(n).map((e=>""===e?void 0:e))}return[]}function Vs(e,t){const i=$e(0,Math.max(e.length,...t.map((e=>{var t;return(null===(t=e.data)||void 0===t?void 0:t.length)||0})))).filter((i=>{const o=e[i],n=t.map((e=>{var t;return null===(t=e.data)||void 0===t?void 0:t[i]}));return o||n.some((e=>0===e||Boolean(e)))}));return{labels:i.map((t=>e[t]||"")),dataSetsValues:t.map((e=>({...e,data:i.map((t=>e.data[t]))})))}}function zs(e,t){const i=new Set(e),o={};i.forEach((e=>{o[e]=new Array(t.length).fill(0)}));for(const i of $e(0,e.length)){const s=e[i];for(const e of $e(0,t.length))o[s][e]+="number"==typeof(n=t[e].data[i])?n:0}var n;return{labels:Object.keys(o),dataSetsValues:t.map(((e,t)=>({...e,data:Object.values(o).map((e=>e[t]))})))}}function Bs(e){return e?e.length>J?e.substring(0,J)+"…":e:""}function Hs(e,t,i,o){return{type:e.type,options:{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:n(e.title),fontColor:i},legend:{onClick:void 0},tooltips:{callbacks:{label:function(e,t){var i,n,s,r,a;let l=null===(n=null===(i=t.datasets)||void 0===i?void 0:i[e.datasetIndex||0])||void 0===n?void 0:n.label;const c=""!==e.yLabel?e.yLabel:null===(a=null===(r=null===(s=t.datasets)||void 0===s?void 0:s[e.datasetIndex||0])||void 0===r?void 0:r.data)||void 0===a?void 0:a[e.index||0],h=o&&"number"==typeof c?fi(c,o):(null==c?void 0:c.toLocaleString())||"";return l?`${l}: ${h}`:h}}}},data:{labels:t.map(Bs),datasets:[]}}}function $s(e,t,i){let o={values:[],formattedValues:[]};if(i)i.invalidXc||i.invalidSheetName||(o={formattedValues:e.getRangeFormattedValues(i),values:e.getRangeValues(i).map((e=>String(e)))});else if(1===t.length)for(let i=0;i<Us(e,t[0]).length;i++)o.formattedValues.push(""),o.values.push("");else if(t[0]){o={formattedValues:$e(0,Us(e,t[0]).length).map((e=>e.toString())),values:o.formattedValues}}return o}function Ws(e,t){for(const i of t){const t=e.getRangeFormats(i.dataRange).find((e=>void 0!==e&&!wi(e)));if(t)return t}}function Gs(e,t){const i=[];for(const[o,n]of Object.entries(t)){let t;if(n.labelCell){const i=n.labelCell,s=i?e.getEvaluatedCell({sheetId:i.sheetId,col:i.zone.left,row:i.zone.top}):void 0;t=s&&i?Bs(s.formattedValue):t=`${Ds.Series} ${parseInt(o)+1}`}else t=t=`${Ds.Series} ${parseInt(o)+1}`;let s=n.dataRange?Us(e,n):[];i.push({data:s,label:t})}return i}function qs(e){return 0===e?"origin":e-1}class Zs extends ps{constructor(e,t,i){super(e,t,i),this.type="bar",this.dataSets=Ss(i,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Pi(i,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated}static transformDefinition(e,t){return ys(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,Ts,As)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,stacked:!1,aggregated:!1,legendPosition:"top",title:e.title||"",type:"bar",verticalAxisPosition:"left",labelRange:e.auxiliaryRange||void 0}}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}copyForSheetId(e){const t=vs(this.sheetId,e,this.dataSets),i=bs(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,i,e);return new Zs(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Zs(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,i){return{type:"bar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated}}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>ws(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:gs(this.background||w),fontColor:gs(Rs(this.background)),dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:o}=fs(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const n=this.getDefinitionWithSpecificDataSets(t,i);return new Zs(n,this.sheetId,this.getters)}}function js(e){return e.dataRange&&!Pt.test(e.dataRange)?37:0}function Ys(e,t){return t((t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):0),(t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):0))}function Xs(e){return e.sectionRule&&Number(e.sectionRule.rangeMin)>=Number(e.sectionRule.rangeMax)?42:0}function Ks(e,t){if(""===e)switch(t){case"rangeMin":return 38;case"rangeMax":return 40}return 0}function Qs(e,t){if(isNaN(e))switch(t){case"rangeMin":return 39;case"rangeMax":return 41;case"lowerInflectionPointValue":return 43;case"upperInflectionPointValue":return 44}return 0}class Js extends ps{constructor(e,t,i){super(e,t,i),this.type="gauge",this.dataRange=Pi(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,js,e.chainValidations(Ys(Ks,e.batchValidations),Ys(Qs,e.batchValidations),Xs),e.chainValidations((i=Qs,(0,e.batchValidations)((e=>e.sectionRule?i(e.sectionRule.lowerInflectionPoint.value,"lowerInflectionPointValue"):0),(e=>e.sectionRule?i(e.sectionRule.upperInflectionPoint.value,"upperInflectionPointValue"):0)))));var i}static transformDefinition(e,t){let i;return e.dataRange&&(i=ms(Bi(e.dataRange),t)),{...e,dataRange:i?Wi(i):void 0}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||"",type:"gauge",dataRange:e.range?e.range[0]:void 0,sectionRule:{colors:{lowerColor:"#cc0000",middleColor:"#f1c232",upperColor:"#6aa84f"},rangeMin:"0",rangeMax:"100",lowerInflectionPoint:{type:"percentage",value:"15"},upperInflectionPoint:{type:"percentage",value:"40"}}}}copyForSheetId(e){const t=bs(this.sheetId,e,this.dataRange),i=this.getDefinitionWithSpecificRanges(t,e);return new Js(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.dataRange,e);return new Js(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.dataRange)}getDefinitionWithSpecificRanges(e,t){return{background:this.background,sectionRule:this.sectionRule,title:this.title,type:"gauge",dataRange:e?this.getters.getRangeString(e,t||this.sheetId):void 0}}getDefinitionForExcel(){}getContextCreation(){return{background:this.background,title:this.title,range:this.dataRange?[this.getters.getRangeString(this.dataRange,this.sheetId)]:void 0}}updateRanges(e){const t=Cs(this.dataRange,e);if(this.dataRange===t)return this;const i=this.getDefinitionWithSpecificRanges(t);return new Js(i,this.sheetId,this.getters)}}const er={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},tr={inSeconds:function(e){return Math.floor(e/er.second)},inMinutes:function(e){return Math.floor(e/er.minute)},inHours:function(e){return Math.floor(e/er.hour)},inDays:function(e){return Math.floor(e/er.day)},inMonths:function(e){return Math.floor(e/er.month)},inYears:function(e){return Math.floor(e/er.year)}},ir=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function or(e,t){const i=function(e){const t=(e=(e=e.replace(/y/g,"Y")).replace(/d/g,"D")).indexOf("h");e=t>=0?e.slice(0,t).replace(/m/g,"M")+e.slice(t):e.replace(/m/g,"M");e.includes("a")||(e=e.replace(/h/g,"H"));return e}(t),o=function(e,t){const i=e.map((e=>{var t;return null===(t=we(e))||void 0===t?void 0:t.jsDate}));if(i.some((e=>void 0===e))||e.length<2)return;const o=i.map((e=>e.getTime())),n=Math.max(...o)-Math.min(...o),s=function(e){if(e.includes("s"))return"second";if(e.includes("m"))return"minute";if(e.includes("h")||e.includes("H"))return"hour";if(e.includes("D"))return"day";if(e.includes("M"))return"month";return"year"}(t);if(er.second>=er[s]&&tr.inSeconds(n)<180)return"second";if(er.minute>=er[s]&&tr.inMinutes(n)<180)return"minute";if(er.hour>=er[s]&&tr.inHours(n)<96)return"hour";if(er.day>=er[s]&&tr.inDays(n)<90)return"day";if(er.month>=er[s]&&tr.inMonths(n)<36)return"month";return"year"}(e,i),n={};return o&&(n[o]=i),{parser:i,displayFormats:n,unit:o}}class nr extends ps{constructor(e,t,i){super(e,t,i),this.type="line",this.dataSets=Ss(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Pi(this.getters,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.stacked=e.stacked,this.aggregated=e.aggregated,this.cumulative=e.cumulative}static validateChartDefinition(e,t){return e.checkValidations(t,Ts,As)}static transformDefinition(e,t){return ys(e,t)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,labelsAsText:!1,legendPosition:"top",title:e.title||"",type:"line",verticalAxisPosition:"left",labelRange:e.auxiliaryRange||void 0,stacked:!1,aggregated:!1,cumulative:!1}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,i){return{type:"line",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,stacked:this.stacked,aggregated:this.aggregated,cumulative:this.cumulative}}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:o}=fs(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const n=this.getDefinitionWithSpecificDataSets(t,i);return new nr(n,this.sheetId,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>ws(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:gs(this.background||w),fontColor:gs(Rs(this.background)),dataSets:e}}copyForSheetId(e){const t=vs(this.sheetId,e,this.dataSets),i=bs(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,i,e);return new nr(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new nr(t,e,this.getters)}}function sr(e,t){return ar(e,t)||lr(e,t)}function rr(e,t){return function(e,t){return!e.labelsAsText&&ar(e.labelRange,t)}(e,t)?"time":function(e,t){return!e.labelsAsText&&lr(e.labelRange,t)}(e,t)?"linear":"category"}function ar(e,t){if(!e||!lr(e,t))return!1;const i=t.getEvaluatedCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}).format;return Boolean(i&&ir.test(i))}function lr(e,t){if(!e)return!1;const i=t.getRangeValues(e);return!i.some((e=>isNaN(Number(e))&&e))&&!i.every((e=>!e))}class cr extends ps{constructor(e,t,i){super(e,t,i),this.type="pie",this.dataSets=Ss(i,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Pi(i,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated}static transformDefinition(e,t){return ys(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,Ts,As)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,legendPosition:"top",title:e.title||"",type:"pie",labelRange:e.auxiliaryRange||void 0,aggregated:!1}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,i){return{type:"pie",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,aggregated:this.aggregated}}copyForSheetId(e){const t=vs(this.sheetId,e,this.dataSets),i=bs(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,i,e);return new cr(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new cr(t,e,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>ws(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:gs(this.background||w),fontColor:gs(Rs(this.background)),verticalAxisPosition:"left",dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:o}=fs(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const n=this.getDefinitionWithSpecificDataSets(t,i);return new cr(n,this.sheetId,this.getters)}}function hr(e,t){const i=[],o=Math.max(...t.map((e=>e.data.length)));for(let t=0;t<=o;t++)i.push(e.next());return i}function dr(e){return e.keyValue&&!Pt.test(e.keyValue)?35:0}function ur(e){return e.baseline&&!Pt.test(e.baseline)?36:0}class gr extends ps{constructor(e,t,i){super(e,t,i),this.type="scorecard",this.keyValue=Pi(i,t,e.keyValue),this.baseline=Pi(i,t,e.baseline),this.baselineMode=e.baselineMode,this.baselineDescr=e.baselineDescr,this.background=e.background,this.baselineColorUp=e.baselineColorUp,this.baselineColorDown=e.baselineColorDown}static validateChartDefinition(e,t){return e.checkValidations(t,dr,ur)}static getDefinitionFromContextCreation(e){return{background:e.background,type:"scorecard",keyValue:e.range?e.range[0]:void 0,title:e.title||"",baselineMode:te,baselineColorUp:ie,baselineColorDown:oe,baseline:e.auxiliaryRange||""}}static transformDefinition(e,t){let i,o;return e.baseline&&(i=ms(Bi(e.baseline),t)),e.keyValue&&(o=ms(Bi(e.keyValue),t)),{...e,baseline:i?Wi(i):void 0,keyValue:o?Wi(o):void 0}}copyForSheetId(e){const t=bs(this.sheetId,e,this.baseline),i=bs(this.sheetId,e,this.keyValue),o=this.getDefinitionWithSpecificRanges(t,i,e);return new gr(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,e);return new gr(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue)}getContextCreation(){return{background:this.background,title:this.title,range:this.keyValue?[this.getters.getRangeString(this.keyValue,this.sheetId)]:void 0,auxiliaryRange:this.baseline?this.getters.getRangeString(this.baseline,this.sheetId):void 0}}getDefinitionWithSpecificRanges(e,t,i){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:"scorecard",background:this.background,baseline:e?this.getters.getRangeString(e,i||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,i||this.sheetId):void 0}}getDefinitionForExcel(){}updateRanges(e){const t=Cs(this.baseline,e),i=Cs(this.keyValue,e);if(this.baseline===t&&this.keyValue===i)return this;const o=this.getDefinitionWithSpecificRanges(t,i);return new gr(o,this.sheetId,this.getters)}}const pr=new Ro;pr.add("bar",{match:e=>"bar"===e,createChart:(e,t,i)=>new Zs(e,t,i),getChartRuntime:function(e,t){let i=$s(t,e.dataSets,e.labelRange).formattedValues,o=Gs(t,e.dataSets);({labels:i,dataSetsValues:o}=Vs(i,o)),e.aggregated&&({labels:i,dataSetsValues:o}=zs(i,o));const n=function(e,t,i){var o;const n=Rs(e.background),s=Hs(e,t,n,i),r={labels:{fontColor:n}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,s.options.legend={...null===(o=s.options)||void 0===o?void 0:o.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:n}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:n,beginAtZero:!0,callback:e=>i?fi(e,i):(null==e?void 0:e.toLocaleString())||e}}]},e.stacked&&(s.options.scales.xAxes[0].stacked=!0,s.options.scales.yAxes[0].stacked=!0),s}(e,i,Ws(t,e.dataSets)),s=new Is;for(let{label:e,data:t}of o){const i=s.next(),o={label:e,data:t,borderColor:i,backgroundColor:i};n.data.datasets.push(o)}return{chartJsConfig:n,background:e.background||w}},validateChartDefinition:(e,t)=>Zs.validateChartDefinition(e,t),transformDefinition:(e,t)=>Zs.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Zs.getDefinitionFromContextCreation(e),name:s("Bar"),sequence:10}),pr.add("line",{match:e=>"line"===e,createChart:(e,t,i)=>new nr(e,t,i),getChartRuntime:function(e,t){const i=rr(e,t),o=$s(t,e.dataSets,e.labelRange);let n="linear"===i?o.values:o.formattedValues,s=Gs(t,e.dataSets);({labels:n,dataSetsValues:s}=Vs(n,s)),"time"===i&&({labels:n,dataSetsValues:s}=function(e,t){if(0===e.length||e.every((e=>!e)))return{labels:e,dataSetsValues:t};const i=[...e],o=Fe(t);for(let e=0;e<i.length;e++)if(!i[e]){i[e]=lt(i,e);for(let t of o)t.data[e]=void 0}return{labels:i,dataSetsValues:o}}(n,s)),e.aggregated&&({labels:n,dataSetsValues:s}=zs(n,s));const r=Ws(t,e.dataSets),a=function(e,t,i){var o;const n=Rs(e.background),s=Hs(e,t,n,i),r={labels:{fontColor:n,generateLabels(e){const{data:t}=e,i=window.Chart.defaults.global.legend.labels.generateLabels(e);for(const[e,o]of i.entries())o.fillStyle=t.datasets[e].borderColor;return i}}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,s.options.legend={...null===(o=s.options)||void 0===o?void 0:o.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:n}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:n,beginAtZero:!0,callback:e=>i?fi(e,i):(null==e?void 0:e.toLocaleString())||e}}]},e.stacked&&(s.options.scales.yAxes[0].stacked=!0),s}(e,n,r),l=function(e,t){if(t)return e.getEvaluatedCell({sheetId:t.sheetId,col:t.zone.left,row:t.zone.top}).format}(t,e.labelRange);"time"===i?(a.options.scales.xAxes[0].type="time",a.options.scales.xAxes[0].time=or(n,l),a.options.scales.xAxes[0].ticks.maxTicksLimit=15):"linear"===i&&(a.options.scales.xAxes[0].type="linear",a.options.scales.xAxes[0].ticks.callback=e=>fi(e,l),a.options.tooltips.callbacks.title=e=>{var t;return fi((null===(t=e[0])||void 0===t?void 0:t.xLabel)||"",l)});const c=new Is;for(let[t,{label:o,data:r}]of s.entries()){["linear","time"].includes(i)&&(r=r.map(((e,t)=>({x:n[t]||void 0,y:e}))));const s=c.next();let l=At(s);if(e.stacked&&(l.a=ne),e.cumulative){let e=0;r=r.map((t=>isNaN(t)?t:(e+=parseFloat(t),e)))}const h={label:o,data:r,lineTension:0,borderColor:s,backgroundColor:Tt(l),pointBackgroundColor:s,fill:!!e.stacked&&qs(t)};a.data.datasets.push(h)}return{chartJsConfig:a,background:e.background||w}},validateChartDefinition:(e,t)=>nr.validateChartDefinition(e,t),transformDefinition:(e,t)=>nr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>nr.getDefinitionFromContextCreation(e),name:s("Line"),sequence:20}),pr.add("pie",{match:e=>"pie"===e,createChart:(e,t,i)=>new cr(e,t,i),getChartRuntime:function(e,t){let i=$s(t,e.dataSets,e.labelRange).formattedValues,o=Gs(t,e.dataSets);({labels:i,dataSetsValues:o}=Vs(i,o)),e.aggregated&&({labels:i,dataSetsValues:o}=zs(i,o));const n=function(e,t,i){var o;const n=Rs(e.background),s=Hs(e,t,n,i),r={labels:{fontColor:n}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,s.options.legend={...null===(o=s.options)||void 0===o?void 0:o.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.tooltips.callbacks.title=function(e,t){return t.datasets[e[0].datasetIndex].label},s}(e,i,Ws(t,e.dataSets)),s=new Is;for(let{label:e,data:t}of o){const i={label:e,data:t,borderColor:"#FFFFFF",backgroundColor:hr(s,o)};n.data.datasets.push(i)}return{chartJsConfig:n,background:e.background||w}},validateChartDefinition:(e,t)=>cr.validateChartDefinition(e,t),transformDefinition:(e,t)=>cr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>cr.getDefinitionFromContextCreation(e),name:s("Pie"),sequence:30}),pr.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,i)=>new gr(e,t,i),getChartRuntime:function(e,t){let i,o,s="",r="";if(e.keyValue){const o={sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top};i=t.getEvaluatedCell(o),s=String(i.value),r=i.formattedValue}const a=e.baseline;if(a){const i={sheetId:e.baseline.sheetId,col:e.baseline.zone.left,row:e.baseline.zone.top};o=t.getEvaluatedCell(i)}const{background:l,fontColor:c}=t.getStyleOfSingleCellChart(e.background,e.keyValue);return{title:n(e.title),keyValue:r||s,baselineDisplay:Ms(o,i,e.baselineMode),baselineArrow:Ns(o,i,e.baselineMode),baselineColor:Os(o,e.baselineMode,i,e.baselineColorUp,e.baselineColorDown),baselineDescr:e.baselineDescr?n(e.baselineDescr):"",fontColor:c,background:l,baselineStyle:"percentage"!==e.baselineMode&&a?t.getCellStyle({sheetId:a.sheetId,col:a.zone.left,row:a.zone.top}):void 0,keyValueStyle:e.keyValue?t.getCellStyle({sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top}):void 0}},validateChartDefinition:(e,t)=>gr.validateChartDefinition(e,t),transformDefinition:(e,t)=>gr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>gr.getDefinitionFromContextCreation(e),name:s("Scorecard"),sequence:40}),pr.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,i)=>new Js(e,t,i),getChartRuntime:function(e,t){const i=function(e){const t=Hs(e,[],Rs(e.background));return t.options.hover=void 0,t.options.events=[],t.options.layout={padding:{left:30,right:30,top:e.title?10:25,bottom:25}},t.options.needle={radiusPercentage:2,widthPercentage:3.2,lengthPercentage:80,color:"#000000"},t.options.valueLabel={display:!1,formatter:null,color:"#FFFFFF",backgroundColor:"#000000",fontSize:30,borderRadius:5,padding:{top:5,right:5,bottom:5,left:5},bottomMarginPercentage:5},t}(e),o=e.sectionRule.colors,n=e.sectionRule.lowerInflectionPoint,s=e.sectionRule.upperInflectionPoint,r=Number(n.value),a=Number(s.value),l=Number(e.sectionRule.rangeMin),c=Number(e.sectionRule.rangeMax),h=c-l,d=[];if(""!==n.value){const e="number"===n.type?r:l+h*r/100;d.push({value:Le(e,l,c),color:o.lowerColor})}if(""!==s.value){const e="number"===s.type?a:l+h*a/100;d.push({value:Le(e,l,c),color:o.middleColor})}const u=[],g=[];d.sort(((e,t)=>e.value-t.value)).map((e=>{u.push(e.value),g.push(e.color)})),u.push(c),g.push(o.upperColor);const p=e.dataRange,m=h/30;let f=l-m,v=null,b=!1;if(void 0!==p){const e=t.getEvaluatedCell({sheetId:p.sheetId,col:p.zone.left,row:p.zone.top});e.type===cn.number&&(f=Le(e.value,l-m,c+m),v=()=>t.getRangeFormattedValues(p)[0],b=!0)}return i.options.valueLabel.display=b,i.options.valueLabel.formatter=v,i.data.datasets.push({data:u,minValue:Number(e.sectionRule.rangeMin),value:f,backgroundColor:g}),{chartJsConfig:i,background:t.getStyleOfSingleCellChart(e.background,p).background}},validateChartDefinition:(e,t)=>Js.validateChartDefinition(e,t),transformDefinition:(e,t)=>Js.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Js.getDefinitionFromContextCreation(e),name:s("Gauge"),sequence:50});const mr=new Ro;mr.add("line",po),mr.add("bar",po),mr.add("pie",po),mr.add("gauge",po),mr.add("scorecard",yo);const fr=new Ro;vo`
345
345
  .o-chart-container {
346
346
  width: 100%;
347
347
  height: 100%;
348
348
  position: relative;
349
349
  }
350
- `;class vr extends t.Component{get chartType(){return this.env.model.getters.getChartType(this.props.figure.id)}get chartComponent(){const e=this.chartType,t=mr.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}vr.template="o-spreadsheet-ChartFigure",vr.components={},vr.props={figure:Object,onFigureDeleted:Function};class br extends t.Component{get figureId(){return this.props.figure.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}}function Cr(e,t){const i=Fe(t),o=e.getSheetViewDimension(),n=o.width,s=o.height;if(i.width>n){const e=n/i.width;i.width=n,i.height=i.height*e}if(i.height>s){const e=s/i.height;i.height=s,i.width=i.width*e}return i}br.template="o-spreadsheet-ImageFigure",br.components={},br.props={figure:Object,onFigureDeleted:Function};const Sr=new Ro;function Er(e,t){return{id:"copy",name:s("Copy"),sequence:2,description:"Ctrl+C",action:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("COPY"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function wr(e,t){return{id:"cut",name:s("Cut"),sequence:3,description:"Ctrl+X",action:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("CUT"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function yr(e,t,i){return{id:"delete",name:s("Delete"),sequence:10,action:()=>{i.model.dispatch("DELETE_FIGURE",{sheetId:i.model.getters.getActiveSheetId(),id:e}),t()}}}Sr.add("chart",{Component:vr,SidePanelComponent:"ChartPanel",menuBuilder:function(e,t,i){return ss([{id:"edit",name:s("Edit"),sequence:1,action:()=>{i.model.dispatch("SELECT_FIGURE",{id:e}),i.openSidePanel("ChartPanel")}},Er(e,i),wr(e,i),yr(e,t,i)])}}),Sr.add("image",{Component:br,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t,i){return ss([Er(e,i),wr(e,i),{id:"reset_size",name:s("Reset size"),sequence:4,action:()=>{const t=i.model.getters.getImageSize(e),{height:o,width:n}=Cr(i.model.getters,t);i.model.dispatch("UPDATE_FIGURE",{sheetId:i.model.getters.getActiveSheetId(),id:e,height:o,width:n})}},yr(e,t,i)])}});const xr=(new Ro).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let i=e.base;"after"===e.position&&i++;for(let o=0;o<e.quantity;o++)t.push(o+i);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],i=[...e.elements].sort(((e,t)=>e-t));for(let o of We(i)){const i=0===o[0]?0:o[0]-1,n=0===o[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:o.length,base:i,sheetId:e.sheetId,position:n})}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 pn.values())xr.contains(e)||xr.add(e,Ir);function Ir(e){return[e]}function Rr(e,t){const i=pr.getAll().find((t=>t.match(e.type)));if(!i)throw new Error("Unknown chart type.");return i.transformDefinition(e,t)}function Tr(e,t){var i;let o=e;e.left!==e.right&&(o={...e,left:e.left+1});const s=[Wi(o)],r=t.getActiveSheetId(),a=t.getCell({sheetId:r,col:e.left,row:e.top});if(1===uo(e)&&(null==a?void 0:a.content))return{type:"scorecard",title:"",background:(null===(i=a.style)||void 0===i?void 0:i.fillColor)||void 0,keyValue:Wi(e),baselineMode:te,baselineColorUp:ie,baselineColorDown:oe};let l="";const c=t.getEvaluatedCellsInZone(r,{...o,bottom:o.top}),h=!!c.find((e=>e.type!==cn.empty&&e.type!==cn.number));if(h){const e=c.filter((e=>e.type!==cn.error&&e.type!==cn.empty)).map((e=>e.formattedValue)),t=e.splice(-1)[0];l=e.join(", "),t&&(l+=(l?" "+n("and")+" ":"")+t)}let d;e.left!==e.right&&(d=Wi({...e,right:e.left,top:h?e.top+1:e.top}));const u=o.right===o.left?"none":"top";return sr(d?t.getRangeFromSheetXC(r,d):void 0,t)?{title:l,dataSets:s,labelsAsText:!1,stacked:!1,aggregated:!1,cumulative:!1,labelRange:d,type:"line",dataSetsHaveTitle:h,verticalAxisPosition:"left",legendPosition:u}:{title:l,dataSets:s,labelRange:d,type:"bar",stacked:!1,aggregated:!1,dataSetsHaveTitle:h,verticalAxisPosition:"left",legendPosition:u}}const Ar=[cn.number,cn.error,cn.text,cn.boolean];function Mr(e,t,i,o,n){let r=fn.Success,a=o.right>o.left;if(e.model.getters.doesIntersectMerge(t,o)){let i;a=!1;for(let n=o.top;n<=o.bottom;n++){i=[];for(let s=o.left;s<=o.right;s++){let o=e.model.getters.getMerge({sheetId:t,col:s,row:n});o&&!i.includes(o.id.toString())&&i.push(o.id.toString())}if(i.length>=2){a=!0;break}}}const{col:l,row:c}=i;if(a)r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n});else{const i=e.model.getters.getContiguousZone(t,o);Ki(i,o)?r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n}):e.askConfirmation(s("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),(()=>{o=i,r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n})}),(()=>{r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n})}))}if(r.isCancelledBecause(63)){const{col:t,row:n}=i;e.model.selection.selectZone({cell:{col:t,row:n},zone:o}),e.raiseError(s("Cannot sort. To sort, select only cells or only merges that have the same size."))}}function Or(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause(19)&&e.raiseError(s("This operation is not allowed with multiple selections."))}const Nr={filterOverlap:s("You cannot create overlapping filters."),nonContinuousTargets:s("A filter can only be created on a continuous selection."),mergeInFilter:s("You can't create a filter over a range that contains a merge.")};function _r(e,t,i){const o=e.model.dispatch("CREATE_FILTER_TABLE",{target:i,sheetId:t});o.isCancelledBecause(78)?e.raiseError(Nr.filterOverlap):o.isCancelledBecause(80)?e.raiseError(Nr.mergeInFilter):o.isCancelledBecause(81)&&e.raiseError(Nr.nonContinuousTargets)}const Fr={wrongPasteSelection:s("This operation is not allowed with multiple selections."),willRemoveExistingMerge:s("This operation is not possible due to a merge. Please remove the merges first than try again."),wrongFigurePasteOption:s("Cannot do a special paste of a figure."),frozenPaneOverlap:s("Cannot paste merged cells over a frozen pane.")};function Dr(e,t){t.isSuccessful||(t.reasons.includes(20)?e.raiseError(Fr.wrongPasteSelection):t.reasons.includes(2)?e.raiseError(Fr.willRemoveExistingMerge):t.reasons.includes(22)?e.raiseError(Fr.wrongFigurePasteOption):t.reasons.includes(75)&&e.raiseError(Fr.frozenPaneOverlap))}function kr(e,t,i){const o=e.model.dispatch("PASTE",{target:t,pasteOption:i});Dr(e,o)}function Lr(e,t,i){const o=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,text:i});Dr(e,o)}function Pr(e){const t=e.model.getters.getActiveCols();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.right-t.left+1}}function Ur(e){const t=e.model.getters.getActiveRows();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function Vr(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function zr(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const Br=async e=>{e.model.dispatch("COPY"),await e.clipboard.write(e.model.getters.getClipboardContent())},Hr=async e=>{Or(e),await e.clipboard.write(e.model.getters.getClipboardContent())},$r=async e=>Gr(e),Wr=async e=>Gr(e,"onlyValue");async function Gr(e,t){const i=e.model.getters.getClipboardTextContent(),o=await e.clipboard.readText();switch(o.status){case"ok":const n=e.model.getters.getSelectedZones();o&&o.content!==i?Lr(e,n,o.content):kr(e,n,t);break;case"notImplemented":e.raiseError(s("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(s("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const qr=e=>kr(e,e.model.getters.getSelectedZones(),"onlyFormat"),Zr=e=>!e.model.getters.isCutOperation(),jr=e=>{if(e.model.getters.getSelectedZones().length>1)return s("Delete rows");let t,i;const o=e.model.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,i=o.bottom}return t===i?s("Delete row %s",(t+1).toString()):s("Delete rows %s - %s",(t+1).toString(),(i+1).toString())},Yr=e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){const i=e.model.getters.getSelectedZones()[0];for(let e=i.top;e<=i.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},Xr=(e,t)=>{const i=t.model.getters.getActiveSheetId(),o=t.model.getters.getElementsFromSelection(e),n=t.model.getters.checkElementsIncludeAllVisibleHeaders(i,e,o),s=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(i,e,o);return!n&&!s},Kr=e=>{if(e.model.getters.getSelectedZones().length>1)return s("Delete columns");let t,i;const o=e.model.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,i=o.right}return t===i?s("Delete column %s",Wt(t)):s("Delete columns %s - %s",Wt(t),Wt(i))},Qr=e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){const i=e.model.getters.getSelectedZones()[0];for(let e=i.left;e<=i.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},Jr=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});Dr(e,i)},ea=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});Dr(e,i)},ta=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});Dr(e,i)},ia=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});Dr(e,i)},oa=e=>{const t=e.model.getters.getActiveRows();let i,o;if(t.size)i=Math.min(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.top,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",base:i,quantity:o,dimension:"ROW"})},na=e=>{const t=e.model.getters.getActiveRows();let i,o;if(t.size)i=Math.max(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.bottom,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",base:i,quantity:o,dimension:"ROW"})},sa=e=>{const t=e.model.getters.getActiveCols();let i,o;if(t.size)i=Math.min(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.left,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",dimension:"COL",base:i,quantity:o})},ra=e=>{const t=e.model.getters.getActiveCols();let i,o;if(t.size)i=Math.max(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.right,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",dimension:"COL",base:i,quantity:o})};const aa=e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},la=e=>{let{col:t,row:i}=e.model.getters.getActivePosition();e.model.dispatch("OPEN_CELL_POPOVER",{col:t,row:i,popoverType:"LinkEditor"})},ca=e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,i)},ha=e=>{const{anchor:t,zones:i}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();Mr(e,o,t.cell,i[0],"ascending")},da=e=>{const{anchor:t,zones:i}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();Mr(e,o,t.cell,i[0],"descending")},ua=e=>1===e.model.getters.getSelectedZones().length,ga=new ls;ga.add("cut",{name:s("Cut"),description:"Ctrl+X",sequence:10,action:Hr}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Br}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:$r}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Zr}).addChild("paste_value_only",["paste_special"],{name:s("Paste values only"),sequence:10,action:Wr}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:qr}).add("add_row_before",{name:e=>{const t=Ur(e);return 1===t?s("Insert row"):s("Insert %s rows",t.toString())},sequence:70,action:oa,isVisible:ua}).add("add_column_before",{name:e=>{const t=Pr(e);return 1===t?s("Insert column"):s("Insert %s columns",t.toString())},sequence:90,action:sa,isVisible:ua}).add("insert_cell",{name:s("Insert cells"),sequence:100,isVisible:ua,separator:!0}).addChild("insert_cell_down",["insert_cell"],{name:s("Shift down"),sequence:10,action:Jr}).addChild("insert_cell_right",["insert_cell"],{name:s("Shift right"),sequence:20,action:ea}).add("delete_row",{name:jr,sequence:110,action:Yr,isVisible:ua}).add("delete_column",{name:Kr,sequence:120,action:Qr,isVisible:ua}).add("delete_cell",{name:s("Delete cells"),sequence:130,isVisible:ua}).addChild("delete_cell_up",["delete_cell"],{name:s("Shift up"),sequence:10,action:ta}).addChild("delete_cell_down",["delete_cell"],{name:s("Shift left"),sequence:20,action:ia}).add("insert_link",{name:s("Insert link"),separator:!0,sequence:150,action:la});const pa=new ls;pa.add("cut",{name:s("Cut"),description:"Ctrl+X",sequence:10,action:Hr}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Br}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:$r}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Zr}).addChild("paste_value_only",["paste_special"],{name:s("Paste value only"),sequence:10,action:Wr}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:qr}).add("sort_columns",{name:e=>e.model.getters.getActiveCols().size>1?s("Sort columns"):s("Sort column"),sequence:50,isVisible:ua,separator:!0}).addChild("sort_ascending",["sort_columns"],{name:s("Ascending (A ⟶ Z)"),sequence:10,action:ha}).addChild("sort_descending",["sort_columns"],{name:s("Descending (Z ⟶ A)"),sequence:20,action:da}).add("add_column_before",{name:e=>{const t=Pr(e);return 1===t?s("Insert column left"):s("Insert %s columns left",t.toString())},sequence:70,action:sa}).add("add_column_after",{name:e=>{const t=Pr(e);return 1===t?s("Insert column right"):s("Insert %s columns right",t.toString())},sequence:80,action:ra}).add("delete_column",{name:Kr,sequence:90,action:Qr,isVisible:e=>Xr("COL",e)}).add("clear_column",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return s("Clear columns");let t,i;const o=e.model.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,i=o.right}return t===i?s("Clear column %s",Wt(t)):s("Clear columns %s - %s",Wt(t),Wt(i))},sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId(),i=[...e.model.getters.getActiveCols()].map((i=>e.model.getters.getColsZone(t,i,i)));e.model.dispatch("DELETE_CONTENT",{target:i,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_columns",{name:e=>{const t=e.model.getters.getElementsFromSelection("COL");let i=t[0],o=t[t.length-1];return 1===t.length?s("Hide column %s",Wt(i).toString()):o-i+1===t.length?s("Hide columns %s - %s",Wt(i).toString(),Wt(o).toString()):s("Hide columns")},sequence:85,action:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("COL");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"COL",i)},separator:!0}).add("unhide_columns",{name:s("Unhide columns"),sequence:86,action:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:s("Conditional formatting"),sequence:110,action:aa});const ma=new ls;ma.add("cut",{name:s("Cut"),sequence:10,description:"Ctrl+X",action:Hr}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Br}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:$r}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Zr}).addChild("paste_value_only",["paste_special"],{name:s("Paste value only"),sequence:10,action:Wr}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:qr}).add("add_row_before",{name:e=>{const t=Ur(e);return 1===t?s("Insert row above"):s("Insert %s rows above",t.toString())},sequence:50,action:oa}).add("add_row_after",{name:e=>{const t=Ur(e);return 1===t?s("Insert row below"):s("Insert %s rows below",t.toString())},sequence:60,action:na}).add("delete_row",{name:jr,sequence:70,action:Yr,isVisible:e=>Xr("ROW",e)}).add("clear_row",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return s("Clear rows");let t,i;const o=e.model.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,i=o.bottom}return t===i?s("Clear row %s",(t+1).toString()):s("Clear rows %s - %s",(t+1).toString(),(i+1).toString())},sequence:80,action:e=>{const t=e.model.getters.getActiveSheetId(),i=[...e.model.getters.getActiveRows()].map((i=>e.model.getters.getRowsZone(t,i,i)));e.model.dispatch("DELETE_CONTENT",{target:i,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_rows",{name:e=>{const t=e.model.getters.getElementsFromSelection("ROW");let i=t[0],o=t[t.length-1];return 1===t.length?s("Hide row %s",(i+1).toString()):o-i+1===t.length?s("Hide rows %s - %s",(i+1).toString(),(o+1).toString()):s("Hide rows")},sequence:85,action:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("ROW");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"ROW",i)},separator:!0}).add("unhide_rows",{name:s("Unhide rows"),sequence:86,action:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:s("Conditional formatting"),sequence:90,action:aa});const fa=/(.*?)\((.*?)\)(.*)/,va=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function ba(e,t=""){return function(e){let t=e.match(fa),i=t[1].trim();if(!i)throw new Error(`Function argument definition is missing a name: '${e}'.`);let o,n=[],s=!1,r=!1,a=!1;for(let e of t[2].split(",")){const t=e.trim().toUpperCase();let i=va.find((e=>t===e));i?n.push(i):"RANGE<ANY>"===t?n.push("RANGE"):"OPTIONAL"===t?s=!0:"REPEATING"===t?r=!0:"LAZY"===t?a=!0:t.startsWith("DEFAULT=")&&(o=e.trim().slice(8))}let l=t[3].trim();const c={name:i,description:l,type:n};s&&(c.optional=!0);r&&(c.repeating=!0);a&&(c.lazy=!0);void 0!==o&&(c.default=!0,c.defaultValue=o);return c}(`${e} ${t}`)}function Ca(e){let t=0,i=0,o=0;for(let n of e.args)t++,n.optional||n.repeating||n.default||i++,n.repeating&&o++;const n=e;return n.minArgRequired=i,n.maxArgPossible=o?1/0:t,n.nbrArgRepeating=o,n.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const i=e-t;return e=>{if(e<=i)return e;return i+((e-i)%t||t)}}(t,o),n.hidden=e.hidden||!1,n}const Sa={description:s("Apply a large number format"),args:[ba("value (number)",s("The number.")),ba("unit (string, optional)",s("The formatting unit. Use 'k', 'm', or 'b' to force the unit"))],returns:["NUMBER"],computeFormat:(e,t)=>{const i=Math.abs(Uo(e.value)),o=e.format;if(void 0!==t){switch(null==t?void 0:t.value){case"k":return Ai(o,1e3,"k");case"m":return Ai(o,1e6,"m");case"b":return Ai(o,1e9,"b");default:throw new Error(s("The formatting unit should be 'k', 'm' or 'b'."))}}return i<1e5?Ai(o,0,""):i<1e8?Ai(o,1e3,"k"):i<1e11?Ai(o,1e6,"m"):Ai(o,1e9,"b")},compute:function(e){return Uo(e)}};var Ea=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:Sa});const wa={description:s("Absolute value of a number."),args:[ba("value (number)",s("The number of which to return the absolute value."))],returns:["NUMBER"],compute:function(e){return Math.abs(Uo(e))},isExported:!0},ya={description:s("Inverse cosine of a value, in radians."),args:[ba("value (number)",s("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>Math.abs(t)<=1),s("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},xa={description:s("Inverse hyperbolic cosine of a number."),args:[ba("value (number)",s("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>t>=1),s("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},Ia={description:s("Inverse cotangent of a value."),args:[ba("value (number)",s("The value for which to calculate the inverse cotangent."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Ra={description:s("Inverse hyperbolic cotangent of a value."),args:[ba("value (number)",s("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>Math.abs(t)>1),s("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},Ta={description:s("Inverse sine of a value, in radians."),args:[ba("value (number)",s("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>Math.abs(t)<=1),s("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},Aa={description:s("Inverse hyperbolic sine of a number."),args:[ba("value (number)",s("The value for which to calculate the inverse hyperbolic sine."))],returns:["NUMBER"],compute:function(e){return Math.asinh(Uo(e))},isExported:!0},Ma={description:s("Inverse tangent of a value, in radians."),args:[ba("value (number)",s("The value for which to calculate the inverse tangent."))],returns:["NUMBER"],compute:function(e){return Math.atan(Uo(e))},isExported:!0},Oa={description:s("Angle from the X axis to a point (x,y), in radians."),args:[ba("x (number)",s("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),ba("y (number)",s("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis."))],returns:["NUMBER"],compute:function(e,t){const i=Uo(e),o=Uo(t);return Lo((()=>0!==i||0!==o),s("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(o,i)},isExported:!0},Na={description:s("Inverse hyperbolic tangent of a number."),args:[ba("value (number)",s("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>Math.abs(t)<1),s("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},_a={description:s("Rounds number up to nearest multiple of factor."),args:[ba("value (number)",s("The value to round up to the nearest integer multiple of factor.")),ba("factor (number, default=1)",s("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){const i=Uo(e),o=Uo(t);return Lo((()=>o>=0||i<=0),s("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),i.toString())),o?Math.ceil(i/o)*o:0},isExported:!0},Fa={description:s("Rounds number up to nearest multiple of factor."),args:[ba("number (number)",s("The value to round up to the nearest integer multiple of significance.")),ba("significance (number, default=1)",s("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),ba("mode (number, default=0)",s("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,i=0){let o=Uo(t);if(0===o)return 0;const n=Uo(e);if(o=Math.abs(o),n>=0)return Math.ceil(n/o)*o;return 0===Uo(i)?-Math.floor(Math.abs(n)/o)*o:-Math.ceil(Math.abs(n)/o)*o},isExported:!0},Da={description:s("Rounds number up to nearest multiple of factor."),args:[ba("number (number)",s("The value to round up to the nearest integer multiple of significance.")),ba("significance (number, default=1)",s("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){return Fa.compute(e,t,0)},isExported:!0},ka={description:s("Cosine of an angle provided in radians."),args:[ba("angle (number)",s("The angle to find the cosine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.cos(Uo(e))},isExported:!0},La={description:s("Hyperbolic cosine of any real number."),args:[ba("value (number)",s("Any real value to calculate the hyperbolic cosine of."))],returns:["NUMBER"],compute:function(e){return Math.cosh(Uo(e))},isExported:!0},Pa={description:s("Cotangent of an angle provided in radians."),args:[ba("angle (number)",s("The angle to find the cotangent of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},Ua={description:s("Hyperbolic cotangent of any real number."),args:[ba("value (number)",s("Any real value to calculate the hyperbolic cotangent of."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},Va={description:s("Number of empty values."),args:[ba("value1 (any, range)",s("The first value or range in which to count the number of blanks.")),ba("value2 (any, range, repeating)",s("Additional values or ranges in which to count the number of blanks."))],returns:["NUMBER"],compute:function(...e){return Xo(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},za={description:s("A conditional count across a range."),args:[ba("range (range)",s("The range that is tested against criterion.")),ba("criterion (string)",s("The pattern or test to apply to range."))],returns:["NUMBER"],compute:function(...e){let t=0;return on(e,((e,i)=>{t+=1})),t},isExported:!0},Ba={description:s("Count values depending on multiple criteria."),args:[ba("criteria_range1 (range)",s("The range to check against criterion1.")),ba("criterion1 (string)",s("The pattern or test to apply to criteria_range1.")),ba("criteria_range2 (any, range, repeating)",s("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.")),ba("criterion2 (string, repeating)",s("Additional criteria to check."))],returns:["NUMBER"],compute:function(...e){let t=0;return on(e,((e,i)=>{t+=1})),t},isExported:!0};function Ha(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const $a={description:s("Counts number of unique values in a range."),args:[ba("value1 (any, range)",s("The first value or range to consider for uniqueness.")),ba("value2 (any, range, repeating)",s("Additional values or ranges to consider for uniqueness."))],returns:["NUMBER"],compute:function(...e){return Xo(e,((e,t)=>Ha(t)?e.add(t):e),new Set).size}},Wa={description:s("Counts number of unique values in a range, filtered by a set of criteria."),args:[ba("range (range)",s("The range of cells from which the number of unique values will be counted.")),ba("criteria_range1 (range)",s("The range of cells over which to evaluate criterion1.")),ba("criterion1 (string)",s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),ba("criteria_range2 (any, range, repeating)",s("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.")),ba("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=new Set;return on(t,((t,o)=>{const n=e[t][o];Ha(n)&&i.add(n)})),i.size}},Ga={description:s("Cosecant of an angle provided in radians."),args:[ba("angle (number)",s("The angle to find the cosecant of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},qa={description:s("Hyperbolic cosecant of any real number."),args:[ba("value (number)",s("Any real value to calculate the hyperbolic cosecant of."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},Za={description:s("Converts from another base to decimal."),args:[ba("value (string)",s("The number to convert.")),ba(",base (number)",s("The base to convert the value from."))],returns:["NUMBER"],compute:function(e,t){let i=Uo(t);i=Math.floor(i),Lo((()=>2<=i&&i<=36),s("The base (%s) must be between 2 and 36 inclusive.",i.toString()));const o=zo(e);if(""===o)return 0;Lo((()=>!!o.match(/^-?[a-z0-9]+$/i)),s("The value (%s) must be a valid base %s representation.",o,i.toString()));const n=parseInt(o,i);return Lo((()=>!isNaN(n)),s("The value (%s) must be a valid base %s representation.",o,i.toString())),n},isExported:!0},ja={description:s("Converts an angle value in radians to degrees."),args:[ba("angle (number)",s("The angle to convert from radians to degrees."))],returns:["NUMBER"],compute:function(e){return 180*Uo(e)/Math.PI},isExported:!0},Ya={description:s("Euler's number, e (~2.718) raised to a power."),args:[ba("value (number)",s("The exponent to raise e."))],returns:["NUMBER"],compute:function(e){return Math.exp(Uo(e))},isExported:!0},Xa={description:s("Rounds number down to nearest multiple of factor."),args:[ba("value (number)",s("The value to round down to the nearest integer multiple of factor.")),ba("factor (number, default=1)",s("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){const i=Uo(e),o=Uo(t);return Lo((()=>o>=0||i<=0),s("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),i.toString())),o?Math.floor(i/o)*o:0},isExported:!0},Ka={description:s("Rounds number down to nearest multiple of factor."),args:[ba("number (number)",s("The value to round down to the nearest integer multiple of significance.")),ba("significance (number, default=1)",s("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),ba("mode (number, default=0)",s("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,i=0){let o=Uo(t);if(0===o)return 0;const n=Uo(e);if(o=Math.abs(o),n>=0)return Math.floor(n/o)*o;return 0===Uo(i)?-Math.ceil(Math.abs(n)/o)*o:-Math.floor(Math.abs(n)/o)*o},isExported:!0},Qa={description:s("Rounds number down to nearest multiple of factor."),args:[ba("number (number)",s("The value to round down to the nearest integer multiple of significance.")),ba("significance (number, default=1)",s("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){return Ka.compute(e,t,0)},isExported:!0},Ja={description:s("Whether the provided value is even."),args:[ba("value (number)",s("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Vo(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},el={description:s("Rounds number up to nearest multiple of factor."),args:[ba("number (number)",s("The value to round up to the nearest integer multiple of significance.")),ba("significance (number, default=1)",s("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){return Fa.compute(e,t,0)},isExported:!0},tl={description:s("Whether the provided value is even."),args:[ba("value (number)",s("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Vo(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},il={description:s("The logarithm of a number, base e (euler's number)."),args:[ba("value (number)",s("The value for which to calculate the logarithm, base e."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>t>0),s("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},ol={description:s("Modulo (remainder) operator."),args:[ba("dividend (number)",s("The number to be divided to find the remainder.")),ba("divisor (number)",s("The number to divide by."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const i=Uo(t);Lo((()=>0!==i),s("The divisor must be different from 0."));const o=Uo(e)%i;return o>0&&i<0||o<0&&i>0?o+i:o},isExported:!0},nl={description:s("Rounds a number up to the nearest odd integer."),args:[ba("value (number)",s("The value to round to the next greatest odd number."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){const t=Uo(e);let i=Math.ceil(Math.abs(t));return i=1&i?i:i+1,t<0?-i:i},isExported:!0},sl={description:s("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},rl={description:s("A number raised to a power."),args:[ba("base (number)",s("The number to raise to the exponent power.")),ba("exponent (number)",s("The exponent to raise base to."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const i=Uo(e),o=Uo(t);return Lo((()=>i>=0||Number.isInteger(o)),s("The exponent (%s) must be an integer when the base is negative.",o.toString())),Math.pow(i,o)},isExported:!0},al={description:s("Result of multiplying a series of numbers together."),args:[ba("factor1 (number, range<number>)",s("The first number or range to calculate for the product.")),ba("factor2 (number, range<number>, repeating)",s("More numbers or ranges to calculate for the product."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0,i=1;for(let o of e)if(Array.isArray(o))for(let e of o)for(let o of e)"number"==typeof o&&(i*=o,t+=1);else null!=o&&(i*=Vo(o),t+=1);return 0===t?0:i},isExported:!0},ll={description:s("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},cl={description:s("Random integer between two values, inclusive."),args:[ba("low (number)",s("The low end of the random range.")),ba("high (number)",s("The high end of the random range."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){let i=Uo(e);Number.isInteger(i)||(i=Math.ceil(i));let o=Uo(t);return Number.isInteger(o)||(o=Math.floor(o)),Lo((()=>i<=o),s("The high (%s) must be greater than or equal to the low (%s).",o.toString(),i.toString())),i+Math.ceil((o-i+1)*Math.random())-1},isExported:!0},hl={description:s("Rounds a number according to standard rules."),args:[ba("value (number)",s("The value to round to places number of places.")),ba("places (number, default=0)",s("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Uo(e);let o=Uo(t);const n=Math.abs(i);let s;return 0===o?s=Math.round(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.round(n*Math.pow(10,o))/Math.pow(10,o)),i>=0?s:-s},isExported:!0},dl={description:s("Rounds down a number."),args:[ba("value (number)",s("The value to round to places number of places, always rounding down.")),ba("places (number, default=0)",s("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Uo(e);let o=Uo(t);const n=Math.abs(i);let s;return 0===o?s=Math.floor(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.floor(n*Math.pow(10,o))/Math.pow(10,o)),i>=0?s:-s},isExported:!0},ul={description:s("Rounds up a number."),args:[ba("value (number)",s("The value to round to places number of places, always rounding up.")),ba("places (number, default=0)",s("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Uo(e);let o=Uo(t);const n=Math.abs(i);let s;return 0===o?s=Math.ceil(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.ceil(n*Math.pow(10,o))/Math.pow(10,o)),i>=0?s:-s},isExported:!0},gl={description:s("Secant of an angle provided in radians."),args:[ba("angle (number)",s("The angle to find the secant of, in radians."))],returns:["NUMBER"],compute:function(e){return 1/Math.cos(Uo(e))},isExported:!0},pl={description:s("Hyperbolic secant of any real number."),args:[ba("value (number)",s("Any real value to calculate the hyperbolic secant of."))],returns:["NUMBER"],compute:function(e){return 1/Math.cosh(Uo(e))},isExported:!0},ml={description:s("Sine of an angle provided in radians."),args:[ba("angle (number)",s("The angle to find the sine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.sin(Uo(e))},isExported:!0},fl={description:s("Hyperbolic sine of any real number."),args:[ba("value (number)",s("Any real value to calculate the hyperbolic sine of."))],returns:["NUMBER"],compute:function(e){return Math.sinh(Uo(e))},isExported:!0},vl={description:s("Positive square root of a positive number."),args:[ba("value (number)",s("The number for which to calculate the positive square root."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){const t=Uo(e);return Lo((()=>t>=0),s("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},bl={description:s("Sum of a series of numbers and/or cells."),args:[ba("value1 (number, range<number>)",s("The first number or range to add together.")),ba("value2 (number, range<number>, repeating)",s("Additional numbers or ranges to add to value1."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){return Ko(e,((e,t)=>e+t),0)},isExported:!0},Cl={description:s("A conditional sum across a range."),args:[ba("criteria_range (range)",s("The range which is tested against criterion.")),ba("criterion (string)",s("The pattern or test to apply to range.")),ba("sum_range (range, default=criteria_range)",s("The range to be summed, if different from range."))],returns:["NUMBER"],compute:function(e,t,i){void 0===i&&(i=e);let o=0;return on([e,t],((e,t)=>{const n=i[e][t];"number"==typeof n&&(o+=n)})),o},isExported:!0},Sl={description:s("Sums a range depending on multiple criteria."),args:[ba("sum_range (range)",s("The range to sum.")),ba("criteria_range1 (range)",s("The range to check against criterion1.")),ba("criterion1 (string)",s("The pattern or test to apply to criteria_range1.")),ba("criteria_range2 (any, range, repeating)",s("Additional ranges to check.")),ba("criterion2 (string, repeating)",s("Additional criteria to check."))],returns:["NUMBER"],compute:function(e,...t){let i=0;return on(t,((t,o)=>{const n=e[t][o];"number"==typeof n&&(i+=n)})),i},isExported:!0},El={description:s("Tangent of an angle provided in radians."),args:[ba("angle (number)",s("The angle to find the tangent of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.tan(Uo(e))},isExported:!0},wl={description:s("Hyperbolic tangent of any real number."),args:[ba("value (number)",s("Any real value to calculate the hyperbolic tangent of."))],returns:["NUMBER"],compute:function(e){return Math.tanh(Uo(e))},isExported:!0},yl={description:s("Truncates a number."),args:[ba("value (number)",s("The value to be truncated.")),ba("places (number, default=0)",s("The number of significant digits to the right of the decimal point to retain."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Uo(e);let o=Uo(t);return 0===o?Math.trunc(i):(Number.isInteger(o)||(o=Math.trunc(o)),Math.trunc(i*Math.pow(10,o))/Math.pow(10,o))},isExported:!0};var xl=Object.freeze({__proto__:null,ABS:wa,ACOS:ya,ACOSH:xa,ACOT:Ia,ACOTH:Ra,ASIN:Ta,ASINH:Aa,ATAN:Ma,ATAN2:Oa,ATANH:Na,CEILING:_a,CEILING_MATH:Fa,CEILING_PRECISE:Da,COS:ka,COSH:La,COT:Pa,COTH:Ua,COUNTBLANK:Va,COUNTIF:za,COUNTIFS:Ba,COUNTUNIQUE:$a,COUNTUNIQUEIFS:Wa,CSC:Ga,CSCH:qa,DECIMAL:Za,DEGREES:ja,EXP:Ya,FLOOR:Xa,FLOOR_MATH:Ka,FLOOR_PRECISE:Qa,ISEVEN:Ja,ISO_CEILING:el,ISODD:tl,LN:il,MOD:ol,ODD:nl,PI:sl,POWER:rl,PRODUCT:al,RAND:ll,RANDBETWEEN:cl,ROUND:hl,ROUNDDOWN:dl,ROUNDUP:ul,SEC:gl,SECH:pl,SIN:ml,SINH:fl,SQRT:vl,SUM:bl,SUMIF:Cl,SUMIFS:Sl,TAN:El,TANH:wl,TRUNC:yl});function Il(e,t,i){let o=[],n=[],r=0,a=0;Zo([e],(e=>{o.push(e),r+=1})),Zo([t],(e=>{n.push(e),a+=1})),Lo((()=>r===a),s("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",r.toString(),a.toString()));let l=0,c=0,h=0;for(let e=0;e<r;e++){const t=o[e],i=n[e];"number"==typeof t&&"number"==typeof i&&(l+=1,c+=t,h+=i)}Lo((()=>0!==l&&(!i||1!==l)),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const d=c/l,u=h/l;let g=0;for(let e=0;e<r;e++){const t=o[e],i=n[e];"number"==typeof t&&"number"==typeof i&&(g+=(t-d)*(i-u))}return g/(l-(i?1:0))}function Rl(e,t,i){let o=0,n=0;const r=i?Qo:Ko;n=r(e,((e,t)=>(o+=1,e+t)),0),Lo((()=>0!==o&&(!t||1!==o)),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const a=n/o;return r(e,((e,t)=>e+Math.pow(t-a,2)),0)/(o-(t?1:0))}function Tl(e,t,i){const o=Uo(t);Lo((()=>i?0<=o&&o<=1:0<o&&o<1),s("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let n,r=[],a=0;return Zo(e,(e=>{"number"==typeof e&&(n=rn(r,e,"nextSmaller","asc",r.length,((e,t)=>e[t])),r.splice(n+1,0,e),a++)})),Lo((()=>0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),i||Lo((()=>1/(a+1)<=o&&o<=a/(a+1)),s("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),ai(r,o,i)}const Al={description:s("Average magnitude of deviations from mean."),args:[ba("value1 (number, range<number>)",s("The first value or range of the sample.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){let t=0;const i=Ko(e,((e,i)=>(t+=1,e+i)),0);Lo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const o=i/t;return Ko(e,((e,t)=>e+Math.abs(o-t)),0)/t},isExported:!0},Ml={description:s("Numerical average value in a dataset, ignoring text."),args:[ba("value1 (number, range<number>)",s("The first value or range to consider when calculating the average value.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0;const i=Ko(e,((e,i)=>(t+=1,e+i)),0);return Lo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/t},isExported:!0},Ol=s("[[FUNCTION_NAME]] has mismatched range sizes."),Nl=s("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),_l={description:s("Weighted average."),args:[ba("values (number, range<number>)",s("Values to average.")),ba("weights (number, range<number>)",s("Weights for each corresponding value.")),ba("additional_values (number, range<number>, repeating)",s("Additional values to average.")),ba("additional_weights (number, range<number>, repeating)",s("Additional weights."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t,i,o=0,n=0;Lo((()=>e.length%2==0),s("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let r=0;r<e.length-1;r+=2)if(t=e[r],i=e[r+1],Array.isArray(t)){Lo((()=>Array.isArray(i)),Ol);let e=t.length,r=t[0].length;Lo((()=>e===i.length&&r===i[0].length),Ol);for(let a=0;a<e;a++)for(let e=0;e<r;e++){let r=t[a][e],l=i[a][e],c="number"==typeof r,h="number"==typeof l;Lo((()=>c===h),s("[[FUNCTION_NAME]] expects number values.")),h&&(Lo((()=>l>=0),Nl),o+=r*l,n+=l)}}else i=Uo(i),t=Uo(t),Lo((()=>i>=0),Nl),o+=t*i,n+=i;return Lo((()=>0!==n),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/n}},Fl={description:s("Numerical average value in a dataset."),args:[ba("value1 (number, range<number>)",s("The first value or range to consider when calculating the average value.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0;const i=Qo(e,((e,i)=>(t+=1,e+i)),0);return Lo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/t},isExported:!0},Dl={description:s("Average of values depending on criteria."),args:[ba("criteria_range (range)",s("The range to check against criterion.")),ba("criterion (string)",s("The pattern or test to apply to criteria_range.")),ba("average_range (range, default=criteria_range)",s("The range to average. If not included, criteria_range is used for the average instead."))],returns:["NUMBER"],compute:function(e,t,i){null==i&&(i=e);let o=0,n=0;return on([e,t],((t,s)=>{const r=(i||e)[t][s];"number"==typeof r&&(o+=1,n+=r)})),Lo((()=>0!==o),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),n/o},isExported:!0},kl={description:s("Average of values depending on multiple criteria."),args:[ba("average_range (range)",s("The range to average.")),ba("criteria_range1 (range)",s("The range to check against criterion1.")),ba("criterion1 (string)",s("The pattern or test to apply to criteria_range1.")),ba("criteria_range2 (any, range, repeating)",s("Additional criteria_range and criterion to check.")),ba("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=0,o=0;return on(t,((t,n)=>{const s=e[t][n];"number"==typeof s&&(i+=1,o+=s)})),Lo((()=>0!==i),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/i},isExported:!0},Ll={description:s("The number of numeric values in dataset."),args:[ba("value1 (number, range<number>)",s("The first value or range to consider when counting.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){let t=0;for(let i of e)if(Array.isArray(i))for(let e of i)for(let i of e)"number"==typeof i&&(t+=1);else("string"!=typeof i||ni(i)||we(i))&&(t+=1);return t},isExported:!0},Pl={description:s("The number of values in a dataset."),args:[ba("value1 (any, range)",s("The first value or range to consider when counting.")),ba("value2 (any, range, repeating)",s("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){return Xo(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},Ul={description:s("The covariance of a dataset."),args:[ba("data_y (any, range)",s("The range representing the array or matrix of dependent data.")),ba("data_x (any, range)",s("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return Il(e,t,!1)},isExported:!0},Vl={description:s("The covariance of a dataset."),args:[ba("data_y (any, range)",s("The range representing the array or matrix of dependent data.")),ba("data_x (any, range)",s("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return Il(e,t,!1)},isExported:!0},zl={description:s("The sample covariance of a dataset."),args:[ba("data_y (any, range)",s("The range representing the array or matrix of dependent data.")),ba("data_x (any, range)",s("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return Il(e,t,!0)},isExported:!0},Bl={description:s("Nth largest element from a data set."),args:[ba("data (any, range)",s("Array or range containing the dataset to consider.")),ba("n (number)",s("The rank from largest to smallest of the element to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){const i=Math.trunc(Uo(t));let o,n=[],r=0;Zo([e],(e=>{"number"==typeof e&&(o=rn(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(o+1,0,e),r++,r>i&&(n.shift(),r--))}));const a=n.shift();return Lo((()=>void 0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),Lo((()=>r>=i),s("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",i.toString())),a},isExported:!0},Hl={description:s("Maximum value in a numeric dataset."),args:[ba("value1 (number, range<number>)",s("The first value or range to consider when calculating the maximum value.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=Ko(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},$l={description:s("Maximum numeric value in a dataset."),args:[ba("value1 (any, range)",s("The first value or range to consider when calculating the maximum value.")),ba("value2 (any, range, repeating)",s("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=Qo(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},Wl={description:s("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:[ba("range (range)",s("The range of cells from which the maximum will be determined.")),ba("criteria_range1 (range)",s("The range of cells over which to evaluate criterion1.")),ba("criterion1 (string)",s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),ba("criteria_range2 (any, range, repeating)",s("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.")),ba("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=-1/0;return on(t,((t,o)=>{const n=e[t][o];"number"==typeof n&&(i=i<n?n:i)})),i===-1/0?0:i},isExported:!0},Gl={description:s("Median value in a numeric dataset."),args:[ba("value1 (any, range)",s("The first value or range to consider when calculating the median value.")),ba("value2 (any, range, repeating)",s("Additional values or ranges to consider when calculating the median value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=[];return jo(e,(e=>{t.push(e)})),Tl(t,.5,!0)},isExported:!0},ql={description:s("Minimum value in a numeric dataset."),args:[ba("value1 (number, range<number>)",s("The first value or range to consider when calculating the minimum value.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=Ko(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Zl={description:s("Minimum numeric value in a dataset."),args:[ba("value1 (number, range<number>)",s("The first value or range to consider when calculating the minimum value.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=Qo(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},jl={description:s("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:[ba("range (range)",s("The range of cells from which the minimum will be determined.")),ba("criteria_range1 (range)",s("The range of cells over which to evaluate criterion1.")),ba("criterion1 (string)",s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),ba("criteria_range2 (any, range, repeating)",s("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.")),ba("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=1/0;return on(t,((t,o)=>{const n=e[t][o];"number"==typeof n&&(i=i>n?n:i)})),i===1/0?0:i},isExported:!0},Yl={description:s("Value at a given percentile of a dataset."),args:[ba("data (any, range)",s("The array or range containing the dataset to consider.")),ba("percentile (number)",s("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Kl.compute(e,t)},isExported:!0},Xl={description:s("Value at a given percentile of a dataset exclusive of 0 and 1."),args:[ba("data (any, range)",s("The array or range containing the dataset to consider.")),ba("percentile (number)",s("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Tl([e],t,!1)},isExported:!0},Kl={description:s("Value at a given percentile of a dataset."),args:[ba("data (any, range)",s("The array or range containing the dataset to consider.")),ba("percentile (number)",s("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Tl([e],t,!0)},isExported:!0},Ql={description:s("Value nearest to a specific quartile of a dataset."),args:[ba("data (any, range)",s("The array or range containing the dataset to consider.")),ba("quartile_number (number)",s("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return ec.compute(e,t)},isExported:!0},Jl={description:s("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:[ba("data (any, range)",s("The array or range containing the dataset to consider.")),ba("quartile_number (number)",s("Which quartile value, exclusive of 0 and 4, to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Tl([e],.25*Math.trunc(Uo(t)),!1)},isExported:!0},ec={description:s("Value nearest to a specific quartile of a dataset."),args:[ba("data (any, range)",s("The array or range containing the dataset to consider.")),ba("quartile_number (number)",s("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Tl([e],.25*Math.trunc(Uo(t)),!0)},isExported:!0},tc={description:s("Nth smallest element in a data set."),args:[ba("data (any, range)",s("The array or range containing the dataset to consider.")),ba("n (number)",s("The rank from smallest to largest of the element to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){const i=Math.trunc(Uo(t));let o,n=[],r=0;Zo([e],(e=>{"number"==typeof e&&(o=rn(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(o+1,0,e),r++,r>i&&(n.pop(),r--))}));const a=n.pop();return Lo((()=>void 0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),Lo((()=>r>=i),s("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",i.toString())),a},isExported:!0},ic={description:s("Standard deviation."),args:[ba("value1 (number, range<number>)",s("The first value or range of the sample.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(lc.compute(...e))},isExported:!0},oc={description:s("Standard deviation of entire population."),args:[ba("value1 (number, range<number>)",s("The first value or range of the population.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(cc.compute(...e))},isExported:!0},nc={description:s("Standard deviation."),args:[ba("value1 (number, range<number>)",s("The first value or range of the sample.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(hc.compute(...e))},isExported:!0},sc={description:s("Standard deviation of sample (text as 0)."),args:[ba("value1 (number, range<number>)",s("The first value or range of the sample.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(dc.compute(...e))},isExported:!0},rc={description:s("Standard deviation of entire population."),args:[ba("value1 (number, range<number>)",s("The first value or range of the population.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(uc.compute(...e))},isExported:!0},ac={description:s("Standard deviation of entire population (text as 0)."),args:[ba("value1 (number, range<number>)",s("The first value or range of the population.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(gc.compute(...e))},isExported:!0},lc={description:s("Variance."),args:[ba("value1 (number, range<number>)",s("The first value or range of the sample.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Rl(e,!0,!1)},isExported:!0},cc={description:s("Variance of entire population."),args:[ba("value1 (number, range<number>)",s("The first value or range of the population.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Rl(e,!1,!1)},isExported:!0},hc={description:s("Variance."),args:[ba("value1 (number, range<number>)",s("The first value or range of the sample.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Rl(e,!0,!1)},isExported:!0},dc={description:s("Variance of sample (text as 0)."),args:[ba("value1 (number, range<number>)",s("The first value or range of the sample.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Rl(e,!0,!0)},isExported:!0},uc={description:s("Variance of entire population."),args:[ba("value1 (number, range<number>)",s("The first value or range of the population.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Rl(e,!1,!1)},isExported:!0},gc={description:s("Variance of entire population (text as 0)."),args:[ba("value1 (number, range<number>)",s("The first value or range of the population.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Rl(e,!1,!0)},isExported:!0};var pc=Object.freeze({__proto__:null,AVEDEV:Al,AVERAGE:Ml,AVERAGE_WEIGHTED:_l,AVERAGEA:Fl,AVERAGEIF:Dl,AVERAGEIFS:kl,COUNT:Ll,COUNTA:Pl,COVAR:Ul,COVARIANCE_P:Vl,COVARIANCE_S:zl,LARGE:Bl,MAX:Hl,MAXA:$l,MAXIFS:Wl,MEDIAN:Gl,MIN:ql,MINA:Zl,MINIFS:jl,PERCENTILE:Yl,PERCENTILE_EXC:Xl,PERCENTILE_INC:Kl,QUARTILE:Ql,QUARTILE_EXC:Jl,QUARTILE_INC:ec,SMALL:tc,STDEV:ic,STDEV_P:oc,STDEV_S:nc,STDEVA:sc,STDEVP:rc,STDEVPA:ac,VAR:lc,VAR_P:cc,VAR_S:hc,VARA:dc,VARP:uc,VARPA:gc});function mc(e,t,i){var o;const n=new Map,r=e.length;for(let t=r-1;t>=0;t--)n.set(zo(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(s("The field must be a number or a string"));let a;if("number"==typeof t){if(a=Math.trunc(t)-1,a<0||r-1<a)throw new Error(s("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),r.toString()))}else{const e=zo(t).toUpperCase();if(a=null!==(o=n.get(e))&&void 0!==o?o:-1,-1===a)throw new Error(s("The field (%s) must be one of %s.",zo(t),[...n.keys()].toString()))}const l=i[0].length;if(l<2)throw new Error(s("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const h=e[0].length;for(let t=1;t<l;t++){let o=[],s=!0;for(let r=0;r<i.length;r++){const a=zo(i[r][0]).toUpperCase(),l=n.get(a),c=i[r][t];if(void 0!==c){if(void 0===l){s=!1;break}o.push([e[l].slice(1,h)]),o.push(c)}}if(s){if(!(o.length>0)){c=new Set(Array(h-1).keys());break}on(o,((e,t)=>{c.add(t)}),!0)}}const d=e[a];return[...c].map((e=>d[e+1]))}const fc=[ba("database (range)",s("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.")),ba("field (any)",s("Indicates which column in database contains the values to be extracted and operated on.")),ba("criteria (range)",s("An array or range containing zero or more criteria to filter the database values by before operating."))],vc={description:s("Average of a set of values from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return Ml.compute([o])},isExported:!0},bc={description:s("Counts values from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return Ll.compute([o])},isExported:!0},Cc={description:s("Counts values and text from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return Pl.compute([o])},isExported:!0},Sc={description:s("Single value from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return Lo((()=>1===o.length),s("More than one match found in DGET evaluation.")),o[0]},isExported:!0},Ec={description:s("Maximum of values from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return Hl.compute([o])},isExported:!0},wc={description:s("Minimum of values from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return ql.compute([o])},isExported:!0},yc={description:s("Product of values from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return al.compute([o])},isExported:!0},xc={description:s("Standard deviation of population sample from table."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return ic.compute([o])},isExported:!0},Ic={description:s("Standard deviation of entire population from table."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return rc.compute([o])},isExported:!0},Rc={description:s("Sum of values from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return bl.compute([o])},isExported:!0},Tc={description:s("Variance of population sample from table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return lc.compute([o])},isExported:!0},Ac={description:s("Variance of a population from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return uc.compute([o])},isExported:!0};var Mc=Object.freeze({__proto__:null,DAVERAGE:vc,DCOUNT:bc,DCOUNTA:Cc,DGET:Sc,DMAX:Ec,DMIN:wc,DPRODUCT:yc,DSTDEV:xc,DSTDEVP:Ic,DSUM:Rc,DVAR:Tc,DVARP:Ac});const Oc={description:s("Converts year/month/day into a date."),args:[ba("year (number)",s("The year component of the date.")),ba("month (number)",s("The month component of the date.")),ba("day (number)",s("The day component of the date."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i){let o=Math.trunc(Uo(e));const n=Math.trunc(Uo(t)),r=Math.trunc(Uo(i));Lo((()=>0<=o&&o<=9999),s("The year (%s) must be between 0 and 9999 inclusive.",o.toString())),o<1900&&(o+=1900);const a=Ie(new ue(o,n-1,r));return Lo((()=>a>=0),s("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),a},isExported:!0},Nc={description:s("Converts a date string to a date value."),args:[ba("date_string (string)",s("The string representing the date."))],returns:["NUMBER"],compute:function(e){const t=zo(e),i=we(t);return Lo((()=>null!==i),s("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(i.value)},isExported:!0},_c={description:s("Day of the month that a specific date falls on."),args:[ba("date (string)",s("The date from which to extract the day."))],returns:["NUMBER"],compute:function(e){return Go(e).getDate()},isExported:!0},Fc={description:s("Number of days between two dates."),args:[ba("end_date (date)",s("The end of the date range.")),ba("start_date (date)",s("The start of the date range."))],returns:["NUMBER"],compute:function(e,t){const i=Go(e),o=Go(t),n=i.getTime()-o.getTime();return Math.round(n/pe)},isExported:!0},Dc={description:s("Number of days between two dates on a 360-day year (months of 30 days)."),args:[ba("start_date (date)",s("The start date to consider in the calculation.")),ba("end_date (date)",s("The end date to consider in the calculation.")),ba("method (number, default=0)",s("An indicator of what day count method to use. (0) US NASD method (1) European method"))],returns:["NUMBER"],compute:function(e,t,i=0){const o=Uo(e),n=Uo(t),s=Wo(i)?4:0,r=eh.compute(e,t,s);return Math.sign(n-o)*Math.round(360*r)},isExported:!0},kc={description:s("Date a number of months before/after another date."),args:[ba("start_date (date)",s("The date from which to calculate the result.")),ba("months (number)",s("The number of months before (negative) or after (positive) 'start_date' to calculate."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){return Ie(Ae(Go(e),Math.trunc(Uo(t)),!1))},isExported:!0},Lc={description:s("Last day of a month before or after a date."),args:[ba("start_date (date)",s("The date from which to calculate the result.")),ba("months (number)",s("The number of months before (negative) or after (positive) 'start_date' to consider."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){const i=Go(e),o=Math.trunc(Uo(t)),n=i.getFullYear(),s=i.getMonth();return Ie(new ue(n,s+o+1,0))},isExported:!0},Pc={description:s("Hour component of a specific time."),args:[ba("time (date)",s("The time from which to calculate the hour component."))],returns:["NUMBER"],compute:function(e){return Go(e).getHours()},isExported:!0},Uc={description:s("ISO week number of the year."),args:[ba("date (date)",s("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."))],returns:["NUMBER"],compute:function(e){const t=Go(e),i=t.getFullYear();let o=1;for(;4!==new ue(i,0,o).getDay();)o+=1;const n=new ue(i,0,o-3);let s=31;for(;4!==new ue(i,11,s).getDay();)s-=1;const r=new ue(i,11,s+3);let a,l;switch(a=n.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=n;break;case 1:l=new ue(i,11,s+3+1);break;case-1:let e=1;for(;4!==new ue(i-1,0,e).getDay();)e+=1;l=new ue(i-1,0,e-3)}const c=(t.getTime()-l.getTime())/pe;return Math.floor(c/7)+1},isExported:!0},Vc={description:s("Minute component of a specific time."),args:[ba("time (date)",s("The time from which to calculate the minute component."))],returns:["NUMBER"],compute:function(e){return Go(e).getMinutes()},isExported:!0},zc={description:s("Month of the year a specific date falls in"),args:[ba("date (date)",s("The date from which to extract the month."))],returns:["NUMBER"],compute:function(e){return Go(e).getMonth()+1},isExported:!0},Bc={description:s("Net working days between two provided days."),args:[ba("start_date (date)",s("The start date of the period from which to calculate the number of net working days.")),ba("end_date (date)",s("The end date of the period from which to calculate the number of net working days.")),ba("holidays (date, range<date>, optional)",s("A range or array constant containing the date serial numbers to consider holidays."))],returns:["NUMBER"],compute:function(e,t,i){return $c.compute(e,t,1,i)},isExported:!0};function Hc(e){if("string"==typeof e){Lo((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),s('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let i=0;i<7;i++)"1"===e[i]&&t.push((i+1)%7);return t}if("number"==typeof e)return Lo((()=>1<=e&&e<=7||11<=e&&e<=17),s("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(s("The weekend must be a number or a string."))}const $c={description:s("Net working days between two dates (specifying weekends)."),args:[ba("start_date (date)",s("The start date of the period from which to calculate the number of net working days.")),ba("end_date (date)",s("The end date of the period from which to calculate the number of net working days.")),ba("weekend (any, default=1)",s("A number or string representing which days of the week are considered weekends.")),ba("holidays (date, range<date>, optional)",s("A range or array constant containing the dates to consider as holidays."))],returns:["NUMBER"],compute:function(e,t,i=1,o){const n=Go(e),s=Go(t),r=Hc(i);let a=new Set;void 0!==o&&Zo([o],(e=>{const t=Go(e);a.add(t.getTime())}));const l=n.getTime()>s.getTime(),c=ue.fromTimestamp((l?n:s).getTime());let h=ue.fromTimestamp((l?s:n).getTime());const d=c.getTime();let u=h.getTime(),g=0;for(;u<=d;)r.includes(h.getDay())||a.has(u)||(g+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-g:g},isExported:!0},Wc={description:s("Current date and time as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy hh:mm:ss",compute:function(){let e=ue.now();const t=e.getTime()-ge.getTime(),i=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/pe)+i},isExported:!0},Gc={description:s("Minute component of a specific time."),args:[ba("time (date)",s("The time from which to calculate the second component."))],returns:["NUMBER"],compute:function(e){return Go(e).getSeconds()},isExported:!0},qc={description:s("Converts hour/minute/second into a time."),args:[ba("hour (number)",s("The hour component of the time.")),ba("minute (number)",s("The minute component of the time.")),ba("second (number)",s("The second component of the time."))],returns:["DATE"],computeFormat:()=>"hh:mm:ss a",compute:function(e,t,i){let o=Math.trunc(Uo(e)),n=Math.trunc(Uo(t)),r=Math.trunc(Uo(i));return n+=Math.floor(r/60),r=r%60+(r<0?60:0),o+=Math.floor(n/60),n=n%60+(n<0?60:0),o%=24,Lo((()=>o>=0),s("The function [[FUNCTION_NAME]] result cannot be negative")),o/24+n/1440+r/86400},isExported:!0},Zc={description:s("Converts a time string into its serial number representation."),args:[ba("time_string (string)",s("The string that holds the time representation."))],returns:["NUMBER"],compute:function(e){const t=zo(e),i=we(t);Lo((()=>null!==i),s("The time_string (%s) cannot be parsed to date/time.",t));const o=i.value-Math.trunc(i.value);return o<0?1+o:o},isExported:!0},jc={description:s("Current date as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(){const e=ue.now();return Ie(new ue(e.getFullYear(),e.getMonth(),e.getDate()))},isExported:!0},Yc={description:s("Day of the week of the date provided (as number)."),args:[ba("date (date)",s("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.")),ba("type (number, default=1)",s("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const i=Go(e),o=Math.round(Uo(t)),n=i.getDay();return Lo((()=>[1,2,3].includes(o)),s("The type (%s) must be 1, 2 or 3.",o.toString())),1===o?n+1:2===o?0===n?7:n:0===n?6:n-1},isExported:!0},Xc={description:s("Week number of the year."),args:[ba("date (date)",s("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.")),ba("type (number, default=1)",s("A number representing the day that a week starts on. Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const i=Go(e),o=Math.round(Uo(t));if(Lo((()=>1===o||2===o||11<=o&&o<=17||21===o),s("The type (%s) is out of range.",o.toString())),21===o)return Uc.compute(e);let n;n=1===o||2===o?o-1:o-10==7?0:o-10;const r=i.getFullYear();let a=1,l=new ue(r,0,a);for(;l.getDay()!==n;)a+=1,l=new ue(r,0,a);const c=(i.getTime()-l.getTime())/pe;return c<0?1:Math.floor(c/7)+(1===a?1:2)},isExported:!0},Kc={description:s("Date after a number of workdays."),args:[ba("start_date (date)",s("The date from which to begin counting.")),ba("num_days (number)",s("The number of working days to advance from start_date. If negative, counts backwards.")),ba("holidays (date, range<date>, optional)",s("A range or array constant containing the dates to consider holidays."))],returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i){return Qc.compute(e,t,1,i)},isExported:!0},Qc={description:s("Date after a number of workdays (specifying weekends)."),args:[ba("start_date (date)",s("The date from which to begin counting.")),ba("num_days (number)",s("The number of working days to advance from start_date. If negative, counts backwards.")),ba("weekend (any, default=1)",s("A number or string representing which days of the week are considered weekends.")),ba("holidays (date, range<date>, optional)",s("A range or array constant containing the dates to consider holidays."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i=1,o){let n=Go(e),r=Math.trunc(Uo(t));"string"==typeof i&&Lo((()=>"1111111"!==i),s("The weekend (%s) must be different from '1111111'.",i));const a=Hc(i);let l=new Set;void 0!==o&&Zo([o],(e=>{const t=Go(e);l.add(t.getTime())}));let c=ue.fromTimestamp(n.getTime()),h=c.getTime();const d=Math.sign(r);let u=Math.abs(r);for(;u>0;)c.setDate(c.getDate()+d),h=c.getTime(),a.includes(c.getDay())||l.has(h)||(u-=1);const g=h-ge.getTime();return Math.round(g/pe)},isExported:!0},Jc={description:s("Year specified by a given date."),args:[ba("date (date)",s("The date from which to extract the year."))],returns:["NUMBER"],compute:function(e){return Go(e).getFullYear()},isExported:!0},eh={description:s("Exact number of years between two dates."),args:[ba("start_date (date)",s("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.")),ba("end_date (date)",s("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.")),ba("day_count_convention (number, default=0)",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i=0){let o=Math.trunc(Uo(e)),n=Math.trunc(Uo(t));const r=Math.trunc(Uo(i));return Lo((()=>o>=0),s("The start_date (%s) must be positive or null.",o.toString())),Lo((()=>n>=0),s("The end_date (%s) must be positive or null.",n.toString())),Lo((()=>0<=r&&r<=4),s("The day_count_convention (%s) must be between 0 and 4 inclusive.",r.toString())),Oe(o,n,r)}},th={description:s("First day of the month preceding a date."),args:[ba("date (date)",s("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Go(e),i=t.getFullYear(),o=t.getMonth();return Ie(new ue(i,o,1))}},ih={description:s("Last day of the month following a date."),args:[ba("date (date)",s("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){return Lc.compute(e,0)}},oh={description:s("Quarter of the year a specific date falls in"),args:[ba("date (date)",s("The date from which to extract the quarter."))],returns:["NUMBER"],compute:function(e){return Math.ceil((Go(e).getMonth()+1)/3)}},nh={description:s("First day of the quarter of the year a specific date falls in."),args:[ba("date (date)",s("The date from which to calculate the start of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=oh.compute(e),i=Jc.compute(e);return Ie(new ue(i,3*(t-1),1))}},sh={description:s("Last day of the quarter of the year a specific date falls in."),args:[ba("date (date)",s("The date from which to calculate the end of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=oh.compute(e),i=Jc.compute(e);return Ie(new ue(i,3*t,0))}},rh={description:s("First day of the year a specific date falls in."),args:[ba("date (date)",s("The date from which to calculate the start of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Jc.compute(e);return Ie(new ue(t,0,1))}},ah={description:s("Last day of the year a specific date falls in."),args:[ba("date (date)",s("The date from which to calculate the end of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Jc.compute(e);return Ie(new ue(t+1,0,0))}};var lh=Object.freeze({__proto__:null,DATE:Oc,DATEVALUE:Nc,DAY:_c,DAYS:Fc,DAYS360:Dc,EDATE:kc,EOMONTH:Lc,HOUR:Pc,ISOWEEKNUM:Uc,MINUTE:Vc,MONTH:zc,NETWORKDAYS:Bc,NETWORKDAYS_INTL:$c,NOW:Wc,SECOND:Gc,TIME:qc,TIMEVALUE:Zc,TODAY:jc,WEEKDAY:Yc,WEEKNUM:Xc,WORKDAY:Kc,WORKDAY_INTL:Qc,YEAR:Jc,YEARFRAC:eh,MONTH_START:th,MONTH_END:ih,QUARTER:oh,QUARTER_START:nh,QUARTER_END:sh,YEAR_START:rh,YEAR_END:ah});const ch={description:s("Compare two numeric values, returning 1 if they're equal."),args:[ba("number1 (number)",s("The first number to compare.")),ba("number2 (number, default=0)",s("The second number to compare."))],returns:["NUMBER"],compute:function(e,t=0){return Uo(e)===Uo(t)?1:0},isExported:!0};var hh=Object.freeze({__proto__:null,DELTA:ch});function dh(e,t){Lo((()=>e<t),s("The maturity (%s) must be strictly greater than the settlement (%s).",t.toString(),e.toString()))}function uh(e,t){Lo((()=>t<e),s("The settlement date (%s) must be strictly greater than the issue date (%s).",e.toString(),t.toString()))}function gh(e){Lo((()=>[1,2,4].includes(e)),s("The frequency (%s) must be one of %s",e.toString(),[1,2,4].toString()))}function ph(e){Lo((()=>0<=e&&e<=4),s("The day_count_convention (%s) must be between 0 and 4 inclusive.",e.toString()))}function mh(e){Lo((()=>e>0),s("The redemption (%s) must be strictly positive.",e.toString()))}function fh(e){Lo((()=>e>0),s("The price (%s) must be strictly positive.",e.toString()))}function vh(e){Lo((()=>e>0),s("The number_of_periods (%s) must be greater than 0.",e.toString()))}function bh(e){Lo((()=>e>0),s("The rate (%s) must be strictly positive.",e.toString()))}function Ch(e){Lo((()=>e>0),s("The life (%s) must be strictly positive.",e.toString()))}function Sh(e){Lo((()=>e>=0),s("The cost (%s) must be positive or null.",e.toString()))}function Eh(e){Lo((()=>e>0),s("The period (%s) must be strictly positive.",e.toString()))}function wh(e){Lo((()=>e>=0),s("The salvage (%s) must be positive or null.",e.toString()))}function yh(e){Lo((()=>e>0),s("The present value (%s) must be strictly positive.",e.toString()))}function xh(e,t){Lo((()=>e<=t),s("The period (%s) must be less than or equal life (%s).",e.toString(),t.toString()))}function Ih(e){Lo((()=>e>0),s("The investment (%s) must be strictly positive.",e.toString()))}function Rh(e){Lo((()=>e>0),s("The discount (%s) must be strictly positive.",e.toString()))}function Th(e){Lo((()=>e<1),s("The discount (%s) must be smaller than 1.",e.toString()))}function Ah(e){Lo((()=>e>0),s("The depreciation factor (%s) must be strictly positive.",e.toString()))}function Mh(e,t){const i=Go(e),o=Go(t),n=Go(e);n.setFullYear(i.getFullYear()+1),Lo((()=>o.getTime()<=n.getTime()),s("The settlement date (%s) must at most one year after the maturity date (%s).",e.toString(),t.toString()))}function Oh(e,t,i){vh(i),Lo((()=>e>0),s("The first_period (%s) must be strictly positive.",e.toString())),Lo((()=>t>0),s("The last_period (%s) must be strictly positive.",t.toString())),Lo((()=>e<=t),s("The first_period (%s) must be smaller or equal to the last_period (%s).",e.toString(),t.toString())),Lo((()=>t<=i),s("The last_period (%s) must be smaller or equal to the number_of_periods (%s).",e.toString(),i.toString()))}function Nh(e){Lo((()=>e>-1),s("The rate_guess (%s) must be strictly greater than -1.",e.toString()))}function _h(e,t){Lo((()=>e.length===t.length&&e[0].length===t[0].length),s("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."))}function Fh(e){Lo((()=>e.every((t=>t>=e[0]))),s("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e[0].toString()))}const Dh=[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))];function kh(e,t,i,o,n=1e-10,r){let a,l,c,h,d=i,u=!1,g=0;do{c=e(d),isNaN(c)?(Lo((()=>g<o&&void 0!==r),s("Function [[FUNCTION_NAME]] didn't find any result.")),g++,d=r(h),h=d):(a=d-c/t(d),l=Math.abs(a-d),d=a,u=l<n||Math.abs(c)<n,Lo((()=>g<o),s("Function [[FUNCTION_NAME]] didn't find any result.")),g++)}while(!u);return d}const Lh={description:s("Accrued interest of security paying at maturity."),args:[ba("issue (date)",s("The date the security was initially issued.")),ba("maturity (date)",s("The maturity date of the security.")),ba("rate (number)",s("The annualized rate of interest.")),ba("redemption (number)",s("The redemption amount per 100 face value, or par.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Uo(e)),r=Math.trunc(Uo(t)),a=Uo(o),l=Uo(i),c=Math.trunc(Uo(n));uh(r,s),ph(c),mh(a),bh(l);return a*l*eh.compute(s,r,n)},isExported:!0},Ph={description:s("Depreciation for an accounting period."),args:[ba("cost (number)",s("The initial cost of the asset.")),ba("purchase_date (date)",s("The date the asset was purchased.")),ba("first_period_end (date)",s("The date the first period ended.")),ba("salvage (number)",s("The value of the asset at the end of depreciation.")),ba("period (number)",s("The single period within life for which to calculate depreciation.")),ba("rate (number)",s("The deprecation rate.")),ba("day_count_convention (number, optional)",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r,a=0){a=a||0;const l=Uo(e),c=Math.trunc(Uo(t)),h=Math.trunc(Uo(i)),d=Uo(o),u=Uo(n),g=Uo(r),p=Math.trunc(Uo(a));!function(e){Lo((()=>e>0),s("The cost (%s) must be strictly positive.",e.toString()))}(l),wh(d),function(e,t){Lo((()=>e<=t),s("The salvage (%s) must be smaller or equal than the cost (%s).",e.toString(),t.toString()))}(d,l),function(e){Lo((()=>e>=0),s("The period (%s) must be positive or null.",e.toString()))}(u),bh(g),ph(p),Lo((()=>c<=h),s("The purchase_date (%s) must be before the first_period_end (%s).",c.toString(),h.toString()));const m=u<1&&u>0?1:Math.trunc(u),f=l*g,v=eh.compute(c,h,p),b=c===h?f:f*v,C=l-b-f*m;return C>=d?0===m?b:f:d-C<f?f-(d-C):0},isExported:!0},Uh={description:s("Days in coupon period containing settlement date."),args:Dh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Uo(e)),s=Math.trunc(Uo(t)),r=Math.trunc(Uo(i)),a=Math.trunc(Uo(o));if(dh(n,s),gh(r),ph(a),1===a){const n=$h.compute(e,t,i,o);return Bh.compute(e,t,i,o)-n}return(3===a?365:360)/r},isExported:!0},Vh={description:s("Days from settlement until next coupon."),args:Dh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Uo(e)),s=Math.trunc(Uo(t)),r=Math.trunc(Uo(i)),a=Math.trunc(Uo(o));dh(n,s),gh(r),ph(a);const l=$h.compute(n,s,i,o);if([1,2,3].includes(a))return n-l;if(4===a){const e=Oe(l,n,a);return Math.round(360*e)}const c=Go(n),h=Go(l),d=h.getFullYear(),u=c.getFullYear(),g=h.getMonth()+1,p=c.getMonth()+1;let m=h.getDate(),f=c.getDate();return 2===g&&2===p&&Te(h)&&Te(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&Te(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},zh={description:s("Days from settlement until next coupon."),args:Dh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Uo(e)),s=Math.trunc(Uo(t)),r=Math.trunc(Uo(i)),a=Math.trunc(Uo(o));dh(n,s),gh(r),ph(a);const l=Bh.compute(n,s,i,o);if([1,2,3].includes(a))return l-n;if(4===a){const e=Oe(n,l,a);return Math.round(360*e)}const c=Vh.compute(e,t,i,a);return Uh.compute(e,t,i,a)-c},isExported:!0},Bh={description:s("Next coupon date after the settlement date."),args:Dh,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Uo(e)),s=Math.trunc(Uo(t)),r=Math.trunc(Uo(i)),a=Math.trunc(Uo(o));dh(n,s),gh(r),ph(a);const l=12/r,c=Hh.compute(e,t,i,o);return Ie(Ae(Go(s),-(c-1)*l,!0))},isExported:!0},Hh={description:s("Number of coupons between settlement and maturity."),args:Dh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Uo(e)),s=Math.trunc(Uo(t)),r=Math.trunc(Uo(i)),a=Math.trunc(Uo(o));dh(n,s),gh(r),ph(a);let l=1,c=s;const h=12/r;for(;c>n;)c=Ie(Ae(Go(c),-h,!1)),l++;return l-1},isExported:!0},$h={description:s("Last coupon date prior to or on the settlement date."),args:Dh,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Uo(e)),s=Math.trunc(Uo(t)),r=Math.trunc(Uo(i)),a=Math.trunc(Uo(o));dh(n,s),gh(r),ph(a);const l=12/r,c=Hh.compute(e,t,i,o);return Ie(Ae(Go(s),-c*l,!0))},isExported:!0},Wh={description:s("Cumulative interest paid over a set of periods."),args:[ba("rate (number)",s("The interest rate.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("present_value (number)",s("The current value of the annuity.")),ba("first_period (number)",s("The number of the payment period to begin the cumulative calculation.")),ba("last_period (number)",s("The number of the payment period to end the cumulative calculation.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,i,o,n,s=0){const r=Uo(o),a=Uo(n),l=Uo(e),c=Uo(i),h=Uo(t);Oh(r,a,h),bh(l),yh(c);let d=0;for(let t=r;t<=a;t++){d+=id.compute(e,t,h,i,0,s)}return d},isExported:!0},Gh={description:s("Cumulative principal paid over a set of periods."),args:[ba("rate (number)",s("The interest rate.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("present_value (number)",s("The current value of the annuity.")),ba("first_period (number)",s("The number of the payment period to begin the cumulative calculation.")),ba("last_period (number)",s("The number of the payment period to end the cumulative calculation.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,i,o,n,s=0){const r=Uo(o),a=Uo(n),l=Uo(e),c=Uo(i),h=Uo(t);Oh(r,a,h),bh(l),yh(c);let d=0;for(let t=r;t<=a;t++){d+=ud.compute(e,t,h,i,0,s)}return d},isExported:!0},qh={description:s("Depreciation via declining balance method."),args:[ba("cost (number)",s("The initial cost of the asset.")),ba("salvage (number)",s("The value of the asset at the end of depreciation.")),ba("life (number)",s("The number of periods over which the asset is depreciated.")),ba("period (number)",s("The single period within life for which to calculate depreciation.")),ba("month (number, optional)",s("The number of months in the first year of depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,...n){const r=Uo(e),a=Uo(t),l=Uo(i),c=Math.trunc(Uo(o)),h=n.length?Math.trunc(Uo(n[0])):12,d=l+(12===h?0:1);Sh(r),wh(a),Eh(c),Ch(l),Lo((()=>1<=h&&h<=12),s("The month (%s) must be between 1 and 12 inclusive.",h.toString())),Lo((()=>c<=d),s("The period (%s) must be less than or equal to %s.",c.toString(),d.toString()));const u=h/12;let g=1-Math.pow(a/r,1/l);g=Math.round(1e3*g)/1e3;let p=r,m=r*(1-g*u);for(let e=1;e<c;e++)p=m,m=p*(1-g),e===l&&(m=p*(1-g*(1-u)));return p-m},isExported:!0},Zh={description:s("Depreciation via double-declining balance method."),args:[ba("cost (number)",s("The initial cost of the asset.")),ba("salvage (number)",s("The value of the asset at the end of depreciation.")),ba("life (number)",s("The number of periods over which the asset is depreciated.")),ba("period (number)",s("The single period within life for which to calculate depreciation.")),ba("factor (number, default=2)",s("The factor by which depreciation decreases."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,n=2){n=n||0;const s=Uo(e),r=Uo(t),a=Uo(i),l=Uo(o),c=Uo(n);if(Sh(s),wh(r),Eh(l),Ch(a),xh(l,a),Ah(c),0===s||r>=s)return 0;const h=c/a;if(h>1)return 1===o?s-r:0;if(l<=1)return s*h;const d=s*Math.pow(1-h,l-1),u=s*Math.pow(1-h,l),g=u<r?d-r:d-u;return Math.max(g,0)},isExported:!0},jh={description:s("Discount rate of a security based on price."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("price (number)",s("The price at which the security is bought per 100 face value.")),ba("redemption (number)",s("The redemption amount per 100 face value, or par.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Uo(e)),r=Math.trunc(Uo(t)),a=Uo(i),l=Uo(o),c=Math.trunc(Uo(n));dh(s,r),ph(c),fh(a),mh(l);return(l-a)/l/eh.compute(s,r,c)},isExported:!0},Yh={description:s("Convert a decimal fraction to decimal value."),args:[ba("fractional_price (number)",s("The price quotation given using fractional decimal conventions.")),ba("unit (number)",s("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const i=Uo(e),o=Math.trunc(Uo(t));Lo((()=>o>0),s("The unit (%s) must be strictly positive.",o.toString()));const n=Math.trunc(i);return n+(i-n)*(10**Math.ceil(Math.log10(o))/o)},isExported:!0},Xh={description:s("Convert a decimal value to decimal fraction."),args:[ba("decimal_price (number)",s("The price quotation given as a decimal value.")),ba("unit (number)",s("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const i=Uo(e),o=Math.trunc(Uo(t));Lo((()=>o>0),s("The unit (%s) must be strictly positive.",o.toString()));const n=Math.trunc(i);return n+(i-n)*(o/10**Math.ceil(Math.log10(o)))},isExported:!0},Kh={description:s("Number of periods for an investment to reach a value."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("rate (number)",s("The annualized rate of interest.")),ba("yield (number)",s("The expected annual yield of the security.")),ba("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=0){r=r||0;const a=Math.trunc(Uo(e)),l=Math.trunc(Uo(t)),c=Uo(i),h=Uo(o),d=Math.trunc(Uo(n)),u=Math.trunc(Uo(r));dh(a,l),gh(d),ph(u),Lo((()=>c>=0),s("The rate (%s) must be positive or null.",c.toString())),Lo((()=>h>=0),s("The yield (%s) must be positive or null.",h.toString()));const g=eh.compute(a,l,u),p=g-Math.trunc(g)||1/d,m=Math.ceil(g*d),f=c/d,v=h/d;let b=0,C=0;for(let e=1;e<=m;e++){const t=(f+(e===m?1:0))/(1+v)**e;C+=(p+(e-1)/d)*t,b+=t}return 0===b?0:C/b},isExported:!0},Qh={description:s("Annual effective interest rate."),args:[ba("nominal_rate (number)",s("The nominal interest rate per year.")),ba("periods_per_year (number)",s("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const i=Uo(e),o=Math.trunc(Uo(t));return Lo((()=>i>0),s("The nominal rate (%s) must be strictly greater than 0.",i.toString())),Lo((()=>o>0),s("The number of periods by year (%s) must strictly greater than 0.",o.toString())),Math.pow(1+i/o,o)-1},isExported:!0},Jh={description:s("Future value of an annuity investment."),args:[ba("rate (number)",s("The interest rate.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("payment_amount (number)",s("The amount per period to be paid.")),ba("present_value (number, default=0)",s("The current value of the annuity.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=Uo(e),r=Uo(t),a=Uo(i),l=Uo(o),c=Wo(n)?1:0;return s?-l*(1+s)**r-a*(1+s*c)*((1+s)**r-1)/s:-(l+a*r)},isExported:!0},ed={description:s("Future value of principal from series of rates."),args:[ba("principal (number)",s("The amount of initial capital or value to compound against.")),ba("rate_schedule (number, range<number>)",s("A series of interest rates to compound against the principal."))],returns:["NUMBER"],compute:function(e,t){return Xo([t],((e,t)=>e*(1+Uo(t))),Uo(e))},isExported:!0},td={description:s("Calculates effective interest rate."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("investment (number)",s("The amount invested in the security.")),ba("redemption (number)",s("The amount to be received at maturity.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){const s=Math.trunc(Uo(e)),r=Math.trunc(Uo(t)),a=Uo(o),l=Uo(i);dh(s,r),Ih(l),mh(a);return(a-l)/l/eh.compute(s,r,n)},isExported:!0},id={description:s("Payment on the principal of an investment."),args:[ba("rate (number)",s("The annualized rate of interest.")),ba("period (number)",s("The amortization period, in terms of number of periods.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("present_value (number)",s("The current value of the annuity.")),ba("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,n=0,s=0){return dd.compute(e,i,o,n,s)-ud.compute(e,t,i,o,n,s)},isExported:!0},od={description:s("Internal rate of return given periodic cashflows."),args:[ba("cashflow_amounts (number, range<number>)",s("An array or range containing the income or payments associated with the investment.")),ba("rate_guess (number, default=0.1)",s("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t=.1){const i=Uo(t);Nh(i);let o=!1,n=!1,r=[];jo([e],(e=>{e>0&&(o=!0),e<0&&(n=!0),r.push(e)})),Lo((()=>o&&n),s("The cashflow_amounts must include negative and positive values."));const a=r.shift();return kh((function(e){return function(e,t,i){const o=i.length;let n=0;return i.reduce(((t,i)=>(n++,t+i*e**(o-n))),t*e**o)}(e,a,r)}),(function(e){return function(e,t,i){const o=i.length;let n=0;return i.reduce(((t,i)=>(n++,t+i*(o-n)*e**(o-n-1))),t*o*e**(o-1))}(e,a,r)}),i+1,20,1e-5)-1},isExported:!0},nd={description:s("Returns the interest paid at a particular period of an investment."),args:[ba("rate (number)",s("The interest rate.")),ba("period (number)",s("The period for which you want to view the interest payment.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("present_value (number)",s("The current value of the annuity."))],returns:["NUMBER"],compute:function(e,t,i,o){const n=Uo(e),r=Uo(t),a=Uo(i),l=Uo(o);Lo((()=>0!==a),s("The number of periods must be different than 0.",a.toString()));return-1*(l-l*(r/a))*n},isExported:!0},sd={description:s("Modified Macaulay duration."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("rate (number)",s("The annualized rate of interest.")),ba("yield (number)",s("The expected annual yield of the security.")),ba("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,s=0){return Kh.compute(e,t,i,o,n,s)/(1+Uo(o)/Math.trunc(Uo(n)))},isExported:!0},rd={description:s("Modified internal rate of return."),args:[ba("cashflow_amounts (range<number>)",s("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),ba("financing_rate (number)",s("The interest rate paid on funds invested.")),ba("reinvestment_return_rate (number)",s("The return (as a percentage) earned on reinvestment of income received from the investment."))],returns:["NUMBER"],compute:function(e,t,i){const o=Uo(t),n=Uo(i),r=(a=e,a.length?a[0].map(((e,t)=>a.map((e=>e[t])))):a).flat().filter(ot).map(Uo);var a;const l=r.length;let c=0,h=0;for(const e of $e(0,l)){const t=r[e];t>=0?c+=t*(n+1)**(l-e-1):h+=t/(o+1)**e}Lo((()=>0!==h&&0!==c),s("There must be both positive and negative values in cashflow_amounts."));return(-c/h)**(1/(l-1))-1},isExported:!0},ad={description:s("Annual nominal interest rate."),args:[ba("effective_rate (number)",s("The effective interest rate per year.")),ba("periods_per_year (number)",s("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const i=Uo(e),o=Math.trunc(Uo(t));return Lo((()=>i>0),s("The effective rate (%s) must must strictly greater than 0.",i.toString())),Lo((()=>o>0),s("The number of periods by year (%s) must strictly greater than 0.",o.toString())),(Math.pow(i+1,1/o)-1)*o},isExported:!0},ld={description:s("Number of payment periods for an investment."),args:[ba("rate (number)",s("The interest rate.")),ba("payment_amount (number)",s("The amount of each payment made.")),ba("present_value (number)",s("The current value of the annuity.")),ba("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=Uo(e),r=Uo(t),a=Uo(i),l=Uo(o),c=Wo(n)?1:0;if(0===s)return-(l+a)/r;const h=r*(1+s*c)/s;return Math.log((h-l)/(a+h))/Math.log(1+s)},isExported:!0};const cd={description:s("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:[ba("discount (number)",s("The discount rate of the investment over one period.")),ba("cashflow1 (number, range<number>)",s("The first future cash flow.")),ba("cashflow2 (number, range<number>, repeating)",s("Additional future cash flows."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,...t){const i=Uo(e);return Lo((()=>-1!==i),s("The discount (%s) must be different from -1.",i.toString())),function(e,t,i){let o=0;return Ko(i,((t,i)=>(o++,t+i/(1+e)**o)),t)}(i,0,t)},isExported:!0},hd={description:s("Computes the number of periods needed for an investment to reach a value."),args:[ba("rate (number)",s("The rate at which the investment grows each period.")),ba("present_value (number)",s("The investment's current value.")),ba("future_value (number)",s("The investment's desired future value."))],returns:["NUMBER"],compute:function(e,t,i){const o=Uo(e),n=Uo(t),r=Uo(i);return bh(o),Lo((()=>n>0),s("The present_value (%s) must be strictly positive.",n.toString())),Lo((()=>r>0),s("The future_value (%s) must be strictly positive.",r.toString())),(Math.log(r)-Math.log(n))/Math.log(1+o)},isExported:!0},dd={description:s("Periodic payment for an annuity investment."),args:[ba("rate (number)",s("The annualized rate of interest.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("present_value (number)",s("The current value of the annuity.")),ba("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=Uo(t),r=Uo(e),a=Wo(n)?1:0;let l=Uo(o),c=Uo(i);if(vh(s),0===r)return-(l+c)/s;let h=-(c*(1+r)**s+l);return h=h*r/((1+r*a)*((1+r)**s-1)),h},isExported:!0},ud={description:s("Payment on the principal of an investment."),args:[ba("rate (number)",s("The annualized rate of interest.")),ba("period (number)",s("The amortization period, in terms of number of periods.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("present_value (number)",s("The current value of the annuity.")),ba("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,n=0,r=0){n=n||0,r=r||0;const a=Uo(i),l=Uo(e),c=Uo(t),h=Wo(r)?1:0,d=Uo(n),u=Uo(o);vh(a),Lo((()=>c>0&&c<=a),s("The period must be between 1 and number_of_periods",a.toString()));const g=dd.compute(l,a,u,d,r);if(1===h&&1===c)return g;return g+-Jh.compute(l,0===h?c-1:c-2,g,u+g*h,0)*l},isExported:!0},gd={description:s("Present value of an annuity investment."),args:[ba("rate (number)",s("The interest rate.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("payment_amount (number)",s("The amount per period to be paid.")),ba("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=Uo(e),r=Uo(t),a=Uo(i),l=Uo(o),c=Wo(n)?1:0;return s?-(a*(1+s*c)*((1+s)**r-1)/s+l)/(1+s)**r:-(l+a*r)},isExported:!0},pd={description:s("Price of a security paying periodic interest."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("rate (number)",s("The annualized rate of interest.")),ba("yield (number)",s("The expected annual yield of the security.")),ba("redemption (number)",s("The redemption amount per 100 face value, or par.")),ba("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r,a=0){a=a||0;const l=Math.trunc(Uo(e)),c=Math.trunc(Uo(t)),h=Uo(i),d=Uo(o),u=Uo(n),g=Math.trunc(Uo(r)),p=Math.trunc(Uo(a));dh(l,c),gh(g),ph(p),Lo((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),Lo((()=>d>=0),s("The yield (%s) must be positive or null.",d.toString())),mh(u);const m=eh.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=1+d/g,C=100*h/g;if(1===f)return(C+u)/(v*d/g+1)-C*(1-v);let S=0;for(let e=1;e<=f;e++)S+=C/b**(e-1+v);return u/b**(f-1+v)+S-C*(1-v)},isExported:!0},md={description:s("Price of a discount security."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("discount (number)",s("The discount rate of the security at time of purchase.")),ba("redemption (number)",s("The redemption amount per 100 face value, or par.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Uo(e)),r=Math.trunc(Uo(t)),a=Uo(i),l=Uo(o),c=Math.trunc(Uo(n));dh(s,r),ph(c),Rh(a),mh(l);return l-a*l*eh.compute(s,r,c)},isExported:!0},fd={description:s("Calculates the price of a security paying interest at maturity, based on expected yield."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("issue (date)",s("The date the security was initially issued.")),ba("rate (number)",s("The annualized rate of interest.")),ba("yield (number)",s("The expected annual yield of the security.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=0){r=r||0;const a=Math.trunc(Uo(e)),l=Math.trunc(Uo(t)),c=Math.trunc(Uo(i)),h=Uo(o),d=Uo(n),u=Math.trunc(Uo(r));uh(a,c),dh(a,l),ph(u),Lo((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),Lo((()=>d>=0),s("The yield (%s) must be positive or null.",d.toString()));const g=eh.compute(a,l,u),p=eh.compute(a,c,u);return(100+eh.compute(c,l,u)*h*100)/(1+g*d)-p*h*100},isExported:!0},vd=.1,bd={description:s("Interest rate of an annuity investment."),args:[ba("number_of_periods (number)",s("The number of payments to be made.")),ba("payment_per_period (number)",s("The amount per period to be paid.")),ba("present_value (number)",s("The current value of the annuity.")),ba("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period.")),ba("rate_guess (number, default=0.1)",s("An estimate for what the interest rate will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t,i,o=0,n=0,r=.1){o=o||0,n=n||0,r=r||vd;const a=Uo(e),l=Uo(t),c=Wo(n)?1:0,h=Uo(r);let d=Uo(o),u=Uo(i);vh(a),Lo((()=>[l,u,d].some((e=>e>0))&&[l,u,d].some((e=>e<0))),s("There must be both positive and negative values in [payment_amount, present_value, future_value].",a.toString())),Nh(h),d-=l*c,u+=l*c;return kh((e=>{const t=Math.pow(1+e,a);return d+u*t+l*((t-1)/e)}),(e=>{const t=Math.pow(1+e,a-1),i=Math.pow(1+e,a);return u*a*t+l*(a*t/e-(i-1)/e/e)}),h,40,1e-5)},isExported:!0},Cd={description:s("Amount received at maturity for a security."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("investment (number)",s("The amount invested (irrespective of face value of each security).")),ba("discount (number)",s("The discount rate of the security invested in.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Uo(e)),r=Math.trunc(Uo(t)),a=Uo(i),l=Uo(o),c=Math.trunc(Uo(n));dh(s,r),ph(c),Ih(a),Rh(l);return a/(1-l*eh.compute(s,r,c))},isExported:!0},Sd={description:s("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[ba("number_of_periods (number)",s("The number of periods.")),ba("present_value (number)",s("The present value of the investment.")),ba("future_value (number)",s("The future value of the investment."))],returns:["NUMBER"],compute:function(e,t,i){const o=Uo(e),n=Uo(t),s=Uo(i);return vh(o),(s/n)**(1/o)-1},isExported:!0},Ed={description:s("Depreciation of an asset using the straight-line method."),args:[ba("cost (number)",s("The initial cost of the asset.")),ba("salvage (number)",s("The value of the asset at the end of depreciation.")),ba("life (number)",s("The number of periods over which the asset is depreciated."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i){return(Uo(e)-Uo(t))/Uo(i)},isExported:!0},wd={description:s("Depreciation via sum of years digit method."),args:[ba("cost (number)",s("The initial cost of the asset.")),ba("salvage (number)",s("The value of the asset at the end of depreciation.")),ba("life (number)",s("The number of periods over which the asset is depreciated.")),ba("period (number)",s("The single period within life for which to calculate depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o){const n=Uo(e),s=Uo(t),r=Uo(i),a=Uo(o);Eh(a),Ch(r),xh(a,r);return(r-a+1)/(r*(r+1)/2)*(n-s)},isExported:!0},yd={description:s("Price of a US Treasury bill."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("discount (number)",s("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,i){const o=Math.trunc(Uo(e)),n=Math.trunc(Uo(t)),s=Uo(i);dh(o,n),Mh(o,n),Rh(s),Th(s);return 100*(1-s*eh.compute(o,n,2))},isExported:!0},xd={description:s("Equivalent rate of return for a US Treasury bill."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("discount (number)",s("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,i){const o=Math.trunc(Uo(e)),n=Math.trunc(Uo(t)),s=Uo(i);dh(o,n),Mh(o,n),Rh(s),Th(s);const r=Fc.compute(n,o);if(r<=182)return 365*s/(360-s*r);const a=yd.compute(o,n,s)/100,l=r/(366===r?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},Id={description:s("The yield of a US Treasury bill based on price."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("price (number)",s("The price at which the security is bought per 100 face value."))],returns:["NUMBER"],compute:function(e,t,i){const o=Math.trunc(Uo(e)),n=Math.trunc(Uo(t)),s=Uo(i);dh(o,n),Mh(o,n),fh(s);return(100-s)/s*(1/eh.compute(o,n,2))},isExported:!0},Rd={description:s("Variable declining balance. WARNING : does not handle decimal periods."),args:[ba("cost (number)",s("The initial cost of the asset.")),ba("salvage (number)",s("The value of the asset at the end of depreciation.")),ba("life (number)",s("The number of periods over which the asset is depreciated.")),ba("start (number)",s("Starting period to calculate depreciation.")),ba("end (number)",s("Ending period to calculate depreciation.")),ba("factor (number, default=2)",s("The number of months in the first year of depreciation.")),ba("no_switch (number, default=false)",s("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=2,a=false){r=r||0;const l=Uo(e),c=Uo(t),h=Uo(i),d=Math.trunc(Uo(o)),u=Math.trunc(Uo(n)),g=Uo(r),p=Wo(a);if(Sh(l),wh(c),function(e,t,i){Ch(i),Lo((()=>e>=0),s("The start_period (%s) must be greater or equal than 0.",e.toString())),Lo((()=>t>=0),s("The end_period (%s) must be greater or equal than 0.",t.toString())),Lo((()=>e<=t),s("The start_period (%s) must be smaller or equal to the end_period (%s).",e.toString(),t.toString())),Lo((()=>t<=i),s("The end_period (%s) must be smaller or equal to the life (%s).",e.toString(),i.toString()))}(d,u,h),Ah(g),0===l)return 0;if(c>=l)return d<1?l-c:0;const m=g/h;if(m>=1)return d<1?l-c:0;let f=l,v=0,b=0,C=!1;for(let e=0;e<u;e++){if(!C||p){const t=f*m,i=(f-c)/(h-e);!p&&i>t?(C=!0,v=i):v=t}const t=Math.max(f-v,c);e>=d&&(b+=f-t),f=t}return b},isExported:!0},Td={description:s("Internal rate of return given non-periodic cash flows."),args:[ba("cashflow_amounts (range<number>)",s("An range containing the income or payments associated with the investment.")),ba("cashflow_dates (range<number>)",s("An range with dates corresponding to the cash flows in cashflow_amounts.")),ba("rate_guess (number, default=0.1)",s("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],compute:function(e,t,i=.1){const o=Uo(i=i||0),n=e.flat().map(Uo),r=t.flat().map(Uo);var a;_h(e,t),a=n,Lo((()=>a.some((e=>e>0))&&a.some((e=>e<0))),s("There must be both positive and negative values in cashflow_amounts.")),Fh(r),Nh(o);const l=new Map;for(const e of $e(0,r.length)){const t=r[e];l.has(t)?l.set(t,l.get(t)+n[e]):l.set(t,n[e])}const c=Array.from(l.keys()),h=c.map((e=>l.get(e)));return kh((e=>{let t=h[0];for(const i of $e(1,h.length)){const o=(c[0]-c[i])/365;t+=h[i]*(1+e)**o}return t}),(e=>{let t=0;for(const i of $e(1,h.length)){const o=(c[0]-c[i])/365;t+=o*h[i]*(1+e)**(o-1)}return t}),o,40,1e-5,(e=>e?e/10-.9:-.9))},isExported:!0},Ad={description:s("Net present value given to non-periodic cash flows.."),args:[ba("discount (number)",s("The discount rate of the investment over one period.")),ba("cashflow_amounts (number, range<number>)",s("An range containing the income or payments associated with the investment.")),ba("cashflow_dates (number, range<number>)",s("An range with dates corresponding to the cash flows in cashflow_amounts."))],returns:["NUMBER"],compute:function(e,t,i){const o=Uo(e),n=Array.isArray(t)?t.flat().map(Vo):[Vo(t)],r=Array.isArray(i)?i.flat().map(Vo):[Vo(i)];if(Array.isArray(i)&&Array.isArray(t)?_h(t,i):Lo((()=>n.length===r.length),s("There must be the same number of values in cashflow_amounts and cashflow_dates.")),Fh(r),bh(o),1===n.length)return n[0];const a=new Map;for(const e of $e(0,r.length)){const t=r[e];a.has(t)?a.set(t,a.get(t)+n[e]):a.set(t,n[e])}const l=Array.from(a.keys()),c=l.map((e=>a.get(e)));let h=c[0];for(const e of $e(1,c.length)){const t=(l[0]-l[e])/365;h+=c[e]*(1+o)**t}return h},isExported:!0},Md={description:s("Annual yield of a security paying periodic interest."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("rate (number)",s("The annualized rate of interest.")),ba("price (number)",s("The price at which the security is bought per 100 face value.")),ba("redemption (number)",s("The redemption amount per 100 face value, or par.")),ba("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r,a=0){a=a||0;const l=Math.trunc(Uo(e)),c=Math.trunc(Uo(t)),h=Uo(i),d=Uo(o),u=Uo(n),g=Math.trunc(Uo(r)),p=Math.trunc(Uo(a));dh(l,c),gh(g),ph(p),Lo((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),fh(d),mh(u);const m=eh.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=100*h/g;if(1===f){const e=d+b*(1-v);return(u+b-e)*g*(1/v)/e}const C=kh((function(e){return function(e,t,i,o,n,s){let r=s-(e+n*(1-t))*o**(i-1+t);for(let e=1;e<=i;e++)r+=n*o**(e-1);return r}(d,v,f,e,b,u)}),(function(e){return function(e,t,i,o,n){let s=-(e+n*(1-t))*(i-1+t)*o**(i-2+t);for(let e=1;e<=i;e++)s+=n*(e-1)*o**(e-2);return s}(d,v,f,e,b)}),1+(h+1)/g,100,1e-5);return(C-1)*g},isExported:!0},Od={description:s("Annual yield of a discount security."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("price (number)",s("The price at which the security is bought per 100 face value.")),ba("redemption (number)",s("The redemption amount per 100 face value, or par.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Uo(e)),r=Math.trunc(Uo(t)),a=Uo(i),l=Uo(o),c=Math.trunc(Uo(n));dh(s,r),ph(c),fh(a),mh(l);return(l/a-1)/eh.compute(e,t,n)},isExported:!0},Nd={description:s("Annual yield of a security paying interest at maturity."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("issue (date)",s("The date the security was initially issued.")),ba("rate (number)",s("The annualized rate of interest.")),ba("price (number)",s("The price at which the security is bought.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=0){r=r||0;const a=Math.trunc(Uo(e)),l=Math.trunc(Uo(t)),c=Math.trunc(Uo(i)),h=Uo(o),d=Uo(n),u=Math.trunc(Uo(r));dh(a,l),ph(u),Lo((()=>a>=c),s("The settlement (%s) must be greater than or equal to the issue (%s).",a.toString(),c.toString())),Lo((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),fh(d);const g=eh.compute(c,l,u),p=eh.compute(c,a,u),m=eh.compute(a,l,u);return(100*(1+h*g)/(d+100*h*p)-1)/m},isExported:!0};var _d=Object.freeze({__proto__:null,ACCRINTM:Lh,AMORLINC:Ph,COUPDAYS:Uh,COUPDAYBS:Vh,COUPDAYSNC:zh,COUPNCD:Bh,COUPNUM:Hh,COUPPCD:$h,CUMIPMT:Wh,CUMPRINC:Gh,DB:qh,DDB:Zh,DISC:jh,DOLLARDE:Yh,DOLLARFR:Xh,DURATION:Kh,EFFECT:Qh,FV:Jh,FVSCHEDULE:ed,INTRATE:td,IPMT:id,IRR:od,ISPMT:nd,MDURATION:sd,MIRR:rd,NOMINAL:ad,NPER:ld,NPV:cd,PDURATION:hd,PMT:dd,PPMT:ud,PV:gd,PRICE:pd,PRICEDISC:md,PRICEMAT:fd,RATE:bd,RECEIVED:Cd,RRI:Sd,SLN:Ed,SYD:wd,TBILLPRICE:yd,TBILLEQ:xd,TBILLYIELD:Id,VDB:Rd,XIRR:Td,XNPV:Ad,YIELD:Md,YIELDDISC:Od,YIELDMAT:Nd});const Fd={description:s("Whether a value is an error other than #N/A."),args:[ba("value (any, lazy)",s("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)!=a.NotAvailable}},isExported:!0},Dd={description:s("Whether a value is an error."),args:[ba("value (any, lazy)",s("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},kd={description:s("Whether a value is `true` or `false`."),args:[ba("value (any, lazy)",s("The value to be verified as a logical TRUE or FALSE."))],returns:["BOOLEAN"],compute:function(e){try{return"boolean"==typeof e()}catch(e){return!1}},isExported:!0},Ld={description:s("Whether a value is the error #N/A."),args:[ba("value (any, lazy)",s("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)==a.NotAvailable}},isExported:!0},Pd={description:s("Whether a value is non-textual."),args:[ba("value (any, lazy)",s("The value to be checked."))],returns:["BOOLEAN"],compute:function(e){try{return"string"!=typeof e()}catch(e){return!0}},isExported:!0},Ud={description:s("Whether a value is a number."),args:[ba("value (any, lazy)",s("The value to be verified as a number."))],returns:["BOOLEAN"],compute:function(e){try{return"number"==typeof e()}catch(e){return!1}},isExported:!0},Vd={description:s("Whether a value is text."),args:[ba("value (any, lazy)",s("The value to be verified as text."))],returns:["BOOLEAN"],compute:function(e){try{return"string"==typeof e()}catch(e){return!1}},isExported:!0},zd={description:s("Whether the referenced cell is empty"),args:[ba("value (any, lazy)",s("Reference to the cell that will be checked for emptiness."))],returns:["BOOLEAN"],compute:function(e){try{return null===e()}catch(e){return!1}},isExported:!0},Bd={description:s("Returns the error value #N/A."),args:[],returns:["BOOLEAN"],compute:function(e){throw new g},isExported:!0};var Hd=Object.freeze({__proto__:null,ISERR:Fd,ISERROR:Dd,ISLOGICAL:kd,ISNA:Ld,ISNONTEXT:Pd,ISNUMBER:Ud,ISTEXT:Vd,ISBLANK:zd,NA:Bd});const $d={description:s("Logical `and` operator."),args:[ba("logical_expression1 (boolean, range<boolean>)",s("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.")),ba("logical_expression2 (boolean, range<boolean>, repeating)",s("More expressions that represent logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!0;return Jo(e,(e=>(t=!0,i=i&&e,i))),Lo((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0},Wd={description:s("Returns value depending on logical expression."),args:[ba("logical_expression (boolean)",s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")),ba("value_if_true (any, lazy)",s("The value the function returns if logical_expression is TRUE.")),ba("value_if_false (any, lazy, default=FALSE)",s("The value the function returns if logical_expression is FALSE."))],returns:["ANY"],compute:function(e,t,i=(()=>!1)){const o=Wo(e)?t():i();return null==o?"":o},isExported:!0},Gd={description:s("Value if it is not an error, otherwise 2nd argument."),args:[ba("value (any, lazy)",s("The value to return if value itself is not an error.")),ba('value_if_error (any, lazy, default="empty")',s("The value the function returns if value is an error."))],returns:["ANY"],computeFormat:(e,t=(()=>({value:""})))=>{var i;try{return e().format}catch(e){return null===(i=t())||void 0===i?void 0:i.format}},compute:function(e,t=(()=>"")){let i;try{i=e()}catch(e){i=t()}return null==i?"":i},isExported:!0},qd={description:s("Value if it is not an #N/A error, otherwise 2nd argument."),args:[ba("value (any, lazy)",s("The value to return if value itself is not #N/A an error.")),ba('value_if_error (any, lazy, default="empty")',s("The value the function returns if value is an #N/A error."))],returns:["ANY"],compute:function(e,t=(()=>"")){let i;try{i=e()}catch(o){i=o.errorType===a.NotAvailable?t():e()}return null==i?"":i},isExported:!0},Zd={description:s("Returns a value depending on multiple logical expressions."),args:[ba("condition1 (boolean, lazy)",s("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")),ba("value1 (any, lazy)",s("The returned value if condition1 is TRUE.")),ba("condition2 (boolean, lazy, repeating)",s("Additional conditions to be evaluated if the previous ones are FALSE.")),ba("value2 (any, lazy, repeating)",s("Additional values to be returned if their corresponding conditions are TRUE."))],returns:["ANY"],compute:function(...e){Lo((()=>e.length%2==0),s("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(Wo(e[t]())){const i=e[t+1]();return null!==i?i:""}throw new Error(s("No match."))},isExported:!0},jd={description:s("Returns opposite of provided logical value."),args:[ba("logical_expression (boolean)",s("An expression or reference to a cell holding an expression that represents some logical value."))],returns:["BOOLEAN"],compute:function(e){return!Wo(e)},isExported:!0},Yd={description:s("Logical `or` operator."),args:[ba("logical_expression1 (boolean, range<boolean>)",s("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.")),ba("logical_expression2 (boolean, range<boolean>, repeating)",s("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!1;return Jo(e,(e=>(t=!0,i=i||e,!i))),Lo((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0},Xd={description:s("Logical `xor` operator."),args:[ba("logical_expression1 (boolean, range<boolean>)",s("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.")),ba("logical_expression2 (boolean, range<boolean>, repeating)",s("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!1;return Jo(e,(e=>(t=!0,i=i?!e:e,!0))),Lo((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0};var Kd=Object.freeze({__proto__:null,AND:$d,IF:Wd,IFERROR:Gd,IFNA:qd,IFS:Zd,NOT:jd,OR:Yd,XOR:Xd});function Qd(e,t){if(void 0===e)throw new g(s("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",zo(t)))}const Jd={description:s("Column number of a specified cell."),args:[ba("cell_reference (meta, default='this cell')",s("The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered."))],returns:["NUMBER"],compute:function(e){var t;const i=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this));Lo((()=>!!i),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Hi(i).left+1},isExported:!0},eu={description:s("Number of columns in a specified array or range."),args:[ba("range (meta)",s("The range whose column count will be returned."))],returns:["NUMBER"],compute:function(e){const t=Hi(e);return t.right-t.left+1},isExported:!0},tu={description:s("Horizontal lookup"),args:[ba("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),ba("range (range)",s("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")),ba("index (number)",s("The row index of the value to be returned, where the first row in range is numbered 1.")),ba("is_sorted (boolean, default=true)",s("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."))],returns:["ANY"],compute:function(e,t,i,o=true){const n=Math.trunc(Uo(i)),r=Ho(e);Lo((()=>1<=n&&n<=t[0].length),s("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Wo(o)?rn(t,r,"nextSmaller","asc",t.length,sn):an(t,r,"strict",t.length,sn);const l=t[a];return Qd(l,e),l[n-1]},isExported:!0},iu={description:s("Returns the content of a cell, specified by row and column offset."),args:[ba("reference (any, range)",s("The range of cells from which the values are returned.")),ba("row (number)",s("The index of the row to be returned from within the reference range of cells.")),ba("column (number)",s("The index of the column to be returned from within the reference range of cells."))],returns:["ANY"],computeFormat:(e,t,i)=>{var o;const n=Uo(t.value);return null===(o=e[Uo(i.value)-1][n-1])||void 0===o?void 0:o.format},compute:function(e,t,i){const o=(n=e,Array.isArray(n)&&Array.isArray(n[0])?e:[[e]]);var n;const r=Uo(t),a=Uo(i);return Lo((()=>a>=0&&a-1<o.length&&r>=0&&r-1<o[0].length),s("Index out of range.")),Lo((()=>0!==t&&0!==i),s("This function can only return a single cell value, not an array. Provide valid row and column indices.")),o[a-1][r-1]},isExported:!0},ou={description:s("Look up a value."),args:[ba("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),ba("search_array (range)",s("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.")),ba("result_range (range, optional)",s("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."))],returns:["ANY"],compute:function(e,t,i){let o=t.length,n=t[0].length;const r=Ho(e),a=n>=o,l=rn(t,r,"nextSmaller","asc",a?n:o,a?nn:sn);return-1===l&&Qd(void 0,e),Qd(a?t[0][l]:t[l][n-1],e),void 0===i?a?t[o-1][l]:t[l][n-1]:(o=i.length,n=i[0].length,Lo((()=>1===o||1===n),s("The result_range must be a single row or a single column.")),o>1?(Lo((()=>l<=o-1),s("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(l+1).toString())),i[l][0]):(Lo((()=>l<=n-1),s("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(l+1).toString())),i[0][l]))},isExported:!0},nu={description:s("Position of item in range that matches value."),args:[ba("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),ba("range (any, range)",s("The one-dimensional array to be searched.")),ba("search_type (number, default=1)",s("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."))],returns:["NUMBER"],compute:function(e,t,i=1){let o=Uo(i);const n=Ho(e),r=t.length,a=t[0].length;Lo((()=>1===r||1===a),s("The range must be a single row or a single column."));let l=-1;const c=1===r?nn:sn,h=1===r?t[0].length:t.length;switch(o=Math.sign(o),o){case 1:l=rn(t,n,"nextSmaller","asc",h,c);break;case 0:l=an(t,n,"strict",h,c);break;case-1:l=rn(t,n,"nextGreater","desc",h,c)}return Qd(1===r?t[0][l]:t[l],e),l+1},isExported:!0},su={description:s("Row number of a specified cell."),args:[ba("cell_reference (meta, default='this cell')",s("The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered."))],returns:["NUMBER"],compute:function(e){var t;e=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this)),Lo((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Hi(e).top+1},isExported:!0},ru={description:s("Number of rows in a specified array or range."),args:[ba("range (meta)",s("The range whose row count will be returned."))],returns:["NUMBER"],compute:function(e){const t=Hi(e);return t.bottom-t.top+1},isExported:!0},au={description:s("Vertical lookup."),args:[ba("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),ba("range (any, range)",s("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")),ba("index (number)",s("The column index of the value to be returned, where the first column in range is numbered 1.")),ba("is_sorted (boolean, default=true)",s("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."))],returns:["ANY"],compute:function(e,t,i,o=true){const n=Math.trunc(Uo(i)),r=Ho(e);Lo((()=>1<=n&&n<=t.length),s("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Wo(o)?rn(t,r,"nextSmaller","asc",t[0].length,nn):an(t,r,"strict",t[0].length,nn);const l=t[n-1][a];return Qd(l,e),l},isExported:!0},lu={description:s("Search a range for a match and return the corresponding item from a second range."),args:[ba("search_key (any)",s("The value to search for.")),ba("lookup_range (any, range)",s("The range to consider for the search. Should be a single column or a single row.")),ba("return_range (any, range)",s("The range containing the return value. Should have the same dimensions as lookup_range.")),ba("if_not_found (any, lazy, optional)",s("If a valid match is not found, return this value.")),ba("match_mode (any, default=0)",s("(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match.")),ba("search_mode (any, default=1)",s("(1) Search starting at first item. (-1) Search starting at last item. (2) Perform a binary search that relies on lookup_array being sorted in ascending order. If not sorted, invalid results will be returned. (-2) Perform a binary search that relies on lookup_array being sorted in descending order. If not sorted, invalid results will be returned. "))],returns:["ANY"],compute:function(e,t,i,o,n=0,r=1){const a=Math.trunc(Uo(n)),l=Math.trunc(Uo(r)),c=Ho(e);Lo((()=>1===t.length||1===t[0].length),s("lookup_range should be either a single row or single column.")),Lo((()=>1===i.length||1===i[0].length),s("return_range should be either a single row or single column.")),Lo((()=>i.length===t.length&&i[0].length===t[0].length),s("return_range should have the same dimensions as lookup_range.")),Lo((()=>[-1,1,-2,2].includes(l)),s("searchMode should be a value in [-1, 1, -2, 2].")),Lo((()=>[-1,0,1].includes(a)),s("matchMode should be a value in [-1, 0, 1]."));const h=1===t.length?nn:sn,d=1===t.length?t[0].length:t.length,u=0===a?"strict":1===a?"nextGreater":"nextSmaller",g=-1===l;let p;if(2===l||-2===l){p=rn(t,c,u,2===l?"asc":"desc",d,h)}else p=an(t,c,u,d,h,g);if(-1!==p)return 1===t.length?i[0][p]:i[p][0];const m=null==o?void 0:o();return Qd(m,e),m},isExported:!0};var cu=Object.freeze({__proto__:null,COLUMN:Jd,COLUMNS:eu,HLOOKUP:tu,INDEX:iu,LOOKUP:ou,MATCH:nu,ROW:su,ROWS:ru,VLOOKUP:au,XLOOKUP:lu});const hu={description:s("Sum of two numbers."),args:[ba("value1 (number)",s("The first addend.")),ba("value2 (number)",s("The second addend."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Uo(e)+Uo(t)}},du={description:s("Concatenation of two values."),args:[ba("value1 (string)",s("The value to which value2 will be appended.")),ba("value2 (string)",s("The value to append to value1."))],returns:["STRING"],compute:function(e,t){return zo(e)+zo(t)},isExported:!0},uu={description:s("One number divided by another."),args:[ba("dividend (number)",s("The number to be divided.")),ba("divisor (number)",s("The number to divide by."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){const i=Uo(t);return Lo((()=>0!==i),s("The divisor must be different from zero.")),Uo(e)/i}};function gu(e){return null==e}const pu={number:0,string:"",boolean:!1},mu={description:s("Equal."),args:[ba("value1 (any)",s("The first value.")),ba("value2 (any)",s("The value to test against value1 for equality."))],returns:["BOOLEAN"],compute:function(e,t){return e=gu(e)?pu[typeof t]:e,t=gu(t)?pu[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function fu(e,t,i){e=gu(e)?pu[typeof t]:e,t=gu(t)?pu[typeof e]:t,"number"!=typeof e&&(e=zo(e).toUpperCase()),"number"!=typeof t&&(t=zo(t).toUpperCase());const o=typeof e,n=typeof t;return"string"===o&&"number"===n||("string"!==n||"number"!==o)&&i(e,t)}const vu={description:s("Strictly greater than."),args:[ba("value1 (any)",s("The value to test as being greater than value2.")),ba("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return fu(e,t,((e,t)=>e>t))}},bu={description:s("Greater than or equal to."),args:[ba("value1 (any)",s("The value to test as being greater than or equal to value2.")),ba("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return fu(e,t,((e,t)=>e>=t))}},Cu={description:s("Less than."),args:[ba("value1 (any)",s("The value to test as being less than value2.")),ba("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!bu.compute(e,t)}},Su={description:s("Less than or equal to."),args:[ba("value1 (any)",s("The value to test as being less than or equal to value2.")),ba("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!vu.compute(e,t)}},Eu={description:s("Difference of two numbers."),args:[ba("value1 (number)",s("The minuend, or number to be subtracted from.")),ba("value2 (number)",s("The subtrahend, or number to subtract from value1."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Uo(e)-Uo(t)}},wu={description:s("Product of two numbers"),args:[ba("factor1 (number)",s("The first multiplicand.")),ba("factor2 (number)",s("The second multiplicand."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Uo(e)*Uo(t)}},yu={description:s("Not equal."),args:[ba("value1 (any)",s("The first value.")),ba("value2 (any)",s("The value to test against value1 for inequality."))],returns:["BOOLEAN"],compute:function(e,t){return!mu.compute(e,t)}},xu={description:s("A number raised to a power."),args:[ba("base (number)",s("The number to raise to the exponent power.")),ba("exponent (number)",s("The exponent to raise base to."))],returns:["NUMBER"],compute:function(e,t){return rl.compute(e,t)}},Iu={description:s("A number with the sign reversed."),args:[ba("value (number)",s("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],computeFormat:e=>null==e?void 0:e.format,returns:["NUMBER"],compute:function(e){return-Uo(e)}},Ru={description:s("Value interpreted as a percentage."),args:[ba("percentage (number)",s("The value to interpret as a percentage."))],returns:["NUMBER"],compute:function(e){return Uo(e)/100}},Tu={description:s("A specified number, unchanged."),args:[ba("value (any)",s("The number to return."))],returns:["ANY"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){return null===e?"":e}};var Au=Object.freeze({__proto__:null,ADD:hu,CONCAT:du,DIVIDE:uu,EQ:mu,GT:vu,GTE:bu,LT:Cu,LTE:Su,MINUS:Eu,MULTIPLY:wu,NE:yu,POW:xu,UMINUS:Iu,UNARY_PERCENT:Ru,UPLUS:Tu});const Mu=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,Ou={description:s("Gets character associated with number."),args:[ba("table_number (number)",s("The number of the character to look up from the current Unicode table in decimal format."))],returns:["STRING"],compute:function(e){const t=Math.trunc(Uo(e));return Lo((()=>t>=1),s("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},Nu={description:s("Remove non-printable characters from a piece of text."),args:[ba("text (string)",s("The text whose non-printable characters are to be removed."))],returns:["STRING"],compute:function(e){const t=zo(e);let i="";for(const e of t)e&&e.charCodeAt(0)>31&&(i+=e);return i},isExported:!0},_u={description:s("Appends strings to one another."),args:[ba("string1 (string, range<string>)",s("The initial string.")),ba("string2 (string, range<string>, repeating)",s("More strings to append in sequence."))],returns:["STRING"],compute:function(...e){return Xo(e,((e,t)=>e+zo(t)),"")},isExported:!0},Fu={description:s("Tests whether two strings are identical."),args:[ba("string1 (string)",s("The first string to compare.")),ba("string2 (string)",s("The second string to compare."))],returns:["BOOLEAN"],compute:function(e,t){return zo(e)===zo(t)},isExported:!0},Du={description:s("First position of string found in text, case-sensitive."),args:[ba("search_for (string)",s("The string to look for within text_to_search.")),ba("text_to_search (string)",s("The text to search for the first occurrence of search_for.")),ba("starting_at (number, default=1)",s("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,i=1){const o=zo(e),n=zo(t),r=Uo(i);Lo((()=>""!==n),s("The text_to_search must be non-empty.")),Lo((()=>r>=1),s("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=n.indexOf(o,r-1);return Lo((()=>a>=0),s("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o.toString(),n)),a+1},isExported:!0},ku={description:s("Concatenates elements of arrays with delimiter."),args:[ba("delimiter (string)",s("The character or string to place between each concatenated value.")),ba("value_or_array1 (string, range<string>)",s("The value or values to be appended using delimiter.")),ba("value_or_array2 (string, range<string>, repeating)",s("More values to be appended using delimiter."))],returns:["STRING"],compute:function(e,...t){const i=zo(e);return Xo(t,((e,t)=>(e?e+i:"")+zo(t)),"")}},Lu={description:s("Substring from beginning of specified string."),args:[ba("text (string)",s("The string from which the left portion will be returned.")),ba("number_of_characters (number, optional)",s("The number of characters to return from the left side of string."))],returns:["STRING"],compute:function(e,...t){const i=t.length?Uo(t[0]):1;return Lo((()=>i>=0),s("The number_of_characters (%s) must be positive or null.",i.toString())),zo(e).substring(0,i)},isExported:!0},Pu={description:s("Length of a string."),args:[ba("text (string)",s("The string whose length will be returned."))],returns:["NUMBER"],compute:function(e){return zo(e).length},isExported:!0},Uu={description:s("Converts a specified string to lowercase."),args:[ba("text (string)",s("The string to convert to lowercase."))],returns:["STRING"],compute:function(e){return zo(e).toLowerCase()},isExported:!0},Vu={description:s("A segment of a string."),args:[ba("text (string)",s("The string to extract a segment from.")),ba("starting_at (number)",s("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),ba("extract_length (number)",s("The length of the segment to extract."))],returns:["STRING"],compute:function(e,t,i){const o=zo(e),n=Uo(t),r=Uo(i);return Lo((()=>n>=1),s("The starting_at argument (%s) must be positive greater than one.",n.toString())),Lo((()=>r>=0),s("The extract_length argument (%s) must be positive or null.",r.toString())),o.slice(n-1,n+r-1)},isExported:!0},zu={description:s("Capitalizes each word in a specified string."),args:[ba("text_to_capitalize (string)",s("The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase."))],returns:["STRING"],compute:function(e){return zo(e).replace(Mu,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},Bu={description:s("Replaces part of a text string with different text."),args:[ba("text (string)",s("The text, a part of which will be replaced.")),ba("position (number)",s("The position where the replacement will begin (starting from 1).")),ba("length (number)",s("The number of characters in the text to be replaced.")),ba("new_text (string)",s("The text which will be inserted into the original text."))],returns:["STRING"],compute:function(e,t,i,o){const n=Uo(t);Lo((()=>n>=1),s("The position (%s) must be greater than or equal to 1.",n.toString()));const r=zo(e),a=Uo(i),l=zo(o);return r.substring(0,n-1)+l+r.substring(n-1+a)},isExported:!0},Hu={description:s("A substring from the end of a specified string."),args:[ba("text (string)",s("The string from which the right portion will be returned.")),ba("number_of_characters (number, optional)",s("The number of characters to return from the right side of string."))],returns:["STRING"],compute:function(e,...t){const i=t.length?Uo(t[0]):1;Lo((()=>i>=0),s("The number_of_characters (%s) must be positive or null.",i.toString()));const o=zo(e),n=o.length;return o.substring(n-i,n)},isExported:!0},$u={description:s("First position of string found in text, ignoring case."),args:[ba("search_for (string)",s("The string to look for within text_to_search.")),ba("text_to_search (string)",s("The text to search for the first occurrence of search_for.")),ba("starting_at (number, default=1)",s("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,i=1){const o=zo(e).toLowerCase(),n=zo(t).toLowerCase(),r=Uo(i);Lo((()=>""!==n),s("The text_to_search must be non-empty.")),Lo((()=>r>=1),s("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=n.indexOf(o,r-1);return Lo((()=>a>=0),s("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,n)),a+1},isExported:!0},Wu={description:s("Replaces existing text with new text in a string."),args:[ba("text_to_search (string)",s("The text within which to search and replace.")),ba("search_for (string)",s("The string to search for within text_to_search.")),ba("replace_with (string)",s("The string that will replace search_for.")),ba("occurrence_number (number, optional)",s("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."))],returns:["NUMBER"],compute:function(e,t,i,o){const n=Uo(o);Lo((()=>n>=0),s("The occurrenceNumber (%s) must be positive or null.",n.toString()));const r=zo(e),a=zo(t);if(""===a)return r;const l=zo(i),c=new RegExp(_e(a),"g");if(0===n)return r.replace(c,l);let h=0;return r.replace(c,(e=>++h===n?l:e))},isExported:!0},Gu={description:s("Combines text from multiple strings and/or arrays."),args:[ba("delimiter (string)",s(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")),ba("ignore_empty (boolean)",s("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")),ba("text1 (string, range<string>)",s("Any text item. This could be a string, or an array of strings in a range.")),ba("text2 (string, range<string>, repeating)",s("Additional text item(s)."))],returns:["STRING"],compute:function(e,t,...i){const o=zo(e),n=Wo(t);let s=0;return Xo(i,((e,t)=>n&&""===zo(t)?e:(s++?e+o:"")+zo(t)),"")},isExported:!0},qu={description:s("Removes space characters."),args:[ba("text (string)",s("The text or reference to a cell containing text to be trimmed."))],returns:["STRING"],compute:function(e){return zo(e).trim()},isExported:!0},Zu={description:s("Converts a specified string to uppercase."),args:[ba("text (string)",s("The string to convert to uppercase."))],returns:["STRING"],compute:function(e){return zo(e).toUpperCase()},isExported:!0},ju={description:s("Converts a number to text according to a specified format."),args:[ba("number (number)",s("The number, date or time to format.")),ba("format (string)",s("The pattern by which to format the number, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){return fi(Uo(e),zo(t))},isExported:!0};var Yu=Object.freeze({__proto__:null,CHAR:Ou,CLEAN:Nu,CONCATENATE:_u,EXACT:Fu,FIND:Du,JOIN:ku,LEFT:Lu,LEN:Pu,LOWER:Uu,MID:Vu,PROPER:zu,REPLACE:Bu,RIGHT:Hu,SEARCH:$u,SUBSTITUTE:Wu,TEXTJOIN:Gu,TRIM:qu,UPPER:Zu,TEXT:ju});const Xu={description:s("Creates a hyperlink in a cell."),args:[ba("url (string)",s("The full URL of the link enclosed in quotation marks.")),ba("link_label (string, optional)",s("The text to display in the cell, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){const i=zo(e).trim(),o=zo(t)||i;return""===i?o:Ke(o,i)},isExported:!0};var Ku=Object.freeze({__proto__:null,HYPERLINK:Xu});const Qu=[{name:s("Database"),functions:Mc},{name:s("Date"),functions:lh},{name:s("Financial"),functions:_d},{name:s("Info"),functions:Hd},{name:s("Lookup"),functions:cu},{name:s("Logical"),functions:Kd},{name:s("Math"),functions:xl},{name:s("Misc"),functions:Ea},{name:s("Operator"),functions:Au},{name:s("Statistical"),functions:pc},{name:s("Text"),functions:Yu},{name:s("Engineering"),functions:hh},{name:s("Web"),functions:Ku}],Ju=/^[A-Z0-9\_\.]+$/;function eg(e){return e.map((e=>{if(void 0!==e)return"function"==typeof e?()=>tg(e()):tg(e)}))}function tg(e){return Array.isArray(e)?e.map((e=>e.map((e=>null==e?void 0:e.value)))):null==e?void 0:e.value}const ig=new class extends Ro{constructor(){super(...arguments),this.mapping={}}add(e,t){if(!(e=e.toUpperCase()).match(Ju))throw new Error(s("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const i=Ca(t);return function(e){let t=!1,i=!1,o=!1;for(let n of e){if(n.type.includes("META")&&n.type.length>1)throw new Error(s("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&&!n.repeating)throw new Error(s("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=i||t||o,r=!(n.optional||n.repeating||n.default);if(e&&r)throw new Error(s("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=n.repeating,i=n.optional,o=n.default}}(i.args),this.mapping[e]=function(...e){const t=i.compute.bind(this),o=i.computeFormat?i.computeFormat.bind(this):()=>{};return{value:t(...eg(e)),format:o(...e)}},super.add(e,i),this}};for(let e of Qu){const t=e.functions;for(let i in t){const o=t[i];o.category=o.category||e.name,i=i.replace(/_/g,"."),ig.add(i,{isExported:!1,...o})}}function og(e,t,i){const o=e.model.getters.getActiveSheetId(),n="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(n,{sheetId:o,quantity:i}).isCancelledBecause(65)&&e.raiseError(Ps)}const ng=new ls;ng.add("file",{name:s("File"),sequence:10}).add("edit",{name:s("Edit"),sequence:20}).add("view",{name:s("View"),sequence:30}).add("insert",{name:s("Insert"),sequence:40}).add("format",{name:s("Format"),sequence:50}).add("data",{name:s("Data"),sequence:60}).addChild("save",["file"],{name:s("Save"),description:"Ctrl+S",sequence:10,action:()=>console.log("Not implemented")}).addChild("undo",["edit"],{name:s("Undo"),description:"Ctrl+Z",sequence:10,action:e=>e.model.dispatch("REQUEST_UNDO")}).addChild("redo",["edit"],{name:s("Redo"),description:"Ctrl+Y",sequence:20,action:e=>e.model.dispatch("REQUEST_REDO"),separator:!0}).addChild("copy",["edit"],{name:s("Copy"),description:"Ctrl+C",sequence:30,isReadonlyAllowed:!0,action:Br}).addChild("cut",["edit"],{name:s("Cut"),description:"Ctrl+X",sequence:40,action:Hr}).addChild("paste",["edit"],{name:s("Paste"),description:"Ctrl+V",sequence:50,action:$r}).addChild("paste_special",["edit"],{name:s("Paste special"),sequence:60,separator:!0,isVisible:Zr}).addChild("paste_special_value",["edit","paste_special"],{name:s("Paste value only"),sequence:10,action:Wr}).addChild("paste_special_format",["edit","paste_special"],{name:s("Paste format only"),sequence:20,action:qr}).addChild("sort_range",["data"],{name:s("Sort range"),sequence:20,isVisible:ua,separator:!0}).addChild("sort_ascending",["data","sort_range"],{name:s("Ascending (A ⟶ Z)"),sequence:10,action:ha}).addChild("sort_descending",["data","sort_range"],{name:s("Descending (Z ⟶ A)"),sequence:20,action:da}).addChild("find_and_replace",["edit"],{name:s("Find and replace"),description:"Ctrl+H",sequence:65,isReadonlyAllowed:!0,action:e=>{e.openSidePanel("FindAndReplace",{})},separator:!0}).addChild("edit_delete_cell_values",["edit"],{name:s("Delete values"),sequence:70,action:e=>e.model.dispatch("DELETE_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})}).addChild("edit_delete_row",["edit"],{name:jr,sequence:80,action:Yr,isVisible:e=>Xr("ROW",e)}).addChild("edit_delete_column",["edit"],{name:Kr,sequence:90,action:Qr,isVisible:e=>Xr("COL",e)}).addChild("edit_delete_cell_shift_up",["edit"],{name:s("Delete cell and shift up"),sequence:93,action:ta}).addChild("edit_delete_cell_shift_left",["edit"],{name:s("Delete cell and shift left"),sequence:97,action:ia}).addChild("edit_unhide_columns",["edit"],{name:s("Unhide all columns"),sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"COL",elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0}).addChild("edit_unhide_rows",["edit"],{name:s("Unhide all rows"),sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"ROW",elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0}).addChild("insert_row_before",["insert"],{name:e=>{const t=Ur(e);return 1===t?s("Row above"):s("%s Rows above",t.toString())},sequence:10,action:oa,isVisible:e=>0===e.model.getters.getActiveCols().size}).addChild("insert_row_after",["insert"],{name:e=>{const t=Ur(e);return 1===t?s("Row below"):s("%s Rows below",t.toString())},sequence:20,action:na,isVisible:e=>0===e.model.getters.getActiveCols().size,separator:!0}).addChild("insert_column_before",["insert"],{name:e=>{const t=Pr(e);return 1===t?s("Column left"):s("%s Columns left",t.toString())},sequence:30,action:sa,isVisible:e=>0===e.model.getters.getActiveRows().size}).addChild("insert_column_after",["insert"],{name:e=>{const t=Pr(e);return 1===t?s("Column right"):s("%s Columns right",t.toString())},sequence:40,action:ra,isVisible:e=>0===e.model.getters.getActiveRows().size,separator:!0}).addChild("insert_insert_cell_shift_down",["insert"],{name:s("Insert cells and shift down"),sequence:43,action:Jr}).addChild("insert_insert_cell_shift_right",["insert"],{name:s("Insert cells and shift right"),sequence:47,action:ea,separator:!0}).addChild("insert_chart",["insert"],{name:s("Chart"),sequence:50,action:e=>{const t=e.model.getters,i=e.model.uuidGenerator.uuidv4(),o=t.getActiveSheetId();1===uo(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection();const n={width:536,height:335},s=function(e,t){const{x:i,y:o}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:s}=e.getActiveSheetScrollInfo(),{width:r,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:i+n+Math.max(0,(r-t.width)/2),y:o+s+Math.max(0,(a-t.height)/2)}}(t,n);e.model.dispatch("CREATE_CHART",{sheetId:o,id:i,position:s,size:n,definition:Tr(e.model.getters.getSelectedZone(),e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{id:i}),e.openSidePanel("ChartPanel"))}}).addChild("insert_image",["insert"],{name:s("Image"),sequence:55,action:async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),i=e.model.uuidGenerator.uuidv4(),o=await async function(e){try{return await e.imageProvider.requestImage()}catch{return void e.raiseError(s("An unexpected error occurred during the image transfer"))}}(e);if(!o)throw new Error("No image provider was given to the environment");const n=Cr(e.model.getters,o.size),r=function(e,t){const{x:i,y:o}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:s}=e.getActiveSheetScrollInfo(),r=e.getSheetViewDimension(),a=e.getVisibleRect(e.getActiveMainViewport()),l=Math.min(a.width,r.width-i),c=Math.min(a.height,r.height-o);return{x:i+n+Math.max(0,(l-t.width)/2),y:o+s+Math.max(0,(c-t.height)/2)}}(e.model.getters,n);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:i,position:r,size:n,definition:o})}},isVisible:e=>void 0!==e.imageProvider}).addChild("insert_function",["insert"],{name:s("Function"),sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{name:s("SUM"),action:e=>e.startCellEdition("=SUM("),sequence:0}).addChild("insert_function_average",["insert","insert_function"],{name:s("AVERAGE"),action:e=>e.startCellEdition("=AVERAGE("),sequence:10}).addChild("insert_function_count",["insert","insert_function"],{name:s("COUNT"),action:e=>e.startCellEdition("=COUNT("),sequence:20}).addChild("insert_function_max",["insert","insert_function"],{name:s("MAX"),action:e=>e.startCellEdition("=MAX("),sequence:30}).addChild("insert_function_min",["insert","insert_function"],{name:s("MIN"),action:e=>e.startCellEdition("=MIN("),sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{name:s("All"),sequence:50}).addChild("all_function_list",["insert","insert_function","categorie_function_all"],(()=>sg(ig.getKeys()))).addChild("categories_function_list",["insert","insert_function"],(()=>{const e=ig.content;return[...new Set(ig.getAll().map((e=>e.category)))].filter(ot).sort().map(((t,i)=>{const o=Object.keys(e).filter((i=>e[i].category===t));return{name:t,sequence:60+10*i,children:sg(o)}}))})).addChild("insert_link",["insert"],{name:s("Link"),separator:!0,sequence:70,action:la}).addChild("insert_sheet",["insert"],{name:s("New sheet"),sequence:80,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSheetIds().indexOf(t)+1,o=e.model.uuidGenerator.uuidv4();e.model.dispatch("CREATE_SHEET",{sheetId:o,position:i}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},separator:!0}).addChild("unfreeze_panes",["view"],{name:s("Unfreeze"),sequence:4,isVisible:e=>{const{xSplit:t,ySplit:i}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+i>0},action:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()})}).addChild("freeze_panes",["view"],{name:s("Freeze"),sequence:5,separator:!0}).addChild("unfreeze_rows",["view","freeze_panes"],{name:s("No rows"),action:e=>e.model.dispatch("UNFREEZE_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,sequence:5,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit}).addChild("freeze_first_row",["view","freeze_panes"],{name:s("1 row"),action:e=>og(e,"ROW",1),isReadonlyAllowed:!0,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{name:s("2 rows"),action:e=>og(e,"ROW",2),isReadonlyAllowed:!0,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{name:s("Up to current row"),action:e=>{const{bottom:t}=e.model.getters.getSelectedZone();og(e,"ROW",t+1)},isReadonlyAllowed:!0,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{name:s("No columns"),action:e=>e.model.dispatch("UNFREEZE_COLUMNS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,sequence:25,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit}).addChild("freeze_first_col",["view","freeze_panes"],{name:s("1 column"),action:e=>og(e,"COL",1),isReadonlyAllowed:!0,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{name:s("2 columns"),action:e=>og(e,"COL",2),isReadonlyAllowed:!0,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{name:s("Up to current column"),action:e=>{const{right:t}=e.model.getters.getSelectedZone();og(e,"COL",t+1)},isReadonlyAllowed:!0,sequence:40}).addChild("view_gridlines",["view"],{name:e=>e.model.getters.getGridLinesVisibility(e.model.getters.getActiveSheetId())?s("Hide gridlines"):s("Show gridlines"),action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},sequence:10}).addChild("view_formulas",["view"],{name:e=>e.model.getters.shouldShowFormulas()?s("Hide formulas"):s("Show formulas"),action:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,sequence:15}).addChild("format_number",["format"],{name:s("Numbers"),sequence:10,separator:!0}).addChild("format_number_automatic",["format","format_number"],{name:ks.Automatic,sequence:10,separator:!0,action:e=>Vr(e,"")}).addChild("format_number_number",["format","format_number"],{name:ks.Number,description:"1,000.12",sequence:20,action:e=>Vr(e,"#,##0.00")}).addChild("format_number_percent",["format","format_number"],{name:ks.Percent,description:"10.12%",sequence:30,separator:!0,action:e=>Vr(e,"0.00%")}).addChild("format_number_currency",["format","format_number"],{name:ks.Currency,description:"$1,000.12",sequence:37,action:e=>Vr(e,"[$$]#,##0.00")}).addChild("format_number_currency_rounded",["format","format_number"],{name:ks.CurrencyRounded,description:"$1,000",sequence:38,action:e=>Vr(e,"[$$]#,##0")}).addChild("format_custom_currency",["format","format_number"],{name:ks.CustomCurrency,sequence:39,separator:!0,isVisible:e=>void 0!==e.loadCurrencies,action:e=>{e.openSidePanel("CustomCurrency",{})}}).addChild("format_number_date",["format","format_number"],{name:ks.Date,description:"9/26/2008",sequence:40,action:e=>Vr(e,"m/d/yyyy")}).addChild("format_number_time",["format","format_number"],{name:ks.Time,description:"10:43:00 PM",sequence:50,action:e=>Vr(e,"hh:mm:ss a")}).addChild("format_number_date_time",["format","format_number"],{name:ks.DateTime,description:"9/26/2008 22:43:00",sequence:60,action:e=>Vr(e,"m/d/yyyy hh:mm:ss")}).addChild("format_number_duration",["format","format_number"],{name:ks.Duration,description:"27:51:38",sequence:70,separator:!0,action:e=>Vr(e,"hhhh:mm:ss")}).addChild("format_bold",["format"],{name:s("Bold"),sequence:20,description:"Ctrl+B",action:e=>zr(e,{bold:!e.model.getters.getCurrentStyle().bold})}).addChild("format_italic",["format"],{name:s("Italic"),sequence:30,description:"Ctrl+I",action:e=>zr(e,{italic:!e.model.getters.getCurrentStyle().italic})}).addChild("format_underline",["format"],{name:s("Underline"),description:"Ctrl+U",sequence:40,action:e=>zr(e,{underline:!e.model.getters.getCurrentStyle().underline})}).addChild("format_strikethrough",["format"],{name:s("Strikethrough"),sequence:50,action:e=>zr(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),separator:!0}).addChild("format_font_size",["format"],{name:s("Font size"),sequence:60,separator:!0}).addChild("format_alignment",["format"],{name:s("Alignment"),sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{name:"Left",sequence:10,action:e=>zr(e,{align:"left"})}).addChild("format_alignment_center",["format","format_alignment"],{name:"Center",sequence:20,action:e=>zr(e,{align:"center"})}).addChild("format_alignment_right",["format","format_alignment"],{name:"Right",sequence:30,action:e=>zr(e,{align:"right"}),separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{name:"Top",sequence:40,action:e=>zr(e,{verticalAlign:"top"})}).addChild("format_alignment_middle",["format","format_alignment"],{name:"Middle",sequence:50,action:e=>zr(e,{verticalAlign:"middle"})}).addChild("format_alignment_bottom",["format","format_alignment"],{name:"Bottom",sequence:60,action:e=>zr(e,{verticalAlign:"bottom"}),separator:!0}).addChild("format_wrapping",["format"],{name:s("Wrapping"),sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{name:s("Overflow"),sequence:10,action:e=>zr(e,{wrapping:"overflow"})}).addChild("format_wrapping_wrap",["format","format_wrapping"],{name:s("Wrap"),sequence:20,action:e=>zr(e,{wrapping:"wrap"})}).addChild("format_wrapping_clip",["format","format_wrapping"],{name:s("Clip"),sequence:30,action:e=>zr(e,{wrapping:"clip"})}).addChild("format_cf",["format"],{name:s("Conditional formatting"),sequence:90,action:aa,separator:!0}).addChild("format_clearFormat",["format"],{name:s("Clear formatting"),sequence:100,action:e=>{e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},separator:!0}).addChild("add_data_filter",["data"],{name:s("Create filter"),sequence:10,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSelection().zones;_r(e,t,i)},isVisible:e=>!ca(e),isEnabled:e=>(e=>go(...e.model.getters.getSelectedZones()))(e)}).addChild("remove_data_filter",["data"],{name:s("Remove filter"),sequence:10,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:t,target:e.model.getters.getSelectedZones()})},isVisible:ca});for(let e of de)ng.addChild(`format_font_size_${e}`,["format","format_font_size"],{name:e.toString(),sequence:e,action:t=>zr(t,{fontSize:e})});function sg(e){return e.sort().map(((e,t)=>({name:e,sequence:10*t,action:t=>t.startCellEdition(`=${e}(`)})))}const rg=new class extends Ro{addTransformation(e,t,i){for(let o of t)this.content[o]||(this.content[o]=new Map),this.content[o].set(e,i);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},ag={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function lg(e,t){const i=ag[e.key];e.shiftKey?t.resizeAnchorZone(i,Zn(e)?"end":1):t.moveAnchorCell(i,Zn(e)?"end":1)}const cg=new zi;vo`
350
+ `;class vr extends t.Component{get chartType(){return this.env.model.getters.getChartType(this.props.figure.id)}get chartComponent(){const e=this.chartType,t=mr.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}vr.template="o-spreadsheet-ChartFigure",vr.components={},vr.props={figure:Object,onFigureDeleted:Function};class br extends t.Component{get figureId(){return this.props.figure.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}}function Cr(e,t){const i=Fe(t),o=e.getSheetViewDimension(),n=o.width,s=o.height;if(i.width>n){const e=n/i.width;i.width=n,i.height=i.height*e}if(i.height>s){const e=s/i.height;i.height=s,i.width=i.width*e}return i}br.template="o-spreadsheet-ImageFigure",br.components={},br.props={figure:Object,onFigureDeleted:Function};const Sr=new Ro;function Er(e,t){return{id:"copy",name:s("Copy"),sequence:2,description:"Ctrl+C",action:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("COPY"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function wr(e,t){return{id:"cut",name:s("Cut"),sequence:3,description:"Ctrl+X",action:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("CUT"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function yr(e,t,i){return{id:"delete",name:s("Delete"),sequence:10,action:()=>{i.model.dispatch("DELETE_FIGURE",{sheetId:i.model.getters.getActiveSheetId(),id:e}),t()}}}Sr.add("chart",{Component:vr,SidePanelComponent:"ChartPanel",menuBuilder:function(e,t,i){return ss([{id:"edit",name:s("Edit"),sequence:1,action:()=>{i.model.dispatch("SELECT_FIGURE",{id:e}),i.openSidePanel("ChartPanel")}},Er(e,i),wr(e,i),yr(e,t,i)])}}),Sr.add("image",{Component:br,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t,i){return ss([Er(e,i),wr(e,i),{id:"reset_size",name:s("Reset size"),sequence:4,action:()=>{const t=i.model.getters.getImageSize(e),{height:o,width:n}=Cr(i.model.getters,t);i.model.dispatch("UPDATE_FIGURE",{sheetId:i.model.getters.getActiveSheetId(),id:e,height:o,width:n})}},yr(e,t,i)])}});const xr=(new Ro).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let i=e.base;"after"===e.position&&i++;for(let o=0;o<e.quantity;o++)t.push(o+i);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],i=[...e.elements].sort(((e,t)=>e-t));for(let o of We(i)){const i=0===o[0]?0:o[0]-1,n=0===o[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:o.length,base:i,sheetId:e.sheetId,position:n})}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 pn.values())xr.contains(e)||xr.add(e,Ir);function Ir(e){return[e]}function Rr(e,t){const i=pr.getAll().find((t=>t.match(e.type)));if(!i)throw new Error("Unknown chart type.");return i.transformDefinition(e,t)}function Tr(e,t){var i;let o=e;e.left!==e.right&&(o={...e,left:e.left+1});const s=[Wi(o)],r=t.getActiveSheetId(),a=t.getCell({sheetId:r,col:e.left,row:e.top});if(1===uo(e)&&(null==a?void 0:a.content))return{type:"scorecard",title:"",background:(null===(i=a.style)||void 0===i?void 0:i.fillColor)||void 0,keyValue:Wi(e),baselineMode:te,baselineColorUp:ie,baselineColorDown:oe};let l="";const c=t.getEvaluatedCellsInZone(r,{...o,bottom:o.top}),h=!!c.find((e=>e.type!==cn.empty&&e.type!==cn.number));if(h){const e=c.filter((e=>e.type!==cn.error&&e.type!==cn.empty)).map((e=>e.formattedValue)),t=e.splice(-1)[0];l=e.join(", "),t&&(l+=(l?" "+n("and")+" ":"")+t)}let d;e.left!==e.right&&(d=Wi({...e,right:e.left,top:h?e.top+1:e.top}));const u=o.right===o.left?"none":"top";return sr(d?t.getRangeFromSheetXC(r,d):void 0,t)?{title:l,dataSets:s,labelsAsText:!1,stacked:!1,aggregated:!1,cumulative:!1,labelRange:d,type:"line",dataSetsHaveTitle:h,verticalAxisPosition:"left",legendPosition:u}:{title:l,dataSets:s,labelRange:d,type:"bar",stacked:!1,aggregated:!1,dataSetsHaveTitle:h,verticalAxisPosition:"left",legendPosition:u}}const Ar=[cn.number,cn.error,cn.text,cn.boolean];function Mr(e,t,i,o,n){let r=fn.Success,a=o.right>o.left;if(e.model.getters.doesIntersectMerge(t,o)){let i;a=!1;for(let n=o.top;n<=o.bottom;n++){i=[];for(let s=o.left;s<=o.right;s++){let o=e.model.getters.getMerge({sheetId:t,col:s,row:n});o&&!i.includes(o.id.toString())&&i.push(o.id.toString())}if(i.length>=2){a=!0;break}}}const{col:l,row:c}=i;if(a)r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n});else{const i=e.model.getters.getContiguousZone(t,o);Ki(i,o)?r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n}):e.askConfirmation(s("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),(()=>{o=i,r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n})}),(()=>{r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n})}))}if(r.isCancelledBecause(64)){const{col:t,row:n}=i;e.model.selection.selectZone({cell:{col:t,row:n},zone:o}),e.raiseError(s("Cannot sort. To sort, select only cells or only merges that have the same size."))}}function Or(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause(19)&&e.raiseError(s("This operation is not allowed with multiple selections."))}const Nr={filterOverlap:s("You cannot create overlapping filters."),nonContinuousTargets:s("A filter can only be created on a continuous selection."),mergeInFilter:s("You can't create a filter over a range that contains a merge.")};function _r(e,t,i){const o=e.model.dispatch("CREATE_FILTER_TABLE",{target:i,sheetId:t});o.isCancelledBecause(79)?e.raiseError(Nr.filterOverlap):o.isCancelledBecause(81)?e.raiseError(Nr.mergeInFilter):o.isCancelledBecause(82)&&e.raiseError(Nr.nonContinuousTargets)}const Fr={wrongPasteSelection:s("This operation is not allowed with multiple selections."),willRemoveExistingMerge:s("This operation is not possible due to a merge. Please remove the merges first than try again."),wrongFigurePasteOption:s("Cannot do a special paste of a figure."),frozenPaneOverlap:s("Cannot paste merged cells over a frozen pane.")};function Dr(e,t){t.isSuccessful||(t.reasons.includes(20)?e.raiseError(Fr.wrongPasteSelection):t.reasons.includes(2)?e.raiseError(Fr.willRemoveExistingMerge):t.reasons.includes(22)?e.raiseError(Fr.wrongFigurePasteOption):t.reasons.includes(76)&&e.raiseError(Fr.frozenPaneOverlap))}function kr(e,t,i){const o=e.model.dispatch("PASTE",{target:t,pasteOption:i});Dr(e,o)}function Lr(e,t,i){const o=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,text:i});Dr(e,o)}function Pr(e){const t=e.model.getters.getActiveCols();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.right-t.left+1}}function Ur(e){const t=e.model.getters.getActiveRows();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function Vr(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function zr(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const Br=async e=>{e.model.dispatch("COPY"),await e.clipboard.write(e.model.getters.getClipboardContent())},Hr=async e=>{Or(e),await e.clipboard.write(e.model.getters.getClipboardContent())},$r=async e=>Gr(e),Wr=async e=>Gr(e,"onlyValue");async function Gr(e,t){const i=e.model.getters.getClipboardTextContent(),o=await e.clipboard.readText();switch(o.status){case"ok":const n=e.model.getters.getSelectedZones();o&&o.content!==i?Lr(e,n,o.content):kr(e,n,t);break;case"notImplemented":e.raiseError(s("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(s("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const qr=e=>kr(e,e.model.getters.getSelectedZones(),"onlyFormat"),Zr=e=>!e.model.getters.isCutOperation(),jr=e=>{if(e.model.getters.getSelectedZones().length>1)return s("Delete rows");let t,i;const o=e.model.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,i=o.bottom}return t===i?s("Delete row %s",(t+1).toString()):s("Delete rows %s - %s",(t+1).toString(),(i+1).toString())},Yr=e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){const i=e.model.getters.getSelectedZones()[0];for(let e=i.top;e<=i.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},Xr=(e,t)=>{const i=t.model.getters.getActiveSheetId(),o=t.model.getters.getElementsFromSelection(e),n=t.model.getters.checkElementsIncludeAllVisibleHeaders(i,e,o),s=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(i,e,o);return!n&&!s},Kr=e=>{if(e.model.getters.getSelectedZones().length>1)return s("Delete columns");let t,i;const o=e.model.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,i=o.right}return t===i?s("Delete column %s",Wt(t)):s("Delete columns %s - %s",Wt(t),Wt(i))},Qr=e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){const i=e.model.getters.getSelectedZones()[0];for(let e=i.left;e<=i.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},Jr=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});Dr(e,i)},ea=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});Dr(e,i)},ta=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});Dr(e,i)},ia=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});Dr(e,i)},oa=e=>{const t=e.model.getters.getActiveRows();let i,o;if(t.size)i=Math.min(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.top,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",base:i,quantity:o,dimension:"ROW"})},na=e=>{const t=e.model.getters.getActiveRows();let i,o;if(t.size)i=Math.max(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.bottom,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",base:i,quantity:o,dimension:"ROW"})},sa=e=>{const t=e.model.getters.getActiveCols();let i,o;if(t.size)i=Math.min(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.left,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",dimension:"COL",base:i,quantity:o})},ra=e=>{const t=e.model.getters.getActiveCols();let i,o;if(t.size)i=Math.max(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.right,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",dimension:"COL",base:i,quantity:o})};const aa=e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},la=e=>{let{col:t,row:i}=e.model.getters.getActivePosition();e.model.dispatch("OPEN_CELL_POPOVER",{col:t,row:i,popoverType:"LinkEditor"})},ca=e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,i)},ha=e=>{const{anchor:t,zones:i}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();Mr(e,o,t.cell,i[0],"ascending")},da=e=>{const{anchor:t,zones:i}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();Mr(e,o,t.cell,i[0],"descending")},ua=e=>1===e.model.getters.getSelectedZones().length,ga=new ls;ga.add("cut",{name:s("Cut"),description:"Ctrl+X",sequence:10,action:Hr}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Br}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:$r}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Zr}).addChild("paste_value_only",["paste_special"],{name:s("Paste values only"),sequence:10,action:Wr}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:qr}).add("add_row_before",{name:e=>{const t=Ur(e);return 1===t?s("Insert row"):s("Insert %s rows",t.toString())},sequence:70,action:oa,isVisible:ua}).add("add_column_before",{name:e=>{const t=Pr(e);return 1===t?s("Insert column"):s("Insert %s columns",t.toString())},sequence:90,action:sa,isVisible:ua}).add("insert_cell",{name:s("Insert cells"),sequence:100,isVisible:ua,separator:!0}).addChild("insert_cell_down",["insert_cell"],{name:s("Shift down"),sequence:10,action:Jr}).addChild("insert_cell_right",["insert_cell"],{name:s("Shift right"),sequence:20,action:ea}).add("delete_row",{name:jr,sequence:110,action:Yr,isVisible:ua}).add("delete_column",{name:Kr,sequence:120,action:Qr,isVisible:ua}).add("delete_cell",{name:s("Delete cells"),sequence:130,isVisible:ua}).addChild("delete_cell_up",["delete_cell"],{name:s("Shift up"),sequence:10,action:ta}).addChild("delete_cell_down",["delete_cell"],{name:s("Shift left"),sequence:20,action:ia}).add("insert_link",{name:s("Insert link"),separator:!0,sequence:150,action:la});const pa=new ls;pa.add("cut",{name:s("Cut"),description:"Ctrl+X",sequence:10,action:Hr}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Br}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:$r}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Zr}).addChild("paste_value_only",["paste_special"],{name:s("Paste value only"),sequence:10,action:Wr}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:qr}).add("sort_columns",{name:e=>e.model.getters.getActiveCols().size>1?s("Sort columns"):s("Sort column"),sequence:50,isVisible:ua,separator:!0}).addChild("sort_ascending",["sort_columns"],{name:s("Ascending (A ⟶ Z)"),sequence:10,action:ha}).addChild("sort_descending",["sort_columns"],{name:s("Descending (Z ⟶ A)"),sequence:20,action:da}).add("add_column_before",{name:e=>{const t=Pr(e);return 1===t?s("Insert column left"):s("Insert %s columns left",t.toString())},sequence:70,action:sa}).add("add_column_after",{name:e=>{const t=Pr(e);return 1===t?s("Insert column right"):s("Insert %s columns right",t.toString())},sequence:80,action:ra}).add("delete_column",{name:Kr,sequence:90,action:Qr,isVisible:e=>Xr("COL",e)}).add("clear_column",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return s("Clear columns");let t,i;const o=e.model.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,i=o.right}return t===i?s("Clear column %s",Wt(t)):s("Clear columns %s - %s",Wt(t),Wt(i))},sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId(),i=[...e.model.getters.getActiveCols()].map((i=>e.model.getters.getColsZone(t,i,i)));e.model.dispatch("DELETE_CONTENT",{target:i,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_columns",{name:e=>{const t=e.model.getters.getElementsFromSelection("COL");let i=t[0],o=t[t.length-1];return 1===t.length?s("Hide column %s",Wt(i).toString()):o-i+1===t.length?s("Hide columns %s - %s",Wt(i).toString(),Wt(o).toString()):s("Hide columns")},sequence:85,action:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("COL");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"COL",i)},separator:!0}).add("unhide_columns",{name:s("Unhide columns"),sequence:86,action:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:s("Conditional formatting"),sequence:110,action:aa});const ma=new ls;ma.add("cut",{name:s("Cut"),sequence:10,description:"Ctrl+X",action:Hr}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Br}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:$r}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Zr}).addChild("paste_value_only",["paste_special"],{name:s("Paste value only"),sequence:10,action:Wr}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:qr}).add("add_row_before",{name:e=>{const t=Ur(e);return 1===t?s("Insert row above"):s("Insert %s rows above",t.toString())},sequence:50,action:oa}).add("add_row_after",{name:e=>{const t=Ur(e);return 1===t?s("Insert row below"):s("Insert %s rows below",t.toString())},sequence:60,action:na}).add("delete_row",{name:jr,sequence:70,action:Yr,isVisible:e=>Xr("ROW",e)}).add("clear_row",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return s("Clear rows");let t,i;const o=e.model.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,i=o.bottom}return t===i?s("Clear row %s",(t+1).toString()):s("Clear rows %s - %s",(t+1).toString(),(i+1).toString())},sequence:80,action:e=>{const t=e.model.getters.getActiveSheetId(),i=[...e.model.getters.getActiveRows()].map((i=>e.model.getters.getRowsZone(t,i,i)));e.model.dispatch("DELETE_CONTENT",{target:i,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_rows",{name:e=>{const t=e.model.getters.getElementsFromSelection("ROW");let i=t[0],o=t[t.length-1];return 1===t.length?s("Hide row %s",(i+1).toString()):o-i+1===t.length?s("Hide rows %s - %s",(i+1).toString(),(o+1).toString()):s("Hide rows")},sequence:85,action:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("ROW");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"ROW",i)},separator:!0}).add("unhide_rows",{name:s("Unhide rows"),sequence:86,action:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:s("Conditional formatting"),sequence:90,action:aa});const fa=/(.*?)\((.*?)\)(.*)/,va=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function ba(e,t=""){return function(e){let t=e.match(fa),i=t[1].trim();if(!i)throw new Error(`Function argument definition is missing a name: '${e}'.`);let o,n=[],s=!1,r=!1,a=!1;for(let e of t[2].split(",")){const t=e.trim().toUpperCase();let i=va.find((e=>t===e));i?n.push(i):"RANGE<ANY>"===t?n.push("RANGE"):"OPTIONAL"===t?s=!0:"REPEATING"===t?r=!0:"LAZY"===t?a=!0:t.startsWith("DEFAULT=")&&(o=e.trim().slice(8))}let l=t[3].trim();const c={name:i,description:l,type:n};s&&(c.optional=!0);r&&(c.repeating=!0);a&&(c.lazy=!0);void 0!==o&&(c.default=!0,c.defaultValue=o);return c}(`${e} ${t}`)}function Ca(e){let t=0,i=0,o=0;for(let n of e.args)t++,n.optional||n.repeating||n.default||i++,n.repeating&&o++;const n=e;return n.minArgRequired=i,n.maxArgPossible=o?1/0:t,n.nbrArgRepeating=o,n.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const i=e-t;return e=>{if(e<=i)return e;return i+((e-i)%t||t)}}(t,o),n.hidden=e.hidden||!1,n}const Sa={description:s("Apply a large number format"),args:[ba("value (number)",s("The number.")),ba("unit (string, optional)",s("The formatting unit. Use 'k', 'm', or 'b' to force the unit"))],returns:["NUMBER"],computeFormat:(e,t)=>{const i=Math.abs(Uo(e.value)),o=e.format;if(void 0!==t){switch(null==t?void 0:t.value){case"k":return Ai(o,1e3,"k");case"m":return Ai(o,1e6,"m");case"b":return Ai(o,1e9,"b");default:throw new Error(s("The formatting unit should be 'k', 'm' or 'b'."))}}return i<1e5?Ai(o,0,""):i<1e8?Ai(o,1e3,"k"):i<1e11?Ai(o,1e6,"m"):Ai(o,1e9,"b")},compute:function(e){return Uo(e)}};var Ea=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:Sa});const wa={description:s("Absolute value of a number."),args:[ba("value (number)",s("The number of which to return the absolute value."))],returns:["NUMBER"],compute:function(e){return Math.abs(Uo(e))},isExported:!0},ya={description:s("Inverse cosine of a value, in radians."),args:[ba("value (number)",s("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>Math.abs(t)<=1),s("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},xa={description:s("Inverse hyperbolic cosine of a number."),args:[ba("value (number)",s("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>t>=1),s("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},Ia={description:s("Inverse cotangent of a value."),args:[ba("value (number)",s("The value for which to calculate the inverse cotangent."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Ra={description:s("Inverse hyperbolic cotangent of a value."),args:[ba("value (number)",s("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>Math.abs(t)>1),s("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},Ta={description:s("Inverse sine of a value, in radians."),args:[ba("value (number)",s("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>Math.abs(t)<=1),s("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},Aa={description:s("Inverse hyperbolic sine of a number."),args:[ba("value (number)",s("The value for which to calculate the inverse hyperbolic sine."))],returns:["NUMBER"],compute:function(e){return Math.asinh(Uo(e))},isExported:!0},Ma={description:s("Inverse tangent of a value, in radians."),args:[ba("value (number)",s("The value for which to calculate the inverse tangent."))],returns:["NUMBER"],compute:function(e){return Math.atan(Uo(e))},isExported:!0},Oa={description:s("Angle from the X axis to a point (x,y), in radians."),args:[ba("x (number)",s("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),ba("y (number)",s("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis."))],returns:["NUMBER"],compute:function(e,t){const i=Uo(e),o=Uo(t);return Lo((()=>0!==i||0!==o),s("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(o,i)},isExported:!0},Na={description:s("Inverse hyperbolic tangent of a number."),args:[ba("value (number)",s("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>Math.abs(t)<1),s("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},_a={description:s("Rounds number up to nearest multiple of factor."),args:[ba("value (number)",s("The value to round up to the nearest integer multiple of factor.")),ba("factor (number, default=1)",s("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){const i=Uo(e),o=Uo(t);return Lo((()=>o>=0||i<=0),s("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),i.toString())),o?Math.ceil(i/o)*o:0},isExported:!0},Fa={description:s("Rounds number up to nearest multiple of factor."),args:[ba("number (number)",s("The value to round up to the nearest integer multiple of significance.")),ba("significance (number, default=1)",s("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),ba("mode (number, default=0)",s("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,i=0){let o=Uo(t);if(0===o)return 0;const n=Uo(e);if(o=Math.abs(o),n>=0)return Math.ceil(n/o)*o;return 0===Uo(i)?-Math.floor(Math.abs(n)/o)*o:-Math.ceil(Math.abs(n)/o)*o},isExported:!0},Da={description:s("Rounds number up to nearest multiple of factor."),args:[ba("number (number)",s("The value to round up to the nearest integer multiple of significance.")),ba("significance (number, default=1)",s("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){return Fa.compute(e,t,0)},isExported:!0},ka={description:s("Cosine of an angle provided in radians."),args:[ba("angle (number)",s("The angle to find the cosine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.cos(Uo(e))},isExported:!0},La={description:s("Hyperbolic cosine of any real number."),args:[ba("value (number)",s("Any real value to calculate the hyperbolic cosine of."))],returns:["NUMBER"],compute:function(e){return Math.cosh(Uo(e))},isExported:!0},Pa={description:s("Cotangent of an angle provided in radians."),args:[ba("angle (number)",s("The angle to find the cotangent of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},Ua={description:s("Hyperbolic cotangent of any real number."),args:[ba("value (number)",s("Any real value to calculate the hyperbolic cotangent of."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},Va={description:s("Number of empty values."),args:[ba("value1 (any, range)",s("The first value or range in which to count the number of blanks.")),ba("value2 (any, range, repeating)",s("Additional values or ranges in which to count the number of blanks."))],returns:["NUMBER"],compute:function(...e){return Xo(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},za={description:s("A conditional count across a range."),args:[ba("range (range)",s("The range that is tested against criterion.")),ba("criterion (string)",s("The pattern or test to apply to range."))],returns:["NUMBER"],compute:function(...e){let t=0;return on(e,((e,i)=>{t+=1})),t},isExported:!0},Ba={description:s("Count values depending on multiple criteria."),args:[ba("criteria_range1 (range)",s("The range to check against criterion1.")),ba("criterion1 (string)",s("The pattern or test to apply to criteria_range1.")),ba("criteria_range2 (any, range, repeating)",s("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.")),ba("criterion2 (string, repeating)",s("Additional criteria to check."))],returns:["NUMBER"],compute:function(...e){let t=0;return on(e,((e,i)=>{t+=1})),t},isExported:!0};function Ha(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const $a={description:s("Counts number of unique values in a range."),args:[ba("value1 (any, range)",s("The first value or range to consider for uniqueness.")),ba("value2 (any, range, repeating)",s("Additional values or ranges to consider for uniqueness."))],returns:["NUMBER"],compute:function(...e){return Xo(e,((e,t)=>Ha(t)?e.add(t):e),new Set).size}},Wa={description:s("Counts number of unique values in a range, filtered by a set of criteria."),args:[ba("range (range)",s("The range of cells from which the number of unique values will be counted.")),ba("criteria_range1 (range)",s("The range of cells over which to evaluate criterion1.")),ba("criterion1 (string)",s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),ba("criteria_range2 (any, range, repeating)",s("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.")),ba("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=new Set;return on(t,((t,o)=>{const n=e[t][o];Ha(n)&&i.add(n)})),i.size}},Ga={description:s("Cosecant of an angle provided in radians."),args:[ba("angle (number)",s("The angle to find the cosecant of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},qa={description:s("Hyperbolic cosecant of any real number."),args:[ba("value (number)",s("Any real value to calculate the hyperbolic cosecant of."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},Za={description:s("Converts from another base to decimal."),args:[ba("value (string)",s("The number to convert.")),ba(",base (number)",s("The base to convert the value from."))],returns:["NUMBER"],compute:function(e,t){let i=Uo(t);i=Math.floor(i),Lo((()=>2<=i&&i<=36),s("The base (%s) must be between 2 and 36 inclusive.",i.toString()));const o=zo(e);if(""===o)return 0;Lo((()=>!!o.match(/^-?[a-z0-9]+$/i)),s("The value (%s) must be a valid base %s representation.",o,i.toString()));const n=parseInt(o,i);return Lo((()=>!isNaN(n)),s("The value (%s) must be a valid base %s representation.",o,i.toString())),n},isExported:!0},ja={description:s("Converts an angle value in radians to degrees."),args:[ba("angle (number)",s("The angle to convert from radians to degrees."))],returns:["NUMBER"],compute:function(e){return 180*Uo(e)/Math.PI},isExported:!0},Ya={description:s("Euler's number, e (~2.718) raised to a power."),args:[ba("value (number)",s("The exponent to raise e."))],returns:["NUMBER"],compute:function(e){return Math.exp(Uo(e))},isExported:!0},Xa={description:s("Rounds number down to nearest multiple of factor."),args:[ba("value (number)",s("The value to round down to the nearest integer multiple of factor.")),ba("factor (number, default=1)",s("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){const i=Uo(e),o=Uo(t);return Lo((()=>o>=0||i<=0),s("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),i.toString())),o?Math.floor(i/o)*o:0},isExported:!0},Ka={description:s("Rounds number down to nearest multiple of factor."),args:[ba("number (number)",s("The value to round down to the nearest integer multiple of significance.")),ba("significance (number, default=1)",s("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),ba("mode (number, default=0)",s("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,i=0){let o=Uo(t);if(0===o)return 0;const n=Uo(e);if(o=Math.abs(o),n>=0)return Math.floor(n/o)*o;return 0===Uo(i)?-Math.ceil(Math.abs(n)/o)*o:-Math.floor(Math.abs(n)/o)*o},isExported:!0},Qa={description:s("Rounds number down to nearest multiple of factor."),args:[ba("number (number)",s("The value to round down to the nearest integer multiple of significance.")),ba("significance (number, default=1)",s("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){return Ka.compute(e,t,0)},isExported:!0},Ja={description:s("Whether the provided value is even."),args:[ba("value (number)",s("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Vo(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},el={description:s("Rounds number up to nearest multiple of factor."),args:[ba("number (number)",s("The value to round up to the nearest integer multiple of significance.")),ba("significance (number, default=1)",s("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){return Fa.compute(e,t,0)},isExported:!0},tl={description:s("Whether the provided value is even."),args:[ba("value (number)",s("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Vo(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},il={description:s("The logarithm of a number, base e (euler's number)."),args:[ba("value (number)",s("The value for which to calculate the logarithm, base e."))],returns:["NUMBER"],compute:function(e){const t=Uo(e);return Lo((()=>t>0),s("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},ol={description:s("Modulo (remainder) operator."),args:[ba("dividend (number)",s("The number to be divided to find the remainder.")),ba("divisor (number)",s("The number to divide by."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const i=Uo(t);Lo((()=>0!==i),s("The divisor must be different from 0."));const o=Uo(e)%i;return o>0&&i<0||o<0&&i>0?o+i:o},isExported:!0},nl={description:s("Rounds a number up to the nearest odd integer."),args:[ba("value (number)",s("The value to round to the next greatest odd number."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){const t=Uo(e);let i=Math.ceil(Math.abs(t));return i=1&i?i:i+1,t<0?-i:i},isExported:!0},sl={description:s("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},rl={description:s("A number raised to a power."),args:[ba("base (number)",s("The number to raise to the exponent power.")),ba("exponent (number)",s("The exponent to raise base to."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const i=Uo(e),o=Uo(t);return Lo((()=>i>=0||Number.isInteger(o)),s("The exponent (%s) must be an integer when the base is negative.",o.toString())),Math.pow(i,o)},isExported:!0},al={description:s("Result of multiplying a series of numbers together."),args:[ba("factor1 (number, range<number>)",s("The first number or range to calculate for the product.")),ba("factor2 (number, range<number>, repeating)",s("More numbers or ranges to calculate for the product."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0,i=1;for(let o of e)if(Array.isArray(o))for(let e of o)for(let o of e)"number"==typeof o&&(i*=o,t+=1);else null!=o&&(i*=Vo(o),t+=1);return 0===t?0:i},isExported:!0},ll={description:s("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},cl={description:s("Random integer between two values, inclusive."),args:[ba("low (number)",s("The low end of the random range.")),ba("high (number)",s("The high end of the random range."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){let i=Uo(e);Number.isInteger(i)||(i=Math.ceil(i));let o=Uo(t);return Number.isInteger(o)||(o=Math.floor(o)),Lo((()=>i<=o),s("The high (%s) must be greater than or equal to the low (%s).",o.toString(),i.toString())),i+Math.ceil((o-i+1)*Math.random())-1},isExported:!0},hl={description:s("Rounds a number according to standard rules."),args:[ba("value (number)",s("The value to round to places number of places.")),ba("places (number, default=0)",s("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Uo(e);let o=Uo(t);const n=Math.abs(i);let s;return 0===o?s=Math.round(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.round(n*Math.pow(10,o))/Math.pow(10,o)),i>=0?s:-s},isExported:!0},dl={description:s("Rounds down a number."),args:[ba("value (number)",s("The value to round to places number of places, always rounding down.")),ba("places (number, default=0)",s("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Uo(e);let o=Uo(t);const n=Math.abs(i);let s;return 0===o?s=Math.floor(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.floor(n*Math.pow(10,o))/Math.pow(10,o)),i>=0?s:-s},isExported:!0},ul={description:s("Rounds up a number."),args:[ba("value (number)",s("The value to round to places number of places, always rounding up.")),ba("places (number, default=0)",s("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Uo(e);let o=Uo(t);const n=Math.abs(i);let s;return 0===o?s=Math.ceil(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.ceil(n*Math.pow(10,o))/Math.pow(10,o)),i>=0?s:-s},isExported:!0},gl={description:s("Secant of an angle provided in radians."),args:[ba("angle (number)",s("The angle to find the secant of, in radians."))],returns:["NUMBER"],compute:function(e){return 1/Math.cos(Uo(e))},isExported:!0},pl={description:s("Hyperbolic secant of any real number."),args:[ba("value (number)",s("Any real value to calculate the hyperbolic secant of."))],returns:["NUMBER"],compute:function(e){return 1/Math.cosh(Uo(e))},isExported:!0},ml={description:s("Sine of an angle provided in radians."),args:[ba("angle (number)",s("The angle to find the sine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.sin(Uo(e))},isExported:!0},fl={description:s("Hyperbolic sine of any real number."),args:[ba("value (number)",s("Any real value to calculate the hyperbolic sine of."))],returns:["NUMBER"],compute:function(e){return Math.sinh(Uo(e))},isExported:!0},vl={description:s("Positive square root of a positive number."),args:[ba("value (number)",s("The number for which to calculate the positive square root."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){const t=Uo(e);return Lo((()=>t>=0),s("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},bl={description:s("Sum of a series of numbers and/or cells."),args:[ba("value1 (number, range<number>)",s("The first number or range to add together.")),ba("value2 (number, range<number>, repeating)",s("Additional numbers or ranges to add to value1."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){return Ko(e,((e,t)=>e+t),0)},isExported:!0},Cl={description:s("A conditional sum across a range."),args:[ba("criteria_range (range)",s("The range which is tested against criterion.")),ba("criterion (string)",s("The pattern or test to apply to range.")),ba("sum_range (range, default=criteria_range)",s("The range to be summed, if different from range."))],returns:["NUMBER"],compute:function(e,t,i){void 0===i&&(i=e);let o=0;return on([e,t],((e,t)=>{const n=i[e][t];"number"==typeof n&&(o+=n)})),o},isExported:!0},Sl={description:s("Sums a range depending on multiple criteria."),args:[ba("sum_range (range)",s("The range to sum.")),ba("criteria_range1 (range)",s("The range to check against criterion1.")),ba("criterion1 (string)",s("The pattern or test to apply to criteria_range1.")),ba("criteria_range2 (any, range, repeating)",s("Additional ranges to check.")),ba("criterion2 (string, repeating)",s("Additional criteria to check."))],returns:["NUMBER"],compute:function(e,...t){let i=0;return on(t,((t,o)=>{const n=e[t][o];"number"==typeof n&&(i+=n)})),i},isExported:!0},El={description:s("Tangent of an angle provided in radians."),args:[ba("angle (number)",s("The angle to find the tangent of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.tan(Uo(e))},isExported:!0},wl={description:s("Hyperbolic tangent of any real number."),args:[ba("value (number)",s("Any real value to calculate the hyperbolic tangent of."))],returns:["NUMBER"],compute:function(e){return Math.tanh(Uo(e))},isExported:!0},yl={description:s("Truncates a number."),args:[ba("value (number)",s("The value to be truncated.")),ba("places (number, default=0)",s("The number of significant digits to the right of the decimal point to retain."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Uo(e);let o=Uo(t);return 0===o?Math.trunc(i):(Number.isInteger(o)||(o=Math.trunc(o)),Math.trunc(i*Math.pow(10,o))/Math.pow(10,o))},isExported:!0};var xl=Object.freeze({__proto__:null,ABS:wa,ACOS:ya,ACOSH:xa,ACOT:Ia,ACOTH:Ra,ASIN:Ta,ASINH:Aa,ATAN:Ma,ATAN2:Oa,ATANH:Na,CEILING:_a,CEILING_MATH:Fa,CEILING_PRECISE:Da,COS:ka,COSH:La,COT:Pa,COTH:Ua,COUNTBLANK:Va,COUNTIF:za,COUNTIFS:Ba,COUNTUNIQUE:$a,COUNTUNIQUEIFS:Wa,CSC:Ga,CSCH:qa,DECIMAL:Za,DEGREES:ja,EXP:Ya,FLOOR:Xa,FLOOR_MATH:Ka,FLOOR_PRECISE:Qa,ISEVEN:Ja,ISO_CEILING:el,ISODD:tl,LN:il,MOD:ol,ODD:nl,PI:sl,POWER:rl,PRODUCT:al,RAND:ll,RANDBETWEEN:cl,ROUND:hl,ROUNDDOWN:dl,ROUNDUP:ul,SEC:gl,SECH:pl,SIN:ml,SINH:fl,SQRT:vl,SUM:bl,SUMIF:Cl,SUMIFS:Sl,TAN:El,TANH:wl,TRUNC:yl});function Il(e,t,i){let o=[],n=[],r=0,a=0;Zo([e],(e=>{o.push(e),r+=1})),Zo([t],(e=>{n.push(e),a+=1})),Lo((()=>r===a),s("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",r.toString(),a.toString()));let l=0,c=0,h=0;for(let e=0;e<r;e++){const t=o[e],i=n[e];"number"==typeof t&&"number"==typeof i&&(l+=1,c+=t,h+=i)}Lo((()=>0!==l&&(!i||1!==l)),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const d=c/l,u=h/l;let g=0;for(let e=0;e<r;e++){const t=o[e],i=n[e];"number"==typeof t&&"number"==typeof i&&(g+=(t-d)*(i-u))}return g/(l-(i?1:0))}function Rl(e,t,i){let o=0,n=0;const r=i?Qo:Ko;n=r(e,((e,t)=>(o+=1,e+t)),0),Lo((()=>0!==o&&(!t||1!==o)),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const a=n/o;return r(e,((e,t)=>e+Math.pow(t-a,2)),0)/(o-(t?1:0))}function Tl(e,t,i){const o=Uo(t);Lo((()=>i?0<=o&&o<=1:0<o&&o<1),s("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let n,r=[],a=0;return Zo(e,(e=>{"number"==typeof e&&(n=rn(r,e,"nextSmaller","asc",r.length,((e,t)=>e[t])),r.splice(n+1,0,e),a++)})),Lo((()=>0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),i||Lo((()=>1/(a+1)<=o&&o<=a/(a+1)),s("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),ai(r,o,i)}const Al={description:s("Average magnitude of deviations from mean."),args:[ba("value1 (number, range<number>)",s("The first value or range of the sample.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){let t=0;const i=Ko(e,((e,i)=>(t+=1,e+i)),0);Lo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const o=i/t;return Ko(e,((e,t)=>e+Math.abs(o-t)),0)/t},isExported:!0},Ml={description:s("Numerical average value in a dataset, ignoring text."),args:[ba("value1 (number, range<number>)",s("The first value or range to consider when calculating the average value.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0;const i=Ko(e,((e,i)=>(t+=1,e+i)),0);return Lo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/t},isExported:!0},Ol=s("[[FUNCTION_NAME]] has mismatched range sizes."),Nl=s("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),_l={description:s("Weighted average."),args:[ba("values (number, range<number>)",s("Values to average.")),ba("weights (number, range<number>)",s("Weights for each corresponding value.")),ba("additional_values (number, range<number>, repeating)",s("Additional values to average.")),ba("additional_weights (number, range<number>, repeating)",s("Additional weights."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t,i,o=0,n=0;Lo((()=>e.length%2==0),s("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let r=0;r<e.length-1;r+=2)if(t=e[r],i=e[r+1],Array.isArray(t)){Lo((()=>Array.isArray(i)),Ol);let e=t.length,r=t[0].length;Lo((()=>e===i.length&&r===i[0].length),Ol);for(let a=0;a<e;a++)for(let e=0;e<r;e++){let r=t[a][e],l=i[a][e],c="number"==typeof r,h="number"==typeof l;Lo((()=>c===h),s("[[FUNCTION_NAME]] expects number values.")),h&&(Lo((()=>l>=0),Nl),o+=r*l,n+=l)}}else i=Uo(i),t=Uo(t),Lo((()=>i>=0),Nl),o+=t*i,n+=i;return Lo((()=>0!==n),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/n}},Fl={description:s("Numerical average value in a dataset."),args:[ba("value1 (number, range<number>)",s("The first value or range to consider when calculating the average value.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0;const i=Qo(e,((e,i)=>(t+=1,e+i)),0);return Lo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/t},isExported:!0},Dl={description:s("Average of values depending on criteria."),args:[ba("criteria_range (range)",s("The range to check against criterion.")),ba("criterion (string)",s("The pattern or test to apply to criteria_range.")),ba("average_range (range, default=criteria_range)",s("The range to average. If not included, criteria_range is used for the average instead."))],returns:["NUMBER"],compute:function(e,t,i){null==i&&(i=e);let o=0,n=0;return on([e,t],((t,s)=>{const r=(i||e)[t][s];"number"==typeof r&&(o+=1,n+=r)})),Lo((()=>0!==o),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),n/o},isExported:!0},kl={description:s("Average of values depending on multiple criteria."),args:[ba("average_range (range)",s("The range to average.")),ba("criteria_range1 (range)",s("The range to check against criterion1.")),ba("criterion1 (string)",s("The pattern or test to apply to criteria_range1.")),ba("criteria_range2 (any, range, repeating)",s("Additional criteria_range and criterion to check.")),ba("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=0,o=0;return on(t,((t,n)=>{const s=e[t][n];"number"==typeof s&&(i+=1,o+=s)})),Lo((()=>0!==i),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/i},isExported:!0},Ll={description:s("The number of numeric values in dataset."),args:[ba("value1 (number, range<number>)",s("The first value or range to consider when counting.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){let t=0;for(let i of e)if(Array.isArray(i))for(let e of i)for(let i of e)"number"==typeof i&&(t+=1);else("string"!=typeof i||ni(i)||we(i))&&(t+=1);return t},isExported:!0},Pl={description:s("The number of values in a dataset."),args:[ba("value1 (any, range)",s("The first value or range to consider when counting.")),ba("value2 (any, range, repeating)",s("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){return Xo(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},Ul={description:s("The covariance of a dataset."),args:[ba("data_y (any, range)",s("The range representing the array or matrix of dependent data.")),ba("data_x (any, range)",s("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return Il(e,t,!1)},isExported:!0},Vl={description:s("The covariance of a dataset."),args:[ba("data_y (any, range)",s("The range representing the array or matrix of dependent data.")),ba("data_x (any, range)",s("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return Il(e,t,!1)},isExported:!0},zl={description:s("The sample covariance of a dataset."),args:[ba("data_y (any, range)",s("The range representing the array or matrix of dependent data.")),ba("data_x (any, range)",s("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return Il(e,t,!0)},isExported:!0},Bl={description:s("Nth largest element from a data set."),args:[ba("data (any, range)",s("Array or range containing the dataset to consider.")),ba("n (number)",s("The rank from largest to smallest of the element to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){const i=Math.trunc(Uo(t));let o,n=[],r=0;Zo([e],(e=>{"number"==typeof e&&(o=rn(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(o+1,0,e),r++,r>i&&(n.shift(),r--))}));const a=n.shift();return Lo((()=>void 0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),Lo((()=>r>=i),s("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",i.toString())),a},isExported:!0},Hl={description:s("Maximum value in a numeric dataset."),args:[ba("value1 (number, range<number>)",s("The first value or range to consider when calculating the maximum value.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=Ko(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},$l={description:s("Maximum numeric value in a dataset."),args:[ba("value1 (any, range)",s("The first value or range to consider when calculating the maximum value.")),ba("value2 (any, range, repeating)",s("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=Qo(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},Wl={description:s("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:[ba("range (range)",s("The range of cells from which the maximum will be determined.")),ba("criteria_range1 (range)",s("The range of cells over which to evaluate criterion1.")),ba("criterion1 (string)",s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),ba("criteria_range2 (any, range, repeating)",s("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.")),ba("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=-1/0;return on(t,((t,o)=>{const n=e[t][o];"number"==typeof n&&(i=i<n?n:i)})),i===-1/0?0:i},isExported:!0},Gl={description:s("Median value in a numeric dataset."),args:[ba("value1 (any, range)",s("The first value or range to consider when calculating the median value.")),ba("value2 (any, range, repeating)",s("Additional values or ranges to consider when calculating the median value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=[];return jo(e,(e=>{t.push(e)})),Tl(t,.5,!0)},isExported:!0},ql={description:s("Minimum value in a numeric dataset."),args:[ba("value1 (number, range<number>)",s("The first value or range to consider when calculating the minimum value.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=Ko(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Zl={description:s("Minimum numeric value in a dataset."),args:[ba("value1 (number, range<number>)",s("The first value or range to consider when calculating the minimum value.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=Qo(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},jl={description:s("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:[ba("range (range)",s("The range of cells from which the minimum will be determined.")),ba("criteria_range1 (range)",s("The range of cells over which to evaluate criterion1.")),ba("criterion1 (string)",s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),ba("criteria_range2 (any, range, repeating)",s("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.")),ba("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=1/0;return on(t,((t,o)=>{const n=e[t][o];"number"==typeof n&&(i=i>n?n:i)})),i===1/0?0:i},isExported:!0},Yl={description:s("Value at a given percentile of a dataset."),args:[ba("data (any, range)",s("The array or range containing the dataset to consider.")),ba("percentile (number)",s("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Kl.compute(e,t)},isExported:!0},Xl={description:s("Value at a given percentile of a dataset exclusive of 0 and 1."),args:[ba("data (any, range)",s("The array or range containing the dataset to consider.")),ba("percentile (number)",s("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Tl([e],t,!1)},isExported:!0},Kl={description:s("Value at a given percentile of a dataset."),args:[ba("data (any, range)",s("The array or range containing the dataset to consider.")),ba("percentile (number)",s("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Tl([e],t,!0)},isExported:!0},Ql={description:s("Value nearest to a specific quartile of a dataset."),args:[ba("data (any, range)",s("The array or range containing the dataset to consider.")),ba("quartile_number (number)",s("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return ec.compute(e,t)},isExported:!0},Jl={description:s("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:[ba("data (any, range)",s("The array or range containing the dataset to consider.")),ba("quartile_number (number)",s("Which quartile value, exclusive of 0 and 4, to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Tl([e],.25*Math.trunc(Uo(t)),!1)},isExported:!0},ec={description:s("Value nearest to a specific quartile of a dataset."),args:[ba("data (any, range)",s("The array or range containing the dataset to consider.")),ba("quartile_number (number)",s("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Tl([e],.25*Math.trunc(Uo(t)),!0)},isExported:!0},tc={description:s("Nth smallest element in a data set."),args:[ba("data (any, range)",s("The array or range containing the dataset to consider.")),ba("n (number)",s("The rank from smallest to largest of the element to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){const i=Math.trunc(Uo(t));let o,n=[],r=0;Zo([e],(e=>{"number"==typeof e&&(o=rn(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(o+1,0,e),r++,r>i&&(n.pop(),r--))}));const a=n.pop();return Lo((()=>void 0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),Lo((()=>r>=i),s("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",i.toString())),a},isExported:!0},ic={description:s("Standard deviation."),args:[ba("value1 (number, range<number>)",s("The first value or range of the sample.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(lc.compute(...e))},isExported:!0},oc={description:s("Standard deviation of entire population."),args:[ba("value1 (number, range<number>)",s("The first value or range of the population.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(cc.compute(...e))},isExported:!0},nc={description:s("Standard deviation."),args:[ba("value1 (number, range<number>)",s("The first value or range of the sample.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(hc.compute(...e))},isExported:!0},sc={description:s("Standard deviation of sample (text as 0)."),args:[ba("value1 (number, range<number>)",s("The first value or range of the sample.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(dc.compute(...e))},isExported:!0},rc={description:s("Standard deviation of entire population."),args:[ba("value1 (number, range<number>)",s("The first value or range of the population.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(uc.compute(...e))},isExported:!0},ac={description:s("Standard deviation of entire population (text as 0)."),args:[ba("value1 (number, range<number>)",s("The first value or range of the population.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(gc.compute(...e))},isExported:!0},lc={description:s("Variance."),args:[ba("value1 (number, range<number>)",s("The first value or range of the sample.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Rl(e,!0,!1)},isExported:!0},cc={description:s("Variance of entire population."),args:[ba("value1 (number, range<number>)",s("The first value or range of the population.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Rl(e,!1,!1)},isExported:!0},hc={description:s("Variance."),args:[ba("value1 (number, range<number>)",s("The first value or range of the sample.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Rl(e,!0,!1)},isExported:!0},dc={description:s("Variance of sample (text as 0)."),args:[ba("value1 (number, range<number>)",s("The first value or range of the sample.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Rl(e,!0,!0)},isExported:!0},uc={description:s("Variance of entire population."),args:[ba("value1 (number, range<number>)",s("The first value or range of the population.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Rl(e,!1,!1)},isExported:!0},gc={description:s("Variance of entire population (text as 0)."),args:[ba("value1 (number, range<number>)",s("The first value or range of the population.")),ba("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Rl(e,!1,!0)},isExported:!0};var pc=Object.freeze({__proto__:null,AVEDEV:Al,AVERAGE:Ml,AVERAGE_WEIGHTED:_l,AVERAGEA:Fl,AVERAGEIF:Dl,AVERAGEIFS:kl,COUNT:Ll,COUNTA:Pl,COVAR:Ul,COVARIANCE_P:Vl,COVARIANCE_S:zl,LARGE:Bl,MAX:Hl,MAXA:$l,MAXIFS:Wl,MEDIAN:Gl,MIN:ql,MINA:Zl,MINIFS:jl,PERCENTILE:Yl,PERCENTILE_EXC:Xl,PERCENTILE_INC:Kl,QUARTILE:Ql,QUARTILE_EXC:Jl,QUARTILE_INC:ec,SMALL:tc,STDEV:ic,STDEV_P:oc,STDEV_S:nc,STDEVA:sc,STDEVP:rc,STDEVPA:ac,VAR:lc,VAR_P:cc,VAR_S:hc,VARA:dc,VARP:uc,VARPA:gc});function mc(e,t,i){var o;const n=new Map,r=e.length;for(let t=r-1;t>=0;t--)n.set(zo(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(s("The field must be a number or a string"));let a;if("number"==typeof t){if(a=Math.trunc(t)-1,a<0||r-1<a)throw new Error(s("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),r.toString()))}else{const e=zo(t).toUpperCase();if(a=null!==(o=n.get(e))&&void 0!==o?o:-1,-1===a)throw new Error(s("The field (%s) must be one of %s.",zo(t),[...n.keys()].toString()))}const l=i[0].length;if(l<2)throw new Error(s("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const h=e[0].length;for(let t=1;t<l;t++){let o=[],s=!0;for(let r=0;r<i.length;r++){const a=zo(i[r][0]).toUpperCase(),l=n.get(a),c=i[r][t];if(void 0!==c){if(void 0===l){s=!1;break}o.push([e[l].slice(1,h)]),o.push(c)}}if(s){if(!(o.length>0)){c=new Set(Array(h-1).keys());break}on(o,((e,t)=>{c.add(t)}),!0)}}const d=e[a];return[...c].map((e=>d[e+1]))}const fc=[ba("database (range)",s("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.")),ba("field (any)",s("Indicates which column in database contains the values to be extracted and operated on.")),ba("criteria (range)",s("An array or range containing zero or more criteria to filter the database values by before operating."))],vc={description:s("Average of a set of values from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return Ml.compute([o])},isExported:!0},bc={description:s("Counts values from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return Ll.compute([o])},isExported:!0},Cc={description:s("Counts values and text from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return Pl.compute([o])},isExported:!0},Sc={description:s("Single value from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return Lo((()=>1===o.length),s("More than one match found in DGET evaluation.")),o[0]},isExported:!0},Ec={description:s("Maximum of values from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return Hl.compute([o])},isExported:!0},wc={description:s("Minimum of values from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return ql.compute([o])},isExported:!0},yc={description:s("Product of values from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return al.compute([o])},isExported:!0},xc={description:s("Standard deviation of population sample from table."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return ic.compute([o])},isExported:!0},Ic={description:s("Standard deviation of entire population from table."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return rc.compute([o])},isExported:!0},Rc={description:s("Sum of values from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return bl.compute([o])},isExported:!0},Tc={description:s("Variance of population sample from table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return lc.compute([o])},isExported:!0},Ac={description:s("Variance of a population from a table-like range."),args:fc,returns:["NUMBER"],compute:function(e,t,i){const o=mc(e,t,i);return uc.compute([o])},isExported:!0};var Mc=Object.freeze({__proto__:null,DAVERAGE:vc,DCOUNT:bc,DCOUNTA:Cc,DGET:Sc,DMAX:Ec,DMIN:wc,DPRODUCT:yc,DSTDEV:xc,DSTDEVP:Ic,DSUM:Rc,DVAR:Tc,DVARP:Ac});const Oc={description:s("Converts year/month/day into a date."),args:[ba("year (number)",s("The year component of the date.")),ba("month (number)",s("The month component of the date.")),ba("day (number)",s("The day component of the date."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i){let o=Math.trunc(Uo(e));const n=Math.trunc(Uo(t)),r=Math.trunc(Uo(i));Lo((()=>0<=o&&o<=9999),s("The year (%s) must be between 0 and 9999 inclusive.",o.toString())),o<1900&&(o+=1900);const a=Ie(new ue(o,n-1,r));return Lo((()=>a>=0),s("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),a},isExported:!0},Nc={description:s("Converts a date string to a date value."),args:[ba("date_string (string)",s("The string representing the date."))],returns:["NUMBER"],compute:function(e){const t=zo(e),i=we(t);return Lo((()=>null!==i),s("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(i.value)},isExported:!0},_c={description:s("Day of the month that a specific date falls on."),args:[ba("date (string)",s("The date from which to extract the day."))],returns:["NUMBER"],compute:function(e){return Go(e).getDate()},isExported:!0},Fc={description:s("Number of days between two dates."),args:[ba("end_date (date)",s("The end of the date range.")),ba("start_date (date)",s("The start of the date range."))],returns:["NUMBER"],compute:function(e,t){const i=Go(e),o=Go(t),n=i.getTime()-o.getTime();return Math.round(n/pe)},isExported:!0},Dc={description:s("Number of days between two dates on a 360-day year (months of 30 days)."),args:[ba("start_date (date)",s("The start date to consider in the calculation.")),ba("end_date (date)",s("The end date to consider in the calculation.")),ba("method (number, default=0)",s("An indicator of what day count method to use. (0) US NASD method (1) European method"))],returns:["NUMBER"],compute:function(e,t,i=0){const o=Uo(e),n=Uo(t),s=Wo(i)?4:0,r=eh.compute(e,t,s);return Math.sign(n-o)*Math.round(360*r)},isExported:!0},kc={description:s("Date a number of months before/after another date."),args:[ba("start_date (date)",s("The date from which to calculate the result.")),ba("months (number)",s("The number of months before (negative) or after (positive) 'start_date' to calculate."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){return Ie(Ae(Go(e),Math.trunc(Uo(t)),!1))},isExported:!0},Lc={description:s("Last day of a month before or after a date."),args:[ba("start_date (date)",s("The date from which to calculate the result.")),ba("months (number)",s("The number of months before (negative) or after (positive) 'start_date' to consider."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){const i=Go(e),o=Math.trunc(Uo(t)),n=i.getFullYear(),s=i.getMonth();return Ie(new ue(n,s+o+1,0))},isExported:!0},Pc={description:s("Hour component of a specific time."),args:[ba("time (date)",s("The time from which to calculate the hour component."))],returns:["NUMBER"],compute:function(e){return Go(e).getHours()},isExported:!0},Uc={description:s("ISO week number of the year."),args:[ba("date (date)",s("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."))],returns:["NUMBER"],compute:function(e){const t=Go(e),i=t.getFullYear();let o=1;for(;4!==new ue(i,0,o).getDay();)o+=1;const n=new ue(i,0,o-3);let s=31;for(;4!==new ue(i,11,s).getDay();)s-=1;const r=new ue(i,11,s+3);let a,l;switch(a=n.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=n;break;case 1:l=new ue(i,11,s+3+1);break;case-1:let e=1;for(;4!==new ue(i-1,0,e).getDay();)e+=1;l=new ue(i-1,0,e-3)}const c=(t.getTime()-l.getTime())/pe;return Math.floor(c/7)+1},isExported:!0},Vc={description:s("Minute component of a specific time."),args:[ba("time (date)",s("The time from which to calculate the minute component."))],returns:["NUMBER"],compute:function(e){return Go(e).getMinutes()},isExported:!0},zc={description:s("Month of the year a specific date falls in"),args:[ba("date (date)",s("The date from which to extract the month."))],returns:["NUMBER"],compute:function(e){return Go(e).getMonth()+1},isExported:!0},Bc={description:s("Net working days between two provided days."),args:[ba("start_date (date)",s("The start date of the period from which to calculate the number of net working days.")),ba("end_date (date)",s("The end date of the period from which to calculate the number of net working days.")),ba("holidays (date, range<date>, optional)",s("A range or array constant containing the date serial numbers to consider holidays."))],returns:["NUMBER"],compute:function(e,t,i){return $c.compute(e,t,1,i)},isExported:!0};function Hc(e){if("string"==typeof e){Lo((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),s('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let i=0;i<7;i++)"1"===e[i]&&t.push((i+1)%7);return t}if("number"==typeof e)return Lo((()=>1<=e&&e<=7||11<=e&&e<=17),s("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(s("The weekend must be a number or a string."))}const $c={description:s("Net working days between two dates (specifying weekends)."),args:[ba("start_date (date)",s("The start date of the period from which to calculate the number of net working days.")),ba("end_date (date)",s("The end date of the period from which to calculate the number of net working days.")),ba("weekend (any, default=1)",s("A number or string representing which days of the week are considered weekends.")),ba("holidays (date, range<date>, optional)",s("A range or array constant containing the dates to consider as holidays."))],returns:["NUMBER"],compute:function(e,t,i=1,o){const n=Go(e),s=Go(t),r=Hc(i);let a=new Set;void 0!==o&&Zo([o],(e=>{const t=Go(e);a.add(t.getTime())}));const l=n.getTime()>s.getTime(),c=ue.fromTimestamp((l?n:s).getTime());let h=ue.fromTimestamp((l?s:n).getTime());const d=c.getTime();let u=h.getTime(),g=0;for(;u<=d;)r.includes(h.getDay())||a.has(u)||(g+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-g:g},isExported:!0},Wc={description:s("Current date and time as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy hh:mm:ss",compute:function(){let e=ue.now();const t=e.getTime()-ge.getTime(),i=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/pe)+i},isExported:!0},Gc={description:s("Minute component of a specific time."),args:[ba("time (date)",s("The time from which to calculate the second component."))],returns:["NUMBER"],compute:function(e){return Go(e).getSeconds()},isExported:!0},qc={description:s("Converts hour/minute/second into a time."),args:[ba("hour (number)",s("The hour component of the time.")),ba("minute (number)",s("The minute component of the time.")),ba("second (number)",s("The second component of the time."))],returns:["DATE"],computeFormat:()=>"hh:mm:ss a",compute:function(e,t,i){let o=Math.trunc(Uo(e)),n=Math.trunc(Uo(t)),r=Math.trunc(Uo(i));return n+=Math.floor(r/60),r=r%60+(r<0?60:0),o+=Math.floor(n/60),n=n%60+(n<0?60:0),o%=24,Lo((()=>o>=0),s("The function [[FUNCTION_NAME]] result cannot be negative")),o/24+n/1440+r/86400},isExported:!0},Zc={description:s("Converts a time string into its serial number representation."),args:[ba("time_string (string)",s("The string that holds the time representation."))],returns:["NUMBER"],compute:function(e){const t=zo(e),i=we(t);Lo((()=>null!==i),s("The time_string (%s) cannot be parsed to date/time.",t));const o=i.value-Math.trunc(i.value);return o<0?1+o:o},isExported:!0},jc={description:s("Current date as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(){const e=ue.now();return Ie(new ue(e.getFullYear(),e.getMonth(),e.getDate()))},isExported:!0},Yc={description:s("Day of the week of the date provided (as number)."),args:[ba("date (date)",s("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.")),ba("type (number, default=1)",s("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const i=Go(e),o=Math.round(Uo(t)),n=i.getDay();return Lo((()=>[1,2,3].includes(o)),s("The type (%s) must be 1, 2 or 3.",o.toString())),1===o?n+1:2===o?0===n?7:n:0===n?6:n-1},isExported:!0},Xc={description:s("Week number of the year."),args:[ba("date (date)",s("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.")),ba("type (number, default=1)",s("A number representing the day that a week starts on. Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const i=Go(e),o=Math.round(Uo(t));if(Lo((()=>1===o||2===o||11<=o&&o<=17||21===o),s("The type (%s) is out of range.",o.toString())),21===o)return Uc.compute(e);let n;n=1===o||2===o?o-1:o-10==7?0:o-10;const r=i.getFullYear();let a=1,l=new ue(r,0,a);for(;l.getDay()!==n;)a+=1,l=new ue(r,0,a);const c=(i.getTime()-l.getTime())/pe;return c<0?1:Math.floor(c/7)+(1===a?1:2)},isExported:!0},Kc={description:s("Date after a number of workdays."),args:[ba("start_date (date)",s("The date from which to begin counting.")),ba("num_days (number)",s("The number of working days to advance from start_date. If negative, counts backwards.")),ba("holidays (date, range<date>, optional)",s("A range or array constant containing the dates to consider holidays."))],returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i){return Qc.compute(e,t,1,i)},isExported:!0},Qc={description:s("Date after a number of workdays (specifying weekends)."),args:[ba("start_date (date)",s("The date from which to begin counting.")),ba("num_days (number)",s("The number of working days to advance from start_date. If negative, counts backwards.")),ba("weekend (any, default=1)",s("A number or string representing which days of the week are considered weekends.")),ba("holidays (date, range<date>, optional)",s("A range or array constant containing the dates to consider holidays."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i=1,o){let n=Go(e),r=Math.trunc(Uo(t));"string"==typeof i&&Lo((()=>"1111111"!==i),s("The weekend (%s) must be different from '1111111'.",i));const a=Hc(i);let l=new Set;void 0!==o&&Zo([o],(e=>{const t=Go(e);l.add(t.getTime())}));let c=ue.fromTimestamp(n.getTime()),h=c.getTime();const d=Math.sign(r);let u=Math.abs(r);for(;u>0;)c.setDate(c.getDate()+d),h=c.getTime(),a.includes(c.getDay())||l.has(h)||(u-=1);const g=h-ge.getTime();return Math.round(g/pe)},isExported:!0},Jc={description:s("Year specified by a given date."),args:[ba("date (date)",s("The date from which to extract the year."))],returns:["NUMBER"],compute:function(e){return Go(e).getFullYear()},isExported:!0},eh={description:s("Exact number of years between two dates."),args:[ba("start_date (date)",s("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.")),ba("end_date (date)",s("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.")),ba("day_count_convention (number, default=0)",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i=0){let o=Math.trunc(Uo(e)),n=Math.trunc(Uo(t));const r=Math.trunc(Uo(i));return Lo((()=>o>=0),s("The start_date (%s) must be positive or null.",o.toString())),Lo((()=>n>=0),s("The end_date (%s) must be positive or null.",n.toString())),Lo((()=>0<=r&&r<=4),s("The day_count_convention (%s) must be between 0 and 4 inclusive.",r.toString())),Oe(o,n,r)}},th={description:s("First day of the month preceding a date."),args:[ba("date (date)",s("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Go(e),i=t.getFullYear(),o=t.getMonth();return Ie(new ue(i,o,1))}},ih={description:s("Last day of the month following a date."),args:[ba("date (date)",s("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){return Lc.compute(e,0)}},oh={description:s("Quarter of the year a specific date falls in"),args:[ba("date (date)",s("The date from which to extract the quarter."))],returns:["NUMBER"],compute:function(e){return Math.ceil((Go(e).getMonth()+1)/3)}},nh={description:s("First day of the quarter of the year a specific date falls in."),args:[ba("date (date)",s("The date from which to calculate the start of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=oh.compute(e),i=Jc.compute(e);return Ie(new ue(i,3*(t-1),1))}},sh={description:s("Last day of the quarter of the year a specific date falls in."),args:[ba("date (date)",s("The date from which to calculate the end of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=oh.compute(e),i=Jc.compute(e);return Ie(new ue(i,3*t,0))}},rh={description:s("First day of the year a specific date falls in."),args:[ba("date (date)",s("The date from which to calculate the start of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Jc.compute(e);return Ie(new ue(t,0,1))}},ah={description:s("Last day of the year a specific date falls in."),args:[ba("date (date)",s("The date from which to calculate the end of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Jc.compute(e);return Ie(new ue(t+1,0,0))}};var lh=Object.freeze({__proto__:null,DATE:Oc,DATEVALUE:Nc,DAY:_c,DAYS:Fc,DAYS360:Dc,EDATE:kc,EOMONTH:Lc,HOUR:Pc,ISOWEEKNUM:Uc,MINUTE:Vc,MONTH:zc,NETWORKDAYS:Bc,NETWORKDAYS_INTL:$c,NOW:Wc,SECOND:Gc,TIME:qc,TIMEVALUE:Zc,TODAY:jc,WEEKDAY:Yc,WEEKNUM:Xc,WORKDAY:Kc,WORKDAY_INTL:Qc,YEAR:Jc,YEARFRAC:eh,MONTH_START:th,MONTH_END:ih,QUARTER:oh,QUARTER_START:nh,QUARTER_END:sh,YEAR_START:rh,YEAR_END:ah});const ch={description:s("Compare two numeric values, returning 1 if they're equal."),args:[ba("number1 (number)",s("The first number to compare.")),ba("number2 (number, default=0)",s("The second number to compare."))],returns:["NUMBER"],compute:function(e,t=0){return Uo(e)===Uo(t)?1:0},isExported:!0};var hh=Object.freeze({__proto__:null,DELTA:ch});function dh(e,t){Lo((()=>e<t),s("The maturity (%s) must be strictly greater than the settlement (%s).",t.toString(),e.toString()))}function uh(e,t){Lo((()=>t<e),s("The settlement date (%s) must be strictly greater than the issue date (%s).",e.toString(),t.toString()))}function gh(e){Lo((()=>[1,2,4].includes(e)),s("The frequency (%s) must be one of %s",e.toString(),[1,2,4].toString()))}function ph(e){Lo((()=>0<=e&&e<=4),s("The day_count_convention (%s) must be between 0 and 4 inclusive.",e.toString()))}function mh(e){Lo((()=>e>0),s("The redemption (%s) must be strictly positive.",e.toString()))}function fh(e){Lo((()=>e>0),s("The price (%s) must be strictly positive.",e.toString()))}function vh(e){Lo((()=>e>0),s("The number_of_periods (%s) must be greater than 0.",e.toString()))}function bh(e){Lo((()=>e>0),s("The rate (%s) must be strictly positive.",e.toString()))}function Ch(e){Lo((()=>e>0),s("The life (%s) must be strictly positive.",e.toString()))}function Sh(e){Lo((()=>e>=0),s("The cost (%s) must be positive or null.",e.toString()))}function Eh(e){Lo((()=>e>0),s("The period (%s) must be strictly positive.",e.toString()))}function wh(e){Lo((()=>e>=0),s("The salvage (%s) must be positive or null.",e.toString()))}function yh(e){Lo((()=>e>0),s("The present value (%s) must be strictly positive.",e.toString()))}function xh(e,t){Lo((()=>e<=t),s("The period (%s) must be less than or equal life (%s).",e.toString(),t.toString()))}function Ih(e){Lo((()=>e>0),s("The investment (%s) must be strictly positive.",e.toString()))}function Rh(e){Lo((()=>e>0),s("The discount (%s) must be strictly positive.",e.toString()))}function Th(e){Lo((()=>e<1),s("The discount (%s) must be smaller than 1.",e.toString()))}function Ah(e){Lo((()=>e>0),s("The depreciation factor (%s) must be strictly positive.",e.toString()))}function Mh(e,t){const i=Go(e),o=Go(t),n=Go(e);n.setFullYear(i.getFullYear()+1),Lo((()=>o.getTime()<=n.getTime()),s("The settlement date (%s) must at most one year after the maturity date (%s).",e.toString(),t.toString()))}function Oh(e,t,i){vh(i),Lo((()=>e>0),s("The first_period (%s) must be strictly positive.",e.toString())),Lo((()=>t>0),s("The last_period (%s) must be strictly positive.",t.toString())),Lo((()=>e<=t),s("The first_period (%s) must be smaller or equal to the last_period (%s).",e.toString(),t.toString())),Lo((()=>t<=i),s("The last_period (%s) must be smaller or equal to the number_of_periods (%s).",e.toString(),i.toString()))}function Nh(e){Lo((()=>e>-1),s("The rate_guess (%s) must be strictly greater than -1.",e.toString()))}function _h(e,t){Lo((()=>e.length===t.length&&e[0].length===t[0].length),s("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."))}function Fh(e){Lo((()=>e.every((t=>t>=e[0]))),s("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e[0].toString()))}const Dh=[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))];function kh(e,t,i,o,n=1e-10,r){let a,l,c,h,d=i,u=!1,g=0;do{c=e(d),isNaN(c)?(Lo((()=>g<o&&void 0!==r),s("Function [[FUNCTION_NAME]] didn't find any result.")),g++,d=r(h),h=d):(a=d-c/t(d),l=Math.abs(a-d),d=a,u=l<n||Math.abs(c)<n,Lo((()=>g<o),s("Function [[FUNCTION_NAME]] didn't find any result.")),g++)}while(!u);return d}const Lh={description:s("Accrued interest of security paying at maturity."),args:[ba("issue (date)",s("The date the security was initially issued.")),ba("maturity (date)",s("The maturity date of the security.")),ba("rate (number)",s("The annualized rate of interest.")),ba("redemption (number)",s("The redemption amount per 100 face value, or par.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Uo(e)),r=Math.trunc(Uo(t)),a=Uo(o),l=Uo(i),c=Math.trunc(Uo(n));uh(r,s),ph(c),mh(a),bh(l);return a*l*eh.compute(s,r,n)},isExported:!0},Ph={description:s("Depreciation for an accounting period."),args:[ba("cost (number)",s("The initial cost of the asset.")),ba("purchase_date (date)",s("The date the asset was purchased.")),ba("first_period_end (date)",s("The date the first period ended.")),ba("salvage (number)",s("The value of the asset at the end of depreciation.")),ba("period (number)",s("The single period within life for which to calculate depreciation.")),ba("rate (number)",s("The deprecation rate.")),ba("day_count_convention (number, optional)",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r,a=0){a=a||0;const l=Uo(e),c=Math.trunc(Uo(t)),h=Math.trunc(Uo(i)),d=Uo(o),u=Uo(n),g=Uo(r),p=Math.trunc(Uo(a));!function(e){Lo((()=>e>0),s("The cost (%s) must be strictly positive.",e.toString()))}(l),wh(d),function(e,t){Lo((()=>e<=t),s("The salvage (%s) must be smaller or equal than the cost (%s).",e.toString(),t.toString()))}(d,l),function(e){Lo((()=>e>=0),s("The period (%s) must be positive or null.",e.toString()))}(u),bh(g),ph(p),Lo((()=>c<=h),s("The purchase_date (%s) must be before the first_period_end (%s).",c.toString(),h.toString()));const m=u<1&&u>0?1:Math.trunc(u),f=l*g,v=eh.compute(c,h,p),b=c===h?f:f*v,C=l-b-f*m;return C>=d?0===m?b:f:d-C<f?f-(d-C):0},isExported:!0},Uh={description:s("Days in coupon period containing settlement date."),args:Dh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Uo(e)),s=Math.trunc(Uo(t)),r=Math.trunc(Uo(i)),a=Math.trunc(Uo(o));if(dh(n,s),gh(r),ph(a),1===a){const n=$h.compute(e,t,i,o);return Bh.compute(e,t,i,o)-n}return(3===a?365:360)/r},isExported:!0},Vh={description:s("Days from settlement until next coupon."),args:Dh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Uo(e)),s=Math.trunc(Uo(t)),r=Math.trunc(Uo(i)),a=Math.trunc(Uo(o));dh(n,s),gh(r),ph(a);const l=$h.compute(n,s,i,o);if([1,2,3].includes(a))return n-l;if(4===a){const e=Oe(l,n,a);return Math.round(360*e)}const c=Go(n),h=Go(l),d=h.getFullYear(),u=c.getFullYear(),g=h.getMonth()+1,p=c.getMonth()+1;let m=h.getDate(),f=c.getDate();return 2===g&&2===p&&Te(h)&&Te(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&Te(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},zh={description:s("Days from settlement until next coupon."),args:Dh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Uo(e)),s=Math.trunc(Uo(t)),r=Math.trunc(Uo(i)),a=Math.trunc(Uo(o));dh(n,s),gh(r),ph(a);const l=Bh.compute(n,s,i,o);if([1,2,3].includes(a))return l-n;if(4===a){const e=Oe(n,l,a);return Math.round(360*e)}const c=Vh.compute(e,t,i,a);return Uh.compute(e,t,i,a)-c},isExported:!0},Bh={description:s("Next coupon date after the settlement date."),args:Dh,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Uo(e)),s=Math.trunc(Uo(t)),r=Math.trunc(Uo(i)),a=Math.trunc(Uo(o));dh(n,s),gh(r),ph(a);const l=12/r,c=Hh.compute(e,t,i,o);return Ie(Ae(Go(s),-(c-1)*l,!0))},isExported:!0},Hh={description:s("Number of coupons between settlement and maturity."),args:Dh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Uo(e)),s=Math.trunc(Uo(t)),r=Math.trunc(Uo(i)),a=Math.trunc(Uo(o));dh(n,s),gh(r),ph(a);let l=1,c=s;const h=12/r;for(;c>n;)c=Ie(Ae(Go(c),-h,!1)),l++;return l-1},isExported:!0},$h={description:s("Last coupon date prior to or on the settlement date."),args:Dh,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Uo(e)),s=Math.trunc(Uo(t)),r=Math.trunc(Uo(i)),a=Math.trunc(Uo(o));dh(n,s),gh(r),ph(a);const l=12/r,c=Hh.compute(e,t,i,o);return Ie(Ae(Go(s),-c*l,!0))},isExported:!0},Wh={description:s("Cumulative interest paid over a set of periods."),args:[ba("rate (number)",s("The interest rate.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("present_value (number)",s("The current value of the annuity.")),ba("first_period (number)",s("The number of the payment period to begin the cumulative calculation.")),ba("last_period (number)",s("The number of the payment period to end the cumulative calculation.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,i,o,n,s=0){const r=Uo(o),a=Uo(n),l=Uo(e),c=Uo(i),h=Uo(t);Oh(r,a,h),bh(l),yh(c);let d=0;for(let t=r;t<=a;t++){d+=id.compute(e,t,h,i,0,s)}return d},isExported:!0},Gh={description:s("Cumulative principal paid over a set of periods."),args:[ba("rate (number)",s("The interest rate.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("present_value (number)",s("The current value of the annuity.")),ba("first_period (number)",s("The number of the payment period to begin the cumulative calculation.")),ba("last_period (number)",s("The number of the payment period to end the cumulative calculation.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,i,o,n,s=0){const r=Uo(o),a=Uo(n),l=Uo(e),c=Uo(i),h=Uo(t);Oh(r,a,h),bh(l),yh(c);let d=0;for(let t=r;t<=a;t++){d+=ud.compute(e,t,h,i,0,s)}return d},isExported:!0},qh={description:s("Depreciation via declining balance method."),args:[ba("cost (number)",s("The initial cost of the asset.")),ba("salvage (number)",s("The value of the asset at the end of depreciation.")),ba("life (number)",s("The number of periods over which the asset is depreciated.")),ba("period (number)",s("The single period within life for which to calculate depreciation.")),ba("month (number, optional)",s("The number of months in the first year of depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,...n){const r=Uo(e),a=Uo(t),l=Uo(i),c=Math.trunc(Uo(o)),h=n.length?Math.trunc(Uo(n[0])):12,d=l+(12===h?0:1);Sh(r),wh(a),Eh(c),Ch(l),Lo((()=>1<=h&&h<=12),s("The month (%s) must be between 1 and 12 inclusive.",h.toString())),Lo((()=>c<=d),s("The period (%s) must be less than or equal to %s.",c.toString(),d.toString()));const u=h/12;let g=1-Math.pow(a/r,1/l);g=Math.round(1e3*g)/1e3;let p=r,m=r*(1-g*u);for(let e=1;e<c;e++)p=m,m=p*(1-g),e===l&&(m=p*(1-g*(1-u)));return p-m},isExported:!0},Zh={description:s("Depreciation via double-declining balance method."),args:[ba("cost (number)",s("The initial cost of the asset.")),ba("salvage (number)",s("The value of the asset at the end of depreciation.")),ba("life (number)",s("The number of periods over which the asset is depreciated.")),ba("period (number)",s("The single period within life for which to calculate depreciation.")),ba("factor (number, default=2)",s("The factor by which depreciation decreases."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,n=2){n=n||0;const s=Uo(e),r=Uo(t),a=Uo(i),l=Uo(o),c=Uo(n);if(Sh(s),wh(r),Eh(l),Ch(a),xh(l,a),Ah(c),0===s||r>=s)return 0;const h=c/a;if(h>1)return 1===o?s-r:0;if(l<=1)return s*h;const d=s*Math.pow(1-h,l-1),u=s*Math.pow(1-h,l),g=u<r?d-r:d-u;return Math.max(g,0)},isExported:!0},jh={description:s("Discount rate of a security based on price."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("price (number)",s("The price at which the security is bought per 100 face value.")),ba("redemption (number)",s("The redemption amount per 100 face value, or par.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Uo(e)),r=Math.trunc(Uo(t)),a=Uo(i),l=Uo(o),c=Math.trunc(Uo(n));dh(s,r),ph(c),fh(a),mh(l);return(l-a)/l/eh.compute(s,r,c)},isExported:!0},Yh={description:s("Convert a decimal fraction to decimal value."),args:[ba("fractional_price (number)",s("The price quotation given using fractional decimal conventions.")),ba("unit (number)",s("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const i=Uo(e),o=Math.trunc(Uo(t));Lo((()=>o>0),s("The unit (%s) must be strictly positive.",o.toString()));const n=Math.trunc(i);return n+(i-n)*(10**Math.ceil(Math.log10(o))/o)},isExported:!0},Xh={description:s("Convert a decimal value to decimal fraction."),args:[ba("decimal_price (number)",s("The price quotation given as a decimal value.")),ba("unit (number)",s("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const i=Uo(e),o=Math.trunc(Uo(t));Lo((()=>o>0),s("The unit (%s) must be strictly positive.",o.toString()));const n=Math.trunc(i);return n+(i-n)*(o/10**Math.ceil(Math.log10(o)))},isExported:!0},Kh={description:s("Number of periods for an investment to reach a value."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("rate (number)",s("The annualized rate of interest.")),ba("yield (number)",s("The expected annual yield of the security.")),ba("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=0){r=r||0;const a=Math.trunc(Uo(e)),l=Math.trunc(Uo(t)),c=Uo(i),h=Uo(o),d=Math.trunc(Uo(n)),u=Math.trunc(Uo(r));dh(a,l),gh(d),ph(u),Lo((()=>c>=0),s("The rate (%s) must be positive or null.",c.toString())),Lo((()=>h>=0),s("The yield (%s) must be positive or null.",h.toString()));const g=eh.compute(a,l,u),p=g-Math.trunc(g)||1/d,m=Math.ceil(g*d),f=c/d,v=h/d;let b=0,C=0;for(let e=1;e<=m;e++){const t=(f+(e===m?1:0))/(1+v)**e;C+=(p+(e-1)/d)*t,b+=t}return 0===b?0:C/b},isExported:!0},Qh={description:s("Annual effective interest rate."),args:[ba("nominal_rate (number)",s("The nominal interest rate per year.")),ba("periods_per_year (number)",s("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const i=Uo(e),o=Math.trunc(Uo(t));return Lo((()=>i>0),s("The nominal rate (%s) must be strictly greater than 0.",i.toString())),Lo((()=>o>0),s("The number of periods by year (%s) must strictly greater than 0.",o.toString())),Math.pow(1+i/o,o)-1},isExported:!0},Jh={description:s("Future value of an annuity investment."),args:[ba("rate (number)",s("The interest rate.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("payment_amount (number)",s("The amount per period to be paid.")),ba("present_value (number, default=0)",s("The current value of the annuity.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=Uo(e),r=Uo(t),a=Uo(i),l=Uo(o),c=Wo(n)?1:0;return s?-l*(1+s)**r-a*(1+s*c)*((1+s)**r-1)/s:-(l+a*r)},isExported:!0},ed={description:s("Future value of principal from series of rates."),args:[ba("principal (number)",s("The amount of initial capital or value to compound against.")),ba("rate_schedule (number, range<number>)",s("A series of interest rates to compound against the principal."))],returns:["NUMBER"],compute:function(e,t){return Xo([t],((e,t)=>e*(1+Uo(t))),Uo(e))},isExported:!0},td={description:s("Calculates effective interest rate."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("investment (number)",s("The amount invested in the security.")),ba("redemption (number)",s("The amount to be received at maturity.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){const s=Math.trunc(Uo(e)),r=Math.trunc(Uo(t)),a=Uo(o),l=Uo(i);dh(s,r),Ih(l),mh(a);return(a-l)/l/eh.compute(s,r,n)},isExported:!0},id={description:s("Payment on the principal of an investment."),args:[ba("rate (number)",s("The annualized rate of interest.")),ba("period (number)",s("The amortization period, in terms of number of periods.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("present_value (number)",s("The current value of the annuity.")),ba("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,n=0,s=0){return dd.compute(e,i,o,n,s)-ud.compute(e,t,i,o,n,s)},isExported:!0},od={description:s("Internal rate of return given periodic cashflows."),args:[ba("cashflow_amounts (number, range<number>)",s("An array or range containing the income or payments associated with the investment.")),ba("rate_guess (number, default=0.1)",s("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t=.1){const i=Uo(t);Nh(i);let o=!1,n=!1,r=[];jo([e],(e=>{e>0&&(o=!0),e<0&&(n=!0),r.push(e)})),Lo((()=>o&&n),s("The cashflow_amounts must include negative and positive values."));const a=r.shift();return kh((function(e){return function(e,t,i){const o=i.length;let n=0;return i.reduce(((t,i)=>(n++,t+i*e**(o-n))),t*e**o)}(e,a,r)}),(function(e){return function(e,t,i){const o=i.length;let n=0;return i.reduce(((t,i)=>(n++,t+i*(o-n)*e**(o-n-1))),t*o*e**(o-1))}(e,a,r)}),i+1,20,1e-5)-1},isExported:!0},nd={description:s("Returns the interest paid at a particular period of an investment."),args:[ba("rate (number)",s("The interest rate.")),ba("period (number)",s("The period for which you want to view the interest payment.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("present_value (number)",s("The current value of the annuity."))],returns:["NUMBER"],compute:function(e,t,i,o){const n=Uo(e),r=Uo(t),a=Uo(i),l=Uo(o);Lo((()=>0!==a),s("The number of periods must be different than 0.",a.toString()));return-1*(l-l*(r/a))*n},isExported:!0},sd={description:s("Modified Macaulay duration."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("rate (number)",s("The annualized rate of interest.")),ba("yield (number)",s("The expected annual yield of the security.")),ba("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,s=0){return Kh.compute(e,t,i,o,n,s)/(1+Uo(o)/Math.trunc(Uo(n)))},isExported:!0},rd={description:s("Modified internal rate of return."),args:[ba("cashflow_amounts (range<number>)",s("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),ba("financing_rate (number)",s("The interest rate paid on funds invested.")),ba("reinvestment_return_rate (number)",s("The return (as a percentage) earned on reinvestment of income received from the investment."))],returns:["NUMBER"],compute:function(e,t,i){const o=Uo(t),n=Uo(i),r=(a=e,a.length?a[0].map(((e,t)=>a.map((e=>e[t])))):a).flat().filter(ot).map(Uo);var a;const l=r.length;let c=0,h=0;for(const e of $e(0,l)){const t=r[e];t>=0?c+=t*(n+1)**(l-e-1):h+=t/(o+1)**e}Lo((()=>0!==h&&0!==c),s("There must be both positive and negative values in cashflow_amounts."));return(-c/h)**(1/(l-1))-1},isExported:!0},ad={description:s("Annual nominal interest rate."),args:[ba("effective_rate (number)",s("The effective interest rate per year.")),ba("periods_per_year (number)",s("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const i=Uo(e),o=Math.trunc(Uo(t));return Lo((()=>i>0),s("The effective rate (%s) must must strictly greater than 0.",i.toString())),Lo((()=>o>0),s("The number of periods by year (%s) must strictly greater than 0.",o.toString())),(Math.pow(i+1,1/o)-1)*o},isExported:!0},ld={description:s("Number of payment periods for an investment."),args:[ba("rate (number)",s("The interest rate.")),ba("payment_amount (number)",s("The amount of each payment made.")),ba("present_value (number)",s("The current value of the annuity.")),ba("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=Uo(e),r=Uo(t),a=Uo(i),l=Uo(o),c=Wo(n)?1:0;if(0===s)return-(l+a)/r;const h=r*(1+s*c)/s;return Math.log((h-l)/(a+h))/Math.log(1+s)},isExported:!0};const cd={description:s("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:[ba("discount (number)",s("The discount rate of the investment over one period.")),ba("cashflow1 (number, range<number>)",s("The first future cash flow.")),ba("cashflow2 (number, range<number>, repeating)",s("Additional future cash flows."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,...t){const i=Uo(e);return Lo((()=>-1!==i),s("The discount (%s) must be different from -1.",i.toString())),function(e,t,i){let o=0;return Ko(i,((t,i)=>(o++,t+i/(1+e)**o)),t)}(i,0,t)},isExported:!0},hd={description:s("Computes the number of periods needed for an investment to reach a value."),args:[ba("rate (number)",s("The rate at which the investment grows each period.")),ba("present_value (number)",s("The investment's current value.")),ba("future_value (number)",s("The investment's desired future value."))],returns:["NUMBER"],compute:function(e,t,i){const o=Uo(e),n=Uo(t),r=Uo(i);return bh(o),Lo((()=>n>0),s("The present_value (%s) must be strictly positive.",n.toString())),Lo((()=>r>0),s("The future_value (%s) must be strictly positive.",r.toString())),(Math.log(r)-Math.log(n))/Math.log(1+o)},isExported:!0},dd={description:s("Periodic payment for an annuity investment."),args:[ba("rate (number)",s("The annualized rate of interest.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("present_value (number)",s("The current value of the annuity.")),ba("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=Uo(t),r=Uo(e),a=Wo(n)?1:0;let l=Uo(o),c=Uo(i);if(vh(s),0===r)return-(l+c)/s;let h=-(c*(1+r)**s+l);return h=h*r/((1+r*a)*((1+r)**s-1)),h},isExported:!0},ud={description:s("Payment on the principal of an investment."),args:[ba("rate (number)",s("The annualized rate of interest.")),ba("period (number)",s("The amortization period, in terms of number of periods.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("present_value (number)",s("The current value of the annuity.")),ba("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,n=0,r=0){n=n||0,r=r||0;const a=Uo(i),l=Uo(e),c=Uo(t),h=Wo(r)?1:0,d=Uo(n),u=Uo(o);vh(a),Lo((()=>c>0&&c<=a),s("The period must be between 1 and number_of_periods",a.toString()));const g=dd.compute(l,a,u,d,r);if(1===h&&1===c)return g;return g+-Jh.compute(l,0===h?c-1:c-2,g,u+g*h,0)*l},isExported:!0},gd={description:s("Present value of an annuity investment."),args:[ba("rate (number)",s("The interest rate.")),ba("number_of_periods (number)",s("The number of payments to be made.")),ba("payment_amount (number)",s("The amount per period to be paid.")),ba("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=Uo(e),r=Uo(t),a=Uo(i),l=Uo(o),c=Wo(n)?1:0;return s?-(a*(1+s*c)*((1+s)**r-1)/s+l)/(1+s)**r:-(l+a*r)},isExported:!0},pd={description:s("Price of a security paying periodic interest."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("rate (number)",s("The annualized rate of interest.")),ba("yield (number)",s("The expected annual yield of the security.")),ba("redemption (number)",s("The redemption amount per 100 face value, or par.")),ba("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r,a=0){a=a||0;const l=Math.trunc(Uo(e)),c=Math.trunc(Uo(t)),h=Uo(i),d=Uo(o),u=Uo(n),g=Math.trunc(Uo(r)),p=Math.trunc(Uo(a));dh(l,c),gh(g),ph(p),Lo((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),Lo((()=>d>=0),s("The yield (%s) must be positive or null.",d.toString())),mh(u);const m=eh.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=1+d/g,C=100*h/g;if(1===f)return(C+u)/(v*d/g+1)-C*(1-v);let S=0;for(let e=1;e<=f;e++)S+=C/b**(e-1+v);return u/b**(f-1+v)+S-C*(1-v)},isExported:!0},md={description:s("Price of a discount security."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("discount (number)",s("The discount rate of the security at time of purchase.")),ba("redemption (number)",s("The redemption amount per 100 face value, or par.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Uo(e)),r=Math.trunc(Uo(t)),a=Uo(i),l=Uo(o),c=Math.trunc(Uo(n));dh(s,r),ph(c),Rh(a),mh(l);return l-a*l*eh.compute(s,r,c)},isExported:!0},fd={description:s("Calculates the price of a security paying interest at maturity, based on expected yield."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("issue (date)",s("The date the security was initially issued.")),ba("rate (number)",s("The annualized rate of interest.")),ba("yield (number)",s("The expected annual yield of the security.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=0){r=r||0;const a=Math.trunc(Uo(e)),l=Math.trunc(Uo(t)),c=Math.trunc(Uo(i)),h=Uo(o),d=Uo(n),u=Math.trunc(Uo(r));uh(a,c),dh(a,l),ph(u),Lo((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),Lo((()=>d>=0),s("The yield (%s) must be positive or null.",d.toString()));const g=eh.compute(a,l,u),p=eh.compute(a,c,u);return(100+eh.compute(c,l,u)*h*100)/(1+g*d)-p*h*100},isExported:!0},vd=.1,bd={description:s("Interest rate of an annuity investment."),args:[ba("number_of_periods (number)",s("The number of payments to be made.")),ba("payment_per_period (number)",s("The amount per period to be paid.")),ba("present_value (number)",s("The current value of the annuity.")),ba("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),ba("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period.")),ba("rate_guess (number, default=0.1)",s("An estimate for what the interest rate will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t,i,o=0,n=0,r=.1){o=o||0,n=n||0,r=r||vd;const a=Uo(e),l=Uo(t),c=Wo(n)?1:0,h=Uo(r);let d=Uo(o),u=Uo(i);vh(a),Lo((()=>[l,u,d].some((e=>e>0))&&[l,u,d].some((e=>e<0))),s("There must be both positive and negative values in [payment_amount, present_value, future_value].",a.toString())),Nh(h),d-=l*c,u+=l*c;return kh((e=>{const t=Math.pow(1+e,a);return d+u*t+l*((t-1)/e)}),(e=>{const t=Math.pow(1+e,a-1),i=Math.pow(1+e,a);return u*a*t+l*(a*t/e-(i-1)/e/e)}),h,40,1e-5)},isExported:!0},Cd={description:s("Amount received at maturity for a security."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("investment (number)",s("The amount invested (irrespective of face value of each security).")),ba("discount (number)",s("The discount rate of the security invested in.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Uo(e)),r=Math.trunc(Uo(t)),a=Uo(i),l=Uo(o),c=Math.trunc(Uo(n));dh(s,r),ph(c),Ih(a),Rh(l);return a/(1-l*eh.compute(s,r,c))},isExported:!0},Sd={description:s("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[ba("number_of_periods (number)",s("The number of periods.")),ba("present_value (number)",s("The present value of the investment.")),ba("future_value (number)",s("The future value of the investment."))],returns:["NUMBER"],compute:function(e,t,i){const o=Uo(e),n=Uo(t),s=Uo(i);return vh(o),(s/n)**(1/o)-1},isExported:!0},Ed={description:s("Depreciation of an asset using the straight-line method."),args:[ba("cost (number)",s("The initial cost of the asset.")),ba("salvage (number)",s("The value of the asset at the end of depreciation.")),ba("life (number)",s("The number of periods over which the asset is depreciated."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i){return(Uo(e)-Uo(t))/Uo(i)},isExported:!0},wd={description:s("Depreciation via sum of years digit method."),args:[ba("cost (number)",s("The initial cost of the asset.")),ba("salvage (number)",s("The value of the asset at the end of depreciation.")),ba("life (number)",s("The number of periods over which the asset is depreciated.")),ba("period (number)",s("The single period within life for which to calculate depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o){const n=Uo(e),s=Uo(t),r=Uo(i),a=Uo(o);Eh(a),Ch(r),xh(a,r);return(r-a+1)/(r*(r+1)/2)*(n-s)},isExported:!0},yd={description:s("Price of a US Treasury bill."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("discount (number)",s("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,i){const o=Math.trunc(Uo(e)),n=Math.trunc(Uo(t)),s=Uo(i);dh(o,n),Mh(o,n),Rh(s),Th(s);return 100*(1-s*eh.compute(o,n,2))},isExported:!0},xd={description:s("Equivalent rate of return for a US Treasury bill."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("discount (number)",s("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,i){const o=Math.trunc(Uo(e)),n=Math.trunc(Uo(t)),s=Uo(i);dh(o,n),Mh(o,n),Rh(s),Th(s);const r=Fc.compute(n,o);if(r<=182)return 365*s/(360-s*r);const a=yd.compute(o,n,s)/100,l=r/(366===r?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},Id={description:s("The yield of a US Treasury bill based on price."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("price (number)",s("The price at which the security is bought per 100 face value."))],returns:["NUMBER"],compute:function(e,t,i){const o=Math.trunc(Uo(e)),n=Math.trunc(Uo(t)),s=Uo(i);dh(o,n),Mh(o,n),fh(s);return(100-s)/s*(1/eh.compute(o,n,2))},isExported:!0},Rd={description:s("Variable declining balance. WARNING : does not handle decimal periods."),args:[ba("cost (number)",s("The initial cost of the asset.")),ba("salvage (number)",s("The value of the asset at the end of depreciation.")),ba("life (number)",s("The number of periods over which the asset is depreciated.")),ba("start (number)",s("Starting period to calculate depreciation.")),ba("end (number)",s("Ending period to calculate depreciation.")),ba("factor (number, default=2)",s("The number of months in the first year of depreciation.")),ba("no_switch (number, default=false)",s("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=2,a=false){r=r||0;const l=Uo(e),c=Uo(t),h=Uo(i),d=Math.trunc(Uo(o)),u=Math.trunc(Uo(n)),g=Uo(r),p=Wo(a);if(Sh(l),wh(c),function(e,t,i){Ch(i),Lo((()=>e>=0),s("The start_period (%s) must be greater or equal than 0.",e.toString())),Lo((()=>t>=0),s("The end_period (%s) must be greater or equal than 0.",t.toString())),Lo((()=>e<=t),s("The start_period (%s) must be smaller or equal to the end_period (%s).",e.toString(),t.toString())),Lo((()=>t<=i),s("The end_period (%s) must be smaller or equal to the life (%s).",e.toString(),i.toString()))}(d,u,h),Ah(g),0===l)return 0;if(c>=l)return d<1?l-c:0;const m=g/h;if(m>=1)return d<1?l-c:0;let f=l,v=0,b=0,C=!1;for(let e=0;e<u;e++){if(!C||p){const t=f*m,i=(f-c)/(h-e);!p&&i>t?(C=!0,v=i):v=t}const t=Math.max(f-v,c);e>=d&&(b+=f-t),f=t}return b},isExported:!0},Td={description:s("Internal rate of return given non-periodic cash flows."),args:[ba("cashflow_amounts (range<number>)",s("An range containing the income or payments associated with the investment.")),ba("cashflow_dates (range<number>)",s("An range with dates corresponding to the cash flows in cashflow_amounts.")),ba("rate_guess (number, default=0.1)",s("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],compute:function(e,t,i=.1){const o=Uo(i=i||0),n=e.flat().map(Uo),r=t.flat().map(Uo);var a;_h(e,t),a=n,Lo((()=>a.some((e=>e>0))&&a.some((e=>e<0))),s("There must be both positive and negative values in cashflow_amounts.")),Fh(r),Nh(o);const l=new Map;for(const e of $e(0,r.length)){const t=r[e];l.has(t)?l.set(t,l.get(t)+n[e]):l.set(t,n[e])}const c=Array.from(l.keys()),h=c.map((e=>l.get(e)));return kh((e=>{let t=h[0];for(const i of $e(1,h.length)){const o=(c[0]-c[i])/365;t+=h[i]*(1+e)**o}return t}),(e=>{let t=0;for(const i of $e(1,h.length)){const o=(c[0]-c[i])/365;t+=o*h[i]*(1+e)**(o-1)}return t}),o,40,1e-5,(e=>e?e/10-.9:-.9))},isExported:!0},Ad={description:s("Net present value given to non-periodic cash flows.."),args:[ba("discount (number)",s("The discount rate of the investment over one period.")),ba("cashflow_amounts (number, range<number>)",s("An range containing the income or payments associated with the investment.")),ba("cashflow_dates (number, range<number>)",s("An range with dates corresponding to the cash flows in cashflow_amounts."))],returns:["NUMBER"],compute:function(e,t,i){const o=Uo(e),n=Array.isArray(t)?t.flat().map(Vo):[Vo(t)],r=Array.isArray(i)?i.flat().map(Vo):[Vo(i)];if(Array.isArray(i)&&Array.isArray(t)?_h(t,i):Lo((()=>n.length===r.length),s("There must be the same number of values in cashflow_amounts and cashflow_dates.")),Fh(r),bh(o),1===n.length)return n[0];const a=new Map;for(const e of $e(0,r.length)){const t=r[e];a.has(t)?a.set(t,a.get(t)+n[e]):a.set(t,n[e])}const l=Array.from(a.keys()),c=l.map((e=>a.get(e)));let h=c[0];for(const e of $e(1,c.length)){const t=(l[0]-l[e])/365;h+=c[e]*(1+o)**t}return h},isExported:!0},Md={description:s("Annual yield of a security paying periodic interest."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("rate (number)",s("The annualized rate of interest.")),ba("price (number)",s("The price at which the security is bought per 100 face value.")),ba("redemption (number)",s("The redemption amount per 100 face value, or par.")),ba("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r,a=0){a=a||0;const l=Math.trunc(Uo(e)),c=Math.trunc(Uo(t)),h=Uo(i),d=Uo(o),u=Uo(n),g=Math.trunc(Uo(r)),p=Math.trunc(Uo(a));dh(l,c),gh(g),ph(p),Lo((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),fh(d),mh(u);const m=eh.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=100*h/g;if(1===f){const e=d+b*(1-v);return(u+b-e)*g*(1/v)/e}const C=kh((function(e){return function(e,t,i,o,n,s){let r=s-(e+n*(1-t))*o**(i-1+t);for(let e=1;e<=i;e++)r+=n*o**(e-1);return r}(d,v,f,e,b,u)}),(function(e){return function(e,t,i,o,n){let s=-(e+n*(1-t))*(i-1+t)*o**(i-2+t);for(let e=1;e<=i;e++)s+=n*(e-1)*o**(e-2);return s}(d,v,f,e,b)}),1+(h+1)/g,100,1e-5);return(C-1)*g},isExported:!0},Od={description:s("Annual yield of a discount security."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("price (number)",s("The price at which the security is bought per 100 face value.")),ba("redemption (number)",s("The redemption amount per 100 face value, or par.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Uo(e)),r=Math.trunc(Uo(t)),a=Uo(i),l=Uo(o),c=Math.trunc(Uo(n));dh(s,r),ph(c),fh(a),mh(l);return(l/a-1)/eh.compute(e,t,n)},isExported:!0},Nd={description:s("Annual yield of a security paying interest at maturity."),args:[ba("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),ba("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),ba("issue (date)",s("The date the security was initially issued.")),ba("rate (number)",s("The annualized rate of interest.")),ba("price (number)",s("The price at which the security is bought.")),ba("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=0){r=r||0;const a=Math.trunc(Uo(e)),l=Math.trunc(Uo(t)),c=Math.trunc(Uo(i)),h=Uo(o),d=Uo(n),u=Math.trunc(Uo(r));dh(a,l),ph(u),Lo((()=>a>=c),s("The settlement (%s) must be greater than or equal to the issue (%s).",a.toString(),c.toString())),Lo((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),fh(d);const g=eh.compute(c,l,u),p=eh.compute(c,a,u),m=eh.compute(a,l,u);return(100*(1+h*g)/(d+100*h*p)-1)/m},isExported:!0};var _d=Object.freeze({__proto__:null,ACCRINTM:Lh,AMORLINC:Ph,COUPDAYS:Uh,COUPDAYBS:Vh,COUPDAYSNC:zh,COUPNCD:Bh,COUPNUM:Hh,COUPPCD:$h,CUMIPMT:Wh,CUMPRINC:Gh,DB:qh,DDB:Zh,DISC:jh,DOLLARDE:Yh,DOLLARFR:Xh,DURATION:Kh,EFFECT:Qh,FV:Jh,FVSCHEDULE:ed,INTRATE:td,IPMT:id,IRR:od,ISPMT:nd,MDURATION:sd,MIRR:rd,NOMINAL:ad,NPER:ld,NPV:cd,PDURATION:hd,PMT:dd,PPMT:ud,PV:gd,PRICE:pd,PRICEDISC:md,PRICEMAT:fd,RATE:bd,RECEIVED:Cd,RRI:Sd,SLN:Ed,SYD:wd,TBILLPRICE:yd,TBILLEQ:xd,TBILLYIELD:Id,VDB:Rd,XIRR:Td,XNPV:Ad,YIELD:Md,YIELDDISC:Od,YIELDMAT:Nd});const Fd={description:s("Whether a value is an error other than #N/A."),args:[ba("value (any, lazy)",s("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)!=a.NotAvailable}},isExported:!0},Dd={description:s("Whether a value is an error."),args:[ba("value (any, lazy)",s("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},kd={description:s("Whether a value is `true` or `false`."),args:[ba("value (any, lazy)",s("The value to be verified as a logical TRUE or FALSE."))],returns:["BOOLEAN"],compute:function(e){try{return"boolean"==typeof e()}catch(e){return!1}},isExported:!0},Ld={description:s("Whether a value is the error #N/A."),args:[ba("value (any, lazy)",s("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)==a.NotAvailable}},isExported:!0},Pd={description:s("Whether a value is non-textual."),args:[ba("value (any, lazy)",s("The value to be checked."))],returns:["BOOLEAN"],compute:function(e){try{return"string"!=typeof e()}catch(e){return!0}},isExported:!0},Ud={description:s("Whether a value is a number."),args:[ba("value (any, lazy)",s("The value to be verified as a number."))],returns:["BOOLEAN"],compute:function(e){try{return"number"==typeof e()}catch(e){return!1}},isExported:!0},Vd={description:s("Whether a value is text."),args:[ba("value (any, lazy)",s("The value to be verified as text."))],returns:["BOOLEAN"],compute:function(e){try{return"string"==typeof e()}catch(e){return!1}},isExported:!0},zd={description:s("Whether the referenced cell is empty"),args:[ba("value (any, lazy)",s("Reference to the cell that will be checked for emptiness."))],returns:["BOOLEAN"],compute:function(e){try{return null===e()}catch(e){return!1}},isExported:!0},Bd={description:s("Returns the error value #N/A."),args:[],returns:["BOOLEAN"],compute:function(e){throw new g},isExported:!0};var Hd=Object.freeze({__proto__:null,ISERR:Fd,ISERROR:Dd,ISLOGICAL:kd,ISNA:Ld,ISNONTEXT:Pd,ISNUMBER:Ud,ISTEXT:Vd,ISBLANK:zd,NA:Bd});const $d={description:s("Logical `and` operator."),args:[ba("logical_expression1 (boolean, range<boolean>)",s("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.")),ba("logical_expression2 (boolean, range<boolean>, repeating)",s("More expressions that represent logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!0;return Jo(e,(e=>(t=!0,i=i&&e,i))),Lo((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0},Wd={description:s("Returns value depending on logical expression."),args:[ba("logical_expression (boolean)",s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")),ba("value_if_true (any, lazy)",s("The value the function returns if logical_expression is TRUE.")),ba("value_if_false (any, lazy, default=FALSE)",s("The value the function returns if logical_expression is FALSE."))],returns:["ANY"],compute:function(e,t,i=(()=>!1)){const o=Wo(e)?t():i();return null==o?"":o},isExported:!0},Gd={description:s("Value if it is not an error, otherwise 2nd argument."),args:[ba("value (any, lazy)",s("The value to return if value itself is not an error.")),ba('value_if_error (any, lazy, default="empty")',s("The value the function returns if value is an error."))],returns:["ANY"],computeFormat:(e,t=(()=>({value:""})))=>{var i;try{return e().format}catch(e){return null===(i=t())||void 0===i?void 0:i.format}},compute:function(e,t=(()=>"")){let i;try{i=e()}catch(e){i=t()}return null==i?"":i},isExported:!0},qd={description:s("Value if it is not an #N/A error, otherwise 2nd argument."),args:[ba("value (any, lazy)",s("The value to return if value itself is not #N/A an error.")),ba('value_if_error (any, lazy, default="empty")',s("The value the function returns if value is an #N/A error."))],returns:["ANY"],compute:function(e,t=(()=>"")){let i;try{i=e()}catch(o){i=o.errorType===a.NotAvailable?t():e()}return null==i?"":i},isExported:!0},Zd={description:s("Returns a value depending on multiple logical expressions."),args:[ba("condition1 (boolean, lazy)",s("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")),ba("value1 (any, lazy)",s("The returned value if condition1 is TRUE.")),ba("condition2 (boolean, lazy, repeating)",s("Additional conditions to be evaluated if the previous ones are FALSE.")),ba("value2 (any, lazy, repeating)",s("Additional values to be returned if their corresponding conditions are TRUE."))],returns:["ANY"],compute:function(...e){Lo((()=>e.length%2==0),s("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(Wo(e[t]())){const i=e[t+1]();return null!==i?i:""}throw new Error(s("No match."))},isExported:!0},jd={description:s("Returns opposite of provided logical value."),args:[ba("logical_expression (boolean)",s("An expression or reference to a cell holding an expression that represents some logical value."))],returns:["BOOLEAN"],compute:function(e){return!Wo(e)},isExported:!0},Yd={description:s("Logical `or` operator."),args:[ba("logical_expression1 (boolean, range<boolean>)",s("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.")),ba("logical_expression2 (boolean, range<boolean>, repeating)",s("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!1;return Jo(e,(e=>(t=!0,i=i||e,!i))),Lo((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0},Xd={description:s("Logical `xor` operator."),args:[ba("logical_expression1 (boolean, range<boolean>)",s("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.")),ba("logical_expression2 (boolean, range<boolean>, repeating)",s("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!1;return Jo(e,(e=>(t=!0,i=i?!e:e,!0))),Lo((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0};var Kd=Object.freeze({__proto__:null,AND:$d,IF:Wd,IFERROR:Gd,IFNA:qd,IFS:Zd,NOT:jd,OR:Yd,XOR:Xd});function Qd(e,t){if(void 0===e)throw new g(s("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",zo(t)))}const Jd={description:s("Column number of a specified cell."),args:[ba("cell_reference (meta, default='this cell')",s("The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered."))],returns:["NUMBER"],compute:function(e){var t;const i=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this));Lo((()=>!!i),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Hi(i).left+1},isExported:!0},eu={description:s("Number of columns in a specified array or range."),args:[ba("range (meta)",s("The range whose column count will be returned."))],returns:["NUMBER"],compute:function(e){const t=Hi(e);return t.right-t.left+1},isExported:!0},tu={description:s("Horizontal lookup"),args:[ba("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),ba("range (range)",s("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")),ba("index (number)",s("The row index of the value to be returned, where the first row in range is numbered 1.")),ba("is_sorted (boolean, default=true)",s("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."))],returns:["ANY"],compute:function(e,t,i,o=true){const n=Math.trunc(Uo(i)),r=Ho(e);Lo((()=>1<=n&&n<=t[0].length),s("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Wo(o)?rn(t,r,"nextSmaller","asc",t.length,sn):an(t,r,"strict",t.length,sn);const l=t[a];return Qd(l,e),l[n-1]},isExported:!0},iu={description:s("Returns the content of a cell, specified by row and column offset."),args:[ba("reference (any, range)",s("The range of cells from which the values are returned.")),ba("row (number)",s("The index of the row to be returned from within the reference range of cells.")),ba("column (number)",s("The index of the column to be returned from within the reference range of cells."))],returns:["ANY"],computeFormat:(e,t,i)=>{var o;const n=Uo(t.value);return null===(o=e[Uo(i.value)-1][n-1])||void 0===o?void 0:o.format},compute:function(e,t,i){const o=(n=e,Array.isArray(n)&&Array.isArray(n[0])?e:[[e]]);var n;const r=Uo(t),a=Uo(i);return Lo((()=>a>=0&&a-1<o.length&&r>=0&&r-1<o[0].length),s("Index out of range.")),Lo((()=>0!==t&&0!==i),s("This function can only return a single cell value, not an array. Provide valid row and column indices.")),o[a-1][r-1]},isExported:!0},ou={description:s("Look up a value."),args:[ba("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),ba("search_array (range)",s("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.")),ba("result_range (range, optional)",s("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."))],returns:["ANY"],compute:function(e,t,i){let o=t.length,n=t[0].length;const r=Ho(e),a=n>=o,l=rn(t,r,"nextSmaller","asc",a?n:o,a?nn:sn);return-1===l&&Qd(void 0,e),Qd(a?t[0][l]:t[l][n-1],e),void 0===i?a?t[o-1][l]:t[l][n-1]:(o=i.length,n=i[0].length,Lo((()=>1===o||1===n),s("The result_range must be a single row or a single column.")),o>1?(Lo((()=>l<=o-1),s("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(l+1).toString())),i[l][0]):(Lo((()=>l<=n-1),s("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(l+1).toString())),i[0][l]))},isExported:!0},nu={description:s("Position of item in range that matches value."),args:[ba("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),ba("range (any, range)",s("The one-dimensional array to be searched.")),ba("search_type (number, default=1)",s("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."))],returns:["NUMBER"],compute:function(e,t,i=1){let o=Uo(i);const n=Ho(e),r=t.length,a=t[0].length;Lo((()=>1===r||1===a),s("The range must be a single row or a single column."));let l=-1;const c=1===r?nn:sn,h=1===r?t[0].length:t.length;switch(o=Math.sign(o),o){case 1:l=rn(t,n,"nextSmaller","asc",h,c);break;case 0:l=an(t,n,"strict",h,c);break;case-1:l=rn(t,n,"nextGreater","desc",h,c)}return Qd(1===r?t[0][l]:t[l],e),l+1},isExported:!0},su={description:s("Row number of a specified cell."),args:[ba("cell_reference (meta, default='this cell')",s("The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered."))],returns:["NUMBER"],compute:function(e){var t;e=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this)),Lo((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Hi(e).top+1},isExported:!0},ru={description:s("Number of rows in a specified array or range."),args:[ba("range (meta)",s("The range whose row count will be returned."))],returns:["NUMBER"],compute:function(e){const t=Hi(e);return t.bottom-t.top+1},isExported:!0},au={description:s("Vertical lookup."),args:[ba("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),ba("range (any, range)",s("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")),ba("index (number)",s("The column index of the value to be returned, where the first column in range is numbered 1.")),ba("is_sorted (boolean, default=true)",s("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."))],returns:["ANY"],compute:function(e,t,i,o=true){const n=Math.trunc(Uo(i)),r=Ho(e);Lo((()=>1<=n&&n<=t.length),s("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Wo(o)?rn(t,r,"nextSmaller","asc",t[0].length,nn):an(t,r,"strict",t[0].length,nn);const l=t[n-1][a];return Qd(l,e),l},isExported:!0},lu={description:s("Search a range for a match and return the corresponding item from a second range."),args:[ba("search_key (any)",s("The value to search for.")),ba("lookup_range (any, range)",s("The range to consider for the search. Should be a single column or a single row.")),ba("return_range (any, range)",s("The range containing the return value. Should have the same dimensions as lookup_range.")),ba("if_not_found (any, lazy, optional)",s("If a valid match is not found, return this value.")),ba("match_mode (any, default=0)",s("(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match.")),ba("search_mode (any, default=1)",s("(1) Search starting at first item. (-1) Search starting at last item. (2) Perform a binary search that relies on lookup_array being sorted in ascending order. If not sorted, invalid results will be returned. (-2) Perform a binary search that relies on lookup_array being sorted in descending order. If not sorted, invalid results will be returned. "))],returns:["ANY"],compute:function(e,t,i,o,n=0,r=1){const a=Math.trunc(Uo(n)),l=Math.trunc(Uo(r)),c=Ho(e);Lo((()=>1===t.length||1===t[0].length),s("lookup_range should be either a single row or single column.")),Lo((()=>1===i.length||1===i[0].length),s("return_range should be either a single row or single column.")),Lo((()=>i.length===t.length&&i[0].length===t[0].length),s("return_range should have the same dimensions as lookup_range.")),Lo((()=>[-1,1,-2,2].includes(l)),s("searchMode should be a value in [-1, 1, -2, 2].")),Lo((()=>[-1,0,1].includes(a)),s("matchMode should be a value in [-1, 0, 1]."));const h=1===t.length?nn:sn,d=1===t.length?t[0].length:t.length,u=0===a?"strict":1===a?"nextGreater":"nextSmaller",g=-1===l;let p;if(2===l||-2===l){p=rn(t,c,u,2===l?"asc":"desc",d,h)}else p=an(t,c,u,d,h,g);if(-1!==p)return 1===t.length?i[0][p]:i[p][0];const m=null==o?void 0:o();return Qd(m,e),m},isExported:!0};var cu=Object.freeze({__proto__:null,COLUMN:Jd,COLUMNS:eu,HLOOKUP:tu,INDEX:iu,LOOKUP:ou,MATCH:nu,ROW:su,ROWS:ru,VLOOKUP:au,XLOOKUP:lu});const hu={description:s("Sum of two numbers."),args:[ba("value1 (number)",s("The first addend.")),ba("value2 (number)",s("The second addend."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Uo(e)+Uo(t)}},du={description:s("Concatenation of two values."),args:[ba("value1 (string)",s("The value to which value2 will be appended.")),ba("value2 (string)",s("The value to append to value1."))],returns:["STRING"],compute:function(e,t){return zo(e)+zo(t)},isExported:!0},uu={description:s("One number divided by another."),args:[ba("dividend (number)",s("The number to be divided.")),ba("divisor (number)",s("The number to divide by."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){const i=Uo(t);return Lo((()=>0!==i),s("The divisor must be different from zero.")),Uo(e)/i}};function gu(e){return null==e}const pu={number:0,string:"",boolean:!1},mu={description:s("Equal."),args:[ba("value1 (any)",s("The first value.")),ba("value2 (any)",s("The value to test against value1 for equality."))],returns:["BOOLEAN"],compute:function(e,t){return e=gu(e)?pu[typeof t]:e,t=gu(t)?pu[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function fu(e,t,i){e=gu(e)?pu[typeof t]:e,t=gu(t)?pu[typeof e]:t,"number"!=typeof e&&(e=zo(e).toUpperCase()),"number"!=typeof t&&(t=zo(t).toUpperCase());const o=typeof e,n=typeof t;return"string"===o&&"number"===n||("string"!==n||"number"!==o)&&i(e,t)}const vu={description:s("Strictly greater than."),args:[ba("value1 (any)",s("The value to test as being greater than value2.")),ba("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return fu(e,t,((e,t)=>e>t))}},bu={description:s("Greater than or equal to."),args:[ba("value1 (any)",s("The value to test as being greater than or equal to value2.")),ba("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return fu(e,t,((e,t)=>e>=t))}},Cu={description:s("Less than."),args:[ba("value1 (any)",s("The value to test as being less than value2.")),ba("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!bu.compute(e,t)}},Su={description:s("Less than or equal to."),args:[ba("value1 (any)",s("The value to test as being less than or equal to value2.")),ba("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!vu.compute(e,t)}},Eu={description:s("Difference of two numbers."),args:[ba("value1 (number)",s("The minuend, or number to be subtracted from.")),ba("value2 (number)",s("The subtrahend, or number to subtract from value1."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Uo(e)-Uo(t)}},wu={description:s("Product of two numbers"),args:[ba("factor1 (number)",s("The first multiplicand.")),ba("factor2 (number)",s("The second multiplicand."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Uo(e)*Uo(t)}},yu={description:s("Not equal."),args:[ba("value1 (any)",s("The first value.")),ba("value2 (any)",s("The value to test against value1 for inequality."))],returns:["BOOLEAN"],compute:function(e,t){return!mu.compute(e,t)}},xu={description:s("A number raised to a power."),args:[ba("base (number)",s("The number to raise to the exponent power.")),ba("exponent (number)",s("The exponent to raise base to."))],returns:["NUMBER"],compute:function(e,t){return rl.compute(e,t)}},Iu={description:s("A number with the sign reversed."),args:[ba("value (number)",s("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],computeFormat:e=>null==e?void 0:e.format,returns:["NUMBER"],compute:function(e){return-Uo(e)}},Ru={description:s("Value interpreted as a percentage."),args:[ba("percentage (number)",s("The value to interpret as a percentage."))],returns:["NUMBER"],compute:function(e){return Uo(e)/100}},Tu={description:s("A specified number, unchanged."),args:[ba("value (any)",s("The number to return."))],returns:["ANY"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){return null===e?"":e}};var Au=Object.freeze({__proto__:null,ADD:hu,CONCAT:du,DIVIDE:uu,EQ:mu,GT:vu,GTE:bu,LT:Cu,LTE:Su,MINUS:Eu,MULTIPLY:wu,NE:yu,POW:xu,UMINUS:Iu,UNARY_PERCENT:Ru,UPLUS:Tu});const Mu=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,Ou={description:s("Gets character associated with number."),args:[ba("table_number (number)",s("The number of the character to look up from the current Unicode table in decimal format."))],returns:["STRING"],compute:function(e){const t=Math.trunc(Uo(e));return Lo((()=>t>=1),s("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},Nu={description:s("Remove non-printable characters from a piece of text."),args:[ba("text (string)",s("The text whose non-printable characters are to be removed."))],returns:["STRING"],compute:function(e){const t=zo(e);let i="";for(const e of t)e&&e.charCodeAt(0)>31&&(i+=e);return i},isExported:!0},_u={description:s("Appends strings to one another."),args:[ba("string1 (string, range<string>)",s("The initial string.")),ba("string2 (string, range<string>, repeating)",s("More strings to append in sequence."))],returns:["STRING"],compute:function(...e){return Xo(e,((e,t)=>e+zo(t)),"")},isExported:!0},Fu={description:s("Tests whether two strings are identical."),args:[ba("string1 (string)",s("The first string to compare.")),ba("string2 (string)",s("The second string to compare."))],returns:["BOOLEAN"],compute:function(e,t){return zo(e)===zo(t)},isExported:!0},Du={description:s("First position of string found in text, case-sensitive."),args:[ba("search_for (string)",s("The string to look for within text_to_search.")),ba("text_to_search (string)",s("The text to search for the first occurrence of search_for.")),ba("starting_at (number, default=1)",s("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,i=1){const o=zo(e),n=zo(t),r=Uo(i);Lo((()=>""!==n),s("The text_to_search must be non-empty.")),Lo((()=>r>=1),s("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=n.indexOf(o,r-1);return Lo((()=>a>=0),s("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o.toString(),n)),a+1},isExported:!0},ku={description:s("Concatenates elements of arrays with delimiter."),args:[ba("delimiter (string)",s("The character or string to place between each concatenated value.")),ba("value_or_array1 (string, range<string>)",s("The value or values to be appended using delimiter.")),ba("value_or_array2 (string, range<string>, repeating)",s("More values to be appended using delimiter."))],returns:["STRING"],compute:function(e,...t){const i=zo(e);return Xo(t,((e,t)=>(e?e+i:"")+zo(t)),"")}},Lu={description:s("Substring from beginning of specified string."),args:[ba("text (string)",s("The string from which the left portion will be returned.")),ba("number_of_characters (number, optional)",s("The number of characters to return from the left side of string."))],returns:["STRING"],compute:function(e,...t){const i=t.length?Uo(t[0]):1;return Lo((()=>i>=0),s("The number_of_characters (%s) must be positive or null.",i.toString())),zo(e).substring(0,i)},isExported:!0},Pu={description:s("Length of a string."),args:[ba("text (string)",s("The string whose length will be returned."))],returns:["NUMBER"],compute:function(e){return zo(e).length},isExported:!0},Uu={description:s("Converts a specified string to lowercase."),args:[ba("text (string)",s("The string to convert to lowercase."))],returns:["STRING"],compute:function(e){return zo(e).toLowerCase()},isExported:!0},Vu={description:s("A segment of a string."),args:[ba("text (string)",s("The string to extract a segment from.")),ba("starting_at (number)",s("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),ba("extract_length (number)",s("The length of the segment to extract."))],returns:["STRING"],compute:function(e,t,i){const o=zo(e),n=Uo(t),r=Uo(i);return Lo((()=>n>=1),s("The starting_at argument (%s) must be positive greater than one.",n.toString())),Lo((()=>r>=0),s("The extract_length argument (%s) must be positive or null.",r.toString())),o.slice(n-1,n+r-1)},isExported:!0},zu={description:s("Capitalizes each word in a specified string."),args:[ba("text_to_capitalize (string)",s("The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase."))],returns:["STRING"],compute:function(e){return zo(e).replace(Mu,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},Bu={description:s("Replaces part of a text string with different text."),args:[ba("text (string)",s("The text, a part of which will be replaced.")),ba("position (number)",s("The position where the replacement will begin (starting from 1).")),ba("length (number)",s("The number of characters in the text to be replaced.")),ba("new_text (string)",s("The text which will be inserted into the original text."))],returns:["STRING"],compute:function(e,t,i,o){const n=Uo(t);Lo((()=>n>=1),s("The position (%s) must be greater than or equal to 1.",n.toString()));const r=zo(e),a=Uo(i),l=zo(o);return r.substring(0,n-1)+l+r.substring(n-1+a)},isExported:!0},Hu={description:s("A substring from the end of a specified string."),args:[ba("text (string)",s("The string from which the right portion will be returned.")),ba("number_of_characters (number, optional)",s("The number of characters to return from the right side of string."))],returns:["STRING"],compute:function(e,...t){const i=t.length?Uo(t[0]):1;Lo((()=>i>=0),s("The number_of_characters (%s) must be positive or null.",i.toString()));const o=zo(e),n=o.length;return o.substring(n-i,n)},isExported:!0},$u={description:s("First position of string found in text, ignoring case."),args:[ba("search_for (string)",s("The string to look for within text_to_search.")),ba("text_to_search (string)",s("The text to search for the first occurrence of search_for.")),ba("starting_at (number, default=1)",s("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,i=1){const o=zo(e).toLowerCase(),n=zo(t).toLowerCase(),r=Uo(i);Lo((()=>""!==n),s("The text_to_search must be non-empty.")),Lo((()=>r>=1),s("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=n.indexOf(o,r-1);return Lo((()=>a>=0),s("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,n)),a+1},isExported:!0},Wu={description:s("Replaces existing text with new text in a string."),args:[ba("text_to_search (string)",s("The text within which to search and replace.")),ba("search_for (string)",s("The string to search for within text_to_search.")),ba("replace_with (string)",s("The string that will replace search_for.")),ba("occurrence_number (number, optional)",s("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."))],returns:["NUMBER"],compute:function(e,t,i,o){const n=Uo(o);Lo((()=>n>=0),s("The occurrenceNumber (%s) must be positive or null.",n.toString()));const r=zo(e),a=zo(t);if(""===a)return r;const l=zo(i),c=new RegExp(_e(a),"g");if(0===n)return r.replace(c,l);let h=0;return r.replace(c,(e=>++h===n?l:e))},isExported:!0},Gu={description:s("Combines text from multiple strings and/or arrays."),args:[ba("delimiter (string)",s(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")),ba("ignore_empty (boolean)",s("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")),ba("text1 (string, range<string>)",s("Any text item. This could be a string, or an array of strings in a range.")),ba("text2 (string, range<string>, repeating)",s("Additional text item(s)."))],returns:["STRING"],compute:function(e,t,...i){const o=zo(e),n=Wo(t);let s=0;return Xo(i,((e,t)=>n&&""===zo(t)?e:(s++?e+o:"")+zo(t)),"")},isExported:!0},qu={description:s("Removes space characters."),args:[ba("text (string)",s("The text or reference to a cell containing text to be trimmed."))],returns:["STRING"],compute:function(e){return zo(e).trim()},isExported:!0},Zu={description:s("Converts a specified string to uppercase."),args:[ba("text (string)",s("The string to convert to uppercase."))],returns:["STRING"],compute:function(e){return zo(e).toUpperCase()},isExported:!0},ju={description:s("Converts a number to text according to a specified format."),args:[ba("number (number)",s("The number, date or time to format.")),ba("format (string)",s("The pattern by which to format the number, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){return fi(Uo(e),zo(t))},isExported:!0};var Yu=Object.freeze({__proto__:null,CHAR:Ou,CLEAN:Nu,CONCATENATE:_u,EXACT:Fu,FIND:Du,JOIN:ku,LEFT:Lu,LEN:Pu,LOWER:Uu,MID:Vu,PROPER:zu,REPLACE:Bu,RIGHT:Hu,SEARCH:$u,SUBSTITUTE:Wu,TEXTJOIN:Gu,TRIM:qu,UPPER:Zu,TEXT:ju});const Xu={description:s("Creates a hyperlink in a cell."),args:[ba("url (string)",s("The full URL of the link enclosed in quotation marks.")),ba("link_label (string, optional)",s("The text to display in the cell, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){const i=zo(e).trim(),o=zo(t)||i;return""===i?o:Ke(o,i)},isExported:!0};var Ku=Object.freeze({__proto__:null,HYPERLINK:Xu});const Qu=[{name:s("Database"),functions:Mc},{name:s("Date"),functions:lh},{name:s("Financial"),functions:_d},{name:s("Info"),functions:Hd},{name:s("Lookup"),functions:cu},{name:s("Logical"),functions:Kd},{name:s("Math"),functions:xl},{name:s("Misc"),functions:Ea},{name:s("Operator"),functions:Au},{name:s("Statistical"),functions:pc},{name:s("Text"),functions:Yu},{name:s("Engineering"),functions:hh},{name:s("Web"),functions:Ku}],Ju=/^[A-Z0-9\_\.]+$/;function eg(e){return e.map((e=>{if(void 0!==e)return"function"==typeof e?()=>tg(e()):tg(e)}))}function tg(e){return Array.isArray(e)?e.map((e=>e.map((e=>null==e?void 0:e.value)))):null==e?void 0:e.value}const ig=new class extends Ro{constructor(){super(...arguments),this.mapping={}}add(e,t){if(!(e=e.toUpperCase()).match(Ju))throw new Error(s("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const i=Ca(t);return function(e){let t=!1,i=!1,o=!1;for(let n of e){if(n.type.includes("META")&&n.type.length>1)throw new Error(s("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&&!n.repeating)throw new Error(s("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=i||t||o,r=!(n.optional||n.repeating||n.default);if(e&&r)throw new Error(s("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=n.repeating,i=n.optional,o=n.default}}(i.args),this.mapping[e]=function(...e){const t=i.compute.bind(this),o=i.computeFormat?i.computeFormat.bind(this):()=>{};return{value:t(...eg(e)),format:o(...e)}},super.add(e,i),this}};for(let e of Qu){const t=e.functions;for(let i in t){const o=t[i];o.category=o.category||e.name,i=i.replace(/_/g,"."),ig.add(i,{isExported:!1,...o})}}function og(e,t,i){const o=e.model.getters.getActiveSheetId(),n="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(n,{sheetId:o,quantity:i}).isCancelledBecause(66)&&e.raiseError(Ps)}const ng=new ls;ng.add("file",{name:s("File"),sequence:10}).add("edit",{name:s("Edit"),sequence:20}).add("view",{name:s("View"),sequence:30}).add("insert",{name:s("Insert"),sequence:40}).add("format",{name:s("Format"),sequence:50}).add("data",{name:s("Data"),sequence:60}).addChild("save",["file"],{name:s("Save"),description:"Ctrl+S",sequence:10,action:()=>console.log("Not implemented")}).addChild("undo",["edit"],{name:s("Undo"),description:"Ctrl+Z",sequence:10,action:e=>e.model.dispatch("REQUEST_UNDO")}).addChild("redo",["edit"],{name:s("Redo"),description:"Ctrl+Y",sequence:20,action:e=>e.model.dispatch("REQUEST_REDO"),separator:!0}).addChild("copy",["edit"],{name:s("Copy"),description:"Ctrl+C",sequence:30,isReadonlyAllowed:!0,action:Br}).addChild("cut",["edit"],{name:s("Cut"),description:"Ctrl+X",sequence:40,action:Hr}).addChild("paste",["edit"],{name:s("Paste"),description:"Ctrl+V",sequence:50,action:$r}).addChild("paste_special",["edit"],{name:s("Paste special"),sequence:60,separator:!0,isVisible:Zr}).addChild("paste_special_value",["edit","paste_special"],{name:s("Paste value only"),sequence:10,action:Wr}).addChild("paste_special_format",["edit","paste_special"],{name:s("Paste format only"),sequence:20,action:qr}).addChild("sort_range",["data"],{name:s("Sort range"),sequence:20,isVisible:ua,separator:!0}).addChild("sort_ascending",["data","sort_range"],{name:s("Ascending (A ⟶ Z)"),sequence:10,action:ha}).addChild("sort_descending",["data","sort_range"],{name:s("Descending (Z ⟶ A)"),sequence:20,action:da}).addChild("find_and_replace",["edit"],{name:s("Find and replace"),description:"Ctrl+H",sequence:65,isReadonlyAllowed:!0,action:e=>{e.openSidePanel("FindAndReplace",{})},separator:!0}).addChild("edit_delete_cell_values",["edit"],{name:s("Delete values"),sequence:70,action:e=>e.model.dispatch("DELETE_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})}).addChild("edit_delete_row",["edit"],{name:jr,sequence:80,action:Yr,isVisible:e=>Xr("ROW",e)}).addChild("edit_delete_column",["edit"],{name:Kr,sequence:90,action:Qr,isVisible:e=>Xr("COL",e)}).addChild("edit_delete_cell_shift_up",["edit"],{name:s("Delete cell and shift up"),sequence:93,action:ta}).addChild("edit_delete_cell_shift_left",["edit"],{name:s("Delete cell and shift left"),sequence:97,action:ia}).addChild("edit_unhide_columns",["edit"],{name:s("Unhide all columns"),sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"COL",elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0}).addChild("edit_unhide_rows",["edit"],{name:s("Unhide all rows"),sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"ROW",elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0}).addChild("insert_row_before",["insert"],{name:e=>{const t=Ur(e);return 1===t?s("Row above"):s("%s Rows above",t.toString())},sequence:10,action:oa,isVisible:e=>0===e.model.getters.getActiveCols().size}).addChild("insert_row_after",["insert"],{name:e=>{const t=Ur(e);return 1===t?s("Row below"):s("%s Rows below",t.toString())},sequence:20,action:na,isVisible:e=>0===e.model.getters.getActiveCols().size,separator:!0}).addChild("insert_column_before",["insert"],{name:e=>{const t=Pr(e);return 1===t?s("Column left"):s("%s Columns left",t.toString())},sequence:30,action:sa,isVisible:e=>0===e.model.getters.getActiveRows().size}).addChild("insert_column_after",["insert"],{name:e=>{const t=Pr(e);return 1===t?s("Column right"):s("%s Columns right",t.toString())},sequence:40,action:ra,isVisible:e=>0===e.model.getters.getActiveRows().size,separator:!0}).addChild("insert_insert_cell_shift_down",["insert"],{name:s("Insert cells and shift down"),sequence:43,action:Jr}).addChild("insert_insert_cell_shift_right",["insert"],{name:s("Insert cells and shift right"),sequence:47,action:ea,separator:!0}).addChild("insert_chart",["insert"],{name:s("Chart"),sequence:50,action:e=>{const t=e.model.getters,i=e.model.uuidGenerator.uuidv4(),o=t.getActiveSheetId();1===uo(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection();const n={width:536,height:335},s=function(e,t){const{x:i,y:o}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:s}=e.getActiveSheetScrollInfo(),{width:r,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:i+n+Math.max(0,(r-t.width)/2),y:o+s+Math.max(0,(a-t.height)/2)}}(t,n);e.model.dispatch("CREATE_CHART",{sheetId:o,id:i,position:s,size:n,definition:Tr(e.model.getters.getSelectedZone(),e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{id:i}),e.openSidePanel("ChartPanel"))}}).addChild("insert_image",["insert"],{name:s("Image"),sequence:55,action:async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),i=e.model.uuidGenerator.uuidv4(),o=await async function(e){try{return await e.imageProvider.requestImage()}catch{return void e.raiseError(s("An unexpected error occurred during the image transfer"))}}(e);if(!o)throw new Error("No image provider was given to the environment");const n=Cr(e.model.getters,o.size),r=function(e,t){const{x:i,y:o}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:s}=e.getActiveSheetScrollInfo(),r=e.getSheetViewDimension(),a=e.getVisibleRect(e.getActiveMainViewport()),l=Math.min(a.width,r.width-i),c=Math.min(a.height,r.height-o);return{x:i+n+Math.max(0,(l-t.width)/2),y:o+s+Math.max(0,(c-t.height)/2)}}(e.model.getters,n);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:i,position:r,size:n,definition:o})}},isVisible:e=>void 0!==e.imageProvider}).addChild("insert_function",["insert"],{name:s("Function"),sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{name:s("SUM"),action:e=>e.startCellEdition("=SUM("),sequence:0}).addChild("insert_function_average",["insert","insert_function"],{name:s("AVERAGE"),action:e=>e.startCellEdition("=AVERAGE("),sequence:10}).addChild("insert_function_count",["insert","insert_function"],{name:s("COUNT"),action:e=>e.startCellEdition("=COUNT("),sequence:20}).addChild("insert_function_max",["insert","insert_function"],{name:s("MAX"),action:e=>e.startCellEdition("=MAX("),sequence:30}).addChild("insert_function_min",["insert","insert_function"],{name:s("MIN"),action:e=>e.startCellEdition("=MIN("),sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{name:s("All"),sequence:50}).addChild("all_function_list",["insert","insert_function","categorie_function_all"],(()=>sg(ig.getKeys()))).addChild("categories_function_list",["insert","insert_function"],(()=>{const e=ig.content;return[...new Set(ig.getAll().map((e=>e.category)))].filter(ot).sort().map(((t,i)=>{const o=Object.keys(e).filter((i=>e[i].category===t));return{name:t,sequence:60+10*i,children:sg(o)}}))})).addChild("insert_link",["insert"],{name:s("Link"),separator:!0,sequence:70,action:la}).addChild("insert_sheet",["insert"],{name:s("New sheet"),sequence:80,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSheetIds().indexOf(t)+1,o=e.model.uuidGenerator.uuidv4();e.model.dispatch("CREATE_SHEET",{sheetId:o,position:i}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},separator:!0}).addChild("unfreeze_panes",["view"],{name:s("Unfreeze"),sequence:4,isVisible:e=>{const{xSplit:t,ySplit:i}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+i>0},action:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()})}).addChild("freeze_panes",["view"],{name:s("Freeze"),sequence:5,separator:!0}).addChild("unfreeze_rows",["view","freeze_panes"],{name:s("No rows"),action:e=>e.model.dispatch("UNFREEZE_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,sequence:5,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit}).addChild("freeze_first_row",["view","freeze_panes"],{name:s("1 row"),action:e=>og(e,"ROW",1),isReadonlyAllowed:!0,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{name:s("2 rows"),action:e=>og(e,"ROW",2),isReadonlyAllowed:!0,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{name:s("Up to current row"),action:e=>{const{bottom:t}=e.model.getters.getSelectedZone();og(e,"ROW",t+1)},isReadonlyAllowed:!0,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{name:s("No columns"),action:e=>e.model.dispatch("UNFREEZE_COLUMNS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,sequence:25,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit}).addChild("freeze_first_col",["view","freeze_panes"],{name:s("1 column"),action:e=>og(e,"COL",1),isReadonlyAllowed:!0,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{name:s("2 columns"),action:e=>og(e,"COL",2),isReadonlyAllowed:!0,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{name:s("Up to current column"),action:e=>{const{right:t}=e.model.getters.getSelectedZone();og(e,"COL",t+1)},isReadonlyAllowed:!0,sequence:40}).addChild("view_gridlines",["view"],{name:e=>e.model.getters.getGridLinesVisibility(e.model.getters.getActiveSheetId())?s("Hide gridlines"):s("Show gridlines"),action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},sequence:10}).addChild("view_formulas",["view"],{name:e=>e.model.getters.shouldShowFormulas()?s("Hide formulas"):s("Show formulas"),action:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,sequence:15}).addChild("format_number",["format"],{name:s("Numbers"),sequence:10,separator:!0}).addChild("format_number_automatic",["format","format_number"],{name:ks.Automatic,sequence:10,separator:!0,action:e=>Vr(e,"")}).addChild("format_number_number",["format","format_number"],{name:ks.Number,description:"1,000.12",sequence:20,action:e=>Vr(e,"#,##0.00")}).addChild("format_number_percent",["format","format_number"],{name:ks.Percent,description:"10.12%",sequence:30,separator:!0,action:e=>Vr(e,"0.00%")}).addChild("format_number_currency",["format","format_number"],{name:ks.Currency,description:"$1,000.12",sequence:37,action:e=>Vr(e,"[$$]#,##0.00")}).addChild("format_number_currency_rounded",["format","format_number"],{name:ks.CurrencyRounded,description:"$1,000",sequence:38,action:e=>Vr(e,"[$$]#,##0")}).addChild("format_custom_currency",["format","format_number"],{name:ks.CustomCurrency,sequence:39,separator:!0,isVisible:e=>void 0!==e.loadCurrencies,action:e=>{e.openSidePanel("CustomCurrency",{})}}).addChild("format_number_date",["format","format_number"],{name:ks.Date,description:"9/26/2008",sequence:40,action:e=>Vr(e,"m/d/yyyy")}).addChild("format_number_time",["format","format_number"],{name:ks.Time,description:"10:43:00 PM",sequence:50,action:e=>Vr(e,"hh:mm:ss a")}).addChild("format_number_date_time",["format","format_number"],{name:ks.DateTime,description:"9/26/2008 22:43:00",sequence:60,action:e=>Vr(e,"m/d/yyyy hh:mm:ss")}).addChild("format_number_duration",["format","format_number"],{name:ks.Duration,description:"27:51:38",sequence:70,separator:!0,action:e=>Vr(e,"hhhh:mm:ss")}).addChild("format_bold",["format"],{name:s("Bold"),sequence:20,description:"Ctrl+B",action:e=>zr(e,{bold:!e.model.getters.getCurrentStyle().bold})}).addChild("format_italic",["format"],{name:s("Italic"),sequence:30,description:"Ctrl+I",action:e=>zr(e,{italic:!e.model.getters.getCurrentStyle().italic})}).addChild("format_underline",["format"],{name:s("Underline"),description:"Ctrl+U",sequence:40,action:e=>zr(e,{underline:!e.model.getters.getCurrentStyle().underline})}).addChild("format_strikethrough",["format"],{name:s("Strikethrough"),sequence:50,action:e=>zr(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),separator:!0}).addChild("format_font_size",["format"],{name:s("Font size"),sequence:60,separator:!0}).addChild("format_alignment",["format"],{name:s("Alignment"),sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{name:"Left",sequence:10,action:e=>zr(e,{align:"left"})}).addChild("format_alignment_center",["format","format_alignment"],{name:"Center",sequence:20,action:e=>zr(e,{align:"center"})}).addChild("format_alignment_right",["format","format_alignment"],{name:"Right",sequence:30,action:e=>zr(e,{align:"right"}),separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{name:"Top",sequence:40,action:e=>zr(e,{verticalAlign:"top"})}).addChild("format_alignment_middle",["format","format_alignment"],{name:"Middle",sequence:50,action:e=>zr(e,{verticalAlign:"middle"})}).addChild("format_alignment_bottom",["format","format_alignment"],{name:"Bottom",sequence:60,action:e=>zr(e,{verticalAlign:"bottom"}),separator:!0}).addChild("format_wrapping",["format"],{name:s("Wrapping"),sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{name:s("Overflow"),sequence:10,action:e=>zr(e,{wrapping:"overflow"})}).addChild("format_wrapping_wrap",["format","format_wrapping"],{name:s("Wrap"),sequence:20,action:e=>zr(e,{wrapping:"wrap"})}).addChild("format_wrapping_clip",["format","format_wrapping"],{name:s("Clip"),sequence:30,action:e=>zr(e,{wrapping:"clip"})}).addChild("format_cf",["format"],{name:s("Conditional formatting"),sequence:90,action:aa,separator:!0}).addChild("format_clearFormat",["format"],{name:s("Clear formatting"),sequence:100,action:e=>{e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},separator:!0}).addChild("add_data_filter",["data"],{name:s("Create filter"),sequence:10,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSelection().zones;_r(e,t,i)},isVisible:e=>!ca(e),isEnabled:e=>(e=>go(...e.model.getters.getSelectedZones()))(e)}).addChild("remove_data_filter",["data"],{name:s("Remove filter"),sequence:10,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:t,target:e.model.getters.getSelectedZones()})},isVisible:ca});for(let e of de)ng.addChild(`format_font_size_${e}`,["format","format_font_size"],{name:e.toString(),sequence:e,action:t=>zr(t,{fontSize:e})});function sg(e){return e.sort().map(((e,t)=>({name:e,sequence:10*t,action:t=>t.startCellEdition(`=${e}(`)})))}const rg=new class extends Ro{addTransformation(e,t,i){for(let o of t)this.content[o]||(this.content[o]=new Map),this.content[o].set(e,i);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},ag={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function lg(e,t){const i=ag[e.key];e.shiftKey?t.resizeAnchorZone(i,Zn(e)?"end":1):t.moveAnchorCell(i,Zn(e)?"end":1)}const cg=new zi;vo`
351
351
  .o-selection {
352
352
  .o-selection-input {
353
353
  display: flex;
@@ -397,7 +397,7 @@
397
397
  font-size: calc(100% + 4px);
398
398
  }
399
399
  }
400
- `;class hg extends t.Component{constructor(){super(...arguments),this.id=cg.uuidv4(),this.previousRanges=this.props.ranges||[],this.originSheet=this.env.model.getters.getActiveSheetId(),this.state=t.useState({isMissing:!1,mode:"select-range"}),this.focusedInput=t.useRef("focusedInput")}get ranges(){const e=this.env.model.getters.getSelectionInput(this.id);return(e.length?e:this.props.ranges?this.props.ranges.map(((e,t)=>({xc:e,id:t,isFocused:!1}))):[]).map((e=>({...e,isValidRange:""===e.xc||this.env.model.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}setup(){t.useEffect((()=>{var e;return null===(e=this.focusedInput.el)||void 0===e?void 0:e.focus()}),(()=>[this.focusedInput.el])),t.onMounted((()=>this.enableNewSelectionInput())),t.onWillUnmount((async()=>this.disableNewSelectionInput())),t.onPatched((()=>this.checkChange()))}enableNewSelectionInput(){this.env.model.dispatch("ENABLE_NEW_SELECTION_INPUT",{id:this.id,initialRanges:this.props.ranges,hasSingleRange:this.props.hasSingleRange})}disableNewSelectionInput(){this.env.model.dispatch("DISABLE_SELECTION_INPUT",{id:this.id})}checkChange(){const e=this.env.model.getters.getSelectionInputValue(this.id);this.previousRanges.join()!==e.join()&&this.triggerChange()}getColor(e){return"color: "+(e.color||"#000")+";"}triggerChange(){var e,t;const i=this.env.model.getters.getSelectionInputValue(this.id);null===(t=(e=this.props).onSelectionChanged)||void 0===t||t.call(e,i),this.previousRanges=i}onKeydown(e){if("F2"===e.key)e.preventDefault(),e.stopPropagation(),this.state.mode="select-range"===this.state.mode?"text-edit":"select-range";else if(e.key.startsWith("Arrow"))e.stopPropagation(),"select-range"===this.state.mode&&(e.preventDefault(),lg(e,this.env.model.selection));else if("Enter"===e.key){e.target.blur(),this.confirm()}}extractRanges(e){return this.props.hasSingleRange?e.split(",")[0]:e}focus(e){this.state.isMissing=!1,this.state.mode="select-range",this.env.model.dispatch("FOCUS_RANGE",{id:this.id,rangeId:e})}addEmptyInput(){this.env.model.dispatch("ADD_EMPTY_RANGE",{id:this.id})}removeInput(e){var t,i;this.env.model.dispatch("REMOVE_RANGE",{id:this.id,rangeId:e}),this.triggerChange(),null===(i=(t=this.props).onSelectionConfirmed)||void 0===i||i.call(t)}onInputChanged(e,t){const i=t.target,o=this.extractRanges(i.value);this.env.model.dispatch("CHANGE_RANGE",{id:this.id,rangeId:e,value:o}),this.triggerChange()}confirm(){var e,t;this.env.model.dispatch("UNFOCUS_SELECTION_INPUT");const i=this.env.model.getters.getSelectionInputValue(this.id);this.props.required&&0===i.length&&(this.state.isMissing=!0);const o=this.env.model.getters.getActiveSheetId();this.originSheet!==o&&this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:o,sheetIdTo:this.originSheet}),null===(t=(e=this.props).onSelectionConfirmed)||void 0===t||t.call(e)}}hg.template="o-spreadsheet-SelectionInput",hg.props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},required:{type:Boolean,optional:!0},isInvalid:{type:Boolean,optional:!0},class:{type:String,optional:!0},onSelectionChanged:{type:Function,optional:!0},onSelectionConfirmed:{type:Function,optional:!0}};class dg extends t.Component{constructor(){super(...arguments),this.state=t.useState({datasetDispatchResult:void 0,labelsDispatchResult:void 0}),this.dataSeriesRanges=[]}setup(){this.dataSeriesRanges=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange}get errorMessages(){var e,t;return[...(null===(e=this.state.datasetDispatchResult)||void 0===e?void 0:e.reasons)||[],...(null===(t=this.state.labelsDispatchResult)||void 0===t?void 0:t.reasons)||[]].map((e=>Ds.Errors[e]||Ds.Errors.Unexpected))}get isDatasetInvalid(){var e;return!!(null===(e=this.state.datasetDispatchResult)||void 0===e?void 0:e.isCancelledBecause(32))}get isLabelInvalid(){var e;return!!(null===(e=this.state.labelsDispatchResult)||void 0===e?void 0:e.isCancelledBecause(33))}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.figureId,{dataSetsHaveTitle:e.target.checked})}onDataSeriesRangesChanged(e){this.dataSeriesRanges=e}onDataSeriesConfirmed(){this.state.datasetDispatchResult=this.props.updateChart(this.props.figureId,{dataSets:this.dataSeriesRanges})}onLabelRangeChanged(e){this.labelRange=e[0]}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.figureId,{labelRange:this.labelRange})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}}dg.template="o-spreadsheet-LineBarPieConfigPanel",dg.components={SelectionInput:hg},dg.props={figureId:String,definition:Object,updateChart:Function};class ug extends dg{onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}}ug.template="o-spreadsheet-BarConfigPanel";const gg=218,pg=182;function mg(e){return Tt(Mt({h:360*e.offsetX/gg,s:100,l:100*e.offsetY/pg,a:1}))}vo`
400
+ `;class hg extends t.Component{constructor(){super(...arguments),this.id=cg.uuidv4(),this.previousRanges=this.props.ranges||[],this.originSheet=this.env.model.getters.getActiveSheetId(),this.state=t.useState({isMissing:!1,mode:"select-range"}),this.focusedInput=t.useRef("focusedInput")}get ranges(){const e=this.env.model.getters.getSelectionInput(this.id);return(e.length?e:this.props.ranges?this.props.ranges.map(((e,t)=>({xc:e,id:t,isFocused:!1}))):[]).map((e=>({...e,isValidRange:""===e.xc||this.env.model.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}setup(){t.useEffect((()=>{var e;return null===(e=this.focusedInput.el)||void 0===e?void 0:e.focus()}),(()=>[this.focusedInput.el])),t.onMounted((()=>this.enableNewSelectionInput())),t.onWillUnmount((async()=>this.disableNewSelectionInput())),t.onPatched((()=>this.checkChange()))}enableNewSelectionInput(){this.env.model.dispatch("ENABLE_NEW_SELECTION_INPUT",{id:this.id,initialRanges:this.props.ranges,hasSingleRange:this.props.hasSingleRange})}disableNewSelectionInput(){this.env.model.dispatch("DISABLE_SELECTION_INPUT",{id:this.id})}checkChange(){const e=this.env.model.getters.getSelectionInputValue(this.id);this.previousRanges.join()!==e.join()&&this.triggerChange()}getColor(e){return"color: "+(e.color||"#000")+";"}triggerChange(){var e,t;const i=this.env.model.getters.getSelectionInputValue(this.id);null===(t=(e=this.props).onSelectionChanged)||void 0===t||t.call(e,i),this.previousRanges=i}onKeydown(e){if("F2"===e.key)e.preventDefault(),e.stopPropagation(),this.state.mode="select-range"===this.state.mode?"text-edit":"select-range";else if(e.key.startsWith("Arrow"))e.stopPropagation(),"select-range"===this.state.mode&&(e.preventDefault(),lg(e,this.env.model.selection));else if("Enter"===e.key){e.target.blur(),this.confirm()}}extractRanges(e){return this.props.hasSingleRange?e.split(",")[0]:e}focus(e){this.state.isMissing=!1,this.state.mode="select-range",this.env.model.dispatch("FOCUS_RANGE",{id:this.id,rangeId:e})}addEmptyInput(){this.env.model.dispatch("ADD_EMPTY_RANGE",{id:this.id})}removeInput(e){var t,i;this.env.model.dispatch("REMOVE_RANGE",{id:this.id,rangeId:e}),this.triggerChange(),null===(i=(t=this.props).onSelectionConfirmed)||void 0===i||i.call(t)}onInputChanged(e,t){const i=t.target,o=this.extractRanges(i.value);this.env.model.dispatch("CHANGE_RANGE",{id:this.id,rangeId:e,value:o}),this.triggerChange()}confirm(){var e,t;this.env.model.dispatch("UNFOCUS_SELECTION_INPUT");const i=this.env.model.getters.getSelectionInputValue(this.id);this.props.required&&0===i.length&&(this.state.isMissing=!0);const o=this.env.model.getters.getActiveSheetId();this.originSheet!==o&&this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:o,sheetIdTo:this.originSheet}),null===(t=(e=this.props).onSelectionConfirmed)||void 0===t||t.call(e)}}hg.template="o-spreadsheet-SelectionInput",hg.props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},required:{type:Boolean,optional:!0},isInvalid:{type:Boolean,optional:!0},class:{type:String,optional:!0},onSelectionChanged:{type:Function,optional:!0},onSelectionConfirmed:{type:Function,optional:!0}};class dg extends t.Component{constructor(){super(...arguments),this.state=t.useState({datasetDispatchResult:void 0,labelsDispatchResult:void 0}),this.dataSeriesRanges=[]}setup(){this.dataSeriesRanges=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange}get errorMessages(){var e,t;return[...(null===(e=this.state.datasetDispatchResult)||void 0===e?void 0:e.reasons)||[],...(null===(t=this.state.labelsDispatchResult)||void 0===t?void 0:t.reasons)||[]].map((e=>Ds.Errors[e]||Ds.Errors.Unexpected))}get isDatasetInvalid(){var e;return!!(null===(e=this.state.datasetDispatchResult)||void 0===e?void 0:e.isCancelledBecause(33))}get isLabelInvalid(){var e;return!!(null===(e=this.state.labelsDispatchResult)||void 0===e?void 0:e.isCancelledBecause(34))}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.figureId,{dataSetsHaveTitle:e.target.checked})}onDataSeriesRangesChanged(e){this.dataSeriesRanges=e}onDataSeriesConfirmed(){this.state.datasetDispatchResult=this.props.updateChart(this.props.figureId,{dataSets:this.dataSeriesRanges})}onLabelRangeChanged(e){this.labelRange=e[0]}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.figureId,{labelRange:this.labelRange})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}}dg.template="o-spreadsheet-LineBarPieConfigPanel",dg.components={SelectionInput:hg},dg.props={figureId:String,definition:Object,updateChart:Function};class ug extends dg{onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}}ug.template="o-spreadsheet-BarConfigPanel";const gg=218,pg=182;function mg(e){return Tt(Mt({h:360*e.offsetX/gg,s:100,l:100*e.offsetY/pg,a:1}))}vo`
401
401
  .o-color-picker {
402
402
  padding: ${6}px 0px;
403
403
  box-shadow: 1px 2px 5px 2px rgba(51, 51, 51, 0.15);
@@ -565,7 +565,7 @@
565
565
  }
566
566
  }
567
567
  }
568
- `;class vg extends t.Component{constructor(){super(...arguments),this.colorPickerButtonRef=t.useRef("colorPickerButton")}get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:"border-bottom-style: hidden"}get colorPickerAnchorRect(){const e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}}vg.template="o-spreadsheet-ColorPickerWidget",vg.components={ColorPicker:fg},vg.props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};class bg extends t.Component{constructor(){super(...arguments),this.state=t.useState({fillColorTool:!1})}onClick(e){this.state.fillColorTool=!1}setup(){t.useExternalListener(window,"click",this.onClick)}toggleColorPicker(){this.state.fillColorTool=!this.state.fillColorTool}updateBackgroundColor(e){this.props.updateChart(this.props.figureId,{background:e})}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}updateSelect(e,t){this.props.updateChart(this.props.figureId,{[e]:t.target.value})}}bg.template="o-spreadsheet-LineBarPieDesignPanel",bg.components={ColorPickerWidget:vg},bg.props={figureId:String,definition:Object,updateChart:Function};class Cg extends bg{}Cg.template="o-spreadsheet-BarChartDesignPanel";class Sg extends t.Component{constructor(){super(...arguments),this.state=t.useState({dataRangeDispatchResult:void 0}),this.dataRange=this.props.definition.dataRange}get configurationErrorMessages(){var e;return[...(null===(e=this.state.dataRangeDispatchResult)||void 0===e?void 0:e.reasons)||[]].map((e=>Ds.Errors[e]||Ds.Errors.Unexpected))}get isDataRangeInvalid(){var e;return!!(null===(e=this.state.dataRangeDispatchResult)||void 0===e?void 0:e.isCancelledBecause(36))}onDataRangeChanged(e){this.dataRange=e[0]}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.figureId,{dataRange:this.dataRange})}}Sg.template="o-spreadsheet-GaugeChartConfigPanel",Sg.components={SelectionInput:hg},Sg.props={figureId:String,definition:Object,updateChart:Function},vo`
568
+ `;class vg extends t.Component{constructor(){super(...arguments),this.colorPickerButtonRef=t.useRef("colorPickerButton")}get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:"border-bottom-style: hidden"}get colorPickerAnchorRect(){const e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}}vg.template="o-spreadsheet-ColorPickerWidget",vg.components={ColorPicker:fg},vg.props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};class bg extends t.Component{constructor(){super(...arguments),this.state=t.useState({fillColorTool:!1})}onClick(e){this.state.fillColorTool=!1}setup(){t.useExternalListener(window,"click",this.onClick)}toggleColorPicker(){this.state.fillColorTool=!this.state.fillColorTool}updateBackgroundColor(e){this.props.updateChart(this.props.figureId,{background:e})}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}updateSelect(e,t){this.props.updateChart(this.props.figureId,{[e]:t.target.value})}}bg.template="o-spreadsheet-LineBarPieDesignPanel",bg.components={ColorPickerWidget:vg},bg.props={figureId:String,definition:Object,updateChart:Function};class Cg extends bg{}Cg.template="o-spreadsheet-BarChartDesignPanel";class Sg extends t.Component{constructor(){super(...arguments),this.state=t.useState({dataRangeDispatchResult:void 0}),this.dataRange=this.props.definition.dataRange}get configurationErrorMessages(){var e;return[...(null===(e=this.state.dataRangeDispatchResult)||void 0===e?void 0:e.reasons)||[]].map((e=>Ds.Errors[e]||Ds.Errors.Unexpected))}get isDataRangeInvalid(){var e;return!!(null===(e=this.state.dataRangeDispatchResult)||void 0===e?void 0:e.isCancelledBecause(37))}onDataRangeChanged(e){this.dataRange=e[0]}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.figureId,{dataRange:this.dataRange})}}Sg.template="o-spreadsheet-GaugeChartConfigPanel",Sg.components={SelectionInput:hg},Sg.props={figureId:String,definition:Object,updateChart:Function},vo`
569
569
  .o-gauge-color-set {
570
570
  table {
571
571
  table-layout: fixed;
@@ -595,7 +595,7 @@
595
595
  box-sizing: border-box;
596
596
  }
597
597
  }
598
- `;class Eg extends t.Component{constructor(){super(...arguments),this.state=t.useState({openedMenu:void 0,sectionRuleDispatchResult:void 0})}setup(){t.useExternalListener(window,"click",this.closeMenus)}get designErrorMessages(){var e;return[...(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.reasons)||[]].map((e=>Ds.Errors[e]||Ds.Errors.Unexpected))}updateBackgroundColor(e){this.state.openedMenu=void 0,this.props.updateChart(this.props.figureId,{background:e})}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}isRangeMinInvalid(){var e,t,i;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(37))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(38))||(null===(i=this.state.sectionRuleDispatchResult)||void 0===i?void 0:i.isCancelledBecause(41)))}isRangeMaxInvalid(){var e,t,i;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(39))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(40))||(null===(i=this.state.sectionRuleDispatchResult)||void 0===i?void 0:i.isCancelledBecause(41)))}get isLowerInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(42))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(44)))}get isUpperInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(43))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(44)))}updateInflectionPointValue(e,t){const i=Fe(this.props.definition.sectionRule);i[e].value=t.target.value,this.updateSectionRule(i)}updateInflectionPointType(e,t){const i=Fe(this.props.definition.sectionRule);i[e].type=t.target.value,this.updateSectionRule(i)}updateSectionColor(e,t){const i=Fe(this.props.definition.sectionRule);i.colors[e]=t,this.updateSectionRule(i),this.closeMenus()}updateRangeMin(e){let t=Fe(this.props.definition.sectionRule);t={...t,rangeMin:e.target.value},this.updateSectionRule(t)}updateRangeMax(e){let t=Fe(this.props.definition.sectionRule);t={...t,rangeMax:e.target.value},this.updateSectionRule(t)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}updateSectionRule(e){this.state.sectionRuleDispatchResult=this.props.updateChart(this.props.figureId,{sectionRule:e})}closeMenus(){this.state.openedMenu=void 0}}Eg.template="o-spreadsheet-GaugeChartDesignPanel",Eg.components={ColorPickerWidget:vg},Eg.props={figureId:String,definition:Object,updateChart:Function};class wg extends dg{get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.figureId);return!!(e&&e instanceof nr)&&sr(e.labelRange,this.env.model.getters)}onUpdateLabelsAsText(e){this.props.updateChart(this.props.figureId,{labelsAsText:e.target.checked})}onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}onUpdateCumulative(e){this.props.updateChart(this.props.figureId,{cumulative:e.target.checked})}}wg.template="o-spreadsheet-LineConfigPanel";class yg extends bg{}yg.template="o-spreadsheet-LineChartDesignPanel";class xg extends t.Component{constructor(){super(...arguments),this.state=t.useState({keyValueDispatchResult:void 0,baselineDispatchResult:void 0}),this.keyValue=this.props.definition.keyValue,this.baseline=this.props.definition.baseline}get errorMessages(){var e,t;return[...(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.reasons)||[],...(null===(t=this.state.baselineDispatchResult)||void 0===t?void 0:t.reasons)||[]].map((e=>Ds.Errors[e]||Ds.Errors.Unexpected))}get isKeyValueInvalid(){var e;return!!(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.isCancelledBecause(34))}get isBaselineInvalid(){var e;return!!(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.isCancelledBecause(35))}onKeyValueRangeChanged(e){this.keyValue=e[0]}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.figureId,{keyValue:this.keyValue})}onBaselineRangeChanged(e){this.baseline=e[0]}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.figureId,{baseline:this.baseline})}updateBaselineMode(e){this.props.updateChart(this.props.figureId,{baselineMode:e.target.value})}}xg.template="o-spreadsheet-ScorecardChartConfigPanel",xg.components={SelectionInput:hg},xg.props={figureId:String,definition:Object,updateChart:Function};class Ig extends t.Component{constructor(){super(...arguments),this.state=t.useState({openedColorPicker:void 0})}setup(){t.useExternalListener(window,"click",this.closeMenus)}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}updateBaselineDescr(e){this.props.updateChart(this.props.figureId,{baselineDescr:e.target.value})}toggleColorPicker(e){this.state.openedColorPicker===e?this.state.openedColorPicker=void 0:this.state.openedColorPicker=e}setColor(e,t){switch(t){case"backgroundColor":this.props.updateChart(this.props.figureId,{background:e});break;case"baselineColorDown":this.props.updateChart(this.props.figureId,{baselineColorDown:e});break;case"baselineColorUp":this.props.updateChart(this.props.figureId,{baselineColorUp:e})}this.closeMenus()}closeMenus(){this.state.openedColorPicker=void 0}}Ig.template="o-spreadsheet-ScorecardChartDesignPanel",Ig.components={ColorPickerWidget:vg},Ig.props={figureId:String,definition:Object,updateChart:Function};const Rg=new Ro;Rg.add("line",{configuration:wg,design:yg}).add("bar",{configuration:ug,design:Cg}).add("pie",{configuration:dg,design:bg}).add("gauge",{configuration:Sg,design:Eg}).add("scorecard",{configuration:xg,design:Ig}),vo`
598
+ `;class Eg extends t.Component{constructor(){super(...arguments),this.state=t.useState({openedMenu:void 0,sectionRuleDispatchResult:void 0})}setup(){t.useExternalListener(window,"click",this.closeMenus)}get designErrorMessages(){var e;return[...(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.reasons)||[]].map((e=>Ds.Errors[e]||Ds.Errors.Unexpected))}updateBackgroundColor(e){this.state.openedMenu=void 0,this.props.updateChart(this.props.figureId,{background:e})}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}isRangeMinInvalid(){var e,t,i;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(38))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(39))||(null===(i=this.state.sectionRuleDispatchResult)||void 0===i?void 0:i.isCancelledBecause(42)))}isRangeMaxInvalid(){var e,t,i;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(40))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(41))||(null===(i=this.state.sectionRuleDispatchResult)||void 0===i?void 0:i.isCancelledBecause(42)))}get isLowerInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(43))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(45)))}get isUpperInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(44))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(45)))}updateInflectionPointValue(e,t){const i=Fe(this.props.definition.sectionRule);i[e].value=t.target.value,this.updateSectionRule(i)}updateInflectionPointType(e,t){const i=Fe(this.props.definition.sectionRule);i[e].type=t.target.value,this.updateSectionRule(i)}updateSectionColor(e,t){const i=Fe(this.props.definition.sectionRule);i.colors[e]=t,this.updateSectionRule(i),this.closeMenus()}updateRangeMin(e){let t=Fe(this.props.definition.sectionRule);t={...t,rangeMin:e.target.value},this.updateSectionRule(t)}updateRangeMax(e){let t=Fe(this.props.definition.sectionRule);t={...t,rangeMax:e.target.value},this.updateSectionRule(t)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}updateSectionRule(e){this.state.sectionRuleDispatchResult=this.props.updateChart(this.props.figureId,{sectionRule:e})}closeMenus(){this.state.openedMenu=void 0}}Eg.template="o-spreadsheet-GaugeChartDesignPanel",Eg.components={ColorPickerWidget:vg},Eg.props={figureId:String,definition:Object,updateChart:Function};class wg extends dg{get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.figureId);return!!(e&&e instanceof nr)&&sr(e.labelRange,this.env.model.getters)}onUpdateLabelsAsText(e){this.props.updateChart(this.props.figureId,{labelsAsText:e.target.checked})}onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}onUpdateCumulative(e){this.props.updateChart(this.props.figureId,{cumulative:e.target.checked})}}wg.template="o-spreadsheet-LineConfigPanel";class yg extends bg{}yg.template="o-spreadsheet-LineChartDesignPanel";class xg extends t.Component{constructor(){super(...arguments),this.state=t.useState({keyValueDispatchResult:void 0,baselineDispatchResult:void 0}),this.keyValue=this.props.definition.keyValue,this.baseline=this.props.definition.baseline}get errorMessages(){var e,t;return[...(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.reasons)||[],...(null===(t=this.state.baselineDispatchResult)||void 0===t?void 0:t.reasons)||[]].map((e=>Ds.Errors[e]||Ds.Errors.Unexpected))}get isKeyValueInvalid(){var e;return!!(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.isCancelledBecause(35))}get isBaselineInvalid(){var e;return!!(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.isCancelledBecause(36))}onKeyValueRangeChanged(e){this.keyValue=e[0]}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.figureId,{keyValue:this.keyValue})}onBaselineRangeChanged(e){this.baseline=e[0]}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.figureId,{baseline:this.baseline})}updateBaselineMode(e){this.props.updateChart(this.props.figureId,{baselineMode:e.target.value})}}xg.template="o-spreadsheet-ScorecardChartConfigPanel",xg.components={SelectionInput:hg},xg.props={figureId:String,definition:Object,updateChart:Function};class Ig extends t.Component{constructor(){super(...arguments),this.state=t.useState({openedColorPicker:void 0})}setup(){t.useExternalListener(window,"click",this.closeMenus)}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}updateBaselineDescr(e){this.props.updateChart(this.props.figureId,{baselineDescr:e.target.value})}toggleColorPicker(e){this.state.openedColorPicker===e?this.state.openedColorPicker=void 0:this.state.openedColorPicker=e}setColor(e,t){switch(t){case"backgroundColor":this.props.updateChart(this.props.figureId,{background:e});break;case"baselineColorDown":this.props.updateChart(this.props.figureId,{baselineColorDown:e});break;case"baselineColorUp":this.props.updateChart(this.props.figureId,{baselineColorUp:e})}this.closeMenus()}closeMenus(){this.state.openedColorPicker=void 0}}Ig.template="o-spreadsheet-ScorecardChartDesignPanel",Ig.components={ColorPickerWidget:vg},Ig.props={figureId:String,definition:Object,updateChart:Function};const Rg=new Ro;Rg.add("line",{configuration:wg,design:yg}).add("bar",{configuration:ug,design:Cg}).add("pie",{configuration:dg,design:bg}).add("gauge",{configuration:Sg,design:Eg}).add("scorecard",{configuration:xg,design:Ig}),vo`
599
599
  .o-chart {
600
600
  .o-panel {
601
601
  display: flex;
@@ -907,7 +907,7 @@
907
907
  }
908
908
  }
909
909
  }
910
- `;class _g extends t.Component{constructor(){super(...arguments),this.icons=Mg,this.cellIsOperators=Fs,this.iconSets=Og,this.getTextDecoration=bo,this.colorNumberString=Et}setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId(),this.state=t.useState({mode:"list",errors:[],rules:this.getDefaultRules()});const e=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===i.length){const e=this.conditionalFormats.find((e=>e.id===i[0]));e&&this.editConditionalFormat(e)}t.onWillUpdateProps((e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===i.length){const e=this.conditionalFormats.find((e=>e.id===i[0]));e&&this.editConditionalFormat(e)}else this.switchToList()}})),t.useExternalListener(window,"click",this.closeMenus)}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId())}get isRangeValid(){return this.state.errors.includes(24)}errorMessage(e){return _s.Errors[e]||_s.Errors.Unexpected}switchToList(){this.state.mode="list",this.state.currentCF=void 0,this.state.currentCFType=void 0,this.state.errors=[],this.state.rules=this.getDefaultRules()}getStyle(e){if("CellIsRule"===e.type)return Eo({"font-weight":e.style.bold?"bold":"normal","text-decoration":bo(e.style),"font-style":e.style.italic?"italic":"normal",color:e.style.textColor||"none","background-color":e.style.fillColor||"none"});if("ColorScaleRule"===e.type){const t=Et(e.minimum.color),i=e.midpoint?Et(e.midpoint.color):null,o=Et(e.maximum.color),n="background-image: linear-gradient(to right, ";return i?n+t+", "+i+", "+o+")":n+t+", "+o+")"}return""}getDescription(e){switch(e.rule.type){case"CellIsRule":const t=Fs[e.rule.operator];return 1===e.rule.values.length?`${t} ${e.rule.values[0]}`:2===e.rule.values.length?n("%s %s and %s",t,e.rule.values[0],e.rule.values[1]):t;case"ColorScaleRule":return _s.ColorScale;case"IconSetRule":return _s.IconSet;default:return""}}saveConditionalFormat(){if(this.state.currentCF){if(this.state.currentCF.ranges.some((e=>!e.match(Pt))))return void(this.state.errors=[25]);const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:this.getEditorRule(),id:"edit"===this.state.mode?this.state.currentCF.id:this.env.model.uuidGenerator.uuidv4()},ranges:this.state.currentCF.ranges.map((t=>this.env.model.getters.getRangeDataFromXc(e,t))),sheetId:e});t.isSuccessful?this.switchToList():this.state.errors=t.reasons}}getEditorRule(){switch(this.state.currentCFType){case"CellIsRule":return this.state.rules.cellIs;case"ColorScaleRule":return this.state.rules.colorScale;case"IconSetRule":return this.state.rules.iconSet}throw new Error(`Invalid cf type: ${this.state.currentCFType}`)}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"IsNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:16777215},midpoint:void 0,maximum:{type:"value",color:6989903}},iconSet:{type:"IconSetRule",icons:{upper:"arrowGood",middle:"arrowNeutral",lower:"arrowBad"},upperInflectionPoint:{type:"percentage",value:"66",operator:"gt"},lowerInflectionPoint:{type:"percentage",value:"33",operator:"gt"}}}}addConditionalFormat(){this.state.mode="add",this.state.currentCFType="CellIsRule",this.state.currentCF={id:this.env.model.uuidGenerator.uuidv4(),ranges:this.env.model.getters.getSelectedZones().map((e=>this.env.model.getters.zoneToXC(this.env.model.getters.getActiveSheetId(),e)))}}deleteConditionalFormat(e){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:e.id,sheetId:this.env.model.getters.getActiveSheetId()})}editConditionalFormat(e){if("reorder"!==this.state.mode)switch(this.state.mode="edit",this.state.currentCF=e,this.state.currentCFType=e.rule.type,e.rule.type){case"CellIsRule":this.state.rules.cellIs=e.rule;break;case"ColorScaleRule":this.state.rules.colorScale=e.rule;break;case"IconSetRule":this.state.rules.iconSet=e.rule}}reorderConditionalFormats(){this.state.mode="reorder"}reorderRule(e,t){this.env.model.dispatch("MOVE_CONDITIONAL_FORMAT",{cfId:e.id,direction:t,sheetId:this.env.model.getters.getActiveSheetId()})}changeRuleType(e){this.state.currentCFType!==e&&this.state.rules&&(this.state.errors=[],this.state.currentCFType=e)}onRangesChanged(e){this.state.currentCF&&(this.state.currentCF.ranges=e)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(51))}get isValue2Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(52))}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.closeMenus()}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.closeMenus()}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes(58)||this.state.errors.includes(50)||this.state.errors.includes(47)||this.state.errors.includes(53);case"midpoint":return this.state.errors.includes(59)||this.state.errors.includes(54)||this.state.errors.includes(49);case"maximum":return this.state.errors.includes(60)||this.state.errors.includes(55);default:return!1}}setColorScaleColor(e,t){const i=this.state.rules.colorScale[e];i&&(i.color=Number.parseInt(t.substr(1),16)),this.closeMenus()}getPreviewGradient(){var e;const t=this.state.rules.colorScale,i=Et(t.minimum.color),o=Et((null===(e=t.midpoint)||void 0===e?void 0:e.color)||x),n=Et(t.maximum.color),s="background-image: linear-gradient(to right, ";return void 0===t.midpoint?s+i+", "+n+")":s+i+", "+o+", "+n+")"}getThresholdColor(e){return Et(e?e.color:x)}onMidpointChange(e){const t=e.target.value,i=this.state.rules.colorScale;i.midpoint="none"===t?void 0:{color:x,value:"",...i.midpoint,type:t}}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes(57)||this.state.errors.includes(62)||this.state.errors.includes(48);case"upperInflectionPoint":return this.state.errors.includes(56)||this.state.errors.includes(61)||this.state.errors.includes(48);default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad}setIcon(e,t){this.state.rules.iconSet.icons[e]=t}}_g.template="o-spreadsheet-ConditionalFormattingPanel",_g.components={SelectionInput:hg,IconPicker:Ng,ColorPickerWidget:vg},_g.props={selection:{type:Object,optional:!0},onCloseSidePanel:Function},vo`
910
+ `;class _g extends t.Component{constructor(){super(...arguments),this.icons=Mg,this.cellIsOperators=Fs,this.iconSets=Og,this.getTextDecoration=bo,this.colorNumberString=Et}setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId(),this.state=t.useState({mode:"list",errors:[],rules:this.getDefaultRules()});const e=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===i.length){const e=this.conditionalFormats.find((e=>e.id===i[0]));e&&this.editConditionalFormat(e)}t.onWillUpdateProps((e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===i.length){const e=this.conditionalFormats.find((e=>e.id===i[0]));e&&this.editConditionalFormat(e)}else this.switchToList()}})),t.useExternalListener(window,"click",this.closeMenus)}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId())}get isRangeValid(){return this.state.errors.includes(24)}errorMessage(e){return _s.Errors[e]||_s.Errors.Unexpected}switchToList(){this.state.mode="list",this.state.currentCF=void 0,this.state.currentCFType=void 0,this.state.errors=[],this.state.rules=this.getDefaultRules()}getStyle(e){if("CellIsRule"===e.type)return Eo({"font-weight":e.style.bold?"bold":"normal","text-decoration":bo(e.style),"font-style":e.style.italic?"italic":"normal",color:e.style.textColor||"none","background-color":e.style.fillColor||"none"});if("ColorScaleRule"===e.type){const t=Et(e.minimum.color),i=e.midpoint?Et(e.midpoint.color):null,o=Et(e.maximum.color),n="background-image: linear-gradient(to right, ";return i?n+t+", "+i+", "+o+")":n+t+", "+o+")"}return""}getDescription(e){switch(e.rule.type){case"CellIsRule":const t=Fs[e.rule.operator];return 1===e.rule.values.length?`${t} ${e.rule.values[0]}`:2===e.rule.values.length?n("%s %s and %s",t,e.rule.values[0],e.rule.values[1]):t;case"ColorScaleRule":return _s.ColorScale;case"IconSetRule":return _s.IconSet;default:return""}}saveConditionalFormat(){if(this.state.currentCF){if(this.state.currentCF.ranges.some((e=>!e.match(Pt))))return void(this.state.errors=[25]);const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:this.getEditorRule(),id:"edit"===this.state.mode?this.state.currentCF.id:this.env.model.uuidGenerator.uuidv4()},ranges:this.state.currentCF.ranges.map((t=>this.env.model.getters.getRangeDataFromXc(e,t))),sheetId:e});t.isSuccessful?this.switchToList():this.state.errors=t.reasons}}getEditorRule(){switch(this.state.currentCFType){case"CellIsRule":return this.state.rules.cellIs;case"ColorScaleRule":return this.state.rules.colorScale;case"IconSetRule":return this.state.rules.iconSet}throw new Error(`Invalid cf type: ${this.state.currentCFType}`)}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"IsNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:16777215},midpoint:void 0,maximum:{type:"value",color:6989903}},iconSet:{type:"IconSetRule",icons:{upper:"arrowGood",middle:"arrowNeutral",lower:"arrowBad"},upperInflectionPoint:{type:"percentage",value:"66",operator:"gt"},lowerInflectionPoint:{type:"percentage",value:"33",operator:"gt"}}}}addConditionalFormat(){this.state.mode="add",this.state.currentCFType="CellIsRule",this.state.currentCF={id:this.env.model.uuidGenerator.uuidv4(),ranges:this.env.model.getters.getSelectedZones().map((e=>this.env.model.getters.zoneToXC(this.env.model.getters.getActiveSheetId(),e)))}}deleteConditionalFormat(e){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:e.id,sheetId:this.env.model.getters.getActiveSheetId()})}editConditionalFormat(e){if("reorder"!==this.state.mode)switch(this.state.mode="edit",this.state.currentCF=e,this.state.currentCFType=e.rule.type,e.rule.type){case"CellIsRule":this.state.rules.cellIs=e.rule;break;case"ColorScaleRule":this.state.rules.colorScale=e.rule;break;case"IconSetRule":this.state.rules.iconSet=e.rule}}reorderConditionalFormats(){this.state.mode="reorder"}reorderRule(e,t){this.env.model.dispatch("MOVE_CONDITIONAL_FORMAT",{cfId:e.id,direction:t,sheetId:this.env.model.getters.getActiveSheetId()})}changeRuleType(e){this.state.currentCFType!==e&&this.state.rules&&(this.state.errors=[],this.state.currentCFType=e)}onRangesChanged(e){this.state.currentCF&&(this.state.currentCF.ranges=e)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(52))}get isValue2Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(53))}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.closeMenus()}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.closeMenus()}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes(59)||this.state.errors.includes(51)||this.state.errors.includes(48)||this.state.errors.includes(54);case"midpoint":return this.state.errors.includes(60)||this.state.errors.includes(55)||this.state.errors.includes(50);case"maximum":return this.state.errors.includes(61)||this.state.errors.includes(56);default:return!1}}setColorScaleColor(e,t){const i=this.state.rules.colorScale[e];i&&(i.color=Number.parseInt(t.substr(1),16)),this.closeMenus()}getPreviewGradient(){var e;const t=this.state.rules.colorScale,i=Et(t.minimum.color),o=Et((null===(e=t.midpoint)||void 0===e?void 0:e.color)||x),n=Et(t.maximum.color),s="background-image: linear-gradient(to right, ";return void 0===t.midpoint?s+i+", "+n+")":s+i+", "+o+", "+n+")"}getThresholdColor(e){return Et(e?e.color:x)}onMidpointChange(e){const t=e.target.value,i=this.state.rules.colorScale;i.midpoint="none"===t?void 0:{color:x,value:"",...i.midpoint,type:t}}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes(58)||this.state.errors.includes(63)||this.state.errors.includes(49);case"upperInflectionPoint":return this.state.errors.includes(57)||this.state.errors.includes(62)||this.state.errors.includes(49);default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad}setIcon(e,t){this.state.rules.iconSet.icons[e]=t}}_g.template="o-spreadsheet-ConditionalFormattingPanel",_g.components={SelectionInput:hg,IconPicker:Ng,ColorPickerWidget:vg},_g.props={selection:{type:Object,optional:!0},onCloseSidePanel:Function},vo`
911
911
  .o-custom-currency {
912
912
  .o-format-proposals {
913
913
  color: black;
@@ -1397,7 +1397,7 @@
1397
1397
  onScroll.bind="onScroll"
1398
1398
  />`,Sp.defaultProps={topOffset:0},Sp.props={topOffset:{type:Number,optional:!0}};const Ep={ROW:ma,COL:pa,CELL:ga};class wp extends t.Component{constructor(){super(...arguments),this.HEADER_HEIGHT=N,this.HEADER_WIDTH=_,this.keyDownMapping={ENTER:()=>{this.env.model.getters.getActiveCell().type===cn.empty?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},TAB:()=>this.env.model.selection.moveAnchorCell("right",1),"SHIFT+TAB":()=>this.env.model.selection.moveAnchorCell("left",1),F2:()=>{this.env.model.getters.getActiveCell().type===cn.empty?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},DELETE:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},BACKSPACE:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},ESCAPE:()=>{this.env.model.getters.hasOpenedPopover()?this.closeOpenedPopover():this.menuState.isOpen?this.closeMenu():this.env.model.dispatch("CLEAN_CLIPBOARD_HIGHLIGHT")},"CTRL+A":()=>this.env.model.selection.loopSelection(),"CTRL+Z":()=>this.env.model.dispatch("REQUEST_UNDO"),"CTRL+Y":()=>this.env.model.dispatch("REQUEST_REDO"),"CTRL+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"CTRL+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"CTRL+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"ALT+=":()=>{var e;const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getSelectedZone(),{anchor:o}=this.env.model.getters.getSelection(),n=this.env.model.getters.getAutomaticSums(t,i,o.cell);if(this.env.model.getters.isSingleCellOrMerge(t,i)||this.env.model.getters.isEmpty(t,i)&&n.length<=1){const i=(null===(e=n[0])||void 0===e?void 0:e.zone)?this.env.model.getters.zoneToXC(t,n[0].zone):"",o=`=SUM(${i})`;this.props.onGridComposerCellFocused(o,{start:5,end:5+i.length})}else this.env.model.dispatch("SUM_SELECTION")},"CTRL+HOME":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:i}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,i)},"CTRL+END":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),i=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,i)},"SHIFT+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},i=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:i,zone:t})},"CTRL+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},i=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:i,zone:t})},"CTRL+SHIFT+ ":()=>{this.env.model.selection.selectAll()},"SHIFT+PAGEDOWN":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"SHIFT+PAGEUP":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PAGEDOWN:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PAGEUP:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"CTRL+K":()=>la(this.env)}}setup(){this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.hiddenInput=t.useRef("hiddenInput"),this.canvasPosition=Yn(this.gridRef),this.hoveredCell=t.useState({col:void 0,row:void 0}),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),t.useExternalListener(document.body,"cut",this.copy.bind(this,!0)),t.useExternalListener(document.body,"copy",this.copy.bind(this,!1)),t.useExternalListener(document.body,"paste",this.paste),t.onMounted((()=>this.focus())),this.props.exposeFocus((()=>this.focus())),up("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),t.useEffect((()=>this.focus()),(()=>[this.env.model.getters.getActiveSheetId()])),this.onMouseWheel=gp(((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.col=void 0,this.hoveredCell.row=void 0}))}onCellHovered({col:e,row:t}){this.hoveredCell.col=e,this.hoveredCell.row=t}get gridOverlayDimensions(){return Eo({top:"26px",left:"48px",height:"calc(100% - 41px)",width:"calc(100% - 63px)"})}onClosePopover(){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.focus()}focus(){var e;this.env.model.getters.getSelectedFigureId()||"inactive"!==this.env.model.getters.getEditionMode()||null===(e=this.hiddenInput.el)||void 0===e||e.focus()}get gridEl(){if(!this.gridRef.el)throw new Error("Grid el is not defined.");return this.gridRef.el}getAutofillPosition(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-4,top:t.y+t.height-4}}get isAutofillVisible(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(0===t.width||0===t.height)}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:_,gridOffsetY:N})}moveCanvas(e,t){const{scrollX:i,scrollY:o}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:i+e,offsetY:o+t})}getClientPositionKey(e){var t,i,o;return`${e.id}-${null===(t=e.position)||void 0===t?void 0:t.sheetId}-${null===(i=e.position)||void 0===i?void 0:i.col}-${null===(o=e.position)||void 0===o?void 0:o.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,{addZone:i,expandZone:o}){i&&this.env.model.dispatch("PREPARE_SELECTION_INPUT_EXPANSION"),this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),"editing"===this.env.model.getters.getEditionMode()&&this.env.model.dispatch("STOP_EDITION"),o?this.env.model.selection.setAnchorCorner(e,t):i?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t);let n=e,s=t;Vg(this.env,((e,t,i)=>{i.preventDefault(),(e!==n&&-1!=e||t!==s&&-1!=t)&&(n=-1===e?n:e,s=-1===t?s:t,this.env.model.selection.setAnchorCorner(n,s))}),(()=>{this.env.model.dispatch("STOP_SELECTION_INPUT"),this.env.model.getters.isPaintingFormat()&&this.env.model.dispatch("PASTE",{target:this.env.model.getters.getSelectedZones()})}))}onCellDoubleClicked(e,t){const i=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:i,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:i,col:e,row:t}).type===cn.empty?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()}closeOpenedPopover(){this.env.model.dispatch("CLOSE_CELL_POPOVER")}processArrows(e){e.preventDefault(),e.stopPropagation(),this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),lg(e,this.env.model.selection),this.env.model.getters.isPaintingFormat()&&this.env.model.dispatch("PASTE",{target:this.env.model.getters.getSelectedZones()})}onKeydown(e){if(e.key.startsWith("Arrow"))return void this.processArrows(e);let t="";Zn(e)&&(t+="CTRL+"),e.altKey&&(t+="ALT+"),e.shiftKey&&(t+="SHIFT+"),t+=e.key.toUpperCase();let i=this.keyDownMapping[t];return i?(e.preventDefault(),e.stopPropagation(),void i()):void 0}onInput(e){(e.isComposing||"insertFromPaste"!==e.inputType)&&e.data&&(e.preventDefault(),e.stopPropagation(),this.props.onGridComposerCellFocused(e.data))}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:i,top:o}=t;let n="CELL";this.env.model.dispatch("STOP_EDITION"),this.env.model.getters.getActiveCols().has(i)?n="COL":this.env.model.getters.getActiveRows().has(o)&&(n="ROW");const{x:s,y:r,width:a,height:l}=this.env.model.getters.getVisibleRect(t);this.toggleContextMenu(n,s+a,r+l)}onCellRightClicked(e,t,{x:i,y:o}){const n=this.env.model.getters.getSelectedZones();let s="CELL";Ji(e,t,n[n.length-1])?this.env.model.getters.getActiveCols().has(e)?s="COL":this.env.model.getters.getActiveRows().has(t)&&(s="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(s,i,o)}toggleContextMenu(e,t,i){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:i},this.menuState.menuItems=Ep[e].getMenuItems()}copy(e,t){if(!this.gridEl.contains(document.activeElement))return;const i=t.clipboardData;if(!i)return void this.displayWarningCopyPasteNotSupported();if("inactive"!==this.env.model.getters.getEditionMode())return;e?Or(this.env):this.env.model.dispatch("COPY");const o=this.env.model.getters.getClipboardContent();for(const e in o)i.setData(e,o[e]);t.preventDefault()}paste(e){if(!this.gridEl.contains(document.activeElement))return;const t=e.clipboardData;if(t){if(t.types.indexOf(hn.PlainText)>-1){const e=t.getData(hn.PlainText),i=this.env.model.getters.getSelectedZones();this.env.model.getters.getClipboardTextContent()===e?kr(this.env,i):Lr(this.env,i,e)}}else this.displayWarningCopyPasteNotSupported()}displayWarningCopyPasteNotSupported(){this.env.raiseError(s("Copy/Paste is not supported in this browser."))}closeMenu(){this.menuState.isOpen=!1,this.focus()}}wp.template="o-spreadsheet-Grid",wp.components={GridComposer:Jg,GridOverlay:rp,GridPopover:ap,HeadersOverlay:dp,Menu:is,Autofill:zg,ClientTag:Hg,Highlight:fp,Popover:Qn,VerticalScrollBar:Sp,HorizontalScrollBar:Cp,FilterIconsOverlay:op},wp.props={sidePanelIsOpen:Boolean,exposeFocus:Function,focusComposer:String,onComposerContentFocused:Function,onGridComposerCellFocused:Function};class yp{constructor(e){this.xmlString=e}toString(){return this.xmlString}}const xp=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart"],Ip="000000",Rp={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},Tp={styleSheet:"http://schemas.openxmlformats.org/spreadsheetml/2006/main",sst:"http://schemas.openxmlformats.org/spreadsheetml/2006/main",Relationships:"http://schemas.openxmlformats.org/package/2006/relationships",Types:"http://schemas.openxmlformats.org/package/2006/content-types",worksheet:"http://schemas.openxmlformats.org/spreadsheetml/2006/main",workbook:"http://schemas.openxmlformats.org/spreadsheetml/2006/main",drawing:"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing",table:"http://schemas.openxmlformats.org/spreadsheetml/2006/main",revision:"http://schemas.microsoft.com/office/spreadsheetml/2014/revision",revision3:"http://schemas.microsoft.com/office/spreadsheetml/2016/revision3",markupCompatibility:"http://schemas.openxmlformats.org/markup-compatibility/2006"},Ap="http://schemas.openxmlformats.org/drawingml/2006/main",Mp="http://schemas.openxmlformats.org/drawingml/2006/chart",Op={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",themes:"application/vnd.openxmlformats-officedocument.theme+xml",table:"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",pivot:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml",externalLink:"application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml"},Np={document:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",sheet:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",sharedStrings:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",styles:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",drawing:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",chart:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",theme:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",table:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/table",hyperlink:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",image:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"},_p="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Fp=.75,Dp=.1317,kp=8.43,Lp=12.75,Pp=30,Up=100,Vp=164,zp={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}]},Bp=["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"],Hp="[Content_Types].xml";var $p;!function(e){e.DiagonalBorderNotSupported="Diagonal Borders",e.BorderStyleNotSupported="Border style",e.FillStyleNotSupported="Fill Style",e.FontNotSupported="Font",e.HorizontalAlignmentNotSupported="Horizontal Alignment",e.VerticalAlignmentNotSupported="Vertical Alignments",e.MultipleRulesCfNotSupported="Multiple rules conditional formats",e.CfTypeNotSupported="Conditional format type",e.CfFormatBorderNotSupported="Borders in conditional formats",e.CfFormatAlignmentNotSupported="Alignment in conditional formats",e.CfFormatNumFmtNotSupported="Num formats in conditional formats",e.CfIconSetEmptyIconNotSupported="IconSets with empty icons",e.BadlyFormattedHyperlink="Badly formatted hyperlink",e.NumFmtIdNotSupported="Number format"}($p||($p={}));class Wp{constructor(){this._parsingWarnings=new Set,this._conversionWarnings=new Set}addParsingWarning(e){this._parsingWarnings.add(e)}addConversionWarning(e){this._conversionWarnings.add(e)}get warnings(){return[...this._parsingWarnings,...this._conversionWarnings]}generateNotSupportedWarning(e,t,i){let o=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;i&&(o+=`Only ${i.join(", ")} are currently supported.`),this._conversionWarnings.has(o)||this._conversionWarnings.add(o)}}const Gp=["thin"],qp=["general","left","center","right"],Zp=["Arial"],jp=["solid"],Yp=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWith","containsBlanks","notContainsBlanks"],Xp={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},Kp={dashDot:"thin",dashDotDot:"thin",dashed:"thin",dotted:"thin",double:"thin",hair:"thin",medium:"thin",mediumDashDot:"thin",mediumDashDotDot:"thin",mediumDashed:"thin",none:void 0,slantDashDot:"thin",thick:"thin",thin:"thin"},Qp={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"};const Jp={aboveAverage:void 0,expression:void 0,cellIs:void 0,colorScale:void 0,dataBar:void 0,iconSet:void 0,top10:void 0,uniqueValues:void 0,duplicateValues:void 0,containsText:"ContainsText",notContainsText:"NotContains",beginsWith:"BeginsWith",endsWith:"EndsWith",containsBlanks:"IsEmpty",notContainsBlanks:"IsNotEmpty",containsErrors:void 0,notContainsErrors:void 0,timePeriod:void 0},em={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},tm={NoIcons:void 0,"3Arrows":"arrows","3ArrowsGray":"arrows","3Symbols":"smiley","3Symbols2":"smiley","3Signs":"dots","3Flags":"dots","3TrafficLights1":"dots","3TrafficLights2":"dots","4Arrows":"arrows","4ArrowsGray":"arrows","4RedToBlack":"dots","4Rating":"smiley","4TrafficLights":"dots","5Arrows":"arrows","5ArrowsGray":"arrows","5Rating":"smiley","5Quarters":"dots","3Stars":"smiley","3Triangles":"arrows","5Boxes":"dots"},im={b:"bottom",t:"top",l:"left",r:"right",tr:"right"},om={areaChart:void 0,area3DChart:void 0,lineChart:"line",line3DChart:void 0,stockChart:void 0,radarChart:void 0,scatterChart:void 0,pieChart:"pie",pie3DChart:void 0,doughnutChart:"pie",barChart:"bar",bar3DChart:void 0,ofPieChart:void 0,surfaceChart:void 0,surface3DChart:void 0,bubbleChart:void 0},nm={1:"AVERAGE",2:"COUNT",3:"COUNTA",4:"MAX",5:"MIN",6:"PRODUCT",7:"STDEV",8:"STDEVP",9:"SUM",10:"VAR",11:"VARP",101:"AVERAGE",102:"COUNT",103:"COUNTA",104:"MAX",105:"MIN",106:"PRODUCT",107:"STDEV",108:"STDEVP",109:"SUM",110:"VAR",111:"VARP"},sm={0:"",1:"0",2:"0.00",3:"#,#00",4:"#,##0.00",9:"0%",10:"0.00%",11:void 0,12:void 0,13:void 0,14:"m/d/yyyy",15:"m/d/yyyy",16:"m/d/yyyy",17:"m/d/yyyy",18:"hh:mm:ss a",19:"hh:mm:ss a",20:"hhhh:mm:ss",21:"hhhh:mm:ss",22:"m/d/yy h:mm",37:void 0,38:void 0,39:void 0,40:void 0,45:"hhhh:mm:ss",46:"hhhh:mm:ss",47:"hhhh:mm:ss",48:void 0,49:void 0},rm={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},am={0:"000000",1:"FFFFFF",2:"FF0000",3:"00FF00",4:"0000FF",5:"FFFF00",6:"FF00FF",7:"00FFFF",8:"000000",9:"FFFFFF",10:"FF0000",11:"00FF00",12:"0000FF",13:"FFFF00",14:"FF00FF",15:"00FFFF",16:"800000",17:"008000",18:"000080",19:"808000",20:"800080",21:"008080",22:"C0C0C0",23:"808080",24:"9999FF",25:"993366",26:"FFFFCC",27:"CCFFFF",28:"660066",29:"FF8080",30:"0066CC",31:"CCCCFF",32:"000080",33:"FF00FF",34:"FFFF00",35:"00FFFF",36:"800080",37:"800000",38:"008080",39:"0000FF",40:"00CCFF",41:"CCFFFF",42:"CCFFCC",43:"FFFF99",44:"99CCFF",45:"FF99CC",46:"CC99FF",47:"FFCC99",48:"3366FF",49:"33CCCC",50:"99CC00",51:"FFCC00",52:"FF9900",53:"FF6600",54:"666699",55:"969696",56:"003366",57:"339966",58:"003300",59:"333300",60:"993300",61:"993366",62:"333399",63:"333333",64:"000000",65:"FFFFFF"},lm={"image/avif":"avif","image/bmp":"bmp","image/gif":"gif","image/vnd.microsoft.icon":"ico","image/jpeg":"jpeg","image/png":"png","image/tiff":"tiff","image/webp":"webp"};function cm(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=Ip;else{if(!e.indexed)return;t=am[e.indexed]}var i;return t=6===(i=t).length?"#"+i+"FF":"#"+i.slice(2)+i.slice(0,2),e.tint&&(t=function(e,t){const i=At(e),o=Ot(i);t<0&&(o.l=o.l*(1+t));t>0&&(o.l=o.l*(1-t)+(100-100*(1-t)));return Tt(Mt(o))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function hm(e,t){const i=e.split("/"),o=t.split("/");let n="",s=0;for(let e=0;e<i.length-1;e++)i[e]===o[e]?s++:n+="../";return n+=o.slice(s).join("/"),n}function dm(e,t=0){const i={};for(let o=0;o<e.length;o++)e[o]&&(i[o+t]=e[o]);return i}function um(e){const t=[];for(let i of Object.keys(e).map(Number))t[i]=e[i];return t}function gm(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,((e,t)=>String.fromCharCode(parseInt(t,16))))}const pm=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function mm(e,t,i){var o,n,s;if(0===e)return;let r=sm[e]||(null===(o=t.find((t=>t.id===e)))||void 0===o?void 0:o.format);if(r)try{let e=r.replace(/(.*?);.*/,"$1");e=e.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]"),e=e.replace(/\[\$\]/g,"");const t=(null===(n=e.match(/"/g))||void 0===n?void 0:n.length)||0;if(t/2+((null===(s=e.match(/\[/g))||void 0===s?void 0:s.length)||0)>1)throw new Error("Multiple escaped blocks in format");if(e=e.replace(/"(.*)"/g,"[$$$1]"),e=e.replace(/_.{1}/g,""),e=e.replace(/\*.{1}/g,""),e=e.replace(/\\ /g," "),e=e.replace(/\\./g,(e=>e[1])),function(e){return null!==e.match(pm)}(e)&&(e=function(e){return e=e.toLowerCase(),e=e.replace(/mmmmm/g,"mmm"),e=e.replace(/am\/pm|a\/m/g,"a"),e=e.replace(/hhhh/g,"hh"),e=e.replace(/\bh\b/g,"hh"),e}(e)),function(e){try{return fi(0,e),!0}catch(e){return!1}}(e))return e}catch(e){}i.generateNotSupportedWarning($p.NumFmtIdNotSupported,r||`nmFmtId ${e}`)}function fm(e,t){const i=e.borders.map((e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning($p.DiagonalBorderNotSupported)}(e,t);const i={top:vm(e.top,t),bottom:vm(e.bottom,t),left:vm(e.left,t),right:vm(e.right,t)};return Object.keys(i).forEach((e=>void 0===i[e]&&delete i[e])),i}));return dm(i,1)}function vm(e,t){if(!e)return;!function(e,t){Gp.includes(e.style)||t.generateNotSupportedWarning($p.BorderStyleNotSupported,e.style,Gp)}(e,t);const i=Kp[e.style];return i?[i,cm(e.color)]:void 0}function bm(e,t){return dm(e.styles.map((i=>Cm({fontStyle:e.fonts[i.fontId],fillStyle:e.fills[i.fillId],alignment:i.alignment},t))),1)}function Cm(e,t){var i,o,n,s,r,a,l,c,h,d,u,g;return function(e,t,i){e&&e.name&&!Zp.includes(e.name)&&i.generateNotSupportedWarning($p.FontNotSupported,e.name,Zp);t&&t.patternType&&!jp.includes(t.patternType)&&i.generateNotSupportedWarning($p.FillStyleNotSupported,t.patternType,jp)}(null==e?void 0:e.fontStyle,null==e?void 0:e.fillStyle,t),function(e,t){e&&!qp.includes(e)&&t.generateNotSupportedWarning($p.HorizontalAlignmentNotSupported,e,qp)}(null===(i=null==e?void 0:e.alignment)||void 0===i?void 0:i.horizontal,t),function(e,t){e&&t.generateNotSupportedWarning($p.VerticalAlignmentNotSupported)}(null===(o=null==e?void 0:e.alignment)||void 0===o?void 0:o.vertical,t),{bold:null===(n=e.fontStyle)||void 0===n?void 0:n.bold,italic:null===(s=e.fontStyle)||void 0===s?void 0:s.italic,strikethrough:null===(r=e.fontStyle)||void 0===r?void 0:r.strike,underline:null===(a=e.fontStyle)||void 0===a?void 0:a.underline,align:(null===(l=e.alignment)||void 0===l?void 0:l.horizontal)?Qp[e.alignment.horizontal]:void 0,fillColor:"solid"===(null===(c=e.fillStyle)||void 0===c?void 0:c.patternType)?cm(null===(h=e.fillStyle)||void 0===h?void 0:h.fgColor):cm(null===(d=e.fillStyle)||void 0===d?void 0:d.bgColor),textColor:cm(null===(u=e.fontStyle)||void 0===u?void 0:u.color),fontSize:null===(g=e.fontStyle)||void 0===g?void 0:g.size}}function Sm(e,t){const i=[];for(let o of e.styles){const n=mm(o.numFmtId,e.numFmts,t);n&&(i[o.numFmtId]=n)}return dm(i,1)}function Em(e,t,i){const o=[];let n=1;for(let r of e){if(0===r.cfRules.length)continue;Im(r,t,i);const e=r.cfRules[0];let a;const l=[];if(void 0!==e.dxfId||"colorScale"===e.type||"iconSet"===e.type){switch(e.type){case"aboveAverage":case"containsErrors":case"notContainsErrors":case"dataBar":case"duplicateValues":case"expression":case"top10":case"uniqueValues":case"timePeriod":continue;case"colorScale":const t=wm(n++,r);t&&o.push(t);continue;case"iconSet":const c=ym(n++,r,i);c&&o.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;a=Jp[e.type],l.push(e.text);break;case"containsBlanks":case"notContainsBlanks":a=Jp[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;a=(s=e.operator).slice(0,1).toUpperCase()+s.slice(1),l.push(e.formula[0]),2===e.formula.length&&l.push(e.formula[1])}a&&void 0!==e.dxfId&&o.push({id:(n++).toString(),ranges:r.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:a,values:l,style:Cm({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},i)}})}}var s;return o}function wm(e,t){const i=t.cfRules[0].colorScale;if(!i||i.cfvos.length!==i.colors.length||i.cfvos.length<2||i.cfvos.length>3)return;const o=[];for(let e=0;e<i.cfvos.length;e++)o.push({color:(n=cm(i.colors[e])||"#FFFFFF",9===n.length&&(n=n.slice(0,7)),parseInt(n.replace("#",""),16)),type:em[i.cfvos[e].type],value:i.cfvos[e].value});var n;const s=o[0],r=2===o.length?o[1]:o[2],a=3===o.length?o[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:s,midpoint:a,maximum:r}}}function ym(e,t,i){const o=t.cfRules[0].iconSet;if(!o)return;let n=o.cfvos,s=o.cfIcons;if(n.length<3||s&&s.length<3)return;n.length>3&&(n=[n[0],n[Math.floor(n.length/2)],n[n.length-1]]),s&&s.length>3&&(s=[s[0],s[Math.floor(s.length/2)],s[s.length-1]]);const r=[];for(let e=1;e<=2;e++){const t=em[n[e].type];if("value"===t)return;r.push({value:n[e].value||"",operator:n[e].gte?"ge":"gt",type:t})}let a={lower:s?xm(s[0].iconSet,s[0].iconId):xm(o.iconSet,0),middle:s?xm(s[1].iconSet,s[1].iconId):xm(o.iconSet,1),upper:s?xm(s[2].iconSet,s[2].iconId):xm(o.iconSet,2)};o.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(let e of Object.keys(a))if(!a[e])switch(i.generateNotSupportedWarning($p.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=Og.dots.good;break;case"middle":a[e]=Og.dots.neutral;break;case"lower":a[e]=Og.dots.bad}return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"IconSetRule",icons:a,upperInflectionPoint:r[1],lowerInflectionPoint:r[0]}}}function xm(e,t){const i=tm[e];return i?0===t?Og[i].bad:1===t?Og[i].neutral:Og[i].good:""}function Im(e,t,i){if(e.cfRules.length>1&&i.generateNotSupportedWarning($p.MultipleRulesCfNotSupported),Yp.includes(e.cfRules[0].type)||i.generateNotSupportedWarning($p.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const o=t[e.cfRules[0].dxfId];o.border&&i.generateNotSupportedWarning($p.CfFormatBorderNotSupported),o.alignment&&i.generateNotSupportedWarning($p.CfFormatAlignmentNotSupported),o.numFmt&&i.generateNotSupportedWarning($p.CfFormatNumFmtNotSupported)}}class Rm{constructor(e=new Am){this.scope=e,this.code=""}append(...e){this.code+=e.map((e=>e.toString())).join("\n")+"\n"}return(e){return new Tm(this.scope,this.code,e)}toString(){return Mm(this.code)}}class Tm{constructor(e,t,i){this.scope=e,this.returnExpression=i,this.code=Mm(t)}toString(){return this.code}wrapInClosure(){const e=this.scope.nextVariableName(),t=new Rm(this.scope);return t.append(`const ${e} = () => {`),t.append(this.code),t.append(`return ${this.returnExpression};`),t.append("}"),t.return(e)}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;const e=this.scope.nextVariableName(),t=new Rm(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}}class Am{constructor(){this.nextId=1,this.declaredVariables=new Set}nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function Mm(e){let t="",i=0;const o=e.split("\n").map((e=>e.trim())).filter((e=>""!==e));for(const e of o)e.startsWith("}")&&i--,t+="\t".repeat(i)+e+"\n",e.endsWith("{")&&i++;return t.trim()}const Om=ig.content,Nm=["%"],_m="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(Nm);function Fm(e){const t=(e=vt(e)).split(""),i=[];for(;t.length;){let e=$m(t)||Lm(t)||Um(t)||zm(t)||Dm(t)||Wm(t)||Vm(t)||Hm(t);e||(e={type:"UNKNOWN",value:t.shift()}),i.push(e)}return i}function Dm(e){return"?"===e[0]?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const km={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function Lm(e){if(e[0]in km){const t=e.shift();return{type:km[t],value:t}}return null}function Pm(e,t){for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0}function Um(e){for(let t of _m)if(Pm(e,t))return e.splice(0,t.length),{type:"OPERATOR",value:t};return null}function Vm(e){const t=rt(e).match(Qt);return t?(e.splice(0,t[0].length),{type:"NUMBER",value:t[0]}):null}function zm(e){if('"'===e[0]){const t=e.shift();let i=t;for(;e[0]&&(e[0]!==t||"\\"===i[i.length-1]);)i+=e.shift();return'"'===e[0]&&(i+=e.shift()),{type:"STRING",value:i}}return null}const Bm=/\w|\.|!|\$/;function Hm(e){let t="";if("'"===e[0]){let i=e.shift();for(t+=i;e[0];)if(i=e.shift(),t+=i,"'"===i){if(!e[0]||"'"!==e[0])break;i=e.shift(),t+=i}if("'"!==i)return{type:"UNKNOWN",value:t}}for(;e[0]&&e[0].match(Bm);)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in Om)return{type:"FUNCTION",value:e};return e.match(Pt)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function $m(e){let t=0;for(;e[0]===he;)t++,e.shift();if(t)return{type:"SPACE",value:he.repeat(t)};for(;" "===e[0];)t++,e.shift();return t?{type:"SPACE",value:" ".repeat(t)}:null}function Wm(e){return Pm(e,K)?(e.splice(0,K.length),{type:"INVALID_REFERENCE",value:K}):null}const Gm=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,qm=["-","+"],Zm=["%"],jm=["*","+","&"],Ym={"^":30,"%":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function Xm(e){var t,i,o;const n=e.shift();if(!n)throw new h(le);switch(n.type){case"DEBUGGER":const r=Jm(e,1e3);return r.debug=!0,r;case"NUMBER":return{type:"NUMBER",value:ri(n.value)};case"STRING":return{type:"STRING",value:Ne(n.value)};case"FUNCTION":const a=function(e){var t;Qm(e,"LEFT_PAREN",s("Missing opening parenthesis"));const i=e[0];if("RIGHT_PAREN"===(null==i?void 0:i.type))return Qm(e,"RIGHT_PAREN"),[];const o=[];o.push(Km(e));for(;"RIGHT_PAREN"!==(null===(t=e[0])||void 0===t?void 0:t.type);)Qm(e,"COMMA",s("Wrong function call")),o.push(Km(e));return Qm(e,"RIGHT_PAREN"),o}(e);return{type:"FUNCALL",value:n.value,args:a};case"INVALID_REFERENCE":throw new u;case"REFERENCE":if(":"===(null===(t=e[0])||void 0===t?void 0:t.value)&&"REFERENCE"===(null===(i=e[1])||void 0===i?void 0:i.type)){e.shift();const t=e.shift();return{type:"REFERENCE",value:`${n.value}:${null==t?void 0:t.value}`}}return{type:"REFERENCE",value:n.value};case"SYMBOL":if(["TRUE","FALSE"].includes(n.value.toUpperCase()))return{type:"BOOLEAN",value:"TRUE"===n.value.toUpperCase()};if(n.value&&Gm.test(n.value)&&"LEFT_PAREN"===(null===(o=e[0])||void 0===o?void 0:o.type))throw new p(n.value);throw new h(s("Invalid formula"));case"LEFT_PAREN":const l=Jm(e);return Qm(e,"RIGHT_PAREN",s("Missing closing parenthesis")),l;case"OPERATOR":const c=n.value;if(qm.includes(c))return{type:"UNARY_OPERATION",value:c,operand:Jm(e,Ym[c])};throw new h(s("Unexpected token: %s",n.value));default:throw new h(s("Unexpected token: %s",n.value))}}function Km(e){const t=e[0];return"COMMA"===(null==t?void 0:t.type)||"RIGHT_PAREN"===(null==t?void 0:t.type)?{type:"EMPTY",value:""}:Jm(e)}function Qm(e,t,i=le){const o=e.shift();if(!o||o.type!==t)throw new h(i)}function Jm(e,t=0){var i;if(0===e.length)throw new h(le);let o=Xm(e);for(;"OPERATOR"===(null===(i=e[0])||void 0===i?void 0:i.type)&&Ym[e[0].value]>t;){const t=e.shift().value;if(Zm.includes(t))o={type:"UNARY_OPERATION",value:t,operand:o,postfix:!0};else{o={type:"BIN_OPERATION",value:t,left:o,right:Jm(e,Ym[t])}}}return o}function ef(e){return tf(Fm(e))}function tf(e){"="===(e=e.filter((e=>"SPACE"!==e.type)))[0].value&&e.splice(0,1);const t=Jm(e);if(e.length)throw new h(le);return t}function of(e,t,i){switch(t===e.type&&(e=i(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>of(e,t,i)))};case"UNARY_OPERATION":return{...e,operand:of(e.operand,t,i)};case"BIN_OPERATION":return{...e,right:of(e.right,t,i),left:of(e.left,t,i)};default:return e}}function nf(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>nf(e)));return`${e.value}(${t.join(",")})`;case"NUMBER":return e.value.toString();case"REFERENCE":default:return e.value;case"STRING":return`"${e.value}"`;case"BOOLEAN":return e.value?"TRUE":"FALSE";case"UNARY_OPERATION":return e.postfix?sf(e)+e.value:e.value+rf(e);case"BIN_OPERATION":return sf(e)+e.value+rf(e)}}function sf(e){const t=e.value,i="left"in e?e.left:e.operand,o=i.value;return"BIN_OPERATION"===i.type&&Ym[o]<Ym[t]?`(${nf(i)})`:nf(i)}function rf(e){const t=e.value,i="right"in e?e.right:e.operand,o=Ym[i.value],n=Ym[t];let s=!1;return"BIN_OPERATION"!==i.type?s=!1:o<n?s=!0:o!==n||jm.includes(t)||(s=!0),s?`(${nf(i)})`:nf(i)}var af;!function(e){e[e.LeftRef=0]="LeftRef",e[e.RightRef=1]="RightRef",e[e.Separator=2]="Separator",e[e.FullColumnSeparator=3]="FullColumnSeparator",e[e.FullRowSeparator=4]="FullRowSeparator",e[e.RightColumnRef=5]="RightColumnRef",e[e.RightRowRef=6]="RightRowRef",e[e.Found=7]="Found"}(af||(af={}));const lf=(e,t=(()=>!0))=>[{goTo:e,guard:t}],cf=(e,t=(()=>!0))=>({goTo:e,guard:t}),hf={[af.LeftRef]:{REFERENCE:lf(af.Separator),NUMBER:lf(af.FullRowSeparator),SYMBOL:[cf(af.FullColumnSeparator,(e=>Ut(e.value))),cf(af.FullRowSeparator,(e=>Vt(e.value)))]},[af.FullColumnSeparator]:{SPACE:lf(af.FullColumnSeparator),OPERATOR:lf(af.RightColumnRef,(e=>":"===e.value))},[af.FullRowSeparator]:{SPACE:lf(af.FullRowSeparator),OPERATOR:lf(af.RightRowRef,(e=>":"===e.value))},[af.Separator]:{SPACE:lf(af.Separator),OPERATOR:lf(af.RightRef,(e=>":"===e.value))},[af.RightRef]:{SPACE:lf(af.RightRef),NUMBER:lf(af.Found),REFERENCE:lf(af.Found,(e=>Ht(e.value))),SYMBOL:lf(af.Found,(e=>zt(e.value)||Bt(e.value)))},[af.RightColumnRef]:{SPACE:lf(af.RightColumnRef),SYMBOL:lf(af.Found,(e=>zt(e.value))),REFERENCE:lf(af.Found,(e=>Ht(e.value)))},[af.RightRowRef]:{SPACE:lf(af.RightRowRef),NUMBER:lf(af.Found),REFERENCE:lf(af.Found,(e=>Ht(e.value))),SYMBOL:lf(af.Found,(e=>Bt(e.value)))},[af.Found]:{}};function df(e){var t;let i=0,o=hf[af.LeftRef];const n=[];for(;void 0!==o;){const s=e[i++];if(!s)return null;const r=null===(t=o[s.type])||void 0===t?void 0:t.find((e=>e.guard(s))),a=r?r.goTo:void 0;switch(a){case void 0:return null;case af.Found:return n.push(s),e.splice(0,i),{type:"REFERENCE",value:rt(n.map((e=>e.value)))};default:o=hf[a],n.push(s)}}return null}function uf(e){const t=Fm(e),i=[];for(;t.length;)i.push(df(t)||t.shift());return i}const gf=ig.content,pf={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},mf={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"},ff={};function vf(e){const t=uf(e),{dependencies:i,constantValues:o}=function(e){const t={numbers:[],strings:[]},i=[];for(const o of e)switch(o.type){case"INVALID_REFERENCE":case"REFERENCE":i.push(o.value);break;case"STRING":const e=Ne(o.value);t.strings.includes(e)||t.strings.push(e);break;case"NUMBER":{const e=ri(o.value);t.numbers.includes(e)||t.numbers.push(e);break}}return{dependencies:i,constantValues:t}}(t),n=function(e,t,i){return rt(e.map((e=>{switch(e.type){case"STRING":const o=Ne(e.value);return`|S${i.strings.indexOf(o)}|`;case"NUMBER":return`|N${i.numbers.indexOf(ri(e.value))}|`;case"REFERENCE":case"INVALID_REFERENCE":return`|${t.indexOf(e.value)}|`;case"SPACE":return"";default:return e.value}})))}(t,i,o);if(!ff[n]){const r=tf([...t]),a=new Am;if("BIN_OPERATION"===r.type&&":"===r.value)throw new h(s("Invalid formula"));if("EMPTY"===r.type)throw new h(s("Invalid formula"));const l=g(r),c=new Rm;c.append(`// ${n}`),c.append(l),c.append(`return ${l.returnExpression};`);let d=new Function("deps","ref","range","ctx",c.toString());function u(e){const t=gf[e.value.toUpperCase()],i=e.args,o=i.length;if(o<t.minArgRequired)throw new h(s("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",e.value.toUpperCase(),t.minArgRequired.toString(),o.toString()));if(o>t.maxArgPossible)throw new h(s("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",e.value.toUpperCase(),t.maxArgPossible.toString(),o.toString()));const n=t.nbrArgRepeating;if(n>1){const i=t.args.length-n;if((o-i)%n!=0)throw new h(s("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(),i.toString(),n.toString()))}let r=[];for(let n=0;n<o;n++){const o=t.getArgToFocus(n+1)-1;if(0<=o&&o<t.args.length){const a=i[n],l=t.args[o],c=l.type||[],d=c.includes("META"),u=l.lazy,p=c.some((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e)),m=c.every((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e));if(m&&"REFERENCE"!==a.type)throw new h(s("Function %s expects the parameter %s to be reference to a cell or range, not a %s.",e.value.toUpperCase(),(n+1).toString(),a.type.toLowerCase()));const f=g(a,d,p,{functionName:e.value.toUpperCase(),paramIndex:n+1});r.push(u?f.wrapInClosure():f)}}return r}function g(e,t=!1,n=!1,r={}){const l=new Rm(a);if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&t)throw new h(s("Argument must be a reference to a cell or range."));switch(e.debug&&l.append("debugger;"),e.type){case"BOOLEAN":return l.return(`{ value: ${e.value} }`);case"NUMBER":return l.return(`{ value: this.constantValues.numbers[${o.numbers.indexOf(e.value)}] }`);case"STRING":return l.return(`{ value: this.constantValues.strings[${o.strings.indexOf(e.value)}] }`);case"REFERENCE":const s=i.indexOf(e.value);return n?l.return(`range(deps[${s}])`):l.return(`ref(deps[${s}], ${t?"true":"false"}, "${r.functionName||pf["="]}", ${r.paramIndex})`);case"FUNCALL":const a=u(e).map((e=>e.assignResultToVariable()));l.append(...a);const c=e.value.toUpperCase();return l.append(`ctx.__lastFnCalled = '${c}';`),l.return(`ctx['${c}'](${a.map((e=>e.returnExpression))})`);case"UNARY_OPERATION":{const t=mf[e.value],i=g(e.operand,!1,!1,{functionName:t}).assignResultToVariable();return l.append(i),l.append(`ctx.__lastFnCalled = '${t}';`),l.return(`ctx['${t}'](${i.returnExpression})`)}case"BIN_OPERATION":{const t=pf[e.value],i=g(e.left,!1,!1,{functionName:t}).assignResultToVariable(),o=g(e.right,!1,!1,{functionName:t}).assignResultToVariable();return l.append(i),l.append(o),l.append(`ctx.__lastFnCalled = '${t}';`),l.return(`ctx['${t}'](${i.returnExpression}, ${o.returnExpression})`)}case"EMPTY":return l.return("undefined")}}ff[n]={execute:d}}return{execute:ff[n].execute,dependencies:i,constantValues:o,tokens:t}}function bf(e){return function(e){let t=[],i="";return e.map(((e,o)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(i=""),e.type){case"FUNCTION":i=e.value;break;case"LEFT_PAREN":t.push({parent:i,argPosition:0}),i="";break;case"RIGHT_PAREN":t.pop();break;case"COMMA":t.length&&t[t.length-1].argPosition++}if(t.length){const i=t[t.length-1];i.parent&&(e.functionContext=Object.assign({},i))}return e}))}(function(e){let t=1;const i=[];return e.map((e=>("LEFT_PAREN"===e.type?(i.push(t),e.parenIndex=t,t++):"RIGHT_PAREN"===e.type&&(e.parenIndex=i.pop()),e)))}(function(e){let t=0;return e.map((e=>{const i=e.value.toString().length,o=Object.assign({},e,{start:t,end:t+i,length:i});return t=o.end,o}))}(uf(e))))}function Cf(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function Sf(e){return Math.round(Fp*e*100)/100}function Ef(e){return Math.round(Dp*e*100)/100}function wf(e){if(e)return{style:e[0],color:{rgb:e[1]}}}function yf(e,t){let i={};e.style&&(i=t.styles[e.style]);const o=function(e,t){if(e.format)return t.formats[e.format];if(e.isFormula){const t=Fm(e.content||""),i=ig.content;if(!t.filter((e=>"FUNCTION"===e.type)).every((e=>i[e.value.toUpperCase()].isExported)))return e.computedFormat}return}(e,t),n={};if(e.border){const i=t.borders[e.border];n.left=wf(i.left),n.right=wf(i.right),n.bottom=wf(i.bottom),n.top=wf(i.top)}const s={font:{size:(null==i?void 0:i.fontSize)||q,color:{rgb:(null==i?void 0:i.textColor)?i.textColor:"000000"},family:2,name:"Arial"},fill:(null==i?void 0:i.fillColor)?{fgColor:{rgb:i.fillColor}}:{reservedAttribute:"none"},numFmt:o?{format:o,id:0}:void 0,border:n||{},alignment:{vertical:"center",horizontal:i.align}};return s.font.strike=!!(null==i?void 0:i.strikethrough)||void 0,s.font.underline=!!(null==i?void 0:i.underline)||void 0,s.font.bold=!!(null==i?void 0:i.bold)||void 0,s.font.italic=!!(null==i?void 0:i.italic)||void 0,s}function xf(e,t){const{id:i}=Rf(t.font,e.fonts),{id:o}=Rf(t.fill,e.fills),{id:n}=Rf(t.border,e.borders),s=function(e,t){if(!e)return 0;let i=rm[e.format];if(!i){const{id:o}=Rf(e,t);i=o+Vp}return i}(t.numFmt,e.numFmts),r={fontId:i,fillId:o,borderId:n,numFmtId:s,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal}},{id:a}=Rf(r,e.styles);return a}function If(e,t,i){let o,n=e.find((e=>e.path===t));return n?(o=`rId${(n.rels.length+1).toString()}`,n.rels.push({...i,id:o})):(o="rId1",e.push({path:t,rels:[{...i,id:o}]})),o}function Rf(e,t){for(let[i,o]of Object.entries(t))if(JSON.stringify(o)===JSON.stringify(e))return{id:parseInt(i,10),list:t};let i=t.findIndex((t=>JSON.stringify(t)===JSON.stringify(e)));return-1===i&&(t.push(e),i=t.length-1),{id:i,list:t}}const Tf=[];function Af(e){const t=Tf.findIndex((t=>t===e));return-1===t?(Tf.push(e),Tf.length):t+1}const Mf=[];function Of(e){const t=Mf.findIndex((t=>t===e));return-1===t?(Mf.push(e),Mf.length):t+1}function Nf(e){return Math.round(914400*e/96)}function _f(e,t,i){let o,n,s=e;if(({xc:s,sheetName:o}=$t(e)),o){const e=i.sheets.findIndex((e=>e.name===o));if(e<0)throw new Error("Unable to find a sheet with the name "+o);n=e}else n=Number(t);const r=Bi(s);return void 0===r.right&&(r.right=i.sheets[n].colNumber),void 0===r.bottom&&(r.bottom=i.sheets[n].rowNumber),(r.right-r.left+1)*(r.bottom-r.top+1)}function Ff(e){return Math.round(96*e/914400)}function Df(e,t){var i;let o=0;for(let n=0;n<e;n++){const e=t.cols.find((e=>n>=e.min&&n<=e.max));(null==e?void 0:e.width)?o+=e.width:(null===(i=t.sheetFormat)||void 0===i?void 0:i.defaultColWidth)?o+=t.sheetFormat.defaultColWidth:o+=kp}return o/Dp}function kf(e,t){var i;let o=0;for(let n=0;n<e;n++){const e=t.rows[n];(null==e?void 0:e.height)?o+=e.height:(null===(i=t.sheetFormat)||void 0===i?void 0:i.defaultRowHeight)?o+=t.sheetFormat.defaultRowHeight:o+=Lp}return o/Fp}function Lf(e){let t=1;return e.figures.map((i=>function(e,t,i){const o=Df(e.anchors[0].col,i)+Ff(e.anchors[0].colOffset),n=Df(e.anchors[1].col,i)+Ff(e.anchors[1].colOffset),s=kf(e.anchors[0].row,i)+Ff(e.anchors[0].rowOffset),r=kf(e.anchors[1].row,i)+Ff(e.anchors[1].rowOffset),a=n-o,l=r-s,c=Pf(e.data);return c?{id:t,x:o,y:s,width:a,height:l,tag:"chart",data:Pf(e.data)}:void 0}(i,(t++).toString(),e))).filter(ot)}function Pf(e){var t;const i=null===(t=e.dataSets[0].label)||void 0===t?void 0:t.replace(/\$/g,"");let o=e.dataSets.map((e=>e.range.replace(/\$/g,"")));return"pie"===e.type&&o.reverse(),{dataSets:o,dataSetsHaveTitle:!1,labelRange:i,title:e.title||"",type:e.type,background:cm({rgb:e.backgroundColor})||"#FFFFFF",verticalAxisPosition:e.verticalAxisPosition,legendPosition:e.legendPosition,stacked:e.stacked||!1,aggregated:!1,cumulative:e.cumulative||!1,labelsAsText:!1}}const Uf=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),Vf=new RegExp(/SUBTOTAL\(([0-9]*),/g),zf=new RegExp(Nt.source,"ig");function Bf(e,t){const i=function(e){const t={};for(let i of e.rows)for(let e of i.cells)e.formula&&void 0!==e.formula.sharedIndex&&e.formula.content&&(t[e.formula.sharedIndex]={refCellXc:e.xc,formula:e.formula.content});return t}(e);for(let o of e.rows.map((e=>e.cells)).flat())(null==o?void 0:o.formula)&&(o.formula.content=void 0===o.formula.sharedIndex||o.formula.content?"="+o.formula.content:"="+$f(o.xc,i[o.formula.sharedIndex]),o.formula.content=Hf(o.formula.content,t))}function Hf(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(Vf,((e,t)=>{const i=nm[t];return i?i+"(":e}))).replace(Uf,((e,i,o,n)=>{var s;i=Number(i)-1,n=n.replace(/\$/g,"");const r=t.externalBooks[i].sheetNames.findIndex((e=>e===o));if(-1===r)return e;const a=null===(s=t.externalBooks[i].datasets.find((e=>e.sheetId===r)))||void 0===s?void 0:s.data;if(!a)return e;const l=a&&a[n];return(Number(l)?l:`"${l}"`)||e}))}function $f(e,t){const i=qt(t.refCellXc);let o,n=t.formula.slice();do{if(o=zf.exec(n),o){const t=qt(o[0].replace("$","")),s=qt(e),r={colFixed:o[0].startsWith("$"),rowFixed:o[0].includes("$",1)},a={col:s.col-i.col,row:s.row-i.row},l={col:r.colFixed?t.col:t.col+a.col,row:r.rowFixed?t.row:t.row+a.row};n=n.slice(0,o.index)+Zt(l.col,l.row,r)+n.slice(o.index+o[0].length)}}while(o);return n}function Wf(e,t){return e.sheets.map((i=>{Bf(i,e);const o=function(e){const t=[0,0];for(let i of e.rows)t[0]=Math.max(t[0],...i.cells.map((e=>qt(e.xc).col))),t[1]=Math.max(t[1],i.index);return t[0]=Math.max(t[0],Pp),t[1]=Math.max(t[1],Up),t}(i),n=i.sheetViews[0];return{id:i.sheetName,areGridLinesVisible:!n||n.showGridLines,name:i.sheetName,colNumber:o[0],rowNumber:o[1],cells:Zf(i,e,o,t),merges:i.merges,cols:Gf(i,o[0]),rows:qf(i,o[1]),conditionalFormats:Em(i.cfs,e.dxfs,t),figures:Lf(i),isVisible:i.isVisible,panes:n?{xSplit:n.pane.xSplit,ySplit:n.pane.ySplit}:{xSplit:0,ySplit:0},filterTables:[]}}))}function Gf(e,t){var i;const o={};for(let s=1;s<t+1;s++){const t=e.cols.find((e=>e.min<=s&&s<=e.max));let r;r=t&&t.width?t.width:(null===(i=e.sheetFormat)||void 0===i?void 0:i.defaultColWidth)?e.sheetFormat.defaultColWidth:kp,o[s-1]={size:(n=r,n?Math.round(n/Dp*100)/100:n),isHidden:null==t?void 0:t.hidden}}var n;return o}function qf(e,t){var i;const o={};for(let s=1;s<t+1;s++){const t=e.rows.find((e=>e.index===s));let r;r=t&&t.height?t.height:(null===(i=e.sheetFormat)||void 0===i?void 0:i.defaultRowHeight)?e.sheetFormat.defaultRowHeight:Lp,o[s-1]={size:(n=r,n?Math.round(n/Fp*100)/100:n),isHidden:null==t?void 0:t.hidden}}var n;return o}function Zf(e,t,i,o){const n={},s=t.sharedStrings.map((e=>e.replace(/\n/g,"")));const r=e.hyperlinks.reduce(((e,t)=>(e[t.xc]=t,e)),{});for(let i of e.rows)for(let e of i.cells)n[e.xc]={content:jf(e,r,s,o),style:e.styleIndex?e.styleIndex+1:void 0,border:e.styleIndex?t.styles[e.styleIndex].borderId+1:void 0,format:e.styleIndex?t.styles[e.styleIndex].numFmtId+1:void 0};for(let o of e.rows.filter((e=>e.styleIndex)))for(let e=1;e<=i[0];e++){const i=Zt(e-1,o.index-1);let s=n[i];s||(s={},n[i]=s),s.style=s.style?s.style:o.styleIndex+1,s.border=s.border?s.border:t.styles[o.styleIndex].borderId+1,s.format=s.format?s.format:t.styles[o.styleIndex].numFmtId+1}for(let o of e.cols.filter((e=>e.styleIndex)))for(let e=o.min;e<=Math.min(o.max,i[0]);e++)for(let s=1;s<=i[1];s++){const i=Zt(e-1,s-1);let r=n[i];r||(r={},n[i]=r),r.style=r.style?r.style:o.styleIndex+1,r.border=r.border?r.border:t.styles[o.styleIndex].borderId+1,r.format=r.format?r.format:t.styles[o.styleIndex].numFmtId+1}return n}function jf(e,t,i,o){let n;switch(e.type){case"sharedString":n=i[parseInt(e.value,10)];break;case"boolean":n=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":n=e.value}return n&&t[e.xc]&&(n=function(e,t,i){const o=e.display||t;e.relTarget||e.location||i.generateNotSupportedWarning($p.BadlyFormattedHyperlink);const n=e.relTarget?e.relTarget:tt($t(e.location).sheetName);return Ke(o,n)}(t[e.xc],n,o)),e.formula&&(n=e.formula.content),n}const Yf={fillColor:"#000000",textColor:"#ffffff",bold:!0},Xf={bold:!0},Kf=["thin","#000000FF"];function Qf(e,t){for(const i of t.sheets)for(const t of i.tables){const o=e.sheets.find((e=>e.name===i.sheetName));o&&t.autoFilter&&(o.filterTables||(o.filterTables=[]),o.filterTables.push({range:t.ref}))}!function(e,t){var i,o,n,s;const r=um(e.styles),a=um(e.borders);for(let l of t.sheets)for(let t of l.tables){const c=e.sheets.find((e=>e.name===l.sheetName));if(!c)continue;const h=Hi(t.ref);for(let e=0;e<t.headerRowCount;e++)Jf(Yf,{...h,bottom:h.top+e},c.cells,r);for(let e=0;e<t.totalsRowCount;e++)Jf(Xf,{...h,top:h.bottom-e},c.cells,r);(null===(i=t.style)||void 0===i?void 0:i.showFirstColumn)&&Jf(Xf,{...h,right:h.left},c.cells,r),(null===(o=t.style)||void 0===o?void 0:o.showLastColumn)&&Jf(Xf,{...h,left:h.right},c.cells,r);for(let e=h.left;e<=h.right;e++)for(let i=h.top;i<=h.bottom;i++){const o=Zt(e,i),r=c.cells[o],l={left:e===h.left||(null===(n=t.style)||void 0===n?void 0:n.showColumnStripes)?Kf:void 0,right:e===h.right?Kf:void 0,top:i===h.top||(null===(s=t.style)||void 0===s?void 0:s.showRowStripes)||i>h.bottom-t.totalsRowCount?Kf:void 0,bottom:i===h.bottom?Kf:void 0},d=(null==r?void 0:r.border)?{...a[r.border],...l}:l;let u=a.findIndex((e=>ht(e,d)));-1===u&&(u=a.length,a.push(d)),r?r.border=u:c.cells[o]={border:u}}}e.styles=dm(r),e.borders=dm(a)}(e,t),function(e,t){for(let i of e){const e=t.find((e=>e.sheetName===i.name)).tables;for(let t of e){const e=t.name+"[";for(let o of so(Hi(t.ref))){const n=Zt(o.col,o.row),s=i.cells[n];if(s&&s.content&&s.content.startsWith("=")){let i;for(;-1!==(i=s.content.indexOf(e));){let o=s.content.slice(i+e.length),r=o.indexOf("]");o.startsWith("[")&&(r=o.indexOf("]",r+1),r=o.indexOf("]",r+1)),o=o.slice(0,r);const a=ev(o,t,n);s.content=s.content.slice(0,i)+a+s.content.slice(e.length+i+r+1)}}}}}}(e.sheets,t.sheets)}function Jf(e,t,i,o){for(let n=t.left;n<=t.right;n++)for(let s=t.top;s<=t.bottom;s++){const t=Zt(n,s),r=i[t],a=(null==r?void 0:r.style)?{...o[r.style],...e}:e;let l=o.findIndex((e=>ht(e,a)));-1===l&&(l=o.length,o.push(a)),r?r.style=l:i[t]={style:l}}}function ev(e,t,i){const o=e.split(","),n=Hi(t.ref),s={...n};let r=!0;if(1===o.length){const e=t.cols.findIndex((e=>e.name===o[0]));s.left=s.right=e+n.left,t.headerRowCount&&(s.top+=t.headerRowCount),t.totalsRowCount&&(s.bottom-=1)}else{switch(o[0].slice(1,o[0].length-1)){case"#All":s.top=t.headerRowCount?n.top+t.headerRowCount:n.top,s.bottom=n.bottom;break;case"#Data":s.top=t.headerRowCount?n.top+t.headerRowCount:n.top,s.bottom=t.totalsRowCount?n.bottom+1:n.bottom;break;case"#This Row":s.top=s.bottom=qt(i).row;break;case"#Headers":s.top=s.bottom=n.top,t.headerRowCount||(r=!1);break;case"#Totals":s.top=s.bottom=n.bottom,t.totalsRowCount||(r=!1)}const e=o[1].slice(1,o[1].length-1),a=t.cols.findIndex((t=>t.name===e));s.left=s.right=a+n.left}return r?s.top!==s.bottom?Wi(s):Zt(s.left,s.top):K}function tv(e,t,i){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:i}}function iv(e){return String(e).replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"")}function ov(e){return new yp(e.map((([e,t])=>`${e}="${iv(t)}"`)).join(" "))}function nv(e,t="text/xml"){const i=(new DOMParser).parseFromString(e.toString(),t),o=i.querySelector("parsererror");if(o){const t=o.innerHTML,i=parseInt(t.split(":")[0],10),n=e.toString().trim().split("\n"),s=n.slice(Math.max(i-3,0),Math.min(i+2,n.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${s}`)}return i}function sv(e,t){return av`
1399
1399
  <Override ContentType="${t}" PartName="${e}" />
1400
- `}function rv(e){return new yp(e.join("\n"))}function av(e,...t){let i=[e[0]];for(let o=0;o<t.length;o++){const n=t[o]instanceof yp?t[o]:iv(t[o]);i.push(n+e[o+1])}return new yp(rt(i))}function lv(e){return e.replace(/[a-z0-9]+:(?=[a-z0-9]+)/gi,"")}function cv(e){return e.replace(/([a-z0-9]+):(?=[a-z0-9]+)/gi,"$1\\:")}class hv{constructor(e){this.value=e}asString(){return gm(String(this.value))}asBool(){return Boolean(Number(this.value))}asNum(){return Number(this.value)}}class dv{constructor(e,t,i){this.currentFile=void 0,this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=i,this.areNamespaceIgnored=null!==(new DOMParser).parseFromString("<t:test xmlns:t='a'/>","text/xml").querySelector("test"),this.relationships={},e.rels&&this.extractRelationships(e.rels).map((e=>{this.relationships[e.id]=e}))}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:"Relationship"},(e=>({id:this.extractAttr(e,"Id",{required:!0}).asString(),target:this.extractAttr(e,"Target",{required:!0}).asString(),type:this.extractAttr(e,"Type",{required:!0}).asString()})))}getListOfFiles(){return Object.values(this.xlsxFileStructure).flat().filter(ot)}mapOnElements(e,t){var i;const o=[],n=this.currentFile;let s;if(e.children){const t=null===(i=this.querySelector(e.parent,e.query))||void 0===i?void 0:i.children;s=t||[]}else s=this.querySelectorAll(e.parent,e.query);if(s)for(let e of s)try{o.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=n,o}catchErrorOnElement(e,t){const i=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([i,e.message].join("\n"))}extractAttr(e,t,i){const o=e.attributes[t];o||this.handleMissingValue(e,`attribute "${t}"`,i);const n=(null==o?void 0:o.value)?o.value:null==i?void 0:i.default;return void 0===n?void 0:new hv(n)}extractTextContent(e,t){var i;if(void 0!==(null==t?void 0:t.default)&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const o="preserve"===(null===(i=null==e?void 0:e.attributes["xml:space"])||void 0===i?void 0:i.value);let n=null==e?void 0:e.textContent;return e&&null!==n||this.handleMissingValue(e,"text content",t),n&&(n=o?n:n.trim()),n?gm(n):null==t?void 0:t.default}extractChildAttr(e,t,i,o){var n;let s;s="number"==typeof t?e.children[t]:this.querySelector(e,t),s||this.handleMissingValue(e,"number"==typeof t?`child at index ${t}`:`child <${t}>`,o);const r=s?null===(n=this.extractAttr(s,i,o))||void 0===n?void 0:n.asString():null==o?void 0:o.default;return void 0!==r?new hv(r):void 0}extractChildTextContent(e,t,i){if(void 0!==(null==i?void 0:i.default)&&"string"!=typeof i.default)throw new Error("extractTextContent default value should be a string");let o=this.querySelector(e,t);return o||this.handleMissingValue(e,`child <${t}>`,i),o?this.extractTextContent(o,i):null==i?void 0:i.default}handleMissingValue(e,t,i){if(null==i?void 0:i.required){if(!(null==i?void 0:i.default))throw new Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`);this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${i.default}`)}}extractColor(e,t,i){var o,n,s,r,a;if(!e)return i?{rgb:i}:void 0;const l=null===(o=this.extractAttr(e,"theme"))||void 0===o?void 0:o.asString();let c;if(void 0!==l){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");c=this.getThemeColor(l,t.clrScheme)}else c=null===(n=this.extractAttr(e,"rgb"))||void 0===n?void 0:n.asString();return{rgb:c,auto:null===(s=this.extractAttr(e,"auto"))||void 0===s?void 0:s.asBool(),indexed:null===(r=this.extractAttr(e,"indexed"))||void 0===r?void 0:r.asNum(),tint:null===(a=this.extractAttr(e,"tint"))||void 0===a?void 0:a.asNum()}}getTargetXmlFile(e){if(!e)throw new Error("Undefined target file");let t=e.target;t=t.replace("../",""),t=t.replace("./","");const i=this.getListOfFiles().find((e=>e.file.fileName.endsWith(t)));if(!i||!i.file)throw new Error("Cannot find target file");return i}querySelector(e,t){return t=this.areNamespaceIgnored?lv(t):cv(t),e.querySelector(t)}querySelectorAll(e,t){return t=this.areNamespaceIgnored?lv(t):cv(t),e.querySelectorAll(t)}getThemeColor(e,t){switch(e){case"0":return"FFFFFF";case"1":return"000000";case"2":return t[3].value;case"3":return t[2].value;default:return t[e].value}}}class uv extends dv{getTheme(){return{clrScheme:this.mapOnElements({query:"a:clrScheme",parent:this.rootFile.file.xml,children:!0},(e=>({name:e.tagName,value:this.extractChildAttr(e,0,"val",{required:!0,default:Ip}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:Ip}).asString()})))}}getSharedStrings(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"si"},(e=>"t"===e.children[0].tagName?this.extractTextContent(e)||"":this.mapOnElements({parent:e,query:"t"},(e=>this.extractTextContent(e)||"")).join("")))}}class gv extends dv{constructor(e,t,i,o){super(e,t,i),this.theme=o}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},(e=>{var t;return{sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),pivot:null===(t=this.extractAttr(e,"pivot"))||void 0===t?void 0:t.asBool(),cfRules:this.extractCFRules(e,this.theme)}}));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:"extLst x14:conditionalFormatting"},(e=>{var t;return{sqref:this.extractChildTextContent(e,"xm:sqref",{required:!0}).split(" "),pivot:null===(t=this.extractAttr(e,"xm:pivot"))||void 0===t?void 0:t.asBool(),cfRules:this.extractCFRules(e,this.theme)}}))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:"cfRule, x14:cfRule"},(e=>{var i,o,n,s,r,a,l,c,h,d,u;const g=this.extractAttr(e,"type",{required:!0}).asString();if("dataBar"===g)throw new Error("Databars conditional formats are not supported.");return{type:g,priority:this.extractAttr(e,"priority",{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:null===(i=this.extractAttr(e,"dxfId"))||void 0===i?void 0:i.asNum(),stopIfTrue:null===(o=this.extractAttr(e,"stopIfTrue"))||void 0===o?void 0:o.asBool(),aboveAverage:null===(n=this.extractAttr(e,"aboveAverage"))||void 0===n?void 0:n.asBool(),percent:null===(s=this.extractAttr(e,"percent"))||void 0===s?void 0:s.asBool(),bottom:null===(r=this.extractAttr(e,"bottom"))||void 0===r?void 0:r.asBool(),operator:null===(a=this.extractAttr(e,"operator"))||void 0===a?void 0:a.asString(),text:null===(l=this.extractAttr(e,"text"))||void 0===l?void 0:l.asString(),timePeriod:null===(c=this.extractAttr(e,"timePeriod"))||void 0===c?void 0:c.asString(),rank:null===(h=this.extractAttr(e,"rank"))||void 0===h?void 0:h.asNum(),stdDev:null===(d=this.extractAttr(e,"stdDev"))||void 0===d?void 0:d.asNum(),equalAverage:null===(u=this.extractAttr(e,"equalAverage"))||void 0===u?void 0:u.asBool()}}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:"formula"},(e=>this.extractTextContent(e,{required:!0})))}extractCfColorScale(e,t){const i=this.querySelector(e,"colorScale");if(i)return{colors:this.mapOnElements({parent:i,query:"color"},(e=>this.extractColor(e,t,"ffffff"))),cfvos:this.extractCFVos(i)}}extractCfIconSet(e){var t,i;const o=this.querySelector(e,"iconSet, x14:iconSet");if(o)return{iconSet:this.extractAttr(o,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(o,"showValue",{default:!0}).asBool(),percent:this.extractAttr(o,"percent",{default:!0}).asBool(),reverse:null===(t=this.extractAttr(o,"reverse"))||void 0===t?void 0:t.asBool(),custom:null===(i=this.extractAttr(o,"custom"))||void 0===i?void 0:i.asBool(),cfvos:this.extractCFVos(o),cfIcons:this.extractCfIcons(o)}}extractCfIcons(e){const t=this.mapOnElements({parent:e,query:"cfIcon, x14:cfIcon"},(e=>({iconSet:this.extractAttr(e,"iconSet",{required:!0}).asString(),iconId:this.extractAttr(e,"iconId",{required:!0}).asNum()})));return 0===t.length?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:"cfvo, x14:cfvo"},(e=>{var t,i;return{type:this.extractAttr(e,"type",{required:!0}).asString(),gte:null===(t=this.extractAttr(e,"gte",{default:!0}))||void 0===t?void 0:t.asBool(),value:e.attributes.val?null===(i=this.extractAttr(e,"val"))||void 0===i?void 0:i.asString():this.extractChildTextContent(e,"f, xm:f")}}))}}class pv extends dv{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!om[t])throw new Error(`Unsupported chart type ${t}`);const i=this.mapOnElements({parent:e,query:"c:title a:t"},(e=>e.textContent||"")).join(""),o=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:i,type:om[t],dataSets:this.extractChartDatasets(this.querySelector(e,`c:${t}`)),backgroundColor:this.extractChildAttr(e,"c:chartSpace > c:spPr a:srgbClr","val",{default:"ffffff"}).asString(),verticalAxisPosition:"r"===this.extractChildAttr(e,"c:valAx > c:axPos","val",{default:"l"}).asString()?"right":"left",legendPosition:im[this.extractChildAttr(e,"c:legendPos","val",{default:"b"}).asString()],stacked:"stacked"===o,fontColor:"000000"}}))[0]}extractChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},(e=>({label:this.extractChildTextContent(e,"c:cat c:f"),range:this.extractChildTextContent(e,"c:val c:f",{required:!0})})))}getChartType(e){const t=this.querySelector(e,"c:plotArea");if(!t)throw new Error("Missing plot area in the chart definition.");for(let e of t.children){const t=lv(e.tagName);if(xp.some((e=>e===t)))return t}throw new Error("Unknown chart type")}}class mv extends dv{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{if("twoCellAnchor"!==lv(e.tagName))throw new Error("Only twoCellAnchor are supported for xlsx drawings.");const t=this.querySelector(e,"c:chart");if(!t)throw new Error("Only chart figures are currently supported.");return{anchors:[this.extractFigureAnchor("xdr:from",e),this.extractFigureAnchor("xdr:to",e)],data:this.extractChart(t)}}))}extractFigureAnchor(e,t){const i=this.querySelector(t,e);if(!i)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(i,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(i,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(i,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(i,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),i=this.getTargetXmlFile(this.relationships[t]),o=new pv(i,this.xlsxFileStructure,this.warningManager).extractChart();if(!o)throw new Error("Unable to extract chart definition");return o}}class fv extends dv{getPivotTable(){return this.mapOnElements({query:":root",parent:this.rootFile.file.xml},(e=>({displayName:this.extractAttr(e,"name",{required:!0}).asString(),id:this.extractAttr(e,"name",{required:!0}).asString(),ref:this.extractChildAttr(e,"location","ref",{required:!0}).asString(),headerRowCount:this.extractChildAttr(e,"location","firstDataRow",{default:0}).asNum(),totalsRowCount:1,cols:[],style:{showFirstColumn:!0,showRowStripes:!0}})))[0]}}class vv extends dv{getTable(){return this.mapOnElements({query:"table",parent:this.rootFile.file.xml},(e=>{var t;return{displayName:this.extractAttr(e,"displayName",{required:!0}).asString(),name:null===(t=this.extractAttr(e,"name"))||void 0===t?void 0:t.asString(),id:this.extractAttr(e,"id",{required:!0}).asString(),ref:this.extractAttr(e,"ref",{required:!0}).asString(),headerRowCount:this.extractAttr(e,"headerRowCount",{default:1}).asNum(),totalsRowCount:this.extractAttr(e,"totalsRowCount",{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)}}))[0]}extractTableCols(e){return this.mapOnElements({query:"tableColumn",parent:e},(e=>({id:this.extractAttr(e,"id",{required:!0}).asString(),name:this.extractAttr(e,"name",{required:!0}).asString(),colFormula:this.extractChildTextContent(e,"calculatedColumnFormula")})))}extractTableStyleInfo(e){return this.mapOnElements({query:"tableStyleInfo",parent:e},(e=>{var t,i,o,n,s;return{name:null===(t=this.extractAttr(e,"name"))||void 0===t?void 0:t.asString(),showFirstColumn:null===(i=this.extractAttr(e,"showFirstColumn"))||void 0===i?void 0:i.asBool(),showLastColumn:null===(o=this.extractAttr(e,"showLastColumn"))||void 0===o?void 0:o.asBool(),showRowStripes:null===(n=this.extractAttr(e,"showRowStripes"))||void 0===n?void 0:n.asBool(),showColumnStripes:null===(s=this.extractAttr(e,"showColumnStripes"))||void 0===s?void 0:s.asBool()}}))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:"autoFilter",parent:e},(e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,"ref",{required:!0}).asString()})))[0]}extractFilterColumns(e){return this.mapOnElements({query:"tableColumn",parent:e},(t=>({colId:this.extractAttr(e,"colId",{required:!0}).asNum(),hiddenButton:this.extractAttr(e,"hiddenButton",{default:!1}).asBool(),filters:this.extractSimpleFilter(t)})))}extractSimpleFilter(e){return this.mapOnElements({query:"filter",parent:e},(e=>({val:this.extractAttr(e,"val",{required:!0}).asString()})))}}class bv extends dv{constructor(e,t,i,o){super(e,t,i),this.theme=o}getSheet(){return this.mapOnElements({query:"worksheet",parent:this.rootFile.file.xml},(e=>{const t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:[...this.extractTables(e),...this.extractPivotTables()],isVisible:"visible"===t.state}}))[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:"sheetView"},(e=>{const t=this.querySelector(e,"pane");return{tabSelected:this.extractAttr(e,"tabSelected",{default:!1}).asBool(),showFormulas:this.extractAttr(e,"showFormulas",{default:!1}).asBool(),showGridLines:this.extractAttr(e,"showGridLines",{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,"showRowColHeaders",{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,"xSplit",{default:0}).asNum():0,ySplit:t?this.extractAttr(t,"ySplit",{default:0}).asNum():0}}}))}extractSheetName(){const e=hm(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id;for(let e of this.querySelectorAll(this.xlsxFileStructure.workbook.file.xml,"sheet"))if(e.attributes["r:id"].value===t)return e.attributes.name.value;throw new Error("Missing sheet name")}getSheetWorkbookInfo(){const e=hm(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id,i=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:"sheet"},(e=>({relationshipId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetId:this.extractAttr(e,"sheetId",{required:!0}).asString(),sheetName:this.extractAttr(e,"name",{required:!0}).asString(),state:this.extractAttr(e,"state",{default:"visible"}).asString()}))).find((e=>e.relationshipId===t));if(!i)throw new Error("Cannot find corresponding workbook sheet");return i}extractConditionalFormats(){return new gv(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},(e=>{var t;const i=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),o=this.getTargetXmlFile(this.relationships[i]);return new mv(o,this.xlsxFileStructure,this.warningManager).extractFigures()}))[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},(e=>{var t;const i=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),o=this.getTargetXmlFile(this.relationships[i]);return new vv(o,this.xlsxFileStructure,this.warningManager).getTable()}))}extractPivotTables(){try{return Object.values(this.relationships).filter((e=>e.type.endsWith("pivotTable"))).map((e=>{const t=this.getTargetXmlFile(e);return new fv(t,this.xlsxFileStructure,this.warningManager).getPivotTable()}))}catch(e){return this.catchErrorOnElement(e),[]}}extractMerges(e){return this.mapOnElements({parent:e,query:"mergeCell"},(e=>this.extractAttr(e,"ref",{required:!0}).asString()))}extractSheetFormat(e){const t=this.querySelector(e,"sheetFormatPr");if(t)return{defaultColWidth:this.extractAttr(t,"defaultColWidth",{default:kp.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:Lp.toString()}).asNum()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},(e=>{var t,i,o,n,s,r,a;return{width:null===(t=this.extractAttr(e,"width"))||void 0===t?void 0:t.asNum(),customWidth:null===(i=this.extractAttr(e,"customWidth"))||void 0===i?void 0:i.asBool(),bestFit:null===(o=this.extractAttr(e,"bestFit"))||void 0===o?void 0:o.asBool(),hidden:null===(n=this.extractAttr(e,"hidden"))||void 0===n?void 0:n.asBool(),min:null===(s=this.extractAttr(e,"min",{required:!0}))||void 0===s?void 0:s.asNum(),max:null===(r=this.extractAttr(e,"max",{required:!0}))||void 0===r?void 0:r.asNum(),styleIndex:null===(a=this.extractAttr(e,"style"))||void 0===a?void 0:a.asNum()}}))}extractRows(e){return this.mapOnElements({parent:e,query:"sheetData row"},(e=>{var t,i,o,n,s;return{index:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asNum(),cells:this.extractCells(e),height:null===(i=this.extractAttr(e,"ht"))||void 0===i?void 0:i.asNum(),customHeight:null===(o=this.extractAttr(e,"customHeight"))||void 0===o?void 0:o.asBool(),hidden:null===(n=this.extractAttr(e,"hidden"))||void 0===n?void 0:n.asBool(),styleIndex:null===(s=this.extractAttr(e,"s"))||void 0===s?void 0:s.asNum()}}))}extractCells(e){return this.mapOnElements({parent:e,query:"c"},(e=>{var t,i,o;return{xc:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asString(),styleIndex:null===(i=this.extractAttr(e,"s"))||void 0===i?void 0:i.asNum(),type:Xp[null===(o=this.extractAttr(e,"t",{default:"n"}))||void 0===o?void 0:o.asString()],value:this.extractChildTextContent(e,"v"),formula:this.extractCellFormula(e)}}))}extractCellFormula(e){var t,i;const o=this.querySelector(e,"f");if(o)return{content:this.extractTextContent(o),sharedIndex:null===(t=this.extractAttr(o,"si"))||void 0===t?void 0:t.asNum(),ref:null===(i=this.extractAttr(o,"ref"))||void 0===i?void 0:i.asString()}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},(e=>{var t,i,o,n;const s=null===(t=this.extractAttr(e,"r:id"))||void 0===t?void 0:t.asString();return{xc:null===(i=this.extractAttr(e,"ref",{required:!0}))||void 0===i?void 0:i.asString(),location:null===(o=this.extractAttr(e,"location"))||void 0===o?void 0:o.asString(),display:null===(n=this.extractAttr(e,"display"))||void 0===n?void 0:n.asString(),relTarget:s?this.relationships[s].target:void 0}}))}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),i={};for(let e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),o=this.extractTextContent(e,{required:!0});i[t]=o}const o=[];for(let e=0;e<Object.keys(i).length;e++)i[e]?o.push(i[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),o.push(""));return o}}class Cv extends dv{constructor(e,t,i){super(e.styles,e,t),this.theme=i}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},(e=>this.extractNumFormats(e)))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},(e=>this.extractFont(e)))}extractFont(e){var t,i,o,n;const s=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),r=this.extractChildAttr(e,"sz","val",{default:q.toString()}).asNum(),a=this.extractColor(this.querySelector(e,"color"),this.theme),l=this.querySelector(e,"i")||void 0,c=l&&"0"!==(null===(t=l.attributes.val)||void 0===t?void 0:t.value),h=this.querySelector(e,"b")||void 0,d=h&&"0"!==(null===(i=h.attributes.val)||void 0===i?void 0:i.value),u=this.querySelector(e,"strike")||void 0,g=u&&"0"!==(null===(o=u.attributes.val)||void 0===o?void 0:o.value),p=this.querySelector(e,"u")||void 0;return{name:s,size:r,color:a,italic:c,bold:d,underline:p&&"none"!==(null===(n=p.attributes.val)||void 0===n?void 0:n.value),strike:g}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},(e=>this.extractFill(e)))}extractFill(e){var t;const i=e.children[0];return"patternFill"===i.tagName?{patternType:null===(t=i.attributes.patternType)||void 0===t?void 0:t.value,bgColor:this.extractColor(this.querySelector(i,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(i,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(i,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},(e=>this.extractBorder(e)))}extractBorder(e){var t,i;const o={left:this.extractSingleBorder(e,"left",this.theme),right:this.extractSingleBorder(e,"right",this.theme),top:this.extractSingleBorder(e,"top",this.theme),bottom:this.extractSingleBorder(e,"bottom",this.theme),diagonal:this.extractSingleBorder(e,"diagonal",this.theme)};return o.diagonal&&(o.diagonalUp=null===(t=this.extractAttr(e,"diagonalUp"))||void 0===t?void 0:t.asBool(),o.diagonalDown=null===(i=this.extractAttr(e,"diagonalDown"))||void 0===i?void 0:i.asBool()),o}extractSingleBorder(e,t,i){const o=this.querySelector(e,t);if(o&&o.attributes.style)return{style:this.extractAttr(o,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(o.children[0],i,"000000")}}extractAlignment(e){var t,i,o,n,s,r,a;return{horizontal:this.extractAttr(e,"horizontal",{default:"general"}).asString(),vertical:this.extractAttr(e,"vertical",{default:"center"}).asString(),textRotation:null===(t=this.extractAttr(e,"textRotation"))||void 0===t?void 0:t.asNum(),wrapText:null===(i=this.extractAttr(e,"wrapText"))||void 0===i?void 0:i.asBool(),indent:null===(o=this.extractAttr(e,"indent"))||void 0===o?void 0:o.asNum(),relativeIndent:null===(n=this.extractAttr(e,"relativeIndent"))||void 0===n?void 0:n.asNum(),justifyLastLine:null===(s=this.extractAttr(e,"justifyLastLine"))||void 0===s?void 0:s.asBool(),shrinkToFit:null===(r=this.extractAttr(e,"shrinkToFit"))||void 0===r?void 0:r.asBool(),readingOrder:null===(a=this.extractAttr(e,"readingOrder"))||void 0===a?void 0:a.asNum()}}getDxfs(){return this.mapOnElements({query:"dxf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"font"),i=this.querySelector(e,"fill"),o=this.querySelector(e,"border"),n=this.querySelector(e,"numFmt"),s=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:i?this.extractFill(i):void 0,numFmt:n?this.extractNumFormats(n):void 0,alignment:s?this.extractAlignment(s):void 0,border:o?this.extractBorder(o):void 0}}))}getStyles(){return this.mapOnElements({query:"cellXfs xf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"alignment");return{fontId:this.extractAttr(e,"fontId",{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,"fillId",{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,"borderId",{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,"numFmtId",{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}}))}}class Sv extends dv{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"externalBook"},(e=>({rId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:"sheetName"},(e=>this.extractAttr(e,"val",{required:!0}).asString())),datasets:this.extractExternalSheetData(e)})))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:"sheetData"},(e=>{const t=this.mapOnElements({parent:e,query:"cell"},(e=>({xc:this.extractAttr(e,"r",{required:!0}).asString(),value:this.extractChildTextContent(e,"v",{required:!0})}))),i={};for(let e of t)i[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:i}}))}}function Ev(e,t){const i=function(e,t){const i=t[Hp],o=i.querySelectorAll(`Override[ContentType="${e}"]`),n=[];for(let e of o){const t=null==e?void 0:e.attributes.PartName.value;n.push(t.substring(1))}return n}(e,t);return function(e,t){const i=[];for(let o of e){const e=wv(o,t);i.push({file:{fileName:o,xml:t[o]},rels:e?{fileName:e,xml:t[e]}:void 0})}return i}(i,t)}function wv(e,t){if(e===Hp)return"_rels/.rels";let i="";const o=e.split("/");for(let e=0;e<o.length-1;e++)i+=o[e]+"/";return i+="_rels/",i+=o[o.length-1]+".rels",t[i]||(i=void 0),i}class yv{constructor(e){this.warningManager=new Wp,this.xmls={};for(let t of Object.keys(e))(t.endsWith(".xml")||t.endsWith(".rels"))&&(this.xmls[t]=nv(new yp(e[t])))}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new uv(e.theme,e,this.warningManager).getTheme():void 0,i=e.sharedStrings?new uv(e.sharedStrings,e,this.warningManager).getSharedStrings():[],o=e.sheets.sort(((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0}))).map((i=>new bv(i,e,this.warningManager,t).getSheet())),n=e.externalLinks.map((t=>new Sv(t,e,this.warningManager).getExternalBook())),s=new Cv(e,this.warningManager,t);return{fonts:s.getFonts(),fills:s.getFills(),borders:s.getBorders(),dxfs:s.getDxfs(),numFmts:s.getNumFormats(),styles:s.getStyles(),sheets:o,sharedStrings:i,externalBooks:n}}buildXlsxFileStructure(){const e={sheets:Ev(Op.sheet,this.xmls),workbook:Ev(Op.workbook,this.xmls)[0],styles:Ev(Op.styles,this.xmls)[0],sharedStrings:Ev(Op.sharedStrings,this.xmls)[0],theme:Ev(Op.themes,this.xmls)[0],charts:Ev(Op.chart,this.xmls),figures:Ev(Op.drawing,this.xmls),tables:Ev(Op.table,this.xmls),pivots:Ev(Op.pivot,this.xmls),externalLinks:Ev(Op.externalLink,this.xmls)};if(!e.workbook.rels)throw Error(s("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:12,sheets:Wf(e,this.warningManager),styles:bm(e,this.warningManager),formats:Sm(e,this.warningManager),borders:fm(e,this.warningManager),entities:{},revisionId:Q};return Qf(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=ut(e.styles[t])})),t}}function xv(e){const t=uf(e);let i=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&Nt.test(e.value)){const t=e.value.trim();return i.includes(t)||i.push(t),`${ae}${i.indexOf(t)}${ae}`}return e.value}))),dependencies:i}}const Iv=12,Rv="Sheet1";function Tv(e,t){if(!e)return _v();if(e["[Content_Types].xml"]){const i=new yv(e);if(e=i.convertXlsx(),t)for(let e of i.warningManager.warnings.sort())console.warn(e)}return"version"in(e=Fe(e))&&e.version<Iv&&(e=function(e){for(let t=Av.findIndex((t=>t.from===e.version));t<Av.length;t++)e=Av[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,i=new zi;for(const o of e.sheets||[])for(const e of o.figures||[])t.has(e.id)&&(e.id+=i.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(_v(),e,{version:Iv}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(Nv(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(Nv(Rv,"Sheet1"));return e}(e),e}(e),e}const Av=[{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 i=t.cells[e];i.content&&i.content.startsWith("=")&&(i.formula=xv(i.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:i,...o}=t.figures[e].data,n=[];for(let e of i)if(e.labelCell){const t=Hi(e.dataRange),i=e.labelCell+":"+Zt(t.right,t.bottom);n.push(i)}else n.push(e.dataRange);o.dataSetsHaveTitle=Boolean(i[0].labelCell),o.dataSets=n,t.figures[e].data=o}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){var t;const i=[],o=new RegExp(re,"g");for(let n of e.sheets||[]){if(!n.name)continue;const e=n.name,s=e.replace(o,"_");let r=1,a=s;for(;i.includes(a);)a=`${s}${r}`,r++;n.name=a,i.push(a);const l=t=>{if(void 0===t)return t;let i=t.replace(e,a),o=t;for(;o!==i;)o=i,i=o.replace(e,a);return o};for(let e in n.cells){const t=n.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(l))}for(let e of n.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(l),i=l(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:i}}for(let e of n.conditionalFormats||[]){e.ranges=e.ranges.map(l);for(const i of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===(null===(t=e.rule[i])||void 0===t?void 0:t.type)&&(e.rule[i].value=l(e.rule[i].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=w,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stacked=!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 i=t.cells[e];if(i.formula){let{text:e,dependencies:t}=i.formula;for(let[i,o]of Object.entries(t)){const t=`\\${ae}${i}\\${ae}`;e=e.replace(new RegExp(t,"g"),o)}i.content=e,delete i.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let i of e.sheets||[])for(let e in i.cells||[]){const o=i.cells[e];o.format&&(o.format=st(o.format,t))}return e.formats=t,e}},{description:"Add isVisible to sheets",from:11,to:12,applyMigration(e){for(let t of e.sheets||[])t.isVisible=!0;return e}}];function Mv(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const i=[],o=[],n=e=>{if("CREATE_SHEET"===e.type)i.push(e.sheetId);else if("sheetId"in e&&!i.includes(e.sheetId))return{...e,sheetId:Rv};return e};for(const e of t)"REMOTE_REVISION"===e.type?o.push({...e,commands:e.commands.map(n)}):o.push(e);return o}(e,t),t=Ov(t,"SORT_CELLS"),t=function(e,t){var i;const o=[],n={};for(const t of e.sheets||[])null===(i=t.figures)||void 0===i||i.forEach((e=>{"chart"===e.tag&&(n[e.id]=e.data)}));for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const i of e.commands){let e=i;switch(i.type){case"CREATE_CHART":n[i.id]=i.definition;break;case"UPDATE_CHART":if(!n[i.id]){console.log(`Fix chart definition: chart with id ${i.id} not found.`);continue}const t={...n[i.id],...i.definition};e={...i,definition:t},n[i.id]=t}t.push(e)}o.push({...e,commands:t})}else o.push(e);return o}(e,t=Ov(t,"SET_DECIMAL")),t}function Ov(e,t){const i=[];for(const o of e)"REMOTE_REVISION"===o.type?i.push({...o,commands:o.commands.filter((e=>e.type!==t))}):i.push(o);return i}function Nv(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[],filterTables:[],isVisible:!0}}function _v(e="Sheet1"){return{version:Iv,sheets:[Nv(Rv,e)],entities:{},styles:{},formats:{},borders:{},revisionId:Q,uniqueFigureIds:!0}}function Fv(e,t){return{...Nv(e,t),charts:[],images:[]}}class Dv{constructor(e,t){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t}exportForExcel(e){}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 i of e){let e=i.call(this,t);Array.isArray(e)||(e=[e]);const o=e.filter((e=>0!==e));if(o.length)return o}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}Dv.getters=[];class kv extends Dv{constructor({getters:e,stateObserver:t,range:i,dispatch:o,uuidGenerator:n}){super(t,o),this.range=i,i.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=n}import(e){}export(e){}adaptRanges(e,t){}garbageCollectExternalResources(){}}class Lv extends kv{constructor(){super(...arguments),this.borders={}}allowDispatch(e){return"SET_BORDER"===e.type?this.checkBordersUnchanged(e):0}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":const t=this.borders[e.sheetId];if(t){const i=t.slice().map((e=>null==e?void 0:e.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,i)}break;case"DELETE_SHEET":const i={...this.borders};delete i[e.sheetId],this.history.update("borders",i);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_FORMATTING":if(e.border){const t=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));this.setBorders(e.sheetId,t,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){let t,i;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,i=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,i=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,i)}handleAddRows(e){let t,i;"before"===e.position?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,i=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,i=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,i)}getCellBorder({sheetId:e,col:t,row:i}){var o,n,s,r,a,l,c,h,d,u,g,p;const m={top:null===(s=null===(n=null===(o=this.borders[e])||void 0===o?void 0:o[t])||void 0===n?void 0:n[i])||void 0===s?void 0:s.horizontal,bottom:null===(l=null===(a=null===(r=this.borders[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[i+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[i])||void 0===d?void 0:d.vertical,right:null===(p=null===(g=null===(u=this.borders[e])||void 0===u?void 0:u[t+1])||void 0===g?void 0:g[i])||void 0===p?void 0:p.vertical};return m.bottom||m.left||m.right||m.top?m:null}ensureColumnBorderContinuity(e,t,i){const o=$e(t+1,i);for(let n=0;n<this.getters.getNumberRows(e);n++){const s=this.getCellBorder({sheetId:e,col:t,row:n}),r=this.getCellBorder({sheetId:e,col:i,row:n});if(s&&r){const t=this.getCommonSides(s,r);for(let i of o)this.addBorder(e,i,n,t)}}}ensureRowBorderContinuity(e,t,i){const o=$e(t+1,i);for(let n=0;n<this.getters.getNumberCols(e);n++){const s=this.getCellBorder({sheetId:e,col:n,row:t}),r=this.getCellBorder({sheetId:e,col:n,row:i});if(s&&r){const t=this.getCommonSides(s,r);for(let i of o)this.addBorder(e,n,i,t)}}}getCommonSides(e,t){const i={};for(let o of["top","bottom","left","right"])e[o]&&e[o]===t[o]&&(i[o]=e[o]);return i}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsRange(e){return this.borders[e]?$e(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,i,{moveFirstLeftBorder:o}={}){this.borders[e]&&(i<0&&this.moveBordersOfColumn(e,t,i,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>i<0?e-t:t-e)).forEach((n=>{(n===t&&o||n!==t)&&this.moveBordersOfColumn(e,n,i,"vertical"),this.moveBordersOfColumn(e,n,i,"horizontal")})))}shiftBordersVertically(e,t,i,{moveFirstTopBorder:o}={}){this.borders[e]&&(i<0&&this.moveBordersOfRow(e,t,i,"horizontal",{destructive:!1}),this.getRowsRange(e).filter((e=>e>=t)).sort(((e,t)=>i<0?e-t:t-e)).forEach((n=>{(n===t&&o||n!==t)&&this.moveBordersOfRow(e,n,i,"horizontal"),this.moveBordersOfRow(e,n,i,"vertical")})))}moveBordersOfRow(e,t,i,o,{destructive:n}={destructive:!0}){const s=this.borders[e];s&&this.getColumnsWithBorders(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=s[r])||void 0===a?void 0:a[t+i])||void 0===l?void 0:l[o],u=null===(h=null===(c=s[r])||void 0===c?void 0:c[t])||void 0===h?void 0:h[o];this.history.update("borders",e,r,t+i,o,n?u:u||d),this.history.update("borders",e,r,t,o,void 0)}))}moveBordersOfColumn(e,t,i,o,{destructive:n}={destructive:!0}){const s=this.borders[e];s&&this.getRowsRange(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=s[t+i])||void 0===a?void 0:a[r])||void 0===l?void 0:l[o],u=null===(h=null===(c=s[t])||void 0===c?void 0:c[r])||void 0===h?void 0:h[o];this.history.update("borders",e,t+i,r,o,n?u:u||d),this.history.update("borders",e,t,r,o,void 0)}))}setBorder(e,t,i,o,n=!0){var s,r,a,l,c,h,d,u,g,p,m,f,v,b,C,S;!n&&(null===(l=null===(a=null===(r=null===(s=this.borders)||void 0===s?void 0:s[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[i])||void 0===l?void 0:l.vertical)||this.history.update("borders",e,t,i,"vertical",null==o?void 0:o.left),!n&&(null===(u=null===(d=null===(h=null===(c=this.borders)||void 0===c?void 0:c[e])||void 0===h?void 0:h[t])||void 0===d?void 0:d[i])||void 0===u?void 0:u.horizontal)||this.history.update("borders",e,t,i,"horizontal",null==o?void 0:o.top),!n&&(null===(f=null===(m=null===(p=null===(g=this.borders)||void 0===g?void 0:g[e])||void 0===p?void 0:p[t+1])||void 0===m?void 0:m[i])||void 0===f?void 0:f.vertical)||this.history.update("borders",e,t+1,i,"vertical",null==o?void 0:o.right),!n&&(null===(S=null===(C=null===(b=null===(v=this.borders)||void 0===v?void 0:v[e])||void 0===b?void 0:b[t])||void 0===C?void 0:C[i+1])||void 0===S?void 0:S.horizontal)||this.history.update("borders",e,t,i+1,"horizontal",null==o?void 0:o.bottom)}clearBorders(e,t){for(let i of t){for(let t=i.top;t<=i.bottom;t++){this.history.update("borders",e,i.right+1,t,"vertical",void 0);for(let o=i.left;o<=i.right;o++)this.history.update("borders",e,o,t,void 0)}for(let t=i.left;t<=i.right;t++)this.history.update("borders",e,t,i.bottom+1,"horizontal",void 0)}}addBorder(e,t,i,o){this.setBorder(e,t,i,{...this.getCellBorder({sheetId:e,col:t,row:i}),...o})}setBorders(e,t,i){if("clear"===i)return this.clearBorders(e,t);for(let o of t){if("h"===i||"hv"===i||"all"===i)for(let t=o.top+1;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++)this.addBorder(e,i,t,{top:j});if("v"===i||"hv"===i||"all"===i)for(let t=o.top;t<=o.bottom;t++)for(let i=o.left+1;i<=o.right;i++)this.addBorder(e,i,t,{left:j});if("left"===i||"all"===i||"external"===i)for(let t=o.top;t<=o.bottom;t++)this.addBorder(e,o.left,t,{left:j});if("right"===i||"all"===i||"external"===i)for(let t=o.top;t<=o.bottom;t++)this.addBorder(e,o.right+1,t,{left:j});if("top"===i||"all"===i||"external"===i)for(let t=o.left;t<=o.right;t++)this.addBorder(e,t,o.top,{top:j});if("bottom"===i||"all"===i||"external"===i)for(let t=o.left;t<=o.right;t++)this.addBorder(e,t,o.bottom+1,{top:j})}}addBordersToMerge(e,t){const{left:i,right:o,top:n,bottom:s}=t,r=this.getCellBorder({sheetId:e,col:i,row:n}),a=this.getCellBorder({sheetId:e,col:o,row:s});this.clearBorders(e,[t]),(null==r?void 0:r.top)&&this.setBorders(e,[{...t,bottom:n}],"top"),(null==r?void 0:r.left)&&this.setBorders(e,[{...t,right:i}],"left"),((null==a?void 0:a.bottom)||(null==r?void 0:r.bottom))&&this.setBorders(e,[{...t,top:s}],"bottom"),((null==a?void 0:a.right)||(null==r?void 0:r.right))&&this.setBorders(e,[{...t,left:o}],"right")}checkBordersUnchanged(e){var t,i,o,n;const s=this.getCellBorder(e),r=!((null===(t=e.border)||void 0===t?void 0:t.bottom)||(null===(i=e.border)||void 0===i?void 0:i.left)||(null===(o=e.border)||void 0===o?void 0:o.right)||(null===(n=e.border)||void 0===n?void 0:n.top));return!s&&r||ht(s,e.border)?88:0}import(e){if(e.borders)for(let t of e.sheets)for(let[i,o]of Object.entries(t.cells))if(null==o?void 0:o.border){const n=e.borders[o.border],{col:s,row:r}=qt(i);this.setBorder(t.id,s,r,n,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Hi(e))}export(e){let t=0;const i={};function o(e){for(let[t,o]of Object.entries(i))if(ht(o,e))return parseInt(t,10);return i[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let i=0;i<t.rowNumber;i++){const n=this.getCellBorder({sheetId:t.id,col:e,row:i});if(n){const s=Zt(e,i),r=t.cells[s],a=o(n);r?r.border=a:t.cells[s]={border:a}}}e.borders=i}exportForExcel(e){this.export(e)}}Lv.getters=["getCellBorder"];class Pv extends kv{constructor(){super(...arguments),this.nextId=1,this.cells={}}adaptRanges(e,t){for(const i of Object.keys(this.cells))for(const o of Object.values(this.cells[i]||{}))if(o.isFormula)for(const n of o.dependencies)if(!t||n.sheetId===t){const t=e(n);"NONE"!==t.changeType&&this.history.update("cells",i,o.id,"dependencies",o.dependencies.indexOf(n),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":return this.checkCellOutOfSheet(e);case"CLEAR_CELL":return this.checkValidations(e,this.chainValidations(this.checkCellOutOfSheet,this.checkUselessClearCell));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.clearFormatting(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case"UPDATE_CELL":this.updateCell(e.sheetId,e.col,e.row,e);break;case"CLEAR_CELL":this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col,row:e.row,content:"",style:null,format:""})}}setFormatter(e,t,i){for(let o of t)for(let t=o.top;t<=o.bottom;t++)for(let n=o.left;n<=o.right;n++)this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,format:i})}clearFormatting(e,t){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:null,format:""})}handleAddColumnsRows(e,t){let i,o;"before"===e.position?(i=$e(e.base,e.base+e.quantity),o=e.base+e.quantity):(i=$e(e.base+1,e.base+e.quantity+1),o=e.base),t(e.sheetId,o,i)}import(e){for(let t of e.sheets)for(let i in t.cells){const o=t.cells[i],{col:n,row:s}=qt(i);if((null==o?void 0:o.content)||(null==o?void 0:o.format)||(null==o?void 0:o.style)){const i=this.importCell(t.id,o,e.styles,e.formats);this.history.update("cells",t.id,i.id,i),this.dispatch("UPDATE_CELL_POSITION",{cellId:i.id,col:n,row:s,sheetId:t.id})}}}export(e){const t={},i={};for(let o of e.sheets){const e={},n=Object.keys(this.cells[o.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const o of n){const n=this.getters.getCell(o);e[Zt(o.col,o.row)]={style:n.style?st(n.style,t):void 0,format:n.format?st(n.format,i):void 0,content:n.content||void 0}}o.cells=e}e.styles=t,e.formats=i}importCell(e,t,i,o){const n=t.style&&i[t.style]||void 0,s=t.format&&o[t.format]||void 0,r=this.getNextUid();return this.createCell(r,(null==t?void 0:t.content)||"",s,n,e)}exportForExcel(e){this.export(e)}getCells(e){return this.cells[e]||{}}getCellById(e){const t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}buildFormulaContent(e,t,i){const o=i||t.dependencies;let n=0;return rt(t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=o[n++];return this.getters.getRangeString(t,e)}return t.value})))}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t)}getCellStyle(e){var t;return(null===(t=this.getters.getCell(e))||void 0===t?void 0:t.style)||{}}zoneToXC(e,t,i=[{colFixed:!1,rowFixed:!1}]){const o=Zt((t=this.getters.expandZone(e,t)).left,t.top,i[0]),n=Zt(t.right,t.bottom,i.length>1?i[1]:i[0]),s=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),r=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=s.col===r.col&&s.row===r.row;return o==n||a?o:o+":"+n}setStyle(e,t,i){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let n=o.top;n<=o.bottom;n++){const o=this.getters.getCell({sheetId:e,col:t,row:n});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,style:i?{...null==o?void 0:o.style,...i}:void 0})}}copyColumnStyle(e,t,i){for(let o=0;o<this.getters.getNumberRows(e);o++){const n=this.getFormat(e,t,o);if(n.style||n.format)for(let t of i)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,...n})}}copyRowStyle(e,t,i){for(let o=0;o<this.getters.getNumberCols(e);o++){const n=this.getFormat(e,o,t);if(n.style||n.format)for(let t of i)this.dispatch("UPDATE_CELL",{sheetId:e,col:o,row:t,...n})}}getFormat(e,t,i){const o={},n=this.getters.getMainCellPosition({sheetId:e,col:t,row:i}),s=this.getters.getCell(n);return s&&(s.style&&(o.style=s.style),s.format&&(o.format=s.format)),o}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,i,o){const n=this.getters.getCell({sheetId:e,col:t,row:i}),s="content"in o||"formula"in o,r=s?vt(null==o?void 0:o.content):(null==n?void 0:n.content)||"";let a;a=void 0!==o.style?o.style||void 0:n?n.style:void 0;let l=("format"in o?o.format:n&&n.format)||Ti(r);if((s&&!r&&!o.formula||!s&&(!n||""===n.content))&&!a&&!l)return void(n&&(this.history.update("cells",e,n.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:i,sheetId:e})));const c=(null==n?void 0:n.id)||this.getNextUid(),h=this.createCell(c,r,l,a,e);this.history.update("cells",e,h.id,h),this.dispatch("UPDATE_CELL_POSITION",{cellId:h.id,col:t,row:i,sheetId:e})}createCell(e,t,i,o,n){if(!t.startsWith("="))return this.createLiteralCell(e,t,i,o);try{return this.createFormulaCell(e,t,i,o,n)}catch(n){return this.createErrorFormula(e,t,i,o,n)}}createLiteralCell(e,t,i,o){return{id:e,content:t,style:o,format:i,isFormula:!1}}createFormulaCell(e,t,i,o,n){const s=vf(t);return s.dependencies.length?this.createFormulaCellWithDependencies(e,s,i,o,n):{id:e,content:t,style:o,format:i,isFormula:!0,compiledFormula:s,dependencies:[]}}createFormulaCellWithDependencies(e,t,i,o,n){const s=t.dependencies.map((e=>this.getters.getRangeFromSheetXC(n,e))),r=this.buildFormulaContent.bind(this);return{id:e,get content(){return r(n,{dependencies:this.dependencies,compiledFormula:this.compiledFormula})},style:o,format:i,isFormula:!0,compiledFormula:t,dependencies:s}}createErrorFormula(e,t,i,o,n){return{id:e,content:t,style:o,format:i,isFormula:!0,compiledFormula:{dependencies:[],tokens:Fm(t),execute:function(){throw n}},dependencies:[]}}checkCellOutOfSheet(e){const{sheetId:t,col:i,row:o}=e;if(!this.getters.tryGetSheet(t))return 27;return Ji(i,o,this.getters.getSheetZone(t))?0:18}checkUselessClearCell(e){const t=this.getters.getCell(e);return t&&(t.content||t.style||t.format)?0:88}}Pv.getters=["zoneToXC","getCells","getFormulaCellContent","getCellStyle","buildFormulaContent","getCellById"];class Uv extends kv{constructor(){super(...arguments),this.charts={},this.createChart=function(e){const t=pr.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(i,o,n){const s=t.find((e=>e.match(o.type)));if(!s)throw new Error(`No builder for this chart: ${o.type}`);return s.createChart(o,n,e)}}(this.getters),this.validateChartDefinition=e=>function(e,t){const i=pr.getAll().find((e=>e.match(t.type)));if(!i)throw new Error("Unknown chart type.");return i.validateChartDefinition(e,t)}(this,e.definition)}adaptRanges(e){for(const[t,i]of Object.entries(this.charts))this.history.update("charts",t,null==i?void 0:i.updateRanges(e))}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return 0}}handle(e){var t;switch(e.type){case"CREATE_CHART":this.addFigure(e.id,e.sheetId,e.position,e.size),this.addChart(e.id,e.definition);break;case"UPDATE_CHART":this.addChart(e.id,e.definition);break;case"DUPLICATE_SHEET":{const i=this.getters.getFigures(e.sheetId);for(const o of i)if("chart"===o.tag){const i=o.id.split(ee).pop(),n=`${e.sheetIdTo}${ee}${i}`,s=null===(t=this.charts[o.id])||void 0===t?void 0:t.copyForSheetId(e.sheetIdTo);s&&this.dispatch("CREATE_CHART",{id:n,position:{x:o.x,y:o.y},size:{width:o.width,height:o.height},definition:s.getDefinition(),sheetId:e.sheetIdTo})}break}case"DELETE_FIGURE":this.history.update("charts",e.id,void 0);break;case"DELETE_SHEET":for(let t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}getContextCreationChart(e){var t;return null===(t=this.charts[e])||void 0===t?void 0:t.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){var t;const i=null===(t=this.charts[e])||void 0===t?void 0:t.type;if(!i)throw new Error("Chart not defined.");return i}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter((([,t])=>(null==t?void 0:t.sheetId)===e)).map((([e])=>e))}getChartDefinition(e){var t;const i=null===(t=this.charts[e])||void 0===t?void 0:t.getDefinition();if(!i)throw new Error(`There is no chart with the given figureId: ${e}`);return i}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)"chart"===e.tag&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){var t;if(e.sheets)for(let i of e.sheets){const e=this.getters.getFigures(i.id),o=[];for(let i of e){const e=i;if(e&&"chart"===e.tag){const i=null===(t=this.charts[e.id])||void 0===t?void 0:t.getDefinition();i&&(e.data=i,o.push(e))}else o.push(e)}i.figures=o}}exportForExcel(e){var t;for(let i of e.sheets){const e=this.getters.getFigures(i.id),o=[];for(let i of e)if(i&&"chart"===i.tag){const e=null===(t=this.charts[i.id])||void 0===t?void 0:t.getDefinitionForExcel();e&&o.push({...i,data:e})}i.charts=o}}addFigure(e,t,i={x:0,y:0},o={width:536,height:335}){if(this.getters.getFigure(t,e))return;const n={id:e,x:i.x,y:i.y,width:o.width,height:o.height,tag:"chart"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:n})}addChart(e,t){const i=this.getters.getFigureSheetId(e);i&&this.history.update("charts",e,this.createChart(e,t,i))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?84:0}checkChartExists(e){return this.getters.getFigureSheetId(e.id)?0:85}}function Vv(e){return""===e?NaN:Number(e)}Uv.getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];class zv extends kv{constructor(){super(...arguments),this.cfRules={}}loopThroughRangesOfSheet(e,t){for(const i of this.cfRules[e])for(const o of i.ranges){const n=t(o);switch(n.changeType){case"REMOVE":let t=i.ranges.slice();t.splice(i.ranges.indexOf(o),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(i),"ranges",t):this.removeConditionalFormatting(i.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(i),"ranges",i.ranges.indexOf(o),n.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){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return this.checkValidations(e,this.checkCFRule,this.checkEmptyRange);case"MOVE_CONDITIONAL_FORMAT":return this.checkValidReordering(e.cfId,e.direction,e.sheetId)}return 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 i={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(i,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"MOVE_CONDITIONAL_FORMAT":this.reorderConditionalFormatting(e.cfId,e.direction,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){var t;return(null===(t=this.cfRules[e])||void 0===t?void 0:t.map((t=>this.mapToConditionalFormat(e,t))))||[]}getRulesSelection(e,t){const i=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{i.add(e)}))})),Array.from(i)}getRulesByZone(e,t){const i=new Set;for(let o=t.top;o<=t.bottom;o++)for(let n=t.left;n<=t.right;n++){this.getRulesByCell(e,n,o).forEach((e=>{i.add(e.id)}))}return i}getRulesByCell(e,t,i){const o=[];for(let n of this.cfRules[e])for(let e of n.ranges)Ji(t,i,e.zone)&&o.push(n);return new Set(o.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e)))}}mapToConditionalFormatInternal(e,t){const i={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return i}addConditionalFormatting(e,t){const i=this.cfRules[t].slice(),o=i.findIndex((t=>t.id===e.id)),n=this.mapToConditionalFormatInternal(t,e);o>-1?i.splice(o,1,n):i.push(n),this.history.update("cfRules",t,i)}checkValidReordering(e,t,i){if(!this.cfRules[i])return 27;const o=this.cfRules[i].findIndex((t=>t.id===e));if(-1===o)return 71;const n="up"===t?o-1:o+1;return n<0||n>=this.cfRules[i].length?71:0}checkEmptyRange(e){return e.ranges.length?0:24}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 i=>{if(t.includes(i.operator)){const t=[],o=e=>void 0===e||""===e;return e>=1&&o(i.values[0])&&t.push(51),e>=2&&o(i.values[1])&&t.push(52),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 53;case"max":return 55;case"mid":return 54;case"upperInflectionPoint":return 56;case"lowerInflectionPoint":return 57}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{vf(e.value||"")}catch(e){switch(t){case"min":return 58;case"max":return 60;case"mid":return 59;case"upperInflectionPoint":return 61;case"lowerInflectionPoint":return 62}}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,i=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(i)?48:0}checkMinBiggerThanMax(e){const t=e.minimum.value,i=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&Vv(t)>=Vv(i)?47:0}checkMidBiggerThanMax(e){var t;const i=null===(t=e.midpoint)||void 0===t?void 0:t.value,o=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&Vv(i)>=Vv(o)?49:0}checkMinBiggerThanMid(e){var t;const i=e.minimum.value,o=null===(t=e.midpoint)||void 0===t?void 0:t.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&Vv(i)>=Vv(o)?50:0}removeConditionalFormatting(e,t){const i=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==i){const e=this.cfRules[t].slice();e.splice(i,1),this.history.update("cfRules",t,e)}}reorderConditionalFormatting(e,t,i){const o=this.cfRules[i].findIndex((t=>t.id===e)),n="up"===t?o-1:o+1;if(!(n<0||n>=this.cfRules[i].length)&&-1!==o&&-1!==n){const e=[...this.cfRules[i]],t=e[o];e[o]=e[n],e[n]=t,this.history.update("cfRules",i,e)}}}zv.getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];class Bv extends kv{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:i,...o}=e,n=o;this.updateFigure(i,n);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId)}}updateFigure(e,t){if("id"in t)for(const[i,o]of Object.entries(t))switch(i){case"x":case"y":void 0!==o&&this.history.update("figures",e,t.id,i,Math.max(o,0));break;case"width":case"height":void 0!==o&&this.history.update("figures",e,t.id,i,o)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){var i;return void 0===(null===(i=this.figures[e])||void 0===i?void 0:i[t])?70:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>null==t?void 0:t[e]))?82:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(ot)}getFigure(e,t){var i;return null===(i=this.figures[e])||void 0===i?void 0:i[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>{var i;return void 0!==(null===(i=this.figures[t])||void 0===i?void 0:i[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 i=void 0;t.figures.push({...e,data:i})}}exportForExcel(e){this.export(e)}}Bv.getters=["getFigures","getFigure","getFigureSheetId"];class Hv{constructor(e){this.filters=[],this.zone=e;const t=new zi;this.id=t.uuidv4();for(const i of $e(e.left,e.right+1)){const e={...this.zone,left:i,right:i};this.filters.push(new $v(t.uuidv4(),e))}}get contentZone(){if(this.zone.bottom!==this.zone.top)return{...this.zone,top:this.zone.top+1}}getFilterId(e){var t;return null===(t=this.filters.find((t=>t.col===e)))||void 0===t?void 0:t.id}clone(){return new Hv(this.zone)}}class $v{constructor(e,t){if(t.left!==t.right)throw new Error("Can only define a filter on a single column");this.id=e,this.zoneWithHeaders=t}get col(){return this.zoneWithHeaders.left}get filteredZone(){const e=this.zoneWithHeaders;if(e.bottom!==e.top)return{...e,top:e.top+1}}}class Wv extends kv{constructor(){super(...arguments),this.tables={}}allowDispatch(e){switch(e.type){case"CREATE_FILTER_TABLE":if(!go(...e.target))return 81;const t=Yi(...e.target),i=()=>this.getFilterTables(e.sheetId).some((e=>Qi(e.zone,t)))?78:0,o=()=>{const i=this.getters.getMergesInZone(e.sheetId,t);for(let e of i)if(Qi(t,e))return 80;return 0};return this.checkValidations(e,i,o);case"ADD_MERGE":for(let t of e.target)for(let i of this.getFilterTables(e.sheetId))if(Qi(i.zone,t))return 80}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break;case"DUPLICATE_SHEET":const i={};for(const t of Object.values(this.tables[e.sheetId]||{}))if(t){const e=Fe(t);i[e.id]=e}this.history.update("tables",e.sheetIdTo,i);break;case"ADD_COLUMNS_ROWS":this.onAddColumnsRows(e);break;case"REMOVE_COLUMNS_ROWS":this.onDeleteColumnsRows(e);break;case"CREATE_FILTER_TABLE":{const t=Yi(...e.target),i=this.createFilterTable(t);this.history.update("tables",e.sheetId,i.id,i);break}case"REMOVE_FILTER_TABLE":{const t={};for(const i of this.getFilterTables(e.sheetId))e.target.every((e=>!Xi(e,i.zone)))&&(t[i.id]=i);this.history.update("tables",e.sheetId,t);break}case"UPDATE_CELL":{const t=e.sheetId;for(let i of this.getFilterTables(t))this.canUpdateCellCmdExtendTable(e,i)&&this.extendTableDown(t,i);break}}}getFilters(e){return this.getFilterTables(e).map((e=>e.filters)).flat()}getFilterTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(ot):[]}getFilter(e){var t;return null===(t=this.getFilterTable(e))||void 0===t?void 0:t.filters.find((t=>t.col===e.col))}getFilterId(e){var t;return null===(t=this.getFilter(e))||void 0===t?void 0:t.id}getFilterTable({sheetId:e,col:t,row:i}){return this.getFilterTables(e).find((e=>Ji(t,i,e.zone)))}getFilterTablesInZone(e,t){return this.getFilterTables(e).filter((e=>eo(e.zone,t)))}doesZonesContainFilter(e,t){for(const i of t)for(const t of this.getFilterTables(e))if(Xi(i,t.zone))return!0;return!1}onAddColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const i=Gi(t.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),o=[];for(const i of t.filters){const t=Gi(i.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);o.push(new $v(i.id,t))}if(o.length<oo(i).numberOfCols){for(let e=i.left;e<=i.right;e++)o.find((t=>t.col===e))||o.push(new $v(this.uuidGenerator.uuidv4(),{...i,left:e,right:e}));o.sort(((e,t)=>e.col-t.col))}this.history.update("tables",e.sheetId,t.id,"zone",i),this.history.update("tables",e.sheetId,t.id,"filters",o)}}onDeleteColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){if("ROW"===e.dimension&&e.elements.includes(t.zone.top)){const i={...this.tables[e.sheetId]};delete i[t.id],this.history.update("tables",e.sheetId,i);continue}const i=ji(t.zone,"COL"===e.dimension?"left":"top",e.elements);if(i){if(Wi(i)!==Wi(t.zone)){const o=[];for(const i of t.filters){const t=ji(i.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.elements);t&&o.push(new $v(i.id,t))}this.history.update("tables",e.sheetId,t.id,"zone",i),this.history.update("tables",e.sheetId,t.id,"filters",o)}}else{const i={...this.tables[e.sheetId]};delete i[t.id],this.history.update("tables",e.sheetId,i)}}}createFilterTable(e){return new Hv(e)}extendTableDown(e,t){const i={...t.zone,bottom:t.zone.bottom+1};this.history.update("tables",e,t.id,"zone",i);for(let i=0;i<t.filters.length;i++){const o=t.filters[i],n={...o.zoneWithHeaders,bottom:o.zoneWithHeaders.bottom+1};this.history.update("tables",e,t.id,"filters",i,"zoneWithHeaders",n)}}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:i,row:o},n){var s;if(!e)return;const r=n.zone;if(!(r.bottom+1===o&&i>=r.left&&i<=r.right))return!1;for(const e of $e(r.left,r.right+1)){const i={sheetId:t,col:e,row:o};if(null===(s=this.getters.getCell(i))||void 0===s?void 0:s.content)return!1;if(this.getters.getFilter(i))return!1;if(this.getters.isInMerge(i))return!1}return!0}import(e){for(const t of e.sheets)for(const e of t.filterTables||[]){const i=this.createFilterTable(Hi(e.range));this.history.update("tables",t.id,i.id,i)}}export(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))t.filterTables.push({range:Wi(e.zone)})}exportForExcel(e){this.export(e)}}Wv.getters=["doesZonesContainFilter","getFilter","getFilters","getFilterTable","getFilterTables","getFilterTablesInZone","getFilterId"];class Gv extends kv{constructor(){super(...arguments),this.sizes={}}handle(e){var t,i;switch(e.type){case"CREATE_SHEET":{const t=this.computeSheetSizes(e.sheetId),i={COL:t.COL.map((e=>({manualSize:void 0,computedSize:at(e)}))),ROW:t.ROW.map((e=>({manualSize:void 0,computedSize:at(e)})))};this.history.update("sizes",e.sheetId,i);break}case"DUPLICATE_SHEET":for(const t of this.sizes[e.sheetId].ROW)t.computedSize();for(const t of this.sizes[e.sheetId].COL)t.computedSize();this.history.update("sizes",e.sheetIdTo,Fe(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const o={...this.sizes};delete o[e.sheetId],this.history.update("sizes",o);break;case"REMOVE_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];for(let i of[...e.elements].sort(((e,t)=>t-e)))t.splice(i,1);const i=Math.min(...e.elements);t=t.map(((t,o)=>"ROW"===e.dimension&&o>=i?{manualSize:t.manualSize,computedSize:at((()=>this.getRowTallestCellSize(e.sheetId,o)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];const i=ct(e.position,e.base),o=t[e.base],n=$e(0,e.quantity).map((()=>({manualSize:o.manualSize,computedSize:at(o.computedSize())})));t.splice(i,0,...n),t=t.map(((t,i)=>"ROW"===e.dimension&&i>e.base+e.quantity?{manualSize:t.manualSize,computedSize:at((()=>this.getRowTallestCellSize(e.sheetId,i)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"RESIZE_COLUMNS_ROWS":for(let t of e.elements)if("ROW"===e.dimension){const i=this.getRowTallestCellSize(e.sheetId,t);this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:at(i)})}else this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:at(e.size||F)});break;case"UPDATE_CELL":const n=null===(i=null===(t=this.sizes[e.sheetId])||void 0===t?void 0:t.ROW)||void 0===i?void 0:i[e.row];if(n&&!n.manualSize){const{sheetId:t,row:i}=e;this.history.update("sizes",t,"ROW",i,"computedSize",at((()=>this.getRowTallestCellSize(t,i))))}break;case"ADD_MERGE":case"REMOVE_MERGE":for(let t of e.target)for(let i of $e(t.top,t.bottom+1)){const t=this.getRowTallestCellSize(e.sheetId,i);t!==this.getRowSize(e.sheetId,i)&&this.history.update("sizes",e.sheetId,"ROW",i,"computedSize",at(t))}}}getColSize(e,t){return this.getHeaderSize(e,"COL",t)}getRowSize(e,t){return this.getHeaderSize(e,"ROW",t)}getHeaderSize(e,t,i){var o,n,s,r;return Math.round((null===(n=null===(o=this.sizes[e])||void 0===o?void 0:o[t][i])||void 0===n?void 0:n.manualSize)||(null===(r=null===(s=this.sizes[e])||void 0===s?void 0:s[t][i])||void 0===r?void 0:r.computedSize())||this.getDefaultHeaderSize(t))}computeSheetSizes(e){var t,i;const o={COL:[],ROW:[]};for(let t of $e(0,this.getters.getNumberCols(e)))o.COL.push(this.getHeaderSize(e,"COL",t));for(let n of $e(0,this.getters.getNumberRows(e))){let s=null===(i=null===(t=this.sizes[e])||void 0===t?void 0:t.ROW)||void 0===i?void 0:i[n].manualSize;if(!s){s=this.getRowTallestCellSize(e,n)}o.ROW.push(s)}return o}getDefaultHeaderSize(e){return"COL"===e?F:D}getCellHeight(e){const t=this.getters.getMerge(e);if(t&&t.bottom!==t.top)return D;return function(e){return e&&e.content?Pe(He(e.style),e.isFormula?1:e.content.split(he).length)+2*z:D}(this.getters.getCell(e))}getRowTallestCellSize(e,t){const i=this.getters.getRowCells(e,t);let o=0;for(let e=0;e<i.length;e++){const t=this.getters.getCellById(i[e]);if(!t)continue;const n=this.getters.getCellPosition(t.id),s=this.getCellHeight(n);s>o&&s>D&&(o=s)}return o<=D?D:o}import(e){for(let t of e.sheets){const e={COL:[],ROW:[]};for(let[i,o]of Object.entries(t.rows))o.size&&(e.ROW[i]=o.size);for(let[i,o]of Object.entries(t.cols))o.size&&(e.COL[i]=o.size);const i=this.computeSheetSizes(t.id);this.sizes[t.id]={COL:i.COL.map(((t,i)=>({manualSize:e.COL[i],computedSize:at(t)}))),ROW:i.ROW.map(((t,i)=>({manualSize:e.ROW[i],computedSize:at(t)})))}}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){var i,o;for(let n of e.sheets){void 0===n.rows&&(n.rows={});for(let e of $e(0,this.getters.getNumberRows(n.id)))(t||(null===(i=this.sizes[n.id].ROW[e])||void 0===i?void 0:i.manualSize))&&(n.rows[e]={...n.rows[e],size:this.getRowSize(n.id,e)});void 0===n.cols&&(n.cols={});for(let e of $e(0,this.getters.getNumberCols(n.id)))(t||(null===(o=this.sizes[n.id].COL[e])||void 0===o?void 0:o.manualSize))&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}}Gv.getters=["getRowSize","getColSize"];class qv extends kv{constructor(){super(...arguments),this.hiddenHeaders={}}allowDispatch(e){switch(e.type){case"HIDE_COLUMNS_ROWS":{if(!this.getters.tryGetSheet(e.sheetId))return 27;const t="COL"===e.dimension?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),i="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=i?66:Math.min(...e.elements)<0||Math.max(...e.elements)>i?86:0}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?8:0:27}return 0}handle(e){switch(e.type){case"CREATE_SHEET":const t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update("hiddenHeaders",e.sheetId,t);break;case"DUPLICATE_SHEET":this.history.update("hiddenHeaders",e.sheetIdTo,Fe(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let i of[...e.elements].sort(((e,t)=>t-e)))t.splice(i,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]],i=ct(e.position,e.base);t.splice(i,0,...Array(e.quantity).fill(!1)),this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"HIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}checkElementsIncludeAllVisibleHeaders(e,t,i){return dt(i,this.getAllVisibleHeaders(e,t))}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]}getHiddenColsGroups(e){const t=[[]],i=this.hiddenHeaders[e].COL;for(let e=0;e<i.length;e++){i[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],i=this.hiddenHeaders[e].ROW;for(let e=0;e<i.length;e++){i[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){return $e(0,this.hiddenHeaders[e][t].length).filter((i=>!this.hiddenHeaders[e][t][i]))}import(e){var t,i;for(let o of e.sheets){this.hiddenHeaders[o.id]={COL:[],ROW:[]};for(let e=0;e<o.rowNumber;e++)this.hiddenHeaders[o.id].ROW[e]=Boolean(null===(t=o.rows[e])||void 0===t?void 0:t.isHidden);for(let e=0;e<o.colNumber;e++)this.hiddenHeaders[o.id].COL[e]=Boolean(null===(i=o.cols[e])||void 0===i?void 0:i.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let i of e.sheets){void 0===i.rows&&(i.rows={});for(let e=0;e<this.getters.getNumberRows(i.id);e++)(t||this.hiddenHeaders[i.id].ROW[e])&&(void 0===i.rows[e]&&(i.rows[e]={}),i.rows[e].isHidden=this.hiddenHeaders[i.id].ROW[e]);void 0===i.cols&&(i.cols={});for(let e=0;e<this.getters.getNumberCols(i.id);e++)(t||this.hiddenHeaders[i.id].COL[e])&&(void 0===i.cols[e]&&(i.cols[e]={}),i.cols[e].isHidden=this.hiddenHeaders[i.id].COL[e])}}}qv.getters=["checkElementsIncludeAllVisibleHeaders","getHiddenColsGroups","getHiddenRowsGroups","isRowHiddenByUser","isColHiddenByUser"];class Zv extends kv{constructor(e){super(e),this.images={},this.syncedImages=new Set,this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?28:0}handle(e){switch(e.type){case"CREATE_IMAGE":this.addFigure(e.figureId,e.sheetId,e.position,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const i of t)if("image"===i.tag){const t=i.id.split(ee).pop(),o=`${e.sheetIdTo}${ee}${t}`,n=this.getImage(i.id);if(n){const t={width:i.width,height:i.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:o,position:{x:i.x,y:i.y},size:t,definition:Fe(n)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.id,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}garbageCollectExternalResources(){var e;const t=new Set(this.getAllImages().map((e=>e.path)));for(const i of this.syncedImages)t.has(i)||null===(e=this.fileStore)||void 0===e||e.delete(i)}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,i,o){const n={id:e,x:i.x,y:i.y,width:o.width,height:o.height,tag:"image"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:n})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter((e=>"image"===e.tag));for(const i of e)this.history.update("images",t.id,i.id,i.data),this.syncedImages.add(i.data.path)}}export(e){var t;for(const i of e.sheets){const e=i.figures.filter((e=>"image"===e.tag));for(const o of e)o.data=null===(t=this.images[i.id])||void 0===t?void 0:t[o.id]}}exportForExcel(e){for(const t of e.sheets){const e=this.getters.getFigures(t.id),i=[];for(const t of e)if("image"===(null==t?void 0:t.tag)){const e=this.getImage(t.id);e&&i.push({...t,data:Fe(e)})}t.images=i}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(ot));return e}}Zv.getters=["getImage","getImagePath","getImageSize"];class jv extends kv{constructor(){super(...arguments),this.nextId=1,this.merges={},this.mergeCellMap={}}allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;for(const i of Object.values(t).filter(ot))this.addMerge(e.sheetIdTo,i.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){const i=t?[t]:Object.keys(this.merges);for(const t of i)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(ot)}getMerge({sheetId:e,col:t,row:i}){var o;const n=this.mergeCellMap[e],s=n?t in n&&(null===(o=n[t])||void 0===o?void 0:o[i]):void 0;return s?this.getMergeById(e,s):void 0}getMergesInZone(e,t){var i;const o=this.mergeCellMap[e];if(!o)return[];const n=new Set;for(const{col:e,row:s}of so(t)){const t=null===(i=o[e])||void 0===i?void 0:i[s];t&&n.add(t)}return Array.from(n).map((t=>this.getMergeById(e,t))).filter(ot)}doesIntersectMerge(e,t){return so(t).some((({col:t,row:i})=>void 0!==this.getMerge({sheetId:e,col:t,row:i})))}doesColumnsHaveCommonMerges(e,t,i){const o=this.getters.getSheet(e);for(let n=0;n<this.getters.getNumberRows(e);n++)if(this.isInSameMerge(o.id,t,n,i,n))return!0;return!1}doesRowsHaveCommonMerges(e,t,i){const o=this.getters.getSheet(e);for(let n=0;n<=this.getters.getNumberCols(e);n++)if(this.isInSameMerge(o.id,n,t,n,i))return!0;return!1}expandZone(e,t){let{left:i,right:o,top:n,bottom:s}=t,r={left:i,right:o,top:n,bottom:s};for(let t in this.merges[e]){const i=this.getMergeById(e,parseInt(t));i&&Qi(i,r)&&(r=Yi(i,r))}return Ki(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,i,o,n){const s=this.getMerge({sheetId:e,col:t,row:i}),r=this.getMerge({sheetId:e,col:o,row:n});return!(!s||!r)&&Ki(s,r)}isInMerge({sheetId:e,col:t,row:i}){var o;const n=this.mergeCellMap[e];return!!n&&(t in n&&Boolean(null===(o=n[t])||void 0===o?void 0:o[i]))}getMainCellPosition(e){if(!this.isInMerge(e))return e;const t=this.getMerge(e).topLeft;return{sheetId:e.sheetId,col:t.col,row:t.row}}getBottomLeftCell(e){if(!this.isInMerge(e))return e;const{bottom:t,left:i}=this.getMerge(e);return{sheetId:e.sheetId,col:i,row:t}}isMergeHidden(e,t){const i=this.getters.getHiddenColsGroups(e),o=this.getters.getHiddenRowsGroups(e);for(let e of i)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of o)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const i=this.getMerge({sheetId:e,col:t.left,row:t.top});if(i)return Ki(t,i);const{numberOfCols:o,numberOfRows:n}=oo(t);return 1===o&&1===n}isMergeDestructive(e,t){let{left:i,right:o,top:n,bottom:s}=t;o=Le(o,0,this.getters.getNumberCols(e)-1),s=Le(s,0,this.getters.getNumberRows(e)-1);for(let t=n;t<=s;t++)for(let s=i;s<=o;s++)if(s!==i||t!==n){const i=this.getters.getCell({sheetId:e,col:s,row:t});if(i&&""!==i.content)return!0}return!1}getMergeById(e,t){var i;const o=null===(i=this.merges[e])||void 0===i?void 0:i[t];return void 0!==o?Xv(t,o):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;return t.some((t=>this.isMergeDestructive(e,t)))?3:0}checkOverlap({target:e}){for(const t of e)for(const i of e)if(t!==i&&Qi(t,i))return 65;return 0}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;const{xSplit:i,ySplit:o}=this.getters.getPaneDivisions(e);for(const e of t)if(e.left<i&&e.right>=i||e.top<o&&e.bottom>=o)return 75;return 0}checkMergedContentUpdate(e){const{col:t,row:i,content:o}=e;if(void 0===o)return 0;const{col:n,row:s}=this.getMainCellPosition(e);return n===t&&s===i?0:4}checkMergeExists(e){const{sheetId:t,target:i}=e;for(const e of i){const{left:i,top:o}=e,n=this.getMerge({sheetId:t,col:i,row:o});if(void 0===n||!Ki(e,n))return 5}return 0}addMerge(e,t){let{left:i,right:o,top:n,bottom:s}=t;o=Le(o,0,this.getters.getNumberCols(e)-1),s=Le(s,0,this.getters.getNumberRows(e)-1);if(Zt(i,n)===Zt(o,s))return;const r=this.getters.getCell({sheetId:e,col:i,row:n});let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,Wi({left:i,top:n,right:o,bottom:s})));let l=new Set;for(let t=n;t<=s;t++)for(let s=i;s<=o;s++){s===i&&t===n||this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,style:r?r.style:null,content:""});const o=this.getMerge({sheetId:e,col:s,row:t});o&&l.add(o.id),this.history.update("mergeCellMap",e,s,t,a)}for(let t of l){const{top:i,bottom:o,left:n,right:s}=this.getMergeById(e,t);for(let t=i;t<=o;t++)for(let i=n;i<=s;i++){const o={sheetId:e,col:i,row:t},n=this.getMerge(o);n&&n.id===a||(this.history.update("mergeCellMap",e,i,t,void 0),this.dispatch("CLEAR_CELL",o))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:i,top:o,bottom:n,right:s}=t,r=this.getMerge({sheetId:e,col:i,row:o});if(void 0!==r&&Ki(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=o;t<=n;t++)for(let o=i;o<=s;o++)this.history.update("mergeCellMap",e,o,t,void 0)}}applyRangeChangeOnSheet(e,t){const i=Object.entries(this.merges[e]||{});for(const[o,n]of i)if(n){const i=n.zone,s=t(n);switch(s.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,i);break;default:const{numberOfCols:t,numberOfRows:n}=oo(s.range.zone);1===t&&1===n?this.removeMerge(e,i):this.history.update("merges",e,parseInt(o,10),s.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:i,row:o}of so(t))this.history.update("mergeCellMap",e,i,o,t.id)}import(e){const t=e.sheets||[];for(let e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let i of t)this.addMerge(e,Hi(i))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...Yv(e))}}exportForExcel(e){this.export(e)}}function Yv(e){return Object.entries(e).map((([e,t])=>t?Xv(parseInt(e,10),t):void 0)).filter(ot).map((e=>Zt(e.left,e.top)+":"+Zt(e.right,e.bottom)))}function Xv(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}jv.getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge"];class Kv{constructor(e){this.providers=[],this.getters=e}allowDispatch(e){return"MOVE_RANGES"===e.type?1===e.target.length?0:26:0}beforeHandle(e){}handle(e){switch(e.type){case"REMOVE_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",i="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";const n=[...e.elements];n.sort(((e,t)=>t-e));const s=We(n);this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};let r=n,a="NONE";for(let e of s){const s=Math.min(...e),l=Math.max(...e);if(n.zone[t]<=s&&s<=n.zone[i]){const e=Math.min(n.zone[i],l)-s+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e)}else if(n.zone[t]>=s&&n.zone[i]<=l)a="REMOVE",r=n.clone({...this.getInvalidRange()});else if(n.zone[t]<=l&&n.zone[i]>=l){const e=l-n.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e),r=this.createAdaptedRange(r,o,"MOVE",-(n.zone[t]-s))}else s<n.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,o,a,-(l-s+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",i="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(n.zone[t]<=e.base&&e.base<n.zone[i])return{changeType:"RESIZE",range:this.createAdaptedRange(n,o,"RESIZE",e.quantity)};if(e.base<n.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(n,o,"MOVE",e.quantity)}}else{if(n.zone[t]<e.base&&e.base<=n.zone[i])return{changeType:"RESIZE",range:this.createAdaptedRange(n,o,"RESIZE",e.quantity)};if(e.base<=n.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(n,o,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId!==e.sheetId)return{changeType:"NONE"};const i=this.getters.getSheetName(e.sheetId);return{changeType:"REMOVE",range:t=t.clone({...this.getInvalidRange(),invalidSheetName:i})}}),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 i=void 0,o=e.sheetId;return{changeType:"CHANGE",range:t.clone({sheetId:o,invalidSheetName:i})}}return{changeType:"NONE"}}));break;case"MOVE_RANGES":{const t=e.target[0];this.executeOnAllRanges((i=>{if(i.sheetId!==e.sheetId||!eo(i.zone,t))return{changeType:"NONE"};const o=e.targetSheetId,n=e.col-t.left,s=e.row-t.top,r=this.createAdaptedRange(i,"both","MOVE",[n,s]),a=e.sheetId!==o||r.prefixSheet;return{changeType:"MOVE",range:r.clone({sheetId:o,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const i=e(t);return"NONE"===i.changeType||$i(i.range.zone)?i:{range:i.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,i,o){const n=ro(e.unboundedZone,t,i,o);return e.clone({zone:n})}executeOnAllRanges(e,t){const i=this.verifyRangeRemoved(e);for(const e of this.providers)e(i,t)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,i,o){const n=e.map((e=>ki.fromRange(e,this.getters)));return n.map((e=>{if(!$i(e.zone))return e;const n=e.prefixSheet?e.sheetId:o,s={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:i),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:i)};return e.clone({sheetId:n,zone:s}).orderZone()}))}getRangeFromSheetXC(e,t){if(!Pt.test(t))return new ki({sheetId:"",zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let i,o=t,n=!1;t.includes("!")&&(({xc:o,sheetName:i}=$t(t)),i&&(n=!0));const s=Bi(o),r=ki.getRangeParts(o,s),a=i&&!this.getters.getSheetIdByName(i)?i:void 0,l=this.getters.getSheetIdByName(i)||e;return new ki({prefixSheet:n,zone:s,sheetId:l,invalidSheetName:a,parts:r},this.getters.getSheetSize).orderZone()}getSelectionRangeString(e,t){const i=ki.fromRange(e,this.getters),o=this.getters.expandZone(i.sheetId,i.zone),n=i.clone({zone:{...o,bottom:i.isFullCol?void 0:o.bottom,right:i.isFullRow?void 0:o.right}});return this.getRangeString(n,t)}getRangeString(e,t){if(!e)return K;if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return K;if(e.zone.left<0||e.zone.top<0)return K;const i=ki.fromRange(e,this.getters);let o=i.sheetId!==t||i.invalidSheetName||i.prefixSheet,n="";if(o&&(n=i.invalidSheetName?i.invalidSheetName:ke(this.getters.getSheetName(i.sheetId))),o&&!n)return K;let s=this.getRangePartString(i,0);return i.parts&&2===i.parts.length&&(i.zone.top!==i.zone.bottom||i.zone.left!==i.zone.right||i.parts[0].rowFixed||i.parts[0].colFixed||i.parts[1].rowFixed||i.parts[1].colFixed)&&(s+=":",s+=this.getRangePartString(i,1)),`${o?n+"!":""}${s}`}getRangeDataFromXc(e,t){return this.getters.getRangeFromSheetXC(e,t).rangeData}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t}}getRangeFromRangeData(e){const t={prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]};return new ki(t,this.getters.getSheetSize)}getRangePartString(e,t){const i=e.parts&&e.parts[t].colFixed?"$":"",o=Wt(0===t?e.zone.left:e.zone.right),n=e.parts&&e.parts[t].rowFixed?"$":"",s=String(0===t?e.zone.top+1:e.zone.bottom+1);let r="";return r=e.isFullCol?0===t&&e.unboundedZone.hasHeader?i+o+n+s:i+o:e.isFullRow?0===t&&e.unboundedZone.hasHeader?i+o+n+s:n+s:i+o+n+s,r}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:K}}}Kv.getters=["getRangeString","getSelectionRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData"];class Qv extends kv{constructor(){super(...arguments),this.sheetIdsMapName={},this.orderedSheetIds=[],this.sheets={},this.cellPosition={}}allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZones)(e);if(0!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?9:0;case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"MOVE_SHEET":try{const t=this.orderedSheetIds.findIndex((t=>t===e.sheetId));return this.findIndexOfTargetSheet(t,e.delta),0}catch(e){return 14}case"RENAME_SHEET":return this.isRenameAllowed(e);case"DELETE_SHEET":return this.orderedSheetIds.length>1?0:9;case"ADD_COLUMNS_ROWS":const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return e.base<0||e.base>=t?86:e.quantity<=0?87:0;case"REMOVE_COLUMNS_ROWS":{const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return Math.min(...e.elements)<0||Math.max(...e.elements)>t?86:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?8:0}case"FREEZE_ROWS":return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case"FREEZE_COLUMNS":return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);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("sheetIdsMapName",t.name,t.id);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.delta);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.name);break;case"HIDE_SHEET":this.hideSheet(e.sheetId);break;case"SHOW_SHEET":this.showSheet(e.sheetId);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e);break;case"FREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,e.quantity,"COL");break;case"FREEZE_ROWS":this.setPaneDivisions(e.sheetId,e.quantity,"ROW");break;case"UNFREEZE_ROWS":this.setPaneDivisions(e.sheetId,0,"ROW");break;case"UNFREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,0,"COL");break;case"UNFREEZE_COLUMNS_ROWS":this.setPaneDivisions(e.sheetId,0,"COL"),this.setPaneDivisions(e.sheetId,0,"ROW")}}import(e){var t,i;for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let o of e.sheets){const e=o.name||n("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:s,rowNumber:r}=this.getImportedSheetSize(o),a={id:o.id,name:e,numberOfCols:s,rows:Vi(r),areGridLinesVisible:void 0===o.areGridLinesVisible||o.areGridLinesVisible,isVisible:o.isVisible,panes:{xSplit:(null===(t=o.panes)||void 0===t?void 0:t.xSplit)||0,ySplit:(null===(i=o.panes)||void 0===i?void 0:i.ySplit)||0}};this.orderedSheetIds.push(a.id),this.sheets[a.id]=a}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(ot).map((e=>{const t=this.sheets[e],i={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},conditionalFormats:[],figures:[],filterTables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible};return(t.panes.xSplit||t.panes.ySplit)&&(i.panes=t.panes),i}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){var t;return null===(t=this.tryGetSheet(e))||void 0===t?void 0:t.name}getSheetIdByName(e){if(e){const t=De(e);for(const e in this.sheetIdsMapName)if(e.toUpperCase()===t.toUpperCase())return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}getEvaluationSheets(){return this.sheets}doesHeaderExist(e,t,i){return"COL"===t?i>=0&&i<this.getNumberCols(e):i>=0&&i<this.getNumberRows(e)}getRow(e,t){const i=this.getSheet(e).rows[t];if(!i)throw new Error(`Row ${i} not found.`);return i}getCell({sheetId:e,col:t,row:i}){var o;const n=this.tryGetSheet(e),s=null===(o=null==n?void 0:n.rows[i])||void 0===o?void 0:o.cells[t];if(void 0!==s)return this.getters.getCellById(s)}getColsZone(e,t,i){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:i}}getRowCells(e,t){var i;return Object.values(null===(i=this.getSheet(e).rows[t])||void 0===i?void 0:i.cells).filter(ot)}getRowsZone(e,t,i){return{top:t,bottom:i,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){let t=1;const i=this.orderedSheetIds.map(this.getSheetName.bind(this));let o=`${e}${t}`;for(;i.includes(o);)o=`${e}${t}`,t++;return o}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,i){const o={...this.getPaneDivisions(e)};"COL"===i?o.xSplit=t:"ROW"===i&&(o.ySplit=t),this.history.update("sheets",e,"panes",o)}checkElementsIncludeAllNonFrozenHeaders(e,t,i){const o=this.getters.getPaneDivisions(e),n="ROW"===t?o.ySplit:o.xSplit,s=this.getters.getNumberHeaders(e,t);if(!n)return!1;return dt(i,$e(n,s))}isEmpty(e,t){return so(t).map((({col:t,row:i})=>this.getCell({sheetId:e,col:t,row:i}))).every((e=>!e||""===e.content))}updateCellPosition(e){const{sheetId:t,cellId:i,col:o,row:n}=e;i?this.setNewPosition(i,t,o,n):this.clearPosition(t,o,n)}setNewPosition(e,t,i,o){const n=this.cellPosition[e];n&&this.clearPosition(t,n.col,n.row),this.history.update("cellPosition",e,{row:o,col:i,sheetId:t}),this.history.update("sheets",t,"rows",o,"cells",i,e)}clearPosition(e,t,i){var o;const n=null===(o=this.sheets[e])||void 0===o?void 0:o.rows[i].cells[t];n&&(this.history.update("cellPosition",n,void 0),this.history.update("sheets",e,"rows",i,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++){this.sheets[e].rows[o].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:o})}}createSheet(e,t,i,o,n){const s={id:e,name:t,numberOfCols:i,rows:Vi(o),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},r=this.orderedSheetIds.slice();r.splice(n,0,s.id);const a=this.sheets;return this.history.update("orderedSheetIds",r),this.history.update("sheets",Object.assign({},a,{[s.id]:s})),s}moveSheet(e,t){const i=this.orderedSheetIds.slice(),o=i.findIndex((t=>t===e)),n=i.splice(o,1);let s=this.findIndexOfTargetSheet(o,t);i.splice(s,0,n[0]),this.history.update("orderedSheetIds",i)}findIndexOfTargetSheet(e,t){for(;0!=t&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(0===t)return e;throw new Error(s("There is not enough visible sheets"))}checkSheetName(e){const{orderedSheetIds:t,sheets:i}=this,o=e.name&&e.name.trim().toLowerCase();return t.find((e=>{var t;return(null===(t=i[e])||void 0===t?void 0:t.name.toLowerCase())===o}))?11:re.test(o)?13:0}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?15:0}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?0:74}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?0:74}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let i of t)if(i.top<e.quantity&&e.quantity<=i.bottom)return 65;return 0}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let i of t)if(i.left<e.quantity&&e.quantity<=i.right)return 65;return 0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const i=e.name;this.history.update("sheets",e.id,"name",t.trim());const o=Object.assign({},this.sheetIdsMapName);o[t]=e.id,delete o[i],this.history.update("sheetIdsMapName",o)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t){const i=this.getSheet(e),o=this.getDuplicateSheetName(i.name),n=Fe(i);n.id=t,n.name=o;for(let e=0;e<=n.numberOfCols;e++)for(let t=0;t<=n.rows.length;t++)n.rows[t]&&(n.rows[t].cells[e]=void 0);const s=this.orderedSheetIds.slice(),r=s.indexOf(e);s.splice(r+1,0,n.id),this.history.update("orderedSheetIds",s),this.history.update("sheets",Object.assign({},this.sheets,{[n.id]:n}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:i}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:n.id,col:e,row:i,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIdsMapName);a[n.name]=n.id,this.history.update("sheetIdsMapName",a)}getDuplicateSheetName(e){let t=1;const i=this.orderedSheetIds.map(this.getSheetName.bind(this)),o=s("Copy of %s",e);let n=o.toString();for(;i.includes(n);)n=`${o} (${t})`,t++;return n}deleteSheet(e){const t=e.name,i=Object.assign({},this.sheets);delete i[e.id],this.history.update("sheets",i);const o=this.orderedSheetIds.slice(),n=o.indexOf(e.id);o.splice(n,1),this.history.update("orderedSheetIds",o);const s=Object.assign({},this.sheetIdsMapName);delete s[t],this.history.update("sheetIdsMapName",s)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let i of t)this.moveCellOnColumnsDeletion(e,i);const i=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",i-t.length);const o=t.filter((t=>t<e.panes.xSplit)).length;o&&this.setPaneDivisions(e.id,e.panes.xSplit-o,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(let i of We(t)){const t=i[i.length-1],o=i[0];this.moveCellOnRowsDeletion(e,t,o),this.updateRowsStructureOnDeletion(e,t,o)}const i=t.filter((t=>t<e.panes.ySplit)).length;i&&this.setPaneDivisions(e.id,e.panes.ySplit-i,"ROW")}addColumns(e,t,i,o){const n="before"===i?t:t+1;this.moveCellsOnAddition(e,n,o,"columns");const s=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",s+o),n<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+o,"COL")}addRows(e,t,i,o){const n="before"===i?t:t+1;this.addEmptyRows(e,o),this.moveCellsOnAddition(e,n,o,"rows"),n<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+o,"ROW")}moveCellOnColumnsDeletion(e,t){for(let i=0;i<e.rows.length;i++){const o=e.rows[i];for(let n in o.cells){const s=Number(n),r=o.cells[n];r&&(s===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:s,row:i}),s>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:s-1,row:i}))}}}moveCellsOnAddition(e,t,i,o){const n=[];for(let s=0;s<e.rows.length;s++){const r=e.rows[s];if("rows"!==o||s>=t)for(let a in r.cells){const l=Number(a),c=r.cells[a];c&&("rows"===o||l>=t)&&n.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c,col:l+("columns"===o?i:0),row:s+("rows"===o?i:0)})}}for(let e of n.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,i){const o=i-t+1;for(let n=0;n<e.rows.length;n++){const s=e.rows[n];if(n>=t&&n<=i)for(let t in s.cells){const i=Number(t);s.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:i,row:n})}if(n>i)for(let t in s.cells){const i=Number(t),r=s.cells[t];r&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:i,row:n-o})}}}updateRowsStructureOnDeletion(e,t,i){const o=[],n=e.rows.map((e=>e.cells)).reverse();for(let s in e.rows){const e=Number(s);e>=t&&e<=i||o.push({cells:n.pop()})}this.history.update("sheets",e.id,"rows",o)}addEmptyRows(e,t){const i=e.rows.slice();for(let e=0;e<t;e++)i.push({cells:{}});this.history.update("sheets",e.id,"rows",i)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(qt);let i=e.rowNumber,o=e.colNumber;for(let{col:e,row:n}of t)i=Math.max(i,n+1),o=Math.max(o,e+1);return{rowNumber:i,colNumber:o}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?27:"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),"ranges"in e&&Array.isArray(e.ranges)&&t.push(...e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone))),!t.every($i))return 25;if(t.length&&"sheetId"in e){const i=this.getSheetZone(e.sheetId);return t.every((e=>eo(e,i)))?0:18}return 0}}Qv.getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheetIds","getVisibleSheetIds","isSheetVisible","getEvaluationSheets","doesHeaderExist","getCell","getCellPosition","getColsZone","getRowCells","getRowsZone","getNumberCols","getNumberRows","getNumberHeaders","getGridLinesVisibility","getNextSheetName","isEmpty","getSheetSize","getSheetZone","getPaneDivisions","checkElementsIncludeAllNonFrozenHeaders"];class Jv extends Dv{constructor({getters:e,stateObserver:t,dispatch:i,uiActions:o,selection:n}){super(t,i),this.getters=e,this.ui=o,this.selection=n}drawGrid(e,t){}}Jv.layers=[];class eb extends Jv{constructor(){super(...arguments),this.customColors=new Set,this.shouldUpdateColors=!1}handle(e){switch(e.type){case"UPDATE_CELL":case"UPDATE_CHART":case"CREATE_CHART":case"ADD_CONDITIONAL_FORMAT":this.shouldUpdateColors=!0}}finalize(){if(this.shouldUpdateColors){this.shouldUpdateColors=!1;for(const e of this.getCustomColors())this.tryToAddColor(e)}}getCustomColors(){let e=[];for(const t of this.getters.getSheetIds()){const i=Object.values(this.getters.getCells(t));e=e.concat(this.getColorsFromCells(i),this.getFormattingColors(t),this.getChartColors(t))}return function(e){const t=[{leadColor:It(255,0,0),colors:[]},{leadColor:It(255,128,0),colors:[]},{leadColor:It(128,128,0),colors:[]},{leadColor:It(128,255,0),colors:[]},{leadColor:It(0,255,0),colors:[]},{leadColor:It(0,255,128),colors:[]},{leadColor:It(0,255,255),colors:[]},{leadColor:It(0,127,255),colors:[]},{leadColor:It(0,0,255),colors:[]},{leadColor:It(127,0,255),colors:[]},{leadColor:It(128,0,128),colors:[]},{leadColor:It(255,0,128),colors:[]}];for(const i of e.map(At)){let e=500,o=0;t.forEach(((t,n)=>{const s=(r=i,a=t.leadColor,Math.sqrt(Math.pow(r.r-a.r,2)+Math.pow(r.g-a.g,2)+Math.pow(r.b-a.b,2)));var r,a;e>s&&(e=s,o=n)})),t[o].colors.push(i)}return t.map((e=>e.colors.sort(((e,t)=>Ot(e).s-Ot(t).s)))).flat().map(Tt)}([...new Set([...new Set([...e,...this.customColors])].filter(yt).map(wt))]).filter((e=>!O.includes(e)))}getColorsFromCells(e){var t,i;const o=new Set;for(const n of e)(null===(t=n.style)||void 0===t?void 0:t.textColor)&&o.add(n.style.textColor),(null===(i=n.style)||void 0===i?void 0:i.fillColor)&&o.add(n.style.fillColor);return[...o]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),i=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(i.push(t.style.textColor),i.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(i.push(Et(t.minimum.color)),i.push(t.midpoint?Et(t.midpoint.color):void 0),i.push(Et(t.maximum.color)))}return i.filter(ot)}getChartColors(e){const t=this.getters.getChartIds(e).map((e=>this.getters.getChart(e)));let i=new Set;for(let e of t){if(void 0===e)continue;const t=e.getDefinition().background;switch(void 0!==t&&i.add(t),e.type){case"gauge":const t=e.sectionRule.colors;i.add(t.lowerColor),i.add(t.middleColor),i.add(t.upperColor);break;case"scorecard":const o=e;i.add(o.baselineColorDown),i.add(o.baselineColorUp)}}return[...i]}tryToAddColor(e){const t=wt(e);e&&!O.includes(t)&&this.customColors.add(t)}}eb.getters=["getCustomColors"];const tb=ig.mapping;class ib extends Jv{constructor(e){super(e),this.isUpToDate=!1,this.evaluatedCells={},this.evalContext=e.custom,this.lazyEvaluation=e.lazyEvaluation}handle(e){switch(dn.has(e.type)&&(this.isUpToDate=!1),e.type){case"UPDATE_CELL":("content"in e||"format"in e)&&(this.isUpToDate=!1);break;case"EVALUATE_CELLS":this.evaluate()}}finalize(){this.isUpToDate||(this.evaluate(),this.isUpToDate=!0)}evaluateFormula(e,t=this.getters.getActiveSheetId()){try{const i=vf(e),o=this.getCompilationParameters((e=>this.getEvaluatedCell(this.getters.getCellPosition(e.id)))),n=[];for(let e of i.dependencies)n.push(this.getters.getRangeFromSheetXC(t,e));return i.execute(n,...o).value}catch(e){return e instanceof c?e.errorType:a.GenericError}}getRangeFormattedValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.formattedValue))}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.value))}getRangeFormats(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.format))}getEvaluatedCell({sheetId:e,col:t,row:i}){var o,n,s;return void 0===this.getters.getCell({sheetId:e,col:t,row:i})?wn(""):(null===(s=null===(n=null===(o=this.evaluatedCells[e])||void 0===o?void 0:o[t])||void 0===n?void 0:n[i])||void 0===s?void 0:s.call(n))||wn("")}getEvaluatedCells(e){const t=this.getters.getCells(e)||{},i={};for(let e of Object.keys(t)){const t=this.getters.getCellPosition(e);i[e]=this.getEvaluatedCell(t)}return i}getColEvaluatedCells(e,t){var i;return Object.values((null===(i=this.evaluatedCells[e])||void 0===i?void 0:i[t])||[]).filter(ot).map((e=>e()))}getEvaluatedCellsInZone(e,t){return so(t).map((({col:t,row:i})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:i})))}setEvaluatedCell(e,t){const{col:i,row:o,sheetId:n}=this.getters.getCellPosition(e);this.evaluatedCells[n]||(this.evaluatedCells[n]={}),this.evaluatedCells[n][i]||(this.evaluatedCells[n][i]={}),this.evaluatedCells[n][i][o]=t,this.lazyEvaluation||this.evaluatedCells[n][i][o]()}*getAllCells(){for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t)yield t[e]}}evaluate(){this.evaluatedCells={};const e=new Set,t=e=>{var t,n;const s=e.id,{col:r,row:a,sheetId:l}=this.getters.getCellPosition(s),c=null===(n=null===(t=this.evaluatedCells[l])||void 0===t?void 0:t[r])||void 0===n?void 0:n[a];return c||at((()=>{try{switch(e.isFormula){case!0:return o(e);case!1:return Sn(e.content,e.format)}}catch(t){return i(t,e)}}))},i=(e,t)=>{e instanceof Error||(e=new Error(e));const i=(null==e?void 0:e.errorType)||a.GenericError,o=n[2].__lastFnCalled||"",s=new c(i,e.message.replace("[[FUNCTION_NAME]]",o),void 0!==e.logLevel?e.logLevel:l.error);return Rn(t.content,s)},o=t=>{const i=t.id;if(e.has(i))throw new d;n[2].__originCellXC=()=>{const e=n[2].getters.getCellPosition(i);return Zt(e.col,e.row)},e.add(i);const o=t.compiledFormula.execute(t.dependencies,...n);if(e.delete(i),Array.isArray(o.value))throw new Error(s("This formula depends on invalid values"));return wn(o.value,t.format||o.format)},n=this.getCompilationParameters((e=>t(e)()));for(const e of this.getAllCells())this.setEvaluatedCell(e.id,t(e))}getCompilationParameters(e){const t=Object.assign(Object.create(tb),this.evalContext,{getters:this.getters}),i=this.getters;const o=t=>{const i=e(t);if(i.type===cn.error)throw i.error;return i},n={};return[function(e,t,n,r){if(t)return{value:Wi(e.zone)};if(!$i(e.zone))throw new u;if(e.zone.bottom!==e.zone.top||e.zone.left!==e.zone.right)throw new Error(r?s("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",n.toString(),r.toString()):s("Function %s expects its parameters to be single values or single cell references, not ranges.",n.toString()));if(e.invalidSheetName)throw new Error(s("Invalid sheet name: %s",e.invalidSheetName));return function(e){let t;if(!i.tryGetSheet(e.sheetId))throw new Error(s("Invalid sheet name"));return t=i.getCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}),t&&""!==t.content?o(t):{value:null,format:null==t?void 0:t.format}}(e)},function(e){const s=e.sheetId;if(!$i(e.zone))throw new u;const r=i.getSheetZone(s),a=Xi(e.zone,r);if(!a)return[[]];const{top:l,left:c,bottom:h,right:d}=a,g=`${s}-${l}-${c}-${h}-${d}`;if(g in n)return n[g];const p=new Array(d-c+1);for(let i=c;i<=d;i++){const n=new Array(h-l+1);for(let s=l;s<=h;s++){const r=t.getters.getCell({sheetId:e.sheetId,col:i,row:s});n[s-l]=r?o(r):void 0}p[i-c]=n}return n[g]=p,p},t]}exportForExcel(e){for(let t of e.sheets)for(const e in t.cells){const i={sheetId:t.id,...qt(e)},o=this.getters.getCell(i);if(o){const n=t.cells[e],s=this.getEvaluatedCell(i);n.value=s.value,n.isFormula=o.isFormula&&!this.isBadExpression(o.content),o.format!==s.format&&(n.computedFormat=s.format)}}}isBadExpression(e){try{return vf(e),!1}catch(e){return!0}}}ib.getters=["evaluateFormula","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getColEvaluatedCells","getEvaluatedCellsInZone"];class ob extends Jv{constructor(){super(...arguments),this.charts={},this.createRuntimeChart=function(e){const t=pr.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(i){const o=t.find((e=>e.match(i.type)));if(!o)throw new Error("No runtime builder for this chart.");return o.getChartRuntime(i,e)}}(this.getters)}handle(e){if(dn.has(e.type)||un.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type)for(const e in this.charts)this.charts[e]=void 0;switch(e.type){case"UPDATE_CHART":case"CREATE_CHART":case"DELETE_FIGURE":this.charts[e.id]=void 0;break;case"DELETE_SHEET":for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0)}}getChartRuntime(e){if(!this.charts[e]){const t=this.getters.getChart(e);if(!t)throw new Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:Rs(e)};if(!t)return{background:w,fontColor:Rs(w)};const i=t.zone.left,o=t.zone.top,n=t.sheetId,s=this.getters.getCellComputedStyle({sheetId:n,col:i,row:o}),r=s.fillColor||w;return{background:r,fontColor:s.textColor||Rs(r)}}}ob.getters=["getChartRuntime","getStyleOfSingleCellChart"];class nb extends Jv{constructor(){super(...arguments),this.isStale=!0,this.computedStyles={},this.computedIcons={},this.uuidGenerator=new zi,this.rulePredicate={CellIsRule:(e,t)=>{if(e.type===cn.error)return!1;const i=t.values.map(En);switch(t.operator){case"IsEmpty":return""===e.value.toString().trim();case"IsNotEmpty":return""!==e.value.toString().trim();case"BeginsWith":return""!==i[0]&&e.value.toString().startsWith(i[0].toString());case"EndsWith":return""!==i[0]&&e.value.toString().endsWith(i[0].toString());case"Between":return e.value>=i[0]&&e.value<=i[1];case"NotBetween":return!(e.value>=i[0]&&e.value<=i[1]);case"ContainsText":return e.value.toString().indexOf(i[0].toString())>-1;case"NotContains":return!e.value||-1==e.value.toString().indexOf(i[0].toString());case"GreaterThan":return e.value>i[0];case"GreaterThanOrEqual":return e.value>=i[0];case"LessThan":return e.value<i[0];case"LessThanOrEqual":return e.value<=i[0];case"NotEqual":return""!==i[0]&&e.value!==i[0];case"Equal":return""===i[0]||e.value===i[0];default:console.warn(s("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}}}handle(e){switch((un.has(e.type)||"UPDATE_CELL"===e.type&&"content"in e)&&(this.isStale=!0),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 i=this.getters.getActiveSheetId(),o=this.getters.getRulesByCell(i,e.originCol,e.originRow);for(const t of o)this.adaptRules(i,t,[Zt(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.origin,e.target,e.operation)}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getCellComputedStyle(e){var t;const{sheetId:i,col:o,row:n}=e,s=this.getters.getCell(e),r=this.computedStyles[i],a=r&&(null===(t=r[o])||void 0===t?void 0:t[n]),l={...null==s?void 0:s.style,...a};return this.getters.getEvaluatedCell(e).link&&!l.textColor&&(l.textColor=I),this.getters.isFilterHeader(e)&&(l.bold=!0),l}getConditionalIcon({col:e,row:t}){var i;const o=this.getters.getActiveSheetId(),n=this.computedIcons[o];return n&&(null===(i=n[e])||void 0===i?void 0:i[t])}computeStyles(){var e;const t=this.getters.getActiveSheetId();this.computedStyles[t]={},this.computedIcons[t]={};const i=this.computedStyles[t];for(let o of this.getters.getConditionalFormats(t).reverse())switch(o.rule.type){case"ColorScaleRule":for(let e of o.ranges)this.applyColorScale(e,o.rule);break;case"IconSetRule":for(let e of o.ranges)this.applyIcon(e,o.rule);break;default:for(let n of o.ranges){const s=this.getters.getRangeFromSheetXC(t,n).zone;for(let n=s.top;n<=s.bottom;n++)for(let r=s.left;r<=s.right;r++){const s=this.rulePredicate[o.rule.type];let a=this.getters.getEvaluatedCell({sheetId:t,col:r,row:n});s&&s(a,o.rule)&&(i[r]||(i[r]=[]),i[r][n]=Object.assign((null===(e=i[r])||void 0===e?void 0:e[n])||{},o.rule.style))}}}}parsePoint(e,t,i){const o=this.getters.getActiveSheetId(),n=this.getters.getEvaluatedCellsInZone(o,this.getters.getRangeFromSheetXC(o,e).zone).filter((e=>e.type===cn.number)).map((e=>e.value));switch(t.type){case"value":return"max"===i?Math.max(...n):Math.min(...n);case"number":return Number(t.value);case"percentage":const e=Math.min(...n);return e+(Math.max(...n)-e)*Number(t.value)/100;case"percentile":return ai(n,Number(t.value)/100,!0);case"formula":const o=t.value&&this.getters.evaluateFormula(t.value);return"number"==typeof o?o:null;default:return null}}applyIcon(e,t){const i=this.parsePoint(e,t.lowerInflectionPoint),o=this.parsePoint(e,t.upperInflectionPoint);if(null===i||null===o||i>o)return;const n=this.getters.getActiveSheetId(),s=this.getters.getRangeFromSheetXC(n,e).zone,r=this.computedIcons[n],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=s.top;e<=s.bottom;e++)for(let l=s.left;l<=s.right;l++){const s=this.getters.getEvaluatedCell({sheetId:n,col:l,row:e});if(s.type!==cn.number)continue;const c=this.computeIcon(s.value,o,t.upperInflectionPoint.operator,i,t.lowerInflectionPoint.operator,a);r[l]||(r[l]=[]),r[l][e]=c}}computeIcon(e,t,i,o,n,s){return"ge"===i&&e>=t||"gt"===i&&e>t?s[0]:"ge"===n&&e>=o||"gt"===n&&e>o?s[1]:s[2]}applyColorScale(e,t){var i;const o=this.parsePoint(e,t.minimum,"min"),n=t.midpoint?this.parsePoint(e,t.midpoint):null,s=this.parsePoint(e,t.maximum,"max");if(null===o||null===s||o>=s||n&&(o>=n||n>=s))return;const r=this.getters.getActiveSheetId(),a=this.getters.getRangeFromSheetXC(r,e).zone,l=this.computedStyles[r],c=[];t.midpoint&&n?(c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,n,t.minimum.color,t.midpoint.color)}),c.push({minValue:n,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(n,s,t.midpoint.color,t.maximum.color)})):c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,s,t.minimum.color,t.maximum.color)});for(let e=a.top;e<=a.bottom;e++)for(let t=a.left;t<=a.right;t++){const a=this.getters.getEvaluatedCell({sheetId:r,col:t,row:e});if(a.type===cn.number){const r=Le(a.value,o,s);let h;h=2===c.length&&n?r<=n?this.colorCell(r,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(r,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(r,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),l[t]||(l[t]=[]),l[t][e]=(null===(i=l[t])||void 0===i?void 0:i[e])||{},l[t][e].fillColor=Et(h)}}}computeColorDiffUnits(e,t,i,o){const n=t-e;return[((i>>16)%256-(o>>16)%256)/n,((i>>8)%256-(o>>8)%256)/n,(i%256-o%256)/n]}colorCell(e,t,i,o){const[n,s,r]=o;return Math.round((i>>16)%256-n*(e-t))<<16|Math.round((i>>8)%256-s*(e-t))<<8|Math.round(i%256-r*(e-t))}adaptRules(e,t,i,o){if(0===i.length&&0===o.length)return;const n=this.getters.getConditionalFormats(e),s=n.findIndex((e=>e.id===t.id));let r=[];s>-1&&(r=n[s].ranges),r=r.concat(i);const a=to(r,o);0!==a.length?this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:t.id,rule:t.rule,stopIfTrue:t.stopIfTrue},ranges:a.map((t=>this.getters.getRangeDataFromXc(e,t))),sheetId:e}):this.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:t.id,sheetId:e})}pasteCf(e,t,i){const o=Zt(t.col,t.row);for(let n of this.getters.getConditionalFormats(e.sheetId))for(let s of n.ranges)if(Ji(e.col,e.row,this.getters.getRangeFromSheetXC(e.sheetId,s).zone)){const s=n,r=[];if("CUT"===i&&r.push(Zt(e.col,e.row)),e.sheetId===t.sheetId)this.adaptRules(e.sheetId,s,[o],r);else{this.adaptRules(e.sheetId,s,[],r);const i=this.getCFToCopyTo(t.sheetId,s);this.adaptRules(t.sheetId,i,[o],[])}}}getCFToCopyTo(e,t){const i=this.getters.getConditionalFormats(e).find((e=>e.stopIfTrue===t.stopIfTrue&&ht(e.rule,t.rule)));return i||{...t,id:this.uuidGenerator.uuidv4(),ranges:[]}}}nb.getters=["getConditionalIcon","getCellComputedStyle"];class sb extends Jv{constructor(){super(...arguments),this.filterValues={},this.hiddenRows=new Set,this.isEvaluationDirty=!1}allowDispatch(e){if("UPDATE_FILTER"===e.type)if(!this.getters.getFilterId(e))return 79;return 0}handle(e){switch(e.type){case"UNDO":case"REDO":case"UPDATE_CELL":case"EVALUATE_CELLS":case"ACTIVATE_SHEET":case"REMOVE_FILTER_TABLE":case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":this.isEvaluationDirty=!0;break;case"START":for(const e of this.getters.getSheetIds()){this.filterValues[e]={};for(const t of this.getters.getFilters(e))this.filterValues[e][t.id]=[]}break;case"CREATE_SHEET":this.filterValues[e.sheetId]={};break;case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":this.updateHiddenRows();break;case"UPDATE_FILTER":this.updateFilter(e),this.updateHiddenRows();break;case"DUPLICATE_SHEET":const t={};for(const i of this.getters.getFilters(e.sheetIdTo)){const o=i.zoneWithHeaders;t[i.id]=this.getFilterValues({sheetId:e.sheetId,col:o.left,row:o.top})}this.filterValues[e.sheetIdTo]=t}}finalize(){this.isEvaluationDirty&&(this.updateHiddenRows(),this.isEvaluationDirty=!1)}isRowFiltered(e,t){return e===this.getters.getActiveSheetId()&&this.hiddenRows.has(t)}getCellBorderWithFilterBorder(e){const{sheetId:t,col:i,row:o}=e;let n;for(let e of this.getters.getFilterTables(t)){const s=e.zone;if(Ji(i,o,s)){const e=this.intersectZoneWithViewport(t,s);n={top:o===e.top?Y:void 0,bottom:o===e.bottom?Y:void 0,left:i===e.left?Y:void 0,right:i===e.right?Y:void 0}}}const s=this.getters.getCellBorder(e),r={...n,...ut(s||{})};return nt(r)?null:r}getFilterHeaders(e){const t=[];for(let i of this.getters.getFilterTables(e)){const o=i.zone;if(!o)continue;const n=o.top;for(let i=o.left;i<=o.right;i++)this.getters.isColHidden(e,i)||this.getters.isRowHidden(e,n)||t.push({col:i,row:n})}return t}getFilterValues(e){const t=this.getters.getFilterId(e),i=e.sheetId;return t&&this.filterValues[i]&&this.filterValues[i][t]||[]}isFilterHeader({sheetId:e,col:t,row:i}){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===i))}isFilterActive(e){var t,i;const o=this.getters.getFilterId(e),n=e.sheetId;return Boolean(o&&(null===(i=null===(t=this.filterValues[n])||void 0===t?void 0:t[o])||void 0===i?void 0:i.length))}intersectZoneWithViewport(e,t){return{left:this.getters.findVisibleHeader(e,"COL",t.left,t.right),right:this.getters.findVisibleHeader(e,"COL",t.right,t.left),top:this.getters.findVisibleHeader(e,"ROW",t.top,t.bottom),bottom:this.getters.findVisibleHeader(e,"ROW",t.bottom,t.top)}}updateFilter({col:e,row:t,values:i,sheetId:o}){const n=this.getters.getFilterId({sheetId:o,col:e,row:t});n&&(this.filterValues[o]||(this.filterValues[o]={}),this.filterValues[o][n]=i)}updateHiddenRows(){var e,t;const i=this.getters.getActiveSheetId(),o=this.getters.getFilters(i).sort(((e,t)=>e.zoneWithHeaders.top-t.zoneWithHeaders.top)),n=new Set;for(let s of o){if(this.getters.isRowHiddenByUser(i,s.zoneWithHeaders.top))continue;if(n.has(s.zoneWithHeaders.top))continue;const o=null===(t=null===(e=this.filterValues[i])||void 0===e?void 0:e[s.id])||void 0===t?void 0:t.map(gt);if(o&&s.filteredZone)for(let e=s.filteredZone.top;e<=s.filteredZone.bottom;e++){const t=this.getCellValueAsString(i,s.col,e);o.includes(t)&&n.add(e)}}this.hiddenRows=n}getCellValueAsString(e,t,i){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:i}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets){const e=t.id;for(const i of t.filterTables){const o=Hi(i.range),n=[],s=[];for(const i of $e(0,oo(o).numberOfCols)){const r={sheetId:t.id,col:o.left+i,row:o.top},a=this.getFilterValues(r),l=this.getters.getFilter(r);if(!l)continue;const c=l.filteredZone?so(l.filteredZone).map((t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue)):[];if(a.length){const e=c.filter((e=>e)).filter((e=>!a.includes(e)));n.push({colId:i,displayedValues:[...new Set(e)],displayBlanks:!a.includes("")&&c.some((e=>!e))})}const h={col:l.col,row:l.zoneWithHeaders.top,sheetId:e},d=this.getters.getEvaluatedCell(h).formattedValue,u=this.getUniqueColNameForExcel(i,d,s);s.push(u),t.cells[Zt(h.col,h.row)]={...t.cells[Zt(h.col,h.row)],content:u,value:u,isFormula:!1}}i.filters=n}}}getUniqueColNameForExcel(e,t,i){t||(t=`Column${e}`);let o=t,n=2;for(;i.includes(o);)o=t+String(n),n++;return o}}sb.getters=["getCellBorderWithFilterBorder","getFilterHeaders","getFilterValues","isFilterHeader","isRowFiltered","isFilterActive"];class rb{constructor(e,t,i,o,n,s){this.getters=e,this.sheetId=t,this.boundaries=i,this.viewportWidth=o.width,this.viewportHeight=o.height,this.offsetScrollbarX=s.x,this.offsetScrollbarY=s.y,this.canScrollVertically=n.canScrollVertically,this.canScrollHorizontally=n.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:i,size:o}=this.getters.getColDimensions(this.sheetId,e),{end:n,size:s}=this.getters.getRowDimensions(this.sheetId,t),r=this.searchHeaderIndex("COL",i-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,r),l=this.searchHeaderIndex("ROW",n-this.viewportHeight,0),c=this.getters.getRowSize(this.sheetId,l);let h=i-this.offsetCorrectionX;this.canScrollHorizontally&&(h+=Math.max(F,Math.min(a,this.viewportWidth-o)),h=Math.max(h,this.viewportWidth));let d=n-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(D+5,Math.min(c,this.viewportHeight-s)),d=Math.max(d,this.viewportHeight)),{width:h,height:d}}getColIndex(e,t=!1){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX,this.left,t)}getRowIndex(e,t=!1){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY,this.top,t)}adjustPosition(e){const t=this.sheetId;e||(e=this.getters.getSheetPosition(t));const i=this.getters.getMainCellPosition({sheetId:t,...e}),{col:o,row:n}=this.getters.getNextVisibleCellPosition(i);Ji(o,this.boundaries.top,this.boundaries)&&this.adjustPositionX(o),Ji(this.boundaries.left,n,this.boundaries)&&this.adjustPositionY(n)}adjustPositionX(e){const t=this.sheetId,{end:i}=this.getters.getColDimensions(t,e),o=this.getters.getNumberCols(t);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<i){let i=e;for(;this.getters.isColHidden(t,i)&&e<o;)i++;const n=this.getters.getColDimensions(t,i).end,s=this.searchHeaderIndex("COL",n-this.viewportWidth-this.offsetCorrectionX,this.boundaries.left,!0);this.offsetX=this.getters.getColDimensions(t,s).end-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX()}else if(this.left>e){let i=e;for(;this.getters.isColHidden(t,i)&&e>0;)i--;this.offsetX=this.getters.getColDimensions(t,i).start-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX()}}adjustPositionY(e){const t=this.sheetId,{end:i}=this.getters.getRowDimensions(t,e),o=this.getters.getNumberRows(t);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<i){let i=e;for(;this.getters.isRowHidden(t,i)&&e<o;)i++;const n=this.getters.getRowDimensions(t,i).end,s=this.searchHeaderIndex("ROW",n-this.viewportHeight-this.offsetCorrectionY,this.boundaries.top,!0);this.offsetY=this.getters.getRowDimensions(t,s).end-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY()}else if(this.top>e){let i=e;for(;this.getters.isRowHidden(t,i)&&e>0;)i--;this.offsetY=this.getters.getRowDimensions(t,i).start-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY()}}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getRect(e){const t=Xi(e,this.zone);if(t){return{x:this.getters.getColRowOffset("COL",this.zone.left,t.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset("ROW",this.zone.top,t.top)+this.offsetCorrectionY,width:Math.min(this.getters.getColRowOffset("COL",t.left,t.right+1),this.viewportWidth),height:Math.min(this.getters.getColRowOffset("ROW",t.top,t.bottom+1),this.viewportHeight)}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,i=0,o=!1){let n=0;const s=this.sheetId,r=this.getters.getNumberHeaders(s,e);for(let a=i;a<=r-1;a++){const i=o||"COL"!==e?a<this.top&&a>this.bottom:a<this.left&&a>this.right;if(!this.getters.isHeaderHidden(s,e,a)&&!i&&(n+="COL"===e?this.getters.getColSize(s,a):this.getters.getRowSize(s,a),n>t))return a}return-1}get zone(){return{left:this.left,right:this.right,top:this.top,bottom:this.bottom}}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetScrollbarX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetScrollbarY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){const{width:e}=this.getMaxSize();this.viewportWidth+this.offsetScrollbarX>e&&(this.offsetScrollbarX=Math.max(0,e-this.viewportWidth))}this.left=this.getColIndex(this.offsetScrollbarX,!0),this.right=this.getColIndex(this.offsetScrollbarX+this.viewportWidth,!0),-1===this.right&&(this.right=this.boundaries.right),this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){const{height:e}=this.getMaxSize();this.viewportHeight+this.offsetScrollbarY>e&&(this.offsetScrollbarY=Math.max(0,e-this.viewportHeight))}this.top=this.getRowIndex(this.offsetScrollbarY,!0),this.bottom=this.getRowIndex(this.offsetScrollbarY+this.viewportWidth,!0),-1===this.bottom&&(this.bottom=this.boundaries.bottom),this.adjustViewportZoneY()}adjustViewportZoneX(){const e=this.sheetId;this.left=this.searchHeaderIndex("COL",this.offsetScrollbarX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex("COL",this.viewportWidth,this.left)),-1===this.left&&(this.left=this.boundaries.left),-1===this.right&&(this.right=this.getters.getNumberCols(e)-1),this.offsetX=this.getters.getColDimensions(e,this.left).start-this.getters.getColDimensions(e,this.boundaries.left).start}adjustViewportZoneY(){const e=this.sheetId;this.top=this.searchHeaderIndex("ROW",this.offsetScrollbarY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex("ROW",this.viewportHeight,this.top)),-1===this.top&&(this.top=this.boundaries.top),-1===this.bottom&&(this.bottom=this.getters.getNumberRows(e)-1),this.offsetY=this.getters.getRowDimensions(e,this.top).start-this.getters.getRowDimensions(e,this.boundaries.top).start}}class ab extends Jv{constructor(){super(...arguments),this.viewports={},this.sheetViewWidth=1e3,this.sheetViewHeight=1e3,this.gridOffsetX=0,this.gridOffsetY=0,this.sheetsWithDirtyViewports=new Set}allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.checkScrollingDirection(e);case"RESIZE_SHEETVIEW":return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return 0}}handleEvent(e){switch(e.type){case"HeadersSelected":case"AlterZone":break;case"ZonesSelected":let{col:t,row:i}=ao(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const o=e.previousAnchor.zone,n=e.anchor.zone,{top:s,bottom:r,left:a,right:l}=this.getters.getActiveMainViewport();o.left===n.left&&o.right===n.right&&(t=a>t||t>l?a:t),o.top===n.top&&o.bottom===n.bottom&&(i=s>i||i>r?s:i)}const o=this.getters.getActiveSheetId();t=Math.min(t,this.getters.getNumberCols(o)-1),i=Math.min(i,this.getters.getNumberRows(o)-1),this.refreshViewport(this.getters.getActiveSheetId(),{col:t,row:i})}}handle(e){var t;switch(this.cleanViewports(),e.type){case"START":this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case"UNDO":case"REDO":this.resetSheetViews();break;case"RESIZE_SHEETVIEW":this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case"SET_VIEWPORT_OFFSET":this.setSheetViewOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const{top:i}=this.getActiveMainViewport(),o=this.getters.getActiveSheetId(),n=this.clipOffsetY(this.getters.getRowDimensions(o,i).start+this.sheetViewHeight);this.shiftVertically(n);break;case"SHIFT_VIEWPORT_UP":{const{top:e}=this.getActiveMainViewport(),t=this.getters.getActiveSheetId(),i=this.clipOffsetY(this.getters.getRowDimensions(t,e).end-this.sheetViewHeight);this.shiftVertically(i);break}case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UPDATE_FILTER":this.resetViewports(e.sheetId);break;case"UPDATE_CELL":("content"in e||"format"in e||void 0!==(null===(t=e.style)||void 0===t?void 0:t.fontSize))&&this.sheetsWithDirtyViewports.add(e.sheetId);break;case"ACTIVATE_SHEET":this.setViewports(),this.refreshViewport(e.sheetIdTo);break;case"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":this.resetViewports(this.getters.getActiveSheetId());break;case"DELETE_SHEET":this.sheetsWithDirtyViewports.delete(e.sheetId);break;case"START_EDITION":const{col:s,row:r}=this.getters.getActivePosition();this.refreshViewport(this.getters.getActiveSheetId(),{col:s,row:r})}}finalize(){for(const e of this.sheetsWithDirtyViewports)this.resetViewports(e);this.sheetsWithDirtyViewports=new Set,this.setViewports()}setViewports(){var e;const t=this.getters.getSheetIds();for(const i of t)(null===(e=this.viewports[i])||void 0===e?void 0:e.bottomRight)||this.resetViewports(i)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getColIndex(e))))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getRowIndex(e))))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getActiveMainViewport(){const e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getActiveSheetDOMScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetScrollbarX,scrollY:t.offsetScrollbarY}}getSheetViewVisibleCols(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>$e(e.left,e.right+1))).flat())].filter((t=>!this.getters.isHeaderHidden(e,"COL",t)))}getSheetViewVisibleRows(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>$e(e.top,e.bottom+1))).flat())].filter((t=>!this.getters.isHeaderHidden(e,"ROW",t)))}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:i,ySplit:o}=this.getters.getPaneDivisions(e);let{width:n,height:s}=t.getMaxSize();return{x:this.getters.getColDimensions(e,i).start,y:this.getters.getRowDimensions(e,o).start,width:n,height:s}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:i}=this.getMainViewportRect(),o=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-o.viewportWidth+1),maxOffsetY:Math.max(0,i-o.viewportHeight+1)}}getColRowOffsetInViewport(e,t,i){const o=this.getters.getActiveSheetId(),n=this.getters.getSheetViewVisibleCols(),s=this.getters.getSheetViewVisibleRows();if(i<t)return-this.getColRowOffsetInViewport(e,i,t);let r=0;const a="COL"===e?n:s;for(let n=t;n<i;n++)a.includes(n)&&(r+="COL"===e?this.getters.getColSize(o,n):this.getters.getRowSize(o,n));return r}isVisibleInViewport({sheetId:e,col:t,row:i}){return this.getSubViewports(e).some((e=>e.isVisible(t,i)))}getEdgeScrollCol(e,t,i){let o=!1,n=0,s=0;const{xSplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(o=!0,s=Kt(e-a),n=1):e<l&&i>=l&&c>0?(o=!0,s=Kt(l-e),n=-1):r&&t<l&&e>l&&(o=!0,s=Kt(e),n="reset"),{canEdgeScroll:o,direction:n,delay:s}}getEdgeScrollRow(e,t,i){let o=!1,n=0,s=0;const{ySplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(o=!0,s=Kt(e-a),n=1):e<l&&i>=l&&c>0?(o=!0,s=Kt(l-e),n=-1):r&&t<l&&e>l&&(o=!0,s=Kt(e),n="reset"),{canEdgeScroll:o,direction:n,delay:s}}getVisibleRect(e){const t=this.getters.getActiveSheetId(),i=this.getSubViewports(t).map((t=>t.getRect(e))).filter(ot);if(0===i.length)return{x:0,y:0,width:0,height:0};const o=Math.min(...i.map((e=>e.x))),n=Math.min(...i.map((e=>e.y))),s=Math.max(...i.map((e=>e.x+e.width)))-o,r=Math.max(...i.map((e=>e.y+e.height)))-n;return{x:o+this.gridOffsetX,y:n+this.gridOffsetY,width:s,height:r}}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,i).start}}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(ot)}checkPositiveDimension(e){return e.width<0||e.height<0?68:0}checkValuesAreDifferent(e){const{height:t,width:i}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===i&&e.height===t?76:0}checkScrollingDirection({offsetX:e,offsetY:t}){const i=this.getMainInternalViewport(this.getters.getActiveSheetId());return!i.canScrollHorizontally&&e>0||!i.canScrollVertically&&t>0?69:0}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e=this.getters.getSheetIds();for(let t of Object.keys(this.viewports))e.includes(t)||delete this.viewports[t]}resetSheetViews(){for(let e of Object.keys(this.viewports)){const t=this.getters.getSheetPosition(e);this.resetViewports(e);const i=this.getSubViewports(e);Object.values(i).forEach((e=>{e.adjustPosition(t)}))}}resizeSheetView(e,t,i=0,o=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=i,this.gridOffsetY=o,this.recomputeViewports()}recomputeViewports(){for(let e of Object.keys(this.viewports))this.resetViewports(e)}setSheetViewOffset(e,t){const i=this.getters.getActiveSheetId(),{maxOffsetX:o,maxOffsetY:n}=this.getMaximumSheetOffset();Object.values(this.getSubViewports(i)).forEach((i=>i.setViewportOffset(Le(e,0,o),Le(t,0,n))))}clipOffsetY(e){const{height:t}=this.getMainViewportRect(),i=t-this.sheetViewHeight;return e=Math.min(e,i),e=Math.max(e,0)}getViewportOffset(e){var t,i;return{x:(null===(t=this.viewports[e])||void 0===t?void 0:t.bottomRight.offsetScrollbarX)||0,y:(null===(i=this.viewports[e])||void 0===i?void 0:i.bottomRight.offsetScrollbarY)||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e),o=this.getters.getNumberCols(e),n=this.getters.getNumberRows(e),s=this.getters.getColRowOffset("COL",0,t,e),r=this.getters.getColRowOffset("ROW",0,i,e),{xRatio:a,yRatio:l}=this.getFrozenSheetViewRatio(e),c=a<1,h=l<1,d=this.getViewportOffset(e),u={topLeft:i&&t&&new rb(this.getters,e,{left:0,right:t-1,top:0,bottom:i-1},{width:s,height:r},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:i&&new rb(this.getters,e,{left:t,right:o-1,top:0,bottom:i-1},{width:this.sheetViewWidth-s,height:r},{canScrollHorizontally:c,canScrollVertically:!1},{x:c?d.x:0,y:0})||void 0,bottomLeft:t&&new rb(this.getters,e,{left:0,right:t-1,top:i,bottom:n-1},{width:s,height:this.sheetViewHeight-r},{canScrollHorizontally:!1,canScrollVertically:h},{x:0,y:h?d.y:0})||void 0,bottomRight:new rb(this.getters,e,{left:t,right:o-1,top:i,bottom:n-1},{width:this.sheetViewWidth-s,height:this.sheetViewHeight-r},{canScrollHorizontally:c,canScrollVertically:h},{x:c?d.x:0,y:h?d.y:0})};this.viewports[e]=u}refreshViewport(e,t){Object.values(this.getSubViewports(e)).forEach((e=>{e.adjustViewportZone(),e.adjustPosition(t)}))}shiftVertically(e){const{top:t}=this.getActiveMainViewport(),{scrollX:i}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(i,e);const{anchor:o}=this.getters.getSelection(),n=this.getActiveMainViewport().top-t;this.selection.selectCell(o.cell.col,o.cell.row+n)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],i=this.getters.getFigures(e),{scrollX:o,scrollY:n}=this.getActiveSheetScrollInfo(),{x:s,y:r}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of i)e.x>=s&&(e.x+e.width<=s+o||e.x>=a+o+s)||e.y>=r&&(e.y+e.height<=r+n||e.y>=l+n+r)||t.push(e);return t}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e),o=this.getters.getColDimensions(e,t).start,n=this.getters.getRowDimensions(e,i).start;return{xRatio:o/(this.sheetViewWidth+this.gridOffsetX),yRatio:n/(this.sheetViewHeight+this.gridOffsetY)}}}ab.getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getActiveSheetDOMScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio"];class lb{constructor(e,t,i){this.index=0,this.cells=e,this.getters=t,this.direction=i}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:i,tooltip:o}=An.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:i,tooltip:o,origin:{col:e.data.col,row:e.data.row}}}}class cb extends Jv{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:Le(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:Le(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:45;case"AUTOFILL_AUTO":const i=this.getters.getSelectedZone();return i.top===i.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||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),i=this.autofillZone;switch(this.direction){case"down":for(let o=t.left;o<=t.right;o++){const n=[];for(let e=t.top;e<=t.bottom;e++)n.push(Zt(o,e));const s=this.createGenerator(n);for(let t=i.top;t<=i.bottom;t++)this.computeNewCell(s,o,t,e)}break;case"up":for(let o=t.left;o<=t.right;o++){const n=[];for(let e=t.bottom;e>=t.top;e--)n.push(Zt(o,e));const s=this.createGenerator(n);for(let t=i.bottom;t>=i.top;t--)this.computeNewCell(s,o,t,e)}break;case"left":for(let o=t.top;o<=t.bottom;o++){const n=[];for(let e=t.right;e>=t.left;e--)n.push(Zt(e,o));const s=this.createGenerator(n);for(let t=i.right;t>=i.left;t--)this.computeNewCell(s,t,o,e)}break;case"right":for(let o=t.top;o<=t.bottom;o++){const n=[];for(let e=t.left;e<=t.right;e++)n.push(Zt(e,o));const s=this.createGenerator(n);for(let t=i.left;t<=i.right;t++)this.computeNewCell(s,t,o,e)}}e&&(this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0)}select(e,t){const i=this.getters.getSelectedZone();if(Ji(e,t,i))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,i.top-1,i.left,i.right),this.steps=i.top-t;break;case"down":this.saveZone(i.bottom+1,t,i.left,i.right),this.steps=t-i.bottom;break;case"left":this.saveZone(i.top,i.bottom,e,i.left-1),this.steps=i.left-e;break;case"right":this.saveZone(i.top,i.bottom,i.right+1,e),this.steps=e-i.right}this.autofill(!1)}}autofillAuto(){var e,t;const i=this.getters.getSelectedZone(),o=this.getters.getActiveSheetId();let n=i.left,s=i.bottom;if(n>0){let t={sheetId:o,col:n-1,row:s};for(;this.getters.getEvaluatedCell(t).type!==cn.empty||(null===(e=this.getters.getCell(t))||void 0===e?void 0:e.content);)s+=1,t={sheetId:o,col:n-1,row:s}}if(s===i.bottom&&(n=i.right,n<=this.getters.getNumberCols(o))){let e={sheetId:o,col:n+1,row:s};for(;this.getters.getEvaluatedCell(e).type!==cn.empty||(null===(t=this.getters.getCell(e))||void 0===t?void 0:t.content);)s+=1,e={sheetId:o,col:n+1,row:s}}s!==i.bottom&&(this.select(i.left,s-1),this.autofill(!0))}computeNewCell(e,t,i,o){const{cellData:n,tooltip:s,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=n;this.tooltip=s,o&&this.dispatch("AUTOFILL_CELL",{originCol:r.col,originRow:r.row,col:t,row:i,content:a,style:l,border:c,format:h})}getRule(e,t){const i=Mn.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((i=>i.condition(e,t)));return i&&i.generateRule(e,t)}createGenerator(e){const t=[],i=[],o=this.getters.getActiveSheetId();for(let t of e){const{col:e,row:n}=qt(t),s=this.getters.getCell({sheetId:o,col:e,row:n});i.push({col:e,row:n,cell:s,sheetId:o})}const n=i.map((e=>e.cell));for(let e of i){let i={type:"COPY_MODIFIER"};if(e&&e.cell){i=this.getRule(e.cell,n)||i}const o=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:o},rule:i})}return new lb(t,this.getters,this.direction)}saveZone(e,t,i,o){this.autofillZone={top:e,bottom:t,left:i,right:o}}getDirection(e,t){const i=this.getters.getSelectedZone(),o={up:{number:i.top-t,value:"up"},down:{number:t-i.bottom,value:"down"},left:{number:i.left-e,value:"left"},right:{number:e-i.right,value:"right"}};if(1===Object.values(o).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(o).find((e=>e.number>0?1:0)).value;const n=o.up.number>0?"up":"down",s=o.left.number>0?"left":"right";return Math.abs(o[n].number)>=Math.abs(o[s].number)?o[n].value:o[s].value}autoFillMerge(e,t,i,o){const n=this.getters.getActiveSheetId(),s={sheetId:n,col:i,row:o},r={sheetId:n,col:e,row:t};if(this.getters.isInMerge(s)&&!this.getters.isInMerge(r)){const e=this.getters.getMerge(s);e&&this.dispatch("REMOVE_MERGE",{sheetId:n,target:[e]})}const a=this.getters.getMerge(r);(null==a?void 0:a.topLeft.col)===e&&(null==a?void 0:a.topLeft.row)===t&&this.dispatch("ADD_MERGE",{sheetId:n,target:[{top:o,bottom:o+a.bottom-a.top,left:i,right:i+a.right-a.left}]})}drawGrid(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:i}=e,{x:o,y:n,width:s,height:r}=this.getters.getVisibleRect(this.autofillZone);s>0&&r>0&&(t.strokeStyle="black",t.lineWidth=i,t.setLineDash([3]),t.strokeRect(o,n,s,r),t.setLineDash([]))}}cb.layers=[5],cb.getters=["getAutofillTooltip"];class hb extends Jv{handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:i}=this.getters.getSelection();for(const o of t){const t=this.getAutomaticSums(e,o,i.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,i){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,i):this.sumData(e,t)}sumData(e,t){const i=this.dimensionsToSum(e,t),o=this.sumDimensions(e,t,i).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return i.has("ROW")&&i.has("COL")&&o.push(this.sumTotal(t)),o}sumAdjacentData(e,t,i){const{col:o,row:n}=Ji(i.col,i.row,t)?i:{col:t.left,row:t.top},s=this.findAdjacentData(e,o,n);return s?this.getters.isSingleCellOrMerge(e,t)||no(Yi(s,t))?[{position:{col:o,row:n},zone:s}]:this.sumDimensions(e,Yi(s,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,i){const o=this.getters.getSheet(e),n=this.getters.getMainCellPosition({sheetId:e,col:t,row:i}),s=this.findSuitableZoneToSum(o,n.col,n.row);if(s)return this.getters.expandZone(e,s)}findSuitableZoneToSum(e,t,i){const o=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:i-1}),n=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:i});if(this.isNumber(n)&&!this.isNumber(o))return this.findHorizontalZone(e,t,i);const s=this.findVerticalZone(e,t,i);if(this.isZoneValid(s))return s;const r=this.findHorizontalZone(e,t,i);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,i){const o={top:0,bottom:i-1,left:t,right:t},n=this.reduceZoneStart(e,o,o.bottom);return{...o,top:n}}findHorizontalZone(e,t,i){const o={top:i,bottom:i,left:0,right:t-1},n=this.reduceZoneStart(e,o,o.right);return{...o,left:n}}reduceZoneStart(e,t,i){const o=this.getters.getEvaluatedCellsInZone(e.id,t),n=$e(i,-1,-1),s=n.filter((e=>o[e]&&!o[e].isAutoSummable)),r=Math.max(...s),a=We(n.filter((e=>this.isNumber(o[e]))))[0]||[];return Math.max(...a)<r?1/0:Math.min(...a)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){var t;return e.type===cn.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(X))}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 i=new Set;return no(t)?(i.add(1===oo(t).numberOfCols?"COL":"ROW"),i):(this.lastColIsEmpty(e,t)&&i.add("ROW"),this.lastRowIsEmpty(e,t)&&i.add("COL"),0===i.size&&i.add("COL"),i)}sumDimensions(e,t,i){return[...i.has("COL")?this.sumColumns(t,e):[],...i.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:i}=e;return{position:{col:i,row:t},zone:{...e,top:t,right:i-1}}}sumColumns(e,t){const i=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,i.bottom-1)},so(i).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const i=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,i.right-1)},so(i).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const i of t){const{col:t,row:o}=i.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:`=SUM(${this.getters.zoneToXC(e,i.zone)})`})}}nextEmptyRow(e,t){let i=t.bottom+1;const{left:o,right:n}=t;for(;!this.getters.isEmpty(e,{bottom:i,top:i,left:o,right:n});)i++;return{...t,top:i,bottom:i}}nextEmptyCol(e,t){let i=t.right+1;const{top:o,bottom:n}=t;for(;!this.getters.isEmpty(e,{left:i,right:i,top:o,bottom:n});)i++;return{...t,left:i,right:i}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}hb.getters=["getAutomaticSums"];class db extends Jv{allowDispatch(e){if("OPEN_CELL_POPOVER"===e.type){try{us.get(e.popoverType)}catch(e){return 72}return 0}return 0}handle(e){switch(e.type){case"ACTIVATE_SHEET":case"CLOSE_CELL_POPOVER":this.persistentPopover=void 0;break;case"OPEN_CELL_POPOVER":this.persistentPopover={col:e.col,row:e.row,sheetId:this.getters.getActiveSheetId(),type:e.popoverType}}}getCellPopover({col:e,row:t}){var i,o;const n=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=null===(o=(i=us.get(this.persistentPopover.type)).onOpen)||void 0===o?void 0:o.call(i,e,this.getters);return(null==t?void 0:t.isOpen)?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}if(void 0===e||void 0===t||!this.getters.isVisibleInViewport({sheetId:n,col:e,row:t}))return{isOpen:!1};const s=this.getters.getMainCellPosition({sheetId:n,col:e,row:t}),r=us.getAll().map((e=>{var t;return null===(t=e.onHover)||void 0===t?void 0:t.call(e,s,this.getters)})).find((e=>null==e?void 0:e.isOpen));return(null==r?void 0:r.isOpen)?{...r,anchorRect:this.computePopoverAnchorRect(s)}:{isOpen:!1}}hasOpenedPopover(){return void 0!==this.persistentPopover}getPersistentPopoverTypeAtPosition({col:e,row:t}){if(this.persistentPopover&&this.persistentPopover.col===e&&this.persistentPopover.row===t)return this.persistentPopover.type}computePopoverAnchorRect({col:e,row:t}){const i=this.getters.getActiveSheetId(),o=this.getters.getMerge({sheetId:i,col:e,row:t});return o?this.getters.getVisibleRect(o):this.getters.getVisibleRect(co({col:e,row:t}))}}db.getters=["getCellPopover","getPersistentPopoverTypeAtPosition","hasOpenedPopover"];var ub;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(ub||(ub={}));class gb extends Jv{constructor(){super(...arguments),this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1},this.toSearch="",this.isSearchDirty=!1}handle(e){switch(e.type){case"UPDATE_SEARCH":this.updateSearch(e.toSearch,e.searchOptions);break;case"CLEAR_SEARCH":this.clearSearch();break;case"SELECT_SEARCH_PREVIOUS_MATCH":this.selectNextCell(ub.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(ub.next);break;case"REPLACE_SEARCH":this.replace(e.replaceWith);break;case"REPLACE_ALL_SEARCH":this.replaceAll(e.replaceWith);break;case"UNDO":case"REDO":case"REMOVE_FILTER_TABLE":case"UPDATE_FILTER":case"REMOVE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"EVALUATE_CELLS":case"UPDATE_CELL":this.isSearchDirty=!0;break;case"ACTIVATE_SHEET":this.refreshSearch()}}finalize(){this.isSearchDirty&&(this.refreshSearch(),this.isSearchDirty=!1)}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(ub.current)}updateRegex(){let e=_e(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),i=[];if(this.toSearch)for(const o of Object.values(t)){const{col:t,row:n}=this.getters.getCellPosition(o.id),s=this.getters.isColHidden(e,t),r=this.getters.isRowHidden(e,n);if(!s&&!r&&(o&&this.currentSearchRegex&&this.currentSearchRegex.test(this.getSearchableString({sheetId:e,col:t,row:n})))){const e={col:t,row:n,selected:!1};i.push(e)}}return i.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 i;i=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,i=(i%t.length+t.length)%t.length,this.selectedMatchIndex=i,this.selection.selectCell(t[i].col,t[i].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}}replaceMatch(e,t){if(!this.currentSearchRegex)return;const i=this.getters.getActiveSheetId(),o=this.getters.getCell({sheetId:i,...e}),{col:n,row:s}=e;if((null==o?void 0:o.isFormula)&&!this.searchOptions.searchFormulas)return;const r=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),a=this.getSearchableString({sheetId:i,col:n,row:s}).replace(r,t);this.dispatch("UPDATE_CELL",{sheetId:i,col:n,row:s,content:a})}replace(e){if(null===this.selectedMatchIndex)return;const t=this.searchMatches[this.selectedMatchIndex];this.replaceMatch(t,e),this.selectNextCell(ub.next)}replaceAll(e){const t=this.searchMatches.length;for(let i=0;i<t;i++)this.replaceMatch(this.searchMatches[i],e)}getSearchableString(e){const t=this.getters.getCell(e);return this.searchOptions.searchFormulas&&(null==t?void 0:t.isFormula)?t.content:this.getters.getEvaluatedCell(e).formattedValue}drawGrid(e){const{ctx:t}=e,i=this.getters.getActiveSheetId();for(const e of this.searchMatches){const o=this.getters.getMerge({sheetId:i,col:e.col,row:e.row}),n=o?o.left:e.col,s=o?o.right:e.col,r=o?o.top:e.row,a=o?o.bottom:e.row,{x:l,y:c,width:h,height:d}=this.getters.getVisibleRect({top:r,left:n,right:s,bottom:a});h>0&&d>0&&(t.fillStyle="#8B008B33",t.fillRect(l,c,h,d),e.selected&&(t.strokeStyle="#8B008B",t.strokeRect(l,c,h,d)))}}}gb.layers=[3],gb.getters=["getSearchMatches","getCurrentSelectedMatchIndex"];class pb extends Jv{isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,i){return"COL"===t?this.isColHidden(e,i):this.isRowHidden(e,i)}getNextVisibleCellPosition({sheetId:e,col:t,row:i}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",i,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,i,o){if(i<=o)for(let n=i;n<=o;n++)if(this.getters.doesHeaderExist(e,t,n)&&!this.isHeaderHidden(e,t,n))return n;if(i>o)for(let n=i;n>=o;n--)if(this.getters.doesHeaderExist(e,t,n)&&!this.isHeaderHidden(e,t,n))return n}findLastVisibleColRowIndex(e,t,{last:i,first:o}){return $e(i,o,-1).find((i=>!this.isHeaderHidden(e,t,i)))||o}findFirstVisibleColRowIndex(e,t){const i=this.getters.getNumberHeaders(e,t);for(let o=0;o<i;o++){if("COL"===t&&!this.isColHidden(e,o))return o;if("ROW"===t&&!this.isRowHidden(e,o))return o}}exportForExcel(e){for(const t of e.sheets)for(const[e,i]of Object.entries(t.rows)){const o=this.isRowHidden(t.id,Number(e));i.isHidden=o}}}pb.getters=["getNextVisibleCellPosition","findVisibleHeader","findLastVisibleColRowIndex","findFirstVisibleColRowIndex","isRowHidden","isColHidden","isHeaderHidden"];class mb extends Jv{getHighlights(){return this.prepareHighlights(this.getters.getComposerHighlights().concat(this.getters.getSelectionInputHighlights()))}prepareHighlights(e){return e.filter((e=>e.zone.top>=0&&e.zone.left>=0&&e.zone.bottom<this.getters.getNumberRows(e.sheetId)&&e.zone.right<this.getters.getNumberCols(e.sheetId))).map((e=>{const{numberOfRows:t,numberOfCols:i}=oo(e.zone),o=t*i==1?this.getters.expandZone(e.sheetId,e.zone):e.zone;return{...e,zone:o}}))}drawGrid(e){const{ctx:t,thinLineWidth:i}=e,o=this.getters.getActiveSheetId(),n=3*i;t.lineWidth=n;const s=this.getHighlights();for(let e of s.filter(((e,t)=>s.findIndex((t=>Ki(t.zone,e.zone)&&t.sheetId===o))===t))){const{x:i,y:o,width:s,height:r}=this.getters.getVisibleRect(e.zone);s>0&&r>0&&(t.strokeStyle=e.color,t.strokeRect(i+n/2,o+n/2,s-n,r-n),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(i+n,o+n,s-2*n,r-2*n))}}}mb.layers=[1],mb.getters=["getHighlights"];class fb extends Jv{constructor(){super(...arguments),this.boxes=[]}getColDimensionsInViewport(e,t){const i=Math.min(...this.getters.getSheetViewVisibleCols()),o=this.getters.getColRowOffsetInViewport("COL",i,t),n=this.getters.getColSize(e,t);return{start:o,size:n,end:o+(this.getters.isColHidden(e,t)?0:n)}}getRowDimensionsInViewport(e,t){const i=Math.min(...this.getters.getSheetViewVisibleRows()),o=this.getters.getColRowOffsetInViewport("ROW",i,t),n=this.getters.getRowSize(e,t);return{start:o,size:n,end:o+(this.getters.isRowHidden(e,t)?0:n)}}getHeaderOffset(e,t,i){let o=this.getters.getColRowOffsetInViewport(e,t,i);return this.getters.isDashboard()||(o+="ROW"===e?N:_),o}drawGrid(e,t){switch(t){case 0:this.boxes=this.getGridBoxes(),this.drawBackground(e),this.drawOverflowingCellBackground(e),this.drawCellBackground(e),this.drawBorders(e),this.drawTexts(e),this.drawIcon(e),this.drawFrozenPanes(e);break;case 7:this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawBackground(e){const{ctx:t,thinLineWidth:i}=e,{width:o,height:n}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,o+m,n+m);const s=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),r=s?.1*i:0;if(s)for(const e of this.boxes)t.strokeStyle="#E2E3E3",t.lineWidth=i,t.strokeRect(e.x+r,e.y+r,e.width-2*r,e.height-2*r)}drawCellBackground(e){const{ctx:t}=e;for(const e of this.boxes){let i=e.style;i.fillColor&&"#ffffff"!==i.fillColor&&(t.fillStyle=i.fillColor||"#ffffff",t.fillRect(e.x,e.y,e.width,e.height)),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())}}drawOverflowingCellBackground(e){var t,i;const{ctx:o,thinLineWidth:n}=e;for(const e of this.boxes)if(e.content&&e.isOverflow){const s=e.content.align||"left";let r,a;const l=e.y+n/2,c=e.height-n,h=Math.min((null===(t=e.clipRect)||void 0===t?void 0:t.width)||1/0,e.content.width);"left"===s?(r=e.x+n/2,a=h-2*n):"right"===s?(r=e.x+e.width-n/2,a=2*n-h):(r=((null===(i=e.clipRect)||void 0===i?void 0:i.x)||e.x+e.width/2-e.content.width/2)+n/2,a=h-2*n),o.fillStyle="#ffffff",o.fillRect(r,l,a,c)}}drawBorders(e){const{ctx:t,thinLineWidth:i}=e;for(let e of this.boxes){const t=e.border;if(t){const{x:i,y:n,width:s,height:r}=e;t.left&&o(t.left,i,n,i,n+r),t.top&&o(t.top,i,n,i+s,n),t.right&&o(t.right,i+s,n,i+s,n+r),t.bottom&&o(t.bottom,i,n+r,i+s,n+r)}}function o([e,o],n,s,r,a){t.strokeStyle=o,t.lineWidth=("thin"===e?2:3)*i,t.beginPath(),t.moveTo(n,s),t.lineTo(r,a),t.stroke()}}drawTexts(e){const{ctx:t,thinLineWidth:i}=e;let o;t.textBaseline="top";for(let e of this.boxes)if(e.content){const n=e.style||{},s=e.content.align||"left",r=Be(n);r!==o&&(o=r,t.font=r),t.fillStyle=n.textColor||"#000";let a=e.x;if(a+="left"===s?V+(e.image?e.image.size+U:0):"right"===s?e.width-V-(e.isFilterHeader?20:0):e.width/2,t.textAlign=s,e.clipRect){t.save(),t.beginPath();const{x:i,y:o,width:n,height:s}=e.clipRect;t.rect(i,o,n,s),t.clip()}const l=He(n),c=e.content.textLines.length;let h=this.computeTextYCoordinate(e,l,c);for(let o of e.content.textLines){if(t.fillText(o,Math.round(a),Math.round(h)),n.strikethrough||n.underline){const e=Ue(t,o,n);let r=a;"right"===s?r-=e:"center"===s&&(r-=e/2),n.strikethrough&&t.fillRect(r,h+l/2,e,2.6*i),n.underline&&t.fillRect(r,h+l+1,e,1.3*i)}h+=V+l}e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const i=e.image.image;if(e.image.clipIcon){t.save(),t.beginPath();const{x:i,y:o,width:n,height:s}=e.image.clipIcon;t.rect(i,o,n,s),t.clip()}const o=e.image.size,n=this.computeTextYCoordinate(e,o);t.drawImage(i,e.x+U,n,o,o),e.image.clipIcon&&t.restore()}}computeTextYCoordinate(e,t,i=1){const o=e.y+1,n=Pe(t,i),s=e.height>n+2*V,r=e.verticalAlign||"middle";if(s){if("middle"===r)return o+(e.height-n)/2;if("bottom"===r)return o+e.height-n-V}return o+V}drawHeaders(e){const{ctx:t,thinLineWidth:i}=e,o=this.getters.getSheetViewVisibleCols(),n=o[0],s=o[o.length-1],r=this.getters.getSheetViewVisibleRows(),a=r[0],l=r[r.length-1],{width:c,height:h}=this.getters.getSheetViewDimensionWithHeaders(),d=this.getters.getSelectedZones(),u=function(e){const t=new Set;for(let i of e)for(let e of $e(i.left,i.right+1))t.add(e);return t}(d),g=function(e){const t=new Set;for(let i of e)for(let e of $e(i.top,i.bottom+1))t.add(e);return t}(d),p=this.getters.getActiveSheetId(),m=this.getters.getNumberCols(p),f=this.getters.getNumberRows(p),E=this.getters.getActiveCols(),w=this.getters.getActiveRows();t.font=`400 11px ${Z}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=i,t.strokeStyle="#333";for(let e=n;e<=s;e++){const i={left:e,right:e,top:0,bottom:f-1},{x:o,width:n}=this.getters.getVisibleRect(i),s=this.getters.doesZonesContainFilter(p,[i]),r=E.has(e),a=u.has(e);t.fillStyle=r?s?R:C:a?s?A:b:s?T:v,t.fillRect(o,0,n,N)}for(let e=a;e<=l;e++){const i={top:e,bottom:e,left:0,right:m-1},{y:o,height:n}=this.getters.getVisibleRect(i),s=this.getters.doesZonesContainFilter(p,[i]),r=w.has(e),a=g.has(e);t.fillStyle=r?s?R:C:a?s?A:b:s?T:v,t.fillRect(0,o,_,n)}t.beginPath(),t.moveTo(_,0),t.lineTo(_,h),t.moveTo(0,N),t.lineTo(c,N),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(const e of o){const i=this.getters.getColSize(p,e),o=Wt(e);t.fillStyle=E.has(e)?"#fff":S;let s=this.getHeaderOffset("COL",n,e);t.fillText(o,s+i/2,13),t.moveTo(s+i,0),t.lineTo(s+i,N)}for(const e of r){const i=this.getters.getRowSize(p,e);t.fillStyle=w.has(e)?"#fff":S;let o=this.getHeaderOffset("ROW",a,e);t.fillText(String(e+1),24,o+i/2),t.moveTo(0,o+i),t.lineTo(_,o+i)}t.stroke()}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:i}=e,{x:o,y:n}=this.getters.getMainViewportCoordinates(),s=this.getters.isDashboard()?0:_,r=this.getters.isDashboard()?0:N;t.lineWidth=6*i,t.strokeStyle="#BCBCBC",t.beginPath(),o&&(t.moveTo(s+o,0),t.lineTo(s+o,r)),n&&(t.moveTo(0,r+n),t.lineTo(s,r+n)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:i}=e,{x:o,y:n}=this.getters.getMainViewportCoordinates(),s=this.getters.getSheetViewVisibleCols(),r=s[0],a=s[s.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:r,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:_,u=this.getters.isDashboard()?0:N;t.lineWidth=6*i,t.strokeStyle="#DADFE8",t.beginPath(),o&&(t.moveTo(d+o,u),t.lineTo(d+o,h.height+u)),n&&(t.moveTo(d,u+n),t.lineTo(h.width+d,u+n)),t.stroke()}findNextEmptyCol(e,t,i){const o=this.getters.getActiveSheetId();let n=e;for(;n<t;){const e={sheetId:o,col:n+1,row:i},t=this.getters.getEvaluatedCell(e),s=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==cn.empty||this.getters.isInMerge(e)||(null==s?void 0:s.left))return n;n++}return n}findPreviousEmptyCol(e,t,i){const o=this.getters.getActiveSheetId();let n=e;for(;n>t;){const e={sheetId:o,col:n-1,row:i},t=this.getters.getEvaluatedCell(e),s=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==cn.empty||this.getters.isInMerge(e)||(null==s?void 0:s.right))return n;n--}return n}computeCellAlignment(e,t){const i=this.getters.getCell(e);if((null==i?void 0:i.isFormula)&&this.getters.shouldShowFormulas())return"left";const{align:o}=this.getters.getCellStyle(e),n=this.getters.getEvaluatedCell(e);return t&&n.type===cn.number?"center"!==o?"left":o:o||n.defaultAlign}createZoneBox(e,t,i){const{left:o,right:n}=i,s=t.left,r=t.top,a={sheetId:e,col:s,row:r},c=this.getters.getEvaluatedCell(a),h=this.getters.shouldShowFormulas(),{x:d,y:u,width:g,height:p}=this.getters.getVisibleRect(t),{verticalAlign:m}=this.getters.getCellStyle(a),f={x:d,y:u,width:g,height:p,border:this.getters.getCellBorderWithFilterBorder(a)||void 0,style:this.getters.getCellComputedStyle(a),verticalAlign:m};if(c.type===cn.empty)return f;const v=this.getters.getConditionalIcon(a),b=He(f.style),C=v?U+b:0;v&&(f.image={type:"icon",size:b,clipIcon:{x:f.x,y:f.y,width:Math.min(C,g),height:p},image:Mg[v].img}),f.isFilterHeader=this.getters.isFilterHeader(a);const S=f.isFilterHeader?19:0,E=this.getters.getCellComputedStyle(a),w=E.wrapping||"overflow",y="wrap"!==w||h?void 0:g-2*V,x=this.getters.getCellMultiLineText(a,y),I=Math.max(...x.map((e=>this.getters.getTextWidth(e,E)+V))),R=C+I+S,T=this.computeCellAlignment(a,R>g);f.content={textLines:x,width:"overflow"===w?I:g,align:T},c.type===cn.error&&c.error.logLevel>l.silent&&(f.error=c.error.message);const A=R>g||b>p;if(v||f.isFilterHeader)f.clipRect={x:f.x+C,y:f.y,width:Math.max(0,g-C-S),height:p};else if(A&&"overflow"===w){let e,i;switch(this.getters.isInMerge(a)?(e=this.getters.getMerge(a).right,i=s):(e=this.findNextEmptyCol(s,n,r),i=this.findPreviousEmptyCol(s,o,r),f.isOverflow=!0),T){case"left":{const i=co({col:e,row:r}),{x:o,y:n,width:s,height:a}=this.getters.getVisibleRect(Yi(t,i));(s<R||b>a||x.length>1)&&(f.clipRect={x:o,y:n,width:s,height:a});break}case"right":{const e=co({col:i,row:r}),{x:o,y:n,width:s,height:a}=this.getters.getVisibleRect(Yi(t,e));(s<R||b>a||x.length>1)&&(f.clipRect={x:o,y:n,width:s,height:a});break}case"center":{const o={...t,left:i,right:e},{x:n,y:s,height:r,width:a}=this.getters.getVisibleRect(o),l=R/2,c=f.x+f.width/2;if(n+a<c+l||n>c-l||b>r||x.length>1){const e=n>c-l?n:c-l,t=n+a-e;f.clipRect={x:e,y:s,width:t,height:r}}break}}}else("clip"===w||"wrap"===w||x.length>1)&&(f.clipRect={x:f.x,y:f.y,width:g,height:p});return f}getGridBoxes(){const e=[],t=this.getters.getSheetViewVisibleCols(),i=t[0],o=t[t.length-1],n=this.getters.getSheetViewVisibleRows(),s={left:i,right:o,top:n[0],bottom:n[n.length-1]},r=this.getters.getActiveSheetId();for(const i of n)for(const o of t){const t={sheetId:r,col:o,row:i};this.getters.isInMerge(t)||e.push(this.createZoneBox(r,co(t),s))}for(const t of this.getters.getMerges(r))if(!this.getters.isMergeHidden(r,t)&&Qi(t,s)){const i=this.createZoneBox(r,t,s),o=this.getters.getCellBorder({sheetId:r,col:t.right,row:t.bottom});i.border={...i.border,bottom:o?o.bottom:void 0,right:o?o.right:void 0},i.isMerge=!0,e.push(i)}return e}}fb.layers=[0,7],fb.getters=["getColDimensionsInViewport","getRowDimensionsInViewport"];class vb extends Jv{constructor(e,t,i){if(i&&t.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");super(e),this.inputHasSingleRange=i,this.ranges=[],this.focusedRangeIndex=null,this.willAddNewRange=!1,this.insertNewRange(0,t),this.activeSheet=this.getters.getActiveSheetId(),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}allowDispatch(e){switch(e.type){case"ADD_EMPTY_RANGE":if(this.inputHasSingleRange&&1===this.ranges.length)return 30;break;case"CHANGE_RANGE":if(this.inputHasSingleRange&&e.value.split(",").length>1)return 30}return 0}handleEvent(e){const t=Wi(e.anchor.zone),i=this.activeSheet,o=this.getters.getActiveSheetId(),n=this.getters.getSheetName(o);this.add([o===i?t:`${ke(n)}!${t}`])}handle(e){switch(e.type){case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"FOCUS_RANGE":this.focus(this.getIndex(e.rangeId));break;case"CHANGE_RANGE":{const t=this.getIndex(e.rangeId);if(null!==t&&this.focusedRangeIndex!==t&&this.focus(t),null!==t){const i=e.value.replace(/^,+/,"").split(",").map((e=>e.trim()));this.setRange(t,i)}break}case"ADD_EMPTY_RANGE":this.insertNewRange(this.ranges.length,[""]),this.focusLast();break;case"REMOVE_RANGE":const t=this.getIndex(e.rangeId);null!==t&&this.removeRange(t);break;case"STOP_SELECTION_INPUT":this.willAddNewRange=!1;break;case"PREPARE_SELECTION_INPUT_EXPANSION":{const e=this.focusedRangeIndex;null===e||this.inputHasSingleRange||(this.willAddNewRange=""!==this.ranges[e].xc.trim());break}case"ACTIVATE_SHEET":if(e.sheetIdFrom!==e.sheetIdTo){const{col:t,row:i}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),o=this.getters.expandZone(e.sheetIdTo,co({col:t,row:i}));this.selection.resetAnchor(this,{cell:{col:t,row:i},zone:o})}}}getSelectionInputValue(){return this.cleanInputs(this.ranges.map((e=>e.xc?e.xc:"")))}getSelectionInputHighlights(){return this.ranges.map((e=>this.inputToHighlights(e))).flat()}focus(e){this.focusedRangeIndex=e}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null}add(e){null!==this.focusedRangeIndex&&0!==e.length&&(this.willAddNewRange?(this.insertNewRange(this.ranges.length,e),this.focusLast(),this.willAddNewRange=!1):this.setRange(this.focusedRangeIndex,e))}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){const i=Math.max(0,...this.ranges.map((e=>Number(e.id))));this.ranges.splice(e,0,...t.map(((e,t)=>({xc:e,id:i+t+1,color:St[(i+t)%St.length]}))))}setRange(e,t){const[,...i]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,i),i.length&&this.focus(e+i.length)}removeRange(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const i=this.cleanInputs([e]).filter((e=>this.getters.isRangeValid(e))).filter((e=>this.shouldBeHighlighted(this.activeSheet,e)));return i.map((e=>{const{sheetName:i}=$t(e);return{zone:this.getters.getRangeFromSheetXC(this.activeSheet,e).zone,sheetId:i&&this.getters.getSheetIdByName(i)||this.activeSheet,color:t}}))}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:i}=$t(t),o=this.getters.getSheetIdByName(i),n=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(o===n||void 0===o&&n===e)}getIndex(e){const t=this.ranges.findIndex((t=>t.id===e));return t>=0?t:null}}vb.layers=[1],vb.getters=[];class bb extends Jv{get currentInput(){return this.focusedInputId?this.inputs[this.focusedInputId]:null}constructor(e){super(e),this.config=e,this.inputs={},this.focusedInputId=null}allowDispatch(e){var t,i;if("FOCUS_RANGE"===e.type){const o=null===(t=this.currentInput)||void 0===t?void 0:t.getIndex(e.rangeId);if(this.focusedInputId===e.id&&(null===(i=this.currentInput)||void 0===i?void 0:i.focusedRangeIndex)===o)return 29}return this.currentInput?this.currentInput.allowDispatch(e):0}handle(e){var t;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];break;case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"ADD_EMPTY_RANGE":case"REMOVE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id];this.selection.capture(t,{cell:{col:0,row:0},zone:co({col:0,row:0})},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}break;case"FOCUS_RANGE":case"CHANGE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id],i=t.ranges.find((t=>t.id===e.rangeId)),o=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(o,(null==i?void 0:i.xc)||"A1").zone;this.selection.capture(t,{cell:{col:n.left,row:n.top},zone:n},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}}null===(t=this.currentInput)||void 0===t||t.handle(e)}getSelectionInput(e){return this.inputs[e]?this.inputs[e].ranges.map(((t,i)=>Object.assign({},t,{color:this.focusedInputId===e&&null!==this.inputs[e].focusedRangeIndex&&this.isRangeValid(t.xc)?t.color:null,isFocused:this.focusedInputId===e&&this.inputs[e].focusedRangeIndex===i}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:i}=$t(e);return null!==t.match(Pt)&&(!i||void 0!==this.getters.getSheetIdByName(i))}getSelectionInputValue(e){return this.inputs[e].getSelectionInputValue()}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].getSelectionInputHighlights():[]}initInput(e,t,i=!1){if(this.inputs[e]=new vb(this.config,t,i),0===t.length){const t=this.inputs[e],i={zone:co({col:0,row:0}),cell:{col:0,row:0}};this.selection.capture(t,i,{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e}}unfocus(){this.selection.release(this.currentInput),this.focusedInputId=null}}bb.layers=[1],bb.getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];class Cb{constructor(){this.subscriptions={}}on(e,t,i){if(!i)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:i})}trigger(e,t){const i=this.subscriptions[e]||[];for(let e=0,o=i.length;e<o;e++){const o=i[e];o.callback.call(o.owner,t)}}off(e,t){const i=this.subscriptions[e];i&&(this.subscriptions[e]=i.filter((e=>e.owner!==t)))}clear(){this.subscriptions={}}}function Sb(e,t){return{...e,definition:Rr(e.definition,t)}}function Eb(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let i=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(let t of e)i>t&&i--}if("ADD_COLUMNS_ROWS"===t.type){i=i>("before"===t.position?t.base-1:t.base)?i+t.quantity:i}return i>0?{...e,quantity:i}:void 0}rg.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],Sb),rg.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],Sb),rg.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const i=t.sheetId;if(e.targetSheetId===i||e.sheetId===i)return;return e})),rg.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),rg.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){var i;if(e.name===t.name)return{...e,name:(null===(i=e.name)||void 0===i?void 0:i.match(/\d+/))?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),rg.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE","CREATE_FILTER_TABLE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const i=[];for(const o of e.target)for(const e of t.target)Qi(o,e)||i.push({...o});if(i.length)return{...e,target:i};return})),rg.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],Eb),rg.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],Eb),rg.addTransformation("CREATE_FILTER_TABLE",["CREATE_FILTER_TABLE","ADD_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;for(const i of e.target)for(const e of t.target)if(Qi(e,i))return;return e}));const wb=[{match:function(e){return"sheetId"in e},fn:Ib},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const i=Ib(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;const o=[];for(const i of e.target){const e=ms(i,t);e&&o.push(e)}if(!o.length)return"IGNORE_COMMAND";return{...e,target:o}}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const i=Ib(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const i="COL"===t.dimension?"col":"row";let o=e[i];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(o))return"IGNORE_COMMAND";for(let t of e)o>=t&&o--}"ADD_COLUMNS_ROWS"===t.type&&(o>t.base||o===t.base&&"before"===t.position)&&(o+=t.quantity);return{...e,[i]:o}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const i of t.target){if(!(e.col===i.left&&e.row===i.top)&&Ji(e.col,e.row,i))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e},fn:function(e,t){const i=Ib(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const i="ADD_COLUMNS_ROWS"===e.type,o=i?"base":"elements";let n=i?[e[o]]:e[o];if("REMOVE_COLUMNS_ROWS"===t.type&&(n=n.map((e=>{if(t.elements.includes(e))return;const i=t.elements.sort(((e,t)=>t-e));for(let t of i)e>t&&e--;return e})).filter(ot)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;n=n.map((i=>i>e?i+t.quantity:i))}if(n.length){let t=n;return i&&(t=n[0]),{...e,[o]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}},{match:function(e){return"ranges"in e},fn:function(e,t){const i=[],o="DELETE_SHEET"===t.type&&t.sheetId;for(const n of e.ranges)if(n._sheetId!==t.sheetId)i.push({...n,_zone:n._zone});else{const e=ms(n._zone,t);e&&o!==n._sheetId&&i.push({...n,_zone:e})}if(!i.length)return"IGNORE_COMMAND";return{...e,ranges:i}}}];function yb(e,t){const i=rg.getTransformation(e.type,t.type);return i?i(e,t):function(e,t){for(const{match:i,fn:o}of wb)if(i(e)){const i=o(e,t);if("SKIP_TRANSFORMATION"===i)continue;if("IGNORE_COMMAND"===i)return;e=i}return e}(e,t)}function xb(e,t){let i=[...e];for(const e of t)i=i.map((t=>yb(t,e))).filter(ot);return i}function Ib(e,t){const i="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===i?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class Rb{constructor(e,t,i,o){this._commands=[],this._changes=[],this.id=e,this.clientId=t,this._commands=[...i],this._changes=o?[...o]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class Tb extends Error{}class Ab extends Cb{constructor(e,t,i=Q){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=i,this.clients={},this.clientId="local",this.pendingMessages=[],this.waitingAck=!1,this.waitingUndoRedoAck=!1,this.isReplayingInitialRevisions=!1,this.processedRevisions=new Set,this.uuidGenerator=new zi,this.debouncedMove=function(e,t,i){let o;return function(){const n=this,s=arguments,r=i&&!o;clearTimeout(o),o=setTimeout((function(){o=null,i||e.apply(n,s)}),t),r&&e.apply(n,s)}}(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t){if(!e.length||!t.length||!this.canApplyOptimisticUpdate())return;const i=new Rb(this.uuidGenerator.uuidv4(),this.clientId,e,t);this.revisions.append(i.id,i),this.trigger("new-local-state-update",{id:i.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:i.id,clientId:i.clientId,commands:i.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_UNDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_REDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:"local",name:"local"},this.clientId="local"),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this))}loadInitialMessages(e){this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1}leave(){delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}snapshot(e){const t=this.uuidGenerator.uuidv4();this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){const e=this.clients[this.clientId];if(!e)throw new Tb("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(ot))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}_move(e){var t;if(!this.clients[this.clientId])return;const i=null===(t=this.clients[this.clientId])||void 0===t?void 0:t.position;if((null==i?void 0:i.col)===e.col&&i.row===e.row&&i.sheetId===e.sheetId)return;const o=i?"CLIENT_MOVED":"CLIENT_JOINED",n=this.getClient();this.clients[this.clientId]={...n,position:e},this.transportService.sendMessage({type:o,version:1,client:{...n,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:i}=e,o=new Rb(e.nextRevisionId,t,i);if(o.clientId!==this.clientId){this.revisions.insert(o.id,o,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:xb(i,t)})}break;case"SNAPSHOT_CREATED":{const t=new Rb(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){if("CLIENT_MOVED"===e.type&&e.client.id===this.clientId)return!0;switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter((({type:e})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const Mb=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];class Ob extends Jv{constructor(){super(...arguments),this.availableColors=new Set(Mb),this.colors={}}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}chooseNewColor(){0===this.availableColors.size&&(this.availableColors=new Set(Mb));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 Tb)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const i of this.getters.getConnectedClients())if(i.id!==this.getters.getClient().id&&i.position&&i.position.sheetId===e&&this.isPositionValid(i.position)){const e=i.position;this.colors[i.id]||(this.colors[i.id]=this.chooseNewColor());const o=this.colors[i.id];t.push({...i,position:e,color:o})}return t}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:i}=e,o=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:n,col:s}=e.position,r=this.getters.expandZone(o,{top:n,bottom:n,left:s,right:s}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);if(c<=0||h<=0)continue;const d=e.color,u=`${d}10`;t.fillStyle=u,t.lineWidth=4*i,t.strokeStyle=d,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,h),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,h),t.font=`bold ${q+1}px ${Z}`}}}Ob.getters=["getClientsToDisplay"],Ob.layers=[6];class Nb extends Jv{allowDispatch(e){if("SORT_CELLS"===e.type){if(!Ji(e.col,e.row,e.zone))throw new Error(s("The anchor must be part of the provided zone"));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return 0}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;return so(t).some((({col:t,row:i})=>!this.getters.isInMerge({sheetId:e,col:t,row:i})))?63:0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const i=this.getters.getMerges(e).filter((e=>Qi(e,t))),o=oo(i[0]);let[n,s]=[o.numberOfCols,o.numberOfRows];return i.every((e=>{let[t,i]=[e.right-e.left+1,e.bottom-e.top+1];return t===n&&i===s}))?0:63}expand(e,t){const{left:i,right:o,top:n,bottom:s}=this.getters.expandZone(e,t);return{left:Math.max(0,i),right:Math.min(this.getters.getNumberCols(e)-1,o),top:Math.max(0,n),bottom:Math.min(this.getters.getNumberRows(e)-1,s)}}checkExpandedValues(e,t){const i=this.expand(e,t);let o;if(this.getters.doesIntersectMerge(e,i)){const{left:t,right:n,top:s,bottom:r}=i;for(let i=t;i<=n;i++)for(let t=s;t<=r;t++){const{col:n,row:s}=this.getters.getMainCellPosition({sheetId:e,col:i,row:t});if(o=this.getters.getEvaluatedCell({sheetId:e,col:n,row:s}),o.formattedValue)return!0}}else for(let t of this.getters.getEvaluatedCellsInZone(e,i))if(t.formattedValue)return!0;return!1}getContiguousZone(e,t){let i,{top:o,bottom:n,left:s,right:r}=t,a=!1;for(;!a;)a=!0,o>0&&(i=this.checkExpandedValues(e,{left:s-1,right:r+1,top:o-1,bottom:o-1}),i&&(a=!1,o--)),s>0&&(i=this.checkExpandedValues(e,{left:s-1,right:s-1,top:o-1,bottom:n+1}),i&&(a=!1,s--)),r<this.getters.getNumberCols(e)-1&&(i=this.checkExpandedValues(e,{left:r+1,right:r+1,top:o-1,bottom:n+1}),i&&(a=!1,r++)),n<this.getters.getNumberRows(e)-1&&(i=this.checkExpandedValues(e,{left:s-1,right:r+1,top:n+1,bottom:n+1}),i&&(a=!1,n++));return{left:s,right:r,top:o,bottom:n}}hasHeader(e,t){if(1===t[0].length)return!1;let i=t.map((t=>t.map((({col:t,row:i})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:i}).type))));return i[0][0]===cn.empty&&(i=i.slice(1)),!i.some((e=>e[0]===cn.empty))&&!!i.some((e=>e[1]!==cn.empty&&e[0]!==e[1]))}sortZone(e,t,i,o,n){const[s,r]=this.mainCellsSteps(e,i);let a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},i),c=this.mainCells(e,i);!n.sortHeaders&&this.hasHeader(e,c)&&(l.top+=r),c=this.mainCells(e,l);const h=function(e,t,i){const o=e.map(((e,t)=>({index:t,type:e.type,value:e.value})));let n=o.filter((e=>e.type===cn.empty)),s=o.filter((e=>e.type!==cn.empty));i&&(s.push(...n.map((e=>({...e,type:cn.number,value:0})))),n=[]);const r="descending"===t?-1:1;return s.sort(((e,t)=>{let i=Ar.indexOf(e.type)-Ar.indexOf(t.type);return 0===i&&(i=e.type===cn.text||e.type===cn.error?e.value.localeCompare(t.value):e.value-t.value),r*i})).concat(n)}(c[a-l.left].map((e=>this.getters.getEvaluatedCell(e))),o,Boolean(n.emptyCellAsZero)),d=h.map((e=>e.index)),[u,g]=[c.length,c[0].length],p=[];for(let e=0;e<u;e++)for(let t=0;t<g;t++){let{col:i,row:o,sheetId:n}=c[e][d[t]];const a=this.getters.getCell({sheetId:n,col:i,row:o});let h=l.left+e*s,u=l.top+t*r,g={sheetId:n,col:h,row:u,content:""};if(a){let e=a.content;if(a.isFormula){const t=u-this.getters.getCellPosition(a.id).row,i=this.getters.createAdaptedRanges(a.dependencies,0,t,n);e=this.getters.buildFormulaContent(n,a,i)}g.style=a.style,g.content=e,g.format=a.format}p.push(g)}p.forEach((e=>this.dispatch("UPDATE_CELL",e)))}mainCellsSteps(e,t){const i=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[i?i.right-i.left+1:1,i?i.bottom-i.top+1:1]}mainCells(e,t){const[i,o]=this.mainCellsSteps(e,t),n=[],s=$e(t.left,t.right+1,i),r=$e(t.top,t.bottom+1,o);for(const t of s){const i=[];n.push(i);for(const o of r)i.push({sheetId:e,col:t,row:o})}return n}}Nb.getters=["getContiguousZone"];class _b extends Jv{constructor(){super(...arguments),this.showFormulas=!1}handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}_b.getters=["shouldShowFormulas"];class Fb extends Jv{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}allowDispatch(e){switch(e.type){case"AUTORESIZE_ROWS":case"AUTORESIZE_COLUMNS":try{this.getters.getSheet(e.sheetId);break}catch(e){return 27}}return 0}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){const i=this.getColMaxWidth(e.sheetId,t);0!==i&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:i,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":for(let t of e.rows)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"ROW",size:null,sheetId:e.sheetId})}}getCellWidth(e){const t=this.getCellText(e),i=this.getters.getCellComputedStyle(e),o=t.split(he);let n=Math.max(...o.map((e=>this.getTextWidth(e,i))));this.getters.getConditionalIcon(e)&&(n+=function(e){return He(e)+2*U}(this.getters.getCellStyle(e)));if(this.getters.isFilterHeader(e)&&(n+=20),n>0&&(n+=2*B,"wrap"===this.getters.getCellStyle(e).wrapping)){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,n)}return n}getTextWidth(e,t){return Ue(this.ctx,e,t)}getCellText(e,t=!1){const i=this.getters.getCell(e);return t&&(null==i?void 0:i.isFormula)?i.content:this.getters.getEvaluatedCell(e).formattedValue}getCellMultiLineText(e,t){const i=this.getters.getCellStyle(e),o=this.getters.getCellText(e,this.getters.shouldShowFormulas()),n=[];for(const e of o.split("\n")){const o=e.split(" ");if(!t){n.push(e);continue}let s="",r=t;for(let e of o){const o=this.splitWordToSpecificWidth(this.ctx,e,t,i),a=o.pop(),l=Ue(this.ctx,a,i);if(o.length)""!==s&&(n.push(s),s="",r=t),o.forEach((e=>{n.push(e)})),s=a,r=t-l;else{const e=""===s?a:" "+a,o=Ue(this.ctx,e,i);o<=r?(s+=e,r-=o):(n.push(s),s=a,r=t-l)}}""!==s&&n.push(s)}return n}getColDimensions(e,t){const i=this.getColRowOffset("COL",0,t,e),o=this.getters.getColSize(e,t);return{start:i,size:o,end:i+(this.getters.isColHidden(e,t)?0:o)}}getRowDimensions(e,t){const i=this.getColRowOffset("ROW",0,t,e),o=this.getters.getRowSize(e,t);return{start:i,size:o,end:i+(this.getters.isRowHidden(e,t)?0:o)}}getColRowOffset(e,t,i,o=this.getters.getActiveSheetId()){if(i<t)return-this.getColRowOffset(e,i,t);let n=0;for(let s=t;s<i;s++)this.getters.isHeaderHidden(o,e,s)||(n+="COL"===e?this.getters.getColSize(o,s):this.getters.getRowSize(o,s));return n}getColMaxWidth(e,t){const i=so(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,...i)}splitWordToSpecificWidth(e,t,i,o){if(Ue(e,t,o)<=i)return[t];const n=[];let s="";for(let r of t){Ue(e,s+r,o)>i?(n.push(s),s=r):s+=r}return n.push(s),n}}Fb.getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getColDimensions","getRowDimensions","getColRowOffset"];class Db{constructor(e,t,i,o){this.getters=t,this.dispatch=i,this.selection=o,this.operation=e,this.sheetId=t.getActiveSheetId()}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0}addMissingDimensions(e,t,i,o){const n=this.getters.getActiveSheetId(),s=t+o-this.getters.getNumberRows(n);s>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(n)-1,sheetId:n,quantity:s,position:"after"});const r=e+i-this.getters.getNumberCols(n);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(n)-1,sheetId:n,quantity:r,position:"after"})}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class kb extends Db{constructor(e,t,i,o,n){if(super(t,i,o,n),!e.length)return this.cells=[[]],this.zones=[],void(this.copiedTables=[]);const s=new Set(e.map((e=>e.left))),r=new Set(e.map((e=>e.right))),a=new Set(e.map((e=>e.top))),l=new Set(e.map((e=>e.bottom))),c=1===a.size&&1===l.size||1===s.size&&1===r.size?function(e){return e.reduce(((e,t)=>{const i=e.length;for(let o=0;o<i;o++)if(Qi(e[o],t))return e[o]=Yi(e[o],t),e;return e[i]=t,e}),[])}(e):[e[e.length-1]],h=c.map((e=>so(e))).flat(),d=[...new Set(h.map((e=>e.col)))].sort(((e,t)=>e-t)),u=[...new Set(h.map((e=>e.row)))].sort(((e,t)=>e-t)),g=[],p=i.getActiveSheetId();for(let e of u){let t=[];for(let o of d){const n={col:o,row:e,sheetId:p};t.push({cell:i.getCell(n),style:i.getCellComputedStyle(n),evaluatedCell:i.getEvaluatedCell(n),border:i.getCellBorder(n)||void 0,position:n})}g.push(t)}const m=[];for(const t of e)for(const e of this.getters.getFilterTablesInZone(p,t)){const t=[];for(const i of $e(e.zone.left,e.zone.right+1))t.push(this.getters.getFilterValues({sheetId:p,col:i,row:e.zone.top}));m.push({filtersValues:t,zone:e.zone})}this.cells=g,this.zones=c,this.copiedTables=m}isCutAllowed(e){return 1!==e.length?19:0}isPasteAllowed(e,t){const i=this.getters.getActiveSheetId();if("CUT"===this.operation&&void 0!==(null==t?void 0:t.pasteOption))return 21;if(e.length>1&&(this.cells.length>1||this.cells[0].length>1))return 20;const o=this.cells.length,n=this.cells[0].length;for(let t of this.getPasteZones(e))if(this.getters.doesIntersectMerge(i,t)&&(e.length>1||!this.getters.isSingleCellOrMerge(i,e[0])||o*n!=1))return 2;const{xSplit:s,ySplit:r}=this.getters.getPaneDivisions(i);for(const t of this.getPasteZones(e))if(t.left<s&&t.right>=s||t.top<r&&t.bottom>=r)return 75;return 0}paste(e,t){"COPY"===this.operation?this.pasteFromCopy(e,t):this.pasteFromCut(e,t);const i=this.cells.length,o=this.cells[0].length,n="CUT"===this.operation;(null==t?void 0:t.selectTarget)&&this.selectPastedZone(o,i,n,e)}pasteFromCopy(e,t){if(1===e.length){const i=this.cells.length,o=this.cells[0].length,n=this.pastedZones(e,o,i);for(const e of n)this.pasteZone(e.left,e.top,t)}else for(const i of e)for(let e=i.left;e<=i.right;e++)for(let o=i.top;o<=i.bottom;o++)this.pasteZone(e,o,t);void 0===(null==t?void 0:t.pasteOption)&&this.pasteCopiedTables(e)}pasteFromCut(e,t){this.clearClippedZones();const i=e[0];this.pasteZone(i.left,i.top,t),this.dispatch("MOVE_RANGES",{target:this.zones,sheetId:this.sheetId,targetSheetId:this.getters.getActiveSheetId(),col:i.left,row:i.top});for(const e of this.copiedTables)this.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.sheetId,target:[e.zone]});this.pasteCopiedTables(e)}pastedZones(e,t,i){const o=e[0],n=Math.max(1,Math.floor((o.right+1-o.left)/t)),s=Math.max(1,Math.floor((o.bottom+1-o.top)/i)),r=[];for(let e=0;e<n;e++)for(let n=0;n<s;n++){const s=o.top+n*i,a=o.left+e*t;r.push({left:a,top:s,bottom:s+i-1,right:a+t-1})}return r}getPasteZones(e){const t=this.cells;if(!t.length||!t[0].length)return e;const i=[],o=t.length,n=t[0].length,s=e[e.length-1],r=s.left,a=s.top,l=Math.max(1,Math.floor((s.right+1-r)/n)),c=Math.max(1,Math.floor((s.bottom+1-a)/o));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)i.push({left:r,top:a,right:r-1+e*n,bottom:a-1+t*o});return i}selectPastedZone(e,t,i,o){const n=o[0],s=n.left,r=n.top;if(t>1||e>1||i){const n=this.pastedZones(o,e,t),a=i?n[0]:Yi(...n);this.selection.selectZone({cell:{col:s,row:r},zone:a})}}clearClippedZones(){for(const e of this.cells)for(const t of e)t.cell&&this.dispatch("CLEAR_CELL",t.position);this.dispatch("CLEAR_FORMATTING",{sheetId:this.sheetId,target:this.zones})}pasteZone(e,t,i){const o=this.cells.length,n=this.cells[0].length,s="onlyValue"!==(null==i?void 0:i.pasteOption)&&(null==i?void 0:i.shouldPasteCF),r=this.getters.getActiveSheetId();this.addMissingDimensions(n,o,e,t);for(let a=0;a<o;a++){const o=this.cells[a];for(let l=0;l<n;l++){const n=o[l],c={col:e+l,row:t+a,sheetId:r};"CUT"!==this.operation&&this.pasteMergeIfExist(n.position,c),this.pasteCell(n,c,this.operation,i),s&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:n.position,target:c,operation:this.operation})}}}pasteCell(e,t,i,o){const{sheetId:n,col:s,row:r}=t,a=this.getters.getEvaluatedCell(t);if("onlyValue"!==(null==o?void 0:o.pasteOption)){const i=this.getters.getCellBorder(t),o=e.border,a={top:(null==i?void 0:i.top)||(null==o?void 0:o.top),bottom:(null==i?void 0:i.bottom)||(null==o?void 0:o.bottom),left:(null==i?void 0:i.left)||(null==o?void 0:o.left),right:(null==i?void 0:i.right)||(null==o?void 0:o.right)};this.dispatch("SET_BORDER",{sheetId:n,col:s,row:r,border:a})}if(e.cell){if("onlyFormat"===(null==o?void 0:o.pasteOption))return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.evaluatedCell.format});if("onlyValue"===(null==o?void 0:o.pasteOption)){const i=fi(e.evaluatedCell.value);return void this.dispatch("UPDATE_CELL",{...t,content:i})}let a=e.cell.content;if(e.cell.isFormula&&"COPY"===i){const t=s-e.position.col,o=r-e.position.row;a=this.getUpdatedContent(n,e.cell,t,o,i)}this.dispatch("UPDATE_CELL",{...t,content:a,style:e.cell.style||null,format:e.cell.format})}else a&&("onlyValue"===(null==o?void 0:o.pasteOption)?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===(null==o?void 0:o.pasteOption)?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,i,o,n){const s=this.getters.createAdaptedRanges(t.dependencies,i,o,e);return this.getters.buildFormulaContent(e,t,s)}pasteMergeIfExist(e,t){let{sheetId:i,col:o,row:n}=e;const{col:s,row:r}=this.getters.getMainCellPosition(e);if(s===o&&r===n){const s=this.getters.getMerge(e);if(!s)return;({sheetId:i,col:o,row:n}=t),this.dispatch("ADD_MERGE",{sheetId:i,force:!0,target:[{left:o,top:n,right:o+s.right-s.left,bottom:n+s.bottom-s.top}]})}}pasteCopiedTables(e){const t=this.getters.getActiveSheetId(),i=e[0],o=this.zones[0],n=[i.left-o.left,i.top-o.top];for(const e of this.copiedTables){const i=ro(e.zone,"both","MOVE",n);this.dispatch("CREATE_FILTER_TABLE",{sheetId:t,target:[i]});for(const o of $e(0,e.filtersValues.length))this.dispatch("UPDATE_FILTER",{sheetId:t,col:i.left+o,row:i.top,values:e.filtersValues[o]})}}getClipboardContent(){return{[hn.PlainText]:this.getPlainTextContent(),[hn.Html]:this.getHTMLContent()}}getPlainTextContent(){return this.cells.map((e=>e.map((e=>e.cell?this.getters.getCellText(e.position,this.getters.shouldShowFormulas()):"")).join("\t"))).join("\n")||"\t"}getHTMLContent(){if(1==this.cells.length&&1==this.cells[0].length)return this.getters.getCellText(this.cells[0][0].position);let e='<table border="1" style="border-collapse:collapse">';for(const t of this.cells){e+="<tr>";for(const i of t){e+=`<td style="${Eo(Co(i.style))}">`+iv(this.getters.getCellText(i.position))+"</td>"}e+="</tr>"}return e+="</table>",e}isColRowDirtyingClipboard(e,t){if(!this.zones)return!1;for(let i of this.zones){if("COL"===t&&e<=i.right)return!0;if("ROW"===t&&e<=i.bottom)return!0}return!1}drawClipboard(e){const{ctx:t,thinLineWidth:i}=e;if(this.sheetId===this.getters.getActiveSheetId()&&this.zones&&this.zones.length){t.setLineDash([8,5]),t.strokeStyle=E,t.lineWidth=3.3*i;for(const e of this.zones){const{x:i,y:o,width:n,height:s}=this.getters.getVisibleRect(e);n>0&&s>0&&t.strokeRect(i,o,n,s)}}}}class Lb{constructor(e,t,i){this.operation=e,this.getters=t,this.dispatch=i,this.sheetId=t.getActiveSheetId();const o=t.getSelectedFigureId();if(!o)throw new Error("No figure selected");const n=t.getFigure(this.sheetId,o);if(!n)throw new Error(`No figure for the given id: ${o}`);switch(this.copiedFigure={...n},n.tag){case"chart":this.copiedFigureContent=new Pb(i,t,this.sheetId,o);break;case"image":this.copiedFigureContent=new Ub(i,t,this.sheetId,o);break;default:throw new Error(`Unknow tag '${n.tag}' for the given figure id: ${o}`)}}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0===e.length?73:void 0!==(null==t?void 0:t.pasteOption)?22:0}paste(e){const t=this.getters.getActiveSheetId(),i={x:this.getters.getColDimensions(t,e[0].left).start,y:this.getters.getRowDimensions(t,e[0].top).start},o={height:this.copiedFigure.height,width:this.copiedFigure.width},n=(new zi).uuidv4();this.copiedFigureContent.paste(t,n,i,o),"CUT"===this.operation&&this.dispatch("DELETE_FIGURE",{sheetId:this.copiedFigureContent.sheetId,id:this.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{id:n})}getClipboardContent(){return{[hn.PlainText]:"\t"}}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class Pb{constructor(e,t,i,o){this.dispatch=e,this.sheetId=i;const n=t.getChart(o);if(!n)throw new Error(`No chart for the given id: ${o}`);this.copiedChart=n.copyInSheetId(i)}paste(e,t,i,o){const n=this.copiedChart.copyInSheetId(e);this.dispatch("CREATE_CHART",{id:t,sheetId:e,position:i,size:o,definition:n.getDefinition()})}}class Ub{constructor(e,t,i,o){this.dispatch=e,this.sheetId=i;const n=t.getImage(o);this.copiedImage=Fe(n)}paste(e,t,i,o){const n=Fe(this.copiedImage);this.dispatch("CREATE_IMAGE",{figureId:t,sheetId:e,position:i,size:o,definition:n})}}class Vb extends Db{constructor(e,t,i,o){super("COPY",t,i,o),this.values=e.replace(/\r/g,"").split("\n").map((e=>e.split("\t")))}isPasteAllowed(e,t){const i=this.getters.getActiveSheetId(),o=this.getPasteZone(e);return this.getters.doesIntersectMerge(i,o)?2:0}paste(e){const t=this.values,i=this.getPasteZone(e),{left:o,top:n}=i,{numberOfCols:s,numberOfRows:r}=oo(i),a=this.getters.getActiveSheetId();this.addMissingDimensions(s,r,o,n);for(let e=0;e<t.length;e++)for(let i=0;i<t[e].length;i++)this.dispatch("UPDATE_CELL",{row:n+e,col:o+i,content:t[e][i],sheetId:a});const l={left:o,top:n,right:o+s-1,bottom:n+r-1};this.selection.selectZone({cell:{col:o,row:n},zone:l})}getClipboardContent(){return{[hn.PlainText]:this.values.map((e=>e.join("\t"))).join("\n")}}getPasteZone(e){const t=this.values.length,i=Math.max(...this.values.map((e=>e.length))),{left:o,top:n}=e[0];return{top:n,left:o,bottom:n+t-1,right:o+i-1}}}class zb extends Jv{constructor(){super(...arguments),this.status="invisible",this._isPaintingFormat=!1}allowDispatch(e){switch(e.type){case"CUT":const t=this.getters.getSelectedZones();return this.getClipboardState(t,e.type).isCutAllowed(t);case"PASTE":if(!this.state)return 23;const i=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);return this.state.isPasteAllowed(e.target,{pasteOption:i});case"PASTE_FROM_OS_CLIPBOARD":return new Vb(e.text,this.getters,this.dispatch,this.selection).isPasteAllowed(e.target);case"INSERT_CELL":{const{cut:t,paste:i}=this.getInsertCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(i)}case"DELETE_CELL":{const{cut:t,paste:i}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(i)}}return 0}handle(e){var t,i;switch(e.type){case"COPY":case"CUT":const o=this.getters.getSelectedZones();this.state=this.getClipboardState(o,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const n=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1,this.state.paste(e.target,{pasteOption:n,shouldPasteCF:!0,selectTarget:!0}),"CUT"===this.state.operation&&(this.state=void 0),this.status="invisible";break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:i}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!$i(t[0])){for(const{col:t,row:i}of so(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:i,sheetId:this.getters.getActiveSheetId()});break}this.getClipboardStateForCopyCells(t,"CUT").paste(i);break}case"INSERT_CELL":{const{cut:t,paste:i}=this.getInsertCellsTargets(e.zone,e.shiftDimension);this.getClipboardStateForCopyCells(t,"CUT").paste(i);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(t=this.state)||void 0===t?void 0:t.operation))return;this.state.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===(i=this.state)||void 0===i?void 0:i.operation))return;for(let t of e.elements){if(this.state.isColRowDirtyingClipboard(t,e.dimension)){this.state=void 0;break}}this.status="invisible";break;case"PASTE_FROM_OS_CLIPBOARD":new Vb(e.text,this.getters,this.dispatch,this.selection).paste(e.target),this.status="invisible";break;case"ACTIVATE_PAINT_FORMAT":{const e=this.getters.getSelectedZones();this.state=this.getClipboardStateForCopyCells(e,"COPY"),this._isPaintingFormat=!0,this.status="visible";break}default:mn(e)&&(this.status="invisible")}}getClipboardContent(){var e;return(null===(e=this.state)||void 0===e?void 0:e.getClipboardContent())||{[hn.PlainText]:"\t"}}getClipboardTextContent(){var e;return(null===(e=this.state)||void 0===e?void 0:e.getClipboardContent()[hn.PlainText])||"\t"}isCutOperation(){return!!this.state&&"CUT"===this.state.operation}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const i=this.getters.getActiveSheetId();let o;return o="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(i)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(i)-1},{cut:[o],paste:[e]}}getInsertCellsTargets(e,t){const i=this.getters.getActiveSheetId();let o,n;return"COL"===t?(o={...e,right:this.getters.getNumberCols(i)-1},n={...e,left:e.right+1,right:e.right+1}):(o={...e,bottom:this.getters.getNumberRows(i)-1},n={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(i)-1}),{cut:[o],paste:[n]}}getClipboardStateForCopyCells(e,t){return new kb(e,t,this.getters,this.dispatch,this.selection)}getClipboardState(e,t){return this.getters.getSelectedFigureId()?new Lb(t,this.getters,this.dispatch):new kb(e,t,this.getters,this.dispatch,this.selection)}drawGrid(e){"visible"===this.status&&this.state&&this.state.drawClipboard(e)}}function Bb(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:i}=$t(e.value),[o,n]=t.split(":"),s=i?`${ke(i)}!`:"",r=Hb(o),a=n?`:${Hb(n)}`:"";return{...e,value:s+r+a}}function Hb(e){switch(function(e){if(function(e){return e.startsWith("$")&&e.length>1&&e.slice(1).includes("$")}(e))return"colrow";if(function(e){return e.startsWith("$")}(e))return"col";if(function(e){return e.includes("$",1)}(e))return"row";return"none"}(e)){case"none":e=$b(e,"colrow");break;case"colrow":e=$b(e,"row");break;case"row":e=$b(e,"col");break;case"col":e=$b(e,"none")}return e}function $b(e,t){let i;switch(e=e.replace(/\$/g,""),t){case"col":return"$"+e;case"row":return i=e.search(/[0-9]/),e.slice(0,i)+"$"+e.slice(i);case"colrow":return i=e.search(/[0-9]/),-1===i||0===i?"$"+e:"$"+(e=e.slice(0,i)+"$"+e.slice(i));case"none":return e}}zb.layers=[2],zb.getters=["getClipboardContent","getClipboardTextContent","isCutOperation","isPaintingFormat"];const Wb=s("The cell you are trying to edit has been deleted.");class Gb extends Jv{constructor(){super(...arguments),this.col=0,this.row=0,this.mode="inactive",this.sheetId="",this.currentContent="",this.currentTokens=[],this.selectionStart=0,this.selectionEnd=0,this.selectionInitialStart=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=e.text||this.getComposerContent(this.getters.getActivePosition());return this.validateSelection(t.length,e.selection.start,e.selection.end)}return 0;default:return 0}}handleEvent(e){if("selecting"===this.mode)if("newAnchor"===e.mode)this.insertSelectedRange(e.anchor.zone);else this.replaceSelectedRanges(e.anchor.zone)}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":"inactive"!==this.mode&&e.text?this.setContent(e.text,e.selection):this.startEdition(e.text,e.selection),this.updateRangeColor();break;case"STOP_EDITION":e.cancel?(this.cancelEditionAndActivateSheet(),this.resetContent()):this.stopEdition(),this.colorIndexByRange={};break;case"SET_CURRENT_CONTENT":this.setContent(e.content,e.selection,!0),this.updateRangeColor();break;case"REPLACE_COMPOSER_CURSOR_SELECTION":this.replaceSelection(e.text);break;case"SELECT_FIGURE":this.cancelEditionAndActivateSheet(),this.resetContent();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.getters.getRangeFromRangeData(e.range),i=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((e=>{const{xc:i,sheetName:o}=$t(e.value),n=o||this.getters.getSheetName(this.sheetId),s=this.getters.getActiveSheetId();if(this.getters.getSheetName(s)!==n)return!1;const r=this.getters.getRangeFromSheetXC(s,i);return Ki(this.getters.expandZone(s,r.zone),t.zone)}));this.previousRef=i.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=i.start;break;case"CHANGE_HIGHLIGHT":const o=this.getters.getRangeFromRangeData(e.range),n=this.getRangeReference(o,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(n),this.previousRef=n,this.selectionStart=this.currentContent.length,this.selectionEnd=this.currentContent.length;break;case"ACTIVATE_SHEET":if(this.currentContent.startsWith("=")||(this.cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){const t=this.getters.getActivePosition(),{col:i,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),n=this.getters.expandZone(e.sheetIdTo,co({col:i,row:o}));this.selection.resetAnchor(this,{cell:{col:i,row:o},zone:n})}break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheetId)||"inactive"===this.mode||(this.sheetId=this.getters.getActiveSheetId(),this.cancelEditionAndActivateSheet(),this.resetContent(),this.ui.notifyUI({type:"ERROR",text:Wb}));break;case"CYCLE_EDITION_REFERENCES":this.cycleReferences()}}getEditionMode(){return this.mode}getCurrentContent(){return"inactive"===this.mode?this.getComposerContent(this.getters.getActivePosition()):this.currentContent}getEditionSheet(){return this.sheetId}getComposerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}getCurrentEditedCell(){return{sheetId:this.sheetId,col:this.col,row:this.row}}isSelectingForComposer(){return"selecting"===this.mode}showSelectionIndicator(){return this.isSelectingForComposer()&&this.canStartComposerRangeSelection()}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((i=>i.start<=e&&i.end>=t))}cycleReferences(){const e=this.getTokensInSelection(),t=e.filter((e=>"REFERENCE"===e.type));if(0===t.length)return;const i=e.map(Bb).map((e=>e.value)).join(""),o=this.currentContent,n=e[0].start,s=e[e.length-1].end,r=o.slice(0,n)+i+o.slice(s),a=r.length-o.length,l={start:t[0].start,end:t[t.length-1].end+a};1===t.length&&this.selectionStart===this.selectionEnd&&(l.start=l.end),this.dispatch("SET_CURRENT_CONTENT",{content:r,selection:l})}validateSelection(e,t,i){return t>=0&&t<=e&&i>=0&&i<=e?0:46}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:Wb});const{top:t,left:i}=Zi({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=i,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:Wb});const{top:t,left:i}=Zi({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=i,this.row=t}onAddElements(e){const{top:t,left:i}=qi({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=i,this.row=t}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=co({col:this.col,row:this.row});this.selection.resetAnchor(this,{cell:{col:this.col,row:this.row},zone:e})}this.mode="selecting",this.selectionInitialStart=this.selectionStart}startEdition(e,t){var i;const o=this.getters.getActiveCell();e&&(null===(i=o.format)||void 0===i?void 0:i.includes("%"))&&ni(e)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const{col:n,row:s,sheetId:r}=this.getters.getActivePosition();this.col=n,this.sheetId=r,this.row=s,this.initialContent=this.getComposerContent({sheetId:r,col:n,row:s}),this.mode="editing",this.setContent(e||this.initialContent,t),this.colorIndexByRange={};const a=co({col:this.col,row:this.row});this.selection.capture(this,{cell:{col:this.col,row:this.row},zone:a},{handleEvent:this.handleEvent.bind(this),release:()=>{this.stopEdition()}})}stopEdition(){if("inactive"!==this.mode){this.cancelEditionAndActivateSheet();const e=this.col,t=this.row;let i=this.currentContent;if(!(this.initialContent!==i))return;if(i){const o=this.getters.getActiveSheetId(),n=this.getters.getEvaluatedCell({sheetId:o,col:this.col,row:this.row});if(i.startsWith("=")){const e=this.currentTokens.filter((e=>"LEFT_PAREN"===e.type)).length,t=this.currentTokens.filter((e=>"RIGHT_PAREN"===e.type)).length,o=e-t;o>0&&(i+=rt(new Array(o).fill(")")))}else n.link&&(i=Ke(i,n.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,col:e,row:t,content:i})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,content:"",col:e,row:t});this.setContent("")}}cancelEditionAndActivateSheet(){if("inactive"===this.mode)return;this.cancelEdition();this.getters.getActiveSheetId()!==this.sheetId&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}getComposerContent(e){const t=this.getters.getCell(e);if(null==t?void 0:t.isFormula)return t.content;const{format:i,value:o,type:n,formattedValue:s}=this.getters.getEvaluatedCell(e);switch(n){case cn.text:case cn.empty:return o;case cn.boolean:return s;case cn.error:return(null==t?void 0:t.content)||"";case cn.number:return i&&wi(i)?s:this.numberComposerContent(o,i)}}numberComposerContent(e,t){return(null==t?void 0:t.includes("%"))?100*e+"%":function(e){const{integerDigits:t,decimalDigits:i}=Ci(e,20);return i?`${t}.${i}`:t}(e)}cancelEdition(){"inactive"!==this.mode&&(this.mode="inactive",this.selection.release(this))}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,i){const o=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(o||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?bf(e):[],this.currentTokens.length>100&&i&&this.ui.notifyUI({type:"ERROR",text:s("This formula has over 100 parts. It can't be processed properly, consider splitting it into multiple cells")})),this.canStartComposerRangeSelection()&&this.startComposerRangeSelection()}insertSelectedRange(e){const t=Math.min(this.selectionStart,this.selectionEnd),i=this.getZoneReference(e);this.canStartComposerRangeSelection()?(this.insertText(i,t),this.selectionInitialStart=t):(this.insertText(","+i,t),this.selectionInitialStart=t+1)}replaceSelectedRanges(e){const t=this.getZoneReference(e);this.replaceText(t,this.selectionInitialStart,this.selectionEnd)}getZoneReference(e,t=[{colFixed:!1,rowFixed:!1}]){const i=this.getters.getActiveSheetId();let o=this.getters.zoneToXC(i,e,t);if(this.getters.getEditionSheet()!==this.getters.getActiveSheetId()){o=`${ke(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${o}`}return o}getRangeReference(e,t=[{colFixed:!1,rowFixed:!1}]){let i=[...t];1===t.length&&uo(e.zone)>1?i.push({...t[0]}):2===t.length&&1===uo(e.zone)&&i.pop();const o=e.clone({parts:i});return this.getters.getSelectionRangeString(o,this.getters.getEditionSheet())}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),i=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,i)}replaceText(e,t,i){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(i,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const i=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),o=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:i,selection:{start:o,end:o}})}updateRangeColor(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return;const e=this.getters.getEditionSheet(),t=this.getReferencedRanges().map((t=>this.getters.getRangeString(t,e))),i={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(i[e]=this.colorIndexByRange[e]);const o=new Set(Object.values(i));let n=0;const s=()=>{for(;o.has(n);)n++;return o.add(n),n};for(const e of t){const t=e in i?i[e]:s();i[e]=t}this.colorIndexByRange=i}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=this.getters.getEditionSheet(),t=e=>{const t=this.colorIndexByRange[e];return St[t%St.length]};return this.getReferencedRanges().map((i=>{const o=this.getters.getRangeString(i,e);return{zone:i.zone,color:t(o),sheetId:i.sheetId}}))}getReferencedRanges(){const e=this.getters.getEditionSheet();return this.currentTokens.filter((e=>"REFERENCE"===e.type)).map((t=>this.getters.getRangeFromSheetXC(e,t.value)))}canStartComposerRangeSelection(){if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(!e)return!1;const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let i=t,o=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(o.type)||Nm.includes(o.value);){if("SPACE"!==o.type||i<1)return!1;i--,o=this.currentTokens[i]}for(i=t+1,o=this.currentTokens[i];o&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(o.type);){if("SPACE"!==o.type)return!1;i++,o=this.currentTokens[i]}return!0}return!1}getTokensInSelection(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return this.currentTokens.filter((i=>i.start<=e&&i.end>=e||i.start>=e&&i.start<t))}}Gb.getters=["getEditionMode","isSelectingForComposer","showSelectionIndicator","getCurrentContent","getEditionSheet","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights","getCurrentEditedCell"];const qb=[{name:s("Sum"),types:[cn.number],compute:e=>bl.compute([e])},{name:s("Avg"),types:[cn.number],compute:e=>Ml.compute([e])},{name:s("Min"),types:[cn.number],compute:e=>ql.compute([e])},{name:s("Max"),types:[cn.number],compute:e=>Hl.compute([e])},{name:s("Count"),types:[cn.number,cn.text,cn.boolean,cn.error],compute:e=>Pl.compute([e])},{name:s("Count Numbers"),types:[cn.number,cn.text,cn.boolean,cn.error],compute:e=>Ll.compute([e])}];class Zb extends Jv{constructor(e){super(e),this.gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]},this.selectedFigureId=null,this.sheetsData={},this.activeSheet=null,this.moveClient=e.moveClient}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{this.getters.getSheet(e.sheetIdTo);break}catch(e){return 27}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return 0}handleEvent(e){const t=e.anchor;let i=[];switch(e.mode){case"overrideSelection":i=[t.zone];break;case"updateAnchor":i=[...this.gridSelection.zones];const o=i.findIndex((t=>Ki(t,e.previousAnchor.zone)));o>=0&&(i[o]=t.zone);break;case"newAnchor":i=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,i),this.selection.resetDefaultAnchor(this,Fe(this.gridSelection.anchor));const{col:o,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:o,row:n}),this.selectedFigureId=null}handle(e){switch(e.type){case"START_EDITION":case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.dispatch("ACTIVATE_SHEET",{sheetIdTo:t,sheetIdFrom:t});const{col:i,row:o}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(i,o),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case"ACTIVATE_SHEET":if(this.getters.isSheetVisible(e.sheetIdTo)||this.dispatch("SHOW_SHEET",{sheetId:e.sheetIdTo}),this.setActiveSheet(e.sheetIdTo),this.sheetsData[e.sheetIdFrom]={gridSelection:Fe(this.gridSelection)},e.sheetIdTo in this.sheetsData)Object.assign(this,this.sheetsData[e.sheetIdTo]),this.selection.resetDefaultAnchor(this,Fe(this.gridSelection.anchor));else{const{col:t,row:i}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0});this.selectCell(t,i)}break;case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:i,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:i,row:o})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:i,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:i,row:o})}break}case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"SELECT_FIGURE":this.selectedFigureId=e.id;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":const n=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of n)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:Fe(t)}}if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:i})}const s=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(s,e))),this.gridSelection.anchor.zone=this.getters.expandZone(s,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones)}this.selection.resetDefaultAnchor(this,Fe(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){const e=new Set;for(let t of this.gridSelection.zones)if(0===t.top&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let i=t.left;i<=t.right;i++)e.add(i);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(let i of this.gridSelection.zones)if(0===i.left&&i.right===this.getters.getNumberCols(t)-1)for(let t=i.top;t<=i.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return Fe(this.gridSelection.zones)}getSelectedZone(){return Fe(this.gridSelection.anchor.zone)}getSelection(){return Fe(this.gridSelection)}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{const t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}getStatisticFnResults(){const e=this.getters.getActiveSheetId(),t=new Set;for(const i of this.gridSelection.zones)for(const{col:o,row:n}of so(i)){if(this.getters.isRowHidden(e,n)||this.getters.isColHidden(e,o))continue;const i=this.getters.getEvaluatedCell({sheetId:e,col:o,row:n});i.type!==cn.empty&&t.add(i)}let i=new Set,o=[];for(let e of t)i.add(e.type),o.push(e.value);let n={};for(let e of qb){let t;e.types.some((e=>i.has(e)))&&(t=e.compute(o)),n[e.name]=t}return n}getAggregate(){let e=0,t=0;const i=this.getters.getActiveSheetId(),o=this.gridSelection.zones.map(so).flat();for(const{col:n,row:s}of o){const o=this.getters.getEvaluatedCell({sheetId:i,col:n,row:s});o.type===cn.number&&(t++,e+=o.value)}return t<2?null:fi(e)}isSelected(e){return!!this.getters.getSelectedZones().find((t=>Ki(t,e)))}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 i=[];const o="COL"===e?"left":"top",n="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[n]-e[o]+1},((t,i)=>e[o]+i));i=i.concat(t)}return[...new Set(i)].sort()}setSelectionMixin(e,t){const{anchor:i,zones:o}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=i,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,i)=>t===i.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(o)}selectCell(e,t){const i=this.getters.getActiveSheetId(),o=this.getters.expandZone(i,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:o,cell:{col:e,row:t}},[o])}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){const t=this.getters.getSheetIds(),i=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[i]})}onColumnsRemoved(e){const{cell:t,zone:i}=this.gridSelection.anchor,o=Zi(i,"left",[...e.elements]);let n={left:t.col,right:t.col,top:t.row,bottom:t.row};n=Zi(n,"left",[...e.elements]);const s={cell:{col:n.left,row:n.top},zone:o};this.setSelectionMixin(s,[o])}onRowsRemoved(e){const{cell:t,zone:i}=this.gridSelection.anchor,o=Zi(i,"top",[...e.elements]);let n={left:t.col,right:t.col,top:t.row,bottom:t.row};n=Zi(n,"top",[...e.elements]);const s={cell:{col:n.left,row:n.top},zone:o};this.setSelectionMixin(s,[o])}onAddElements(e){const t=qi(this.gridSelection.anchor.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),i={cell:{col:t.left,row:t.top},zone:t};this.setSelectionMixin(i,[t])}onMoveElements(e){const t=e.elements.length;this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:e.position});const i="COL"===e.dimension,o=e.elements[0],n=e.elements[t-1],s=e.base<o,r=s&&i?t:0,a=s&&!i?t:0,l=[{left:i?o+r:0,right:i?n+r:this.getters.getNumberCols(e.sheetId)-1,top:i?0:o+a,bottom:i?this.getters.getNumberRows(e.sheetId)-1:n+a}],c=new kb(l,"CUT",this.getters,this.dispatch,this.selection),h=s?e.base:e.base+1,d=[{left:i?h:0,right:i?h+t-1:this.getters.getNumberCols(e.sheetId)-1,top:i?0:h,bottom:i?this.getters.getNumberRows(e.sheetId)-1:h+t-1}];c.paste(d,{selectTarget:!0});const u=s?e.elements.map((e=>e+t)):e.elements;let g=e.base;for(const t of u){const i="COL"===e.dimension?this.getters.getColSize(e.sheetId,t):this.getters.getRowSize(e.sheetId,t);this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:i,elements:[g]}),g+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:u})}isMoveElementAllowed(e){const t="COL"===e.dimension,i=e.elements[0],o=e.elements[e.elements.length-1],n=e.sheetId,s=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(s(n,i-1,i)||s(n,o,o+1)||s(n,e.base-1,e.base))return 2;const r=[e.base,...e.elements],a=t?this.getters.getNumberCols(n):this.getters.getNumberRows(n);return r.some((e=>e<0||e>=a))?86:0}clipSelection(e,t){const i=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:Le(e.left,0,i),right:Le(e.right,0,i),top:Le(e.top,0,o),bottom:Le(e.bottom,0,o)}))),anchor:{cell:{col:Le(t.anchor.cell.col,0,i),row:Le(t.anchor.cell.row,0,o)},zone:{left:Le(t.anchor.zone.left,0,i),right:Le(t.anchor.zone.right,0,i),top:Le(t.anchor.zone.top,0,o),bottom:Le(t.anchor.zone.bottom,0,o)}}}}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:i}=e,o=this.getSelectedZones();t.fillStyle="#f3f7fe";const n=1===o.length&&o[0].left===o[0].right&&o[0].top===o[0].bottom;t.fillStyle=n?"#f3f7fe":"#e9f0ff",t.strokeStyle=E,t.lineWidth=1.5*i;for(const e of o){const{x:i,y:o,width:n,height:s}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(i,o,n,s),t.globalCompositeOperation="source-over",t.strokeRect(i,o,n,s)}t.globalCompositeOperation="source-over";const s=this.getActivePosition();let r;t.strokeStyle=E,t.lineWidth=3*i,r=this.getters.isInMerge(s)?this.getters.getMerge(s):co(s);const{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);c>0&&h>0&&t.strokeRect(a,l,c,h)}}Zb.layers=[6],Zb.getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getStatisticFnResults","getAggregate","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSelected","getElementsFromSelection","isGridSelectionActive"];const jb=(new Ro).add("sheet",Qv).add("header visibility",qv).add("filters",Wv).add("cell",Pv).add("merge",jv).add("headerSize",Gv).add("borders",Lv).add("conditional formatting",zv).add("figures",Bv).add("chart",Uv).add("image",Zv),Yb=(new Ro).add("ui_sheet",Fb).add("header_visibility_ui",pb).add("ui_options",_b).add("selectionInputManager",bb).add("highlight",mb).add("grid renderer",fb).add("autofill",cb).add("find_and_replace",gb).add("sort",Nb).add("automatic_sum",hb).add("format",class extends Jv{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,i){for(const o of t)for(const t of so(o)){const o=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==o){const n=Mi(o,i);this.dispatch("SET_FORMATTING",{sheetId:e,target:[co(t)],format:n})}}}getCellNumberFormat(e){var t;for(const i of[e]){const e=this.getters.getEvaluatedCell(i);if(e.type===cn.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(X)))return e.format||Ri(e.value)}}}).add("cell_popovers",db).add("selection_multiuser",Ob),Xb=(new Ro).add("selection",Zb).add("clipboard",zb).add("edition",Gb),Kb=(new Ro).add("evaluation",ib).add("evaluation_filter",sb).add("evaluation_chart",ob).add("evaluation_cf",nb).add("viewport",ab).add("custom_colors",eb),Qb=new Ro;Qb.add("link",{condition:(e,t)=>!!t.model.getters.getEvaluatedCell(e).link,action:(e,t)=>Fo(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});class Jb{constructor(e){this.fileStore=e}async requestImage(){const e=await this.getImageFromUser(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageSize(t),mimetype:e.type}}getImageFromUser(){return new Promise(((e,t)=>{const i=document.createElement("input");i.setAttribute("type","file"),i.setAttribute("accept","image/*"),i.addEventListener("change",(async()=>{null===i.files||1!=i.files.length?t():e(i.files[0])})),i.click()}))}getImageSize(e){return new Promise(((t,i)=>{const o=new Image;o.src=e,o.addEventListener("load",(()=>{const e={width:o.width,height:o.height};t(e)})),o.addEventListener("error",i)}))}}const eC=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];vo`
1400
+ `}function rv(e){return new yp(e.join("\n"))}function av(e,...t){let i=[e[0]];for(let o=0;o<t.length;o++){const n=t[o]instanceof yp?t[o]:iv(t[o]);i.push(n+e[o+1])}return new yp(rt(i))}function lv(e){return e.replace(/[a-z0-9]+:(?=[a-z0-9]+)/gi,"")}function cv(e){return e.replace(/([a-z0-9]+):(?=[a-z0-9]+)/gi,"$1\\:")}class hv{constructor(e){this.value=e}asString(){return gm(String(this.value))}asBool(){return Boolean(Number(this.value))}asNum(){return Number(this.value)}}class dv{constructor(e,t,i){this.currentFile=void 0,this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=i,this.areNamespaceIgnored=null!==(new DOMParser).parseFromString("<t:test xmlns:t='a'/>","text/xml").querySelector("test"),this.relationships={},e.rels&&this.extractRelationships(e.rels).map((e=>{this.relationships[e.id]=e}))}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:"Relationship"},(e=>({id:this.extractAttr(e,"Id",{required:!0}).asString(),target:this.extractAttr(e,"Target",{required:!0}).asString(),type:this.extractAttr(e,"Type",{required:!0}).asString()})))}getListOfFiles(){return Object.values(this.xlsxFileStructure).flat().filter(ot)}mapOnElements(e,t){var i;const o=[],n=this.currentFile;let s;if(e.children){const t=null===(i=this.querySelector(e.parent,e.query))||void 0===i?void 0:i.children;s=t||[]}else s=this.querySelectorAll(e.parent,e.query);if(s)for(let e of s)try{o.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=n,o}catchErrorOnElement(e,t){const i=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([i,e.message].join("\n"))}extractAttr(e,t,i){const o=e.attributes[t];o||this.handleMissingValue(e,`attribute "${t}"`,i);const n=(null==o?void 0:o.value)?o.value:null==i?void 0:i.default;return void 0===n?void 0:new hv(n)}extractTextContent(e,t){var i;if(void 0!==(null==t?void 0:t.default)&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const o="preserve"===(null===(i=null==e?void 0:e.attributes["xml:space"])||void 0===i?void 0:i.value);let n=null==e?void 0:e.textContent;return e&&null!==n||this.handleMissingValue(e,"text content",t),n&&(n=o?n:n.trim()),n?gm(n):null==t?void 0:t.default}extractChildAttr(e,t,i,o){var n;let s;s="number"==typeof t?e.children[t]:this.querySelector(e,t),s||this.handleMissingValue(e,"number"==typeof t?`child at index ${t}`:`child <${t}>`,o);const r=s?null===(n=this.extractAttr(s,i,o))||void 0===n?void 0:n.asString():null==o?void 0:o.default;return void 0!==r?new hv(r):void 0}extractChildTextContent(e,t,i){if(void 0!==(null==i?void 0:i.default)&&"string"!=typeof i.default)throw new Error("extractTextContent default value should be a string");let o=this.querySelector(e,t);return o||this.handleMissingValue(e,`child <${t}>`,i),o?this.extractTextContent(o,i):null==i?void 0:i.default}handleMissingValue(e,t,i){if(null==i?void 0:i.required){if(!(null==i?void 0:i.default))throw new Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`);this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${i.default}`)}}extractColor(e,t,i){var o,n,s,r,a;if(!e)return i?{rgb:i}:void 0;const l=null===(o=this.extractAttr(e,"theme"))||void 0===o?void 0:o.asString();let c;if(void 0!==l){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");c=this.getThemeColor(l,t.clrScheme)}else c=null===(n=this.extractAttr(e,"rgb"))||void 0===n?void 0:n.asString();return{rgb:c,auto:null===(s=this.extractAttr(e,"auto"))||void 0===s?void 0:s.asBool(),indexed:null===(r=this.extractAttr(e,"indexed"))||void 0===r?void 0:r.asNum(),tint:null===(a=this.extractAttr(e,"tint"))||void 0===a?void 0:a.asNum()}}getTargetXmlFile(e){if(!e)throw new Error("Undefined target file");let t=e.target;t=t.replace("../",""),t=t.replace("./","");const i=this.getListOfFiles().find((e=>e.file.fileName.endsWith(t)));if(!i||!i.file)throw new Error("Cannot find target file");return i}querySelector(e,t){return t=this.areNamespaceIgnored?lv(t):cv(t),e.querySelector(t)}querySelectorAll(e,t){return t=this.areNamespaceIgnored?lv(t):cv(t),e.querySelectorAll(t)}getThemeColor(e,t){switch(e){case"0":return"FFFFFF";case"1":return"000000";case"2":return t[3].value;case"3":return t[2].value;default:return t[e].value}}}class uv extends dv{getTheme(){return{clrScheme:this.mapOnElements({query:"a:clrScheme",parent:this.rootFile.file.xml,children:!0},(e=>({name:e.tagName,value:this.extractChildAttr(e,0,"val",{required:!0,default:Ip}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:Ip}).asString()})))}}getSharedStrings(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"si"},(e=>"t"===e.children[0].tagName?this.extractTextContent(e)||"":this.mapOnElements({parent:e,query:"t"},(e=>this.extractTextContent(e)||"")).join("")))}}class gv extends dv{constructor(e,t,i,o){super(e,t,i),this.theme=o}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},(e=>{var t;return{sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),pivot:null===(t=this.extractAttr(e,"pivot"))||void 0===t?void 0:t.asBool(),cfRules:this.extractCFRules(e,this.theme)}}));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:"extLst x14:conditionalFormatting"},(e=>{var t;return{sqref:this.extractChildTextContent(e,"xm:sqref",{required:!0}).split(" "),pivot:null===(t=this.extractAttr(e,"xm:pivot"))||void 0===t?void 0:t.asBool(),cfRules:this.extractCFRules(e,this.theme)}}))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:"cfRule, x14:cfRule"},(e=>{var i,o,n,s,r,a,l,c,h,d,u;const g=this.extractAttr(e,"type",{required:!0}).asString();if("dataBar"===g)throw new Error("Databars conditional formats are not supported.");return{type:g,priority:this.extractAttr(e,"priority",{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:null===(i=this.extractAttr(e,"dxfId"))||void 0===i?void 0:i.asNum(),stopIfTrue:null===(o=this.extractAttr(e,"stopIfTrue"))||void 0===o?void 0:o.asBool(),aboveAverage:null===(n=this.extractAttr(e,"aboveAverage"))||void 0===n?void 0:n.asBool(),percent:null===(s=this.extractAttr(e,"percent"))||void 0===s?void 0:s.asBool(),bottom:null===(r=this.extractAttr(e,"bottom"))||void 0===r?void 0:r.asBool(),operator:null===(a=this.extractAttr(e,"operator"))||void 0===a?void 0:a.asString(),text:null===(l=this.extractAttr(e,"text"))||void 0===l?void 0:l.asString(),timePeriod:null===(c=this.extractAttr(e,"timePeriod"))||void 0===c?void 0:c.asString(),rank:null===(h=this.extractAttr(e,"rank"))||void 0===h?void 0:h.asNum(),stdDev:null===(d=this.extractAttr(e,"stdDev"))||void 0===d?void 0:d.asNum(),equalAverage:null===(u=this.extractAttr(e,"equalAverage"))||void 0===u?void 0:u.asBool()}}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:"formula"},(e=>this.extractTextContent(e,{required:!0})))}extractCfColorScale(e,t){const i=this.querySelector(e,"colorScale");if(i)return{colors:this.mapOnElements({parent:i,query:"color"},(e=>this.extractColor(e,t,"ffffff"))),cfvos:this.extractCFVos(i)}}extractCfIconSet(e){var t,i;const o=this.querySelector(e,"iconSet, x14:iconSet");if(o)return{iconSet:this.extractAttr(o,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(o,"showValue",{default:!0}).asBool(),percent:this.extractAttr(o,"percent",{default:!0}).asBool(),reverse:null===(t=this.extractAttr(o,"reverse"))||void 0===t?void 0:t.asBool(),custom:null===(i=this.extractAttr(o,"custom"))||void 0===i?void 0:i.asBool(),cfvos:this.extractCFVos(o),cfIcons:this.extractCfIcons(o)}}extractCfIcons(e){const t=this.mapOnElements({parent:e,query:"cfIcon, x14:cfIcon"},(e=>({iconSet:this.extractAttr(e,"iconSet",{required:!0}).asString(),iconId:this.extractAttr(e,"iconId",{required:!0}).asNum()})));return 0===t.length?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:"cfvo, x14:cfvo"},(e=>{var t,i;return{type:this.extractAttr(e,"type",{required:!0}).asString(),gte:null===(t=this.extractAttr(e,"gte",{default:!0}))||void 0===t?void 0:t.asBool(),value:e.attributes.val?null===(i=this.extractAttr(e,"val"))||void 0===i?void 0:i.asString():this.extractChildTextContent(e,"f, xm:f")}}))}}class pv extends dv{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!om[t])throw new Error(`Unsupported chart type ${t}`);const i=this.mapOnElements({parent:e,query:"c:title a:t"},(e=>e.textContent||"")).join(""),o=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:i,type:om[t],dataSets:this.extractChartDatasets(this.querySelector(e,`c:${t}`)),backgroundColor:this.extractChildAttr(e,"c:chartSpace > c:spPr a:srgbClr","val",{default:"ffffff"}).asString(),verticalAxisPosition:"r"===this.extractChildAttr(e,"c:valAx > c:axPos","val",{default:"l"}).asString()?"right":"left",legendPosition:im[this.extractChildAttr(e,"c:legendPos","val",{default:"b"}).asString()],stacked:"stacked"===o,fontColor:"000000"}}))[0]}extractChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},(e=>({label:this.extractChildTextContent(e,"c:cat c:f"),range:this.extractChildTextContent(e,"c:val c:f",{required:!0})})))}getChartType(e){const t=this.querySelector(e,"c:plotArea");if(!t)throw new Error("Missing plot area in the chart definition.");for(let e of t.children){const t=lv(e.tagName);if(xp.some((e=>e===t)))return t}throw new Error("Unknown chart type")}}class mv extends dv{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{if("twoCellAnchor"!==lv(e.tagName))throw new Error("Only twoCellAnchor are supported for xlsx drawings.");const t=this.querySelector(e,"c:chart");if(!t)throw new Error("Only chart figures are currently supported.");return{anchors:[this.extractFigureAnchor("xdr:from",e),this.extractFigureAnchor("xdr:to",e)],data:this.extractChart(t)}}))}extractFigureAnchor(e,t){const i=this.querySelector(t,e);if(!i)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(i,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(i,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(i,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(i,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),i=this.getTargetXmlFile(this.relationships[t]),o=new pv(i,this.xlsxFileStructure,this.warningManager).extractChart();if(!o)throw new Error("Unable to extract chart definition");return o}}class fv extends dv{getPivotTable(){return this.mapOnElements({query:":root",parent:this.rootFile.file.xml},(e=>({displayName:this.extractAttr(e,"name",{required:!0}).asString(),id:this.extractAttr(e,"name",{required:!0}).asString(),ref:this.extractChildAttr(e,"location","ref",{required:!0}).asString(),headerRowCount:this.extractChildAttr(e,"location","firstDataRow",{default:0}).asNum(),totalsRowCount:1,cols:[],style:{showFirstColumn:!0,showRowStripes:!0}})))[0]}}class vv extends dv{getTable(){return this.mapOnElements({query:"table",parent:this.rootFile.file.xml},(e=>{var t;return{displayName:this.extractAttr(e,"displayName",{required:!0}).asString(),name:null===(t=this.extractAttr(e,"name"))||void 0===t?void 0:t.asString(),id:this.extractAttr(e,"id",{required:!0}).asString(),ref:this.extractAttr(e,"ref",{required:!0}).asString(),headerRowCount:this.extractAttr(e,"headerRowCount",{default:1}).asNum(),totalsRowCount:this.extractAttr(e,"totalsRowCount",{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)}}))[0]}extractTableCols(e){return this.mapOnElements({query:"tableColumn",parent:e},(e=>({id:this.extractAttr(e,"id",{required:!0}).asString(),name:this.extractAttr(e,"name",{required:!0}).asString(),colFormula:this.extractChildTextContent(e,"calculatedColumnFormula")})))}extractTableStyleInfo(e){return this.mapOnElements({query:"tableStyleInfo",parent:e},(e=>{var t,i,o,n,s;return{name:null===(t=this.extractAttr(e,"name"))||void 0===t?void 0:t.asString(),showFirstColumn:null===(i=this.extractAttr(e,"showFirstColumn"))||void 0===i?void 0:i.asBool(),showLastColumn:null===(o=this.extractAttr(e,"showLastColumn"))||void 0===o?void 0:o.asBool(),showRowStripes:null===(n=this.extractAttr(e,"showRowStripes"))||void 0===n?void 0:n.asBool(),showColumnStripes:null===(s=this.extractAttr(e,"showColumnStripes"))||void 0===s?void 0:s.asBool()}}))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:"autoFilter",parent:e},(e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,"ref",{required:!0}).asString()})))[0]}extractFilterColumns(e){return this.mapOnElements({query:"tableColumn",parent:e},(t=>({colId:this.extractAttr(e,"colId",{required:!0}).asNum(),hiddenButton:this.extractAttr(e,"hiddenButton",{default:!1}).asBool(),filters:this.extractSimpleFilter(t)})))}extractSimpleFilter(e){return this.mapOnElements({query:"filter",parent:e},(e=>({val:this.extractAttr(e,"val",{required:!0}).asString()})))}}class bv extends dv{constructor(e,t,i,o){super(e,t,i),this.theme=o}getSheet(){return this.mapOnElements({query:"worksheet",parent:this.rootFile.file.xml},(e=>{const t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:[...this.extractTables(e),...this.extractPivotTables()],isVisible:"visible"===t.state}}))[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:"sheetView"},(e=>{const t=this.querySelector(e,"pane");return{tabSelected:this.extractAttr(e,"tabSelected",{default:!1}).asBool(),showFormulas:this.extractAttr(e,"showFormulas",{default:!1}).asBool(),showGridLines:this.extractAttr(e,"showGridLines",{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,"showRowColHeaders",{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,"xSplit",{default:0}).asNum():0,ySplit:t?this.extractAttr(t,"ySplit",{default:0}).asNum():0}}}))}extractSheetName(){const e=hm(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id;for(let e of this.querySelectorAll(this.xlsxFileStructure.workbook.file.xml,"sheet"))if(e.attributes["r:id"].value===t)return e.attributes.name.value;throw new Error("Missing sheet name")}getSheetWorkbookInfo(){const e=hm(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id,i=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:"sheet"},(e=>({relationshipId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetId:this.extractAttr(e,"sheetId",{required:!0}).asString(),sheetName:this.extractAttr(e,"name",{required:!0}).asString(),state:this.extractAttr(e,"state",{default:"visible"}).asString()}))).find((e=>e.relationshipId===t));if(!i)throw new Error("Cannot find corresponding workbook sheet");return i}extractConditionalFormats(){return new gv(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},(e=>{var t;const i=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),o=this.getTargetXmlFile(this.relationships[i]);return new mv(o,this.xlsxFileStructure,this.warningManager).extractFigures()}))[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},(e=>{var t;const i=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),o=this.getTargetXmlFile(this.relationships[i]);return new vv(o,this.xlsxFileStructure,this.warningManager).getTable()}))}extractPivotTables(){try{return Object.values(this.relationships).filter((e=>e.type.endsWith("pivotTable"))).map((e=>{const t=this.getTargetXmlFile(e);return new fv(t,this.xlsxFileStructure,this.warningManager).getPivotTable()}))}catch(e){return this.catchErrorOnElement(e),[]}}extractMerges(e){return this.mapOnElements({parent:e,query:"mergeCell"},(e=>this.extractAttr(e,"ref",{required:!0}).asString()))}extractSheetFormat(e){const t=this.querySelector(e,"sheetFormatPr");if(t)return{defaultColWidth:this.extractAttr(t,"defaultColWidth",{default:kp.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:Lp.toString()}).asNum()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},(e=>{var t,i,o,n,s,r,a;return{width:null===(t=this.extractAttr(e,"width"))||void 0===t?void 0:t.asNum(),customWidth:null===(i=this.extractAttr(e,"customWidth"))||void 0===i?void 0:i.asBool(),bestFit:null===(o=this.extractAttr(e,"bestFit"))||void 0===o?void 0:o.asBool(),hidden:null===(n=this.extractAttr(e,"hidden"))||void 0===n?void 0:n.asBool(),min:null===(s=this.extractAttr(e,"min",{required:!0}))||void 0===s?void 0:s.asNum(),max:null===(r=this.extractAttr(e,"max",{required:!0}))||void 0===r?void 0:r.asNum(),styleIndex:null===(a=this.extractAttr(e,"style"))||void 0===a?void 0:a.asNum()}}))}extractRows(e){return this.mapOnElements({parent:e,query:"sheetData row"},(e=>{var t,i,o,n,s;return{index:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asNum(),cells:this.extractCells(e),height:null===(i=this.extractAttr(e,"ht"))||void 0===i?void 0:i.asNum(),customHeight:null===(o=this.extractAttr(e,"customHeight"))||void 0===o?void 0:o.asBool(),hidden:null===(n=this.extractAttr(e,"hidden"))||void 0===n?void 0:n.asBool(),styleIndex:null===(s=this.extractAttr(e,"s"))||void 0===s?void 0:s.asNum()}}))}extractCells(e){return this.mapOnElements({parent:e,query:"c"},(e=>{var t,i,o;return{xc:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asString(),styleIndex:null===(i=this.extractAttr(e,"s"))||void 0===i?void 0:i.asNum(),type:Xp[null===(o=this.extractAttr(e,"t",{default:"n"}))||void 0===o?void 0:o.asString()],value:this.extractChildTextContent(e,"v"),formula:this.extractCellFormula(e)}}))}extractCellFormula(e){var t,i;const o=this.querySelector(e,"f");if(o)return{content:this.extractTextContent(o),sharedIndex:null===(t=this.extractAttr(o,"si"))||void 0===t?void 0:t.asNum(),ref:null===(i=this.extractAttr(o,"ref"))||void 0===i?void 0:i.asString()}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},(e=>{var t,i,o,n;const s=null===(t=this.extractAttr(e,"r:id"))||void 0===t?void 0:t.asString();return{xc:null===(i=this.extractAttr(e,"ref",{required:!0}))||void 0===i?void 0:i.asString(),location:null===(o=this.extractAttr(e,"location"))||void 0===o?void 0:o.asString(),display:null===(n=this.extractAttr(e,"display"))||void 0===n?void 0:n.asString(),relTarget:s?this.relationships[s].target:void 0}}))}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),i={};for(let e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),o=this.extractTextContent(e,{required:!0});i[t]=o}const o=[];for(let e=0;e<Object.keys(i).length;e++)i[e]?o.push(i[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),o.push(""));return o}}class Cv extends dv{constructor(e,t,i){super(e.styles,e,t),this.theme=i}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},(e=>this.extractNumFormats(e)))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},(e=>this.extractFont(e)))}extractFont(e){var t,i,o,n;const s=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),r=this.extractChildAttr(e,"sz","val",{default:q.toString()}).asNum(),a=this.extractColor(this.querySelector(e,"color"),this.theme),l=this.querySelector(e,"i")||void 0,c=l&&"0"!==(null===(t=l.attributes.val)||void 0===t?void 0:t.value),h=this.querySelector(e,"b")||void 0,d=h&&"0"!==(null===(i=h.attributes.val)||void 0===i?void 0:i.value),u=this.querySelector(e,"strike")||void 0,g=u&&"0"!==(null===(o=u.attributes.val)||void 0===o?void 0:o.value),p=this.querySelector(e,"u")||void 0;return{name:s,size:r,color:a,italic:c,bold:d,underline:p&&"none"!==(null===(n=p.attributes.val)||void 0===n?void 0:n.value),strike:g}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},(e=>this.extractFill(e)))}extractFill(e){var t;const i=e.children[0];return"patternFill"===i.tagName?{patternType:null===(t=i.attributes.patternType)||void 0===t?void 0:t.value,bgColor:this.extractColor(this.querySelector(i,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(i,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(i,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},(e=>this.extractBorder(e)))}extractBorder(e){var t,i;const o={left:this.extractSingleBorder(e,"left",this.theme),right:this.extractSingleBorder(e,"right",this.theme),top:this.extractSingleBorder(e,"top",this.theme),bottom:this.extractSingleBorder(e,"bottom",this.theme),diagonal:this.extractSingleBorder(e,"diagonal",this.theme)};return o.diagonal&&(o.diagonalUp=null===(t=this.extractAttr(e,"diagonalUp"))||void 0===t?void 0:t.asBool(),o.diagonalDown=null===(i=this.extractAttr(e,"diagonalDown"))||void 0===i?void 0:i.asBool()),o}extractSingleBorder(e,t,i){const o=this.querySelector(e,t);if(o&&o.attributes.style)return{style:this.extractAttr(o,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(o.children[0],i,"000000")}}extractAlignment(e){var t,i,o,n,s,r,a;return{horizontal:this.extractAttr(e,"horizontal",{default:"general"}).asString(),vertical:this.extractAttr(e,"vertical",{default:"center"}).asString(),textRotation:null===(t=this.extractAttr(e,"textRotation"))||void 0===t?void 0:t.asNum(),wrapText:null===(i=this.extractAttr(e,"wrapText"))||void 0===i?void 0:i.asBool(),indent:null===(o=this.extractAttr(e,"indent"))||void 0===o?void 0:o.asNum(),relativeIndent:null===(n=this.extractAttr(e,"relativeIndent"))||void 0===n?void 0:n.asNum(),justifyLastLine:null===(s=this.extractAttr(e,"justifyLastLine"))||void 0===s?void 0:s.asBool(),shrinkToFit:null===(r=this.extractAttr(e,"shrinkToFit"))||void 0===r?void 0:r.asBool(),readingOrder:null===(a=this.extractAttr(e,"readingOrder"))||void 0===a?void 0:a.asNum()}}getDxfs(){return this.mapOnElements({query:"dxf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"font"),i=this.querySelector(e,"fill"),o=this.querySelector(e,"border"),n=this.querySelector(e,"numFmt"),s=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:i?this.extractFill(i):void 0,numFmt:n?this.extractNumFormats(n):void 0,alignment:s?this.extractAlignment(s):void 0,border:o?this.extractBorder(o):void 0}}))}getStyles(){return this.mapOnElements({query:"cellXfs xf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"alignment");return{fontId:this.extractAttr(e,"fontId",{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,"fillId",{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,"borderId",{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,"numFmtId",{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}}))}}class Sv extends dv{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"externalBook"},(e=>({rId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:"sheetName"},(e=>this.extractAttr(e,"val",{required:!0}).asString())),datasets:this.extractExternalSheetData(e)})))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:"sheetData"},(e=>{const t=this.mapOnElements({parent:e,query:"cell"},(e=>({xc:this.extractAttr(e,"r",{required:!0}).asString(),value:this.extractChildTextContent(e,"v",{required:!0})}))),i={};for(let e of t)i[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:i}}))}}function Ev(e,t){const i=function(e,t){const i=t[Hp],o=i.querySelectorAll(`Override[ContentType="${e}"]`),n=[];for(let e of o){const t=null==e?void 0:e.attributes.PartName.value;n.push(t.substring(1))}return n}(e,t);return function(e,t){const i=[];for(let o of e){const e=wv(o,t);i.push({file:{fileName:o,xml:t[o]},rels:e?{fileName:e,xml:t[e]}:void 0})}return i}(i,t)}function wv(e,t){if(e===Hp)return"_rels/.rels";let i="";const o=e.split("/");for(let e=0;e<o.length-1;e++)i+=o[e]+"/";return i+="_rels/",i+=o[o.length-1]+".rels",t[i]||(i=void 0),i}class yv{constructor(e){this.warningManager=new Wp,this.xmls={};for(let t of Object.keys(e))(t.endsWith(".xml")||t.endsWith(".rels"))&&(this.xmls[t]=nv(new yp(e[t])))}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new uv(e.theme,e,this.warningManager).getTheme():void 0,i=e.sharedStrings?new uv(e.sharedStrings,e,this.warningManager).getSharedStrings():[],o=e.sheets.sort(((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0}))).map((i=>new bv(i,e,this.warningManager,t).getSheet())),n=e.externalLinks.map((t=>new Sv(t,e,this.warningManager).getExternalBook())),s=new Cv(e,this.warningManager,t);return{fonts:s.getFonts(),fills:s.getFills(),borders:s.getBorders(),dxfs:s.getDxfs(),numFmts:s.getNumFormats(),styles:s.getStyles(),sheets:o,sharedStrings:i,externalBooks:n}}buildXlsxFileStructure(){const e={sheets:Ev(Op.sheet,this.xmls),workbook:Ev(Op.workbook,this.xmls)[0],styles:Ev(Op.styles,this.xmls)[0],sharedStrings:Ev(Op.sharedStrings,this.xmls)[0],theme:Ev(Op.themes,this.xmls)[0],charts:Ev(Op.chart,this.xmls),figures:Ev(Op.drawing,this.xmls),tables:Ev(Op.table,this.xmls),pivots:Ev(Op.pivot,this.xmls),externalLinks:Ev(Op.externalLink,this.xmls)};if(!e.workbook.rels)throw Error(s("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:12,sheets:Wf(e,this.warningManager),styles:bm(e,this.warningManager),formats:Sm(e,this.warningManager),borders:fm(e,this.warningManager),entities:{},revisionId:Q};return Qf(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=ut(e.styles[t])})),t}}function xv(e){const t=uf(e);let i=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&Nt.test(e.value)){const t=e.value.trim();return i.includes(t)||i.push(t),`${ae}${i.indexOf(t)}${ae}`}return e.value}))),dependencies:i}}const Iv=12,Rv="Sheet1";function Tv(e,t){if(!e)return _v();if(e["[Content_Types].xml"]){const i=new yv(e);if(e=i.convertXlsx(),t)for(let e of i.warningManager.warnings.sort())console.warn(e)}return"version"in(e=Fe(e))&&e.version<Iv&&(e=function(e){for(let t=Av.findIndex((t=>t.from===e.version));t<Av.length;t++)e=Av[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,i=new zi;for(const o of e.sheets||[])for(const e of o.figures||[])t.has(e.id)&&(e.id+=i.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(_v(),e,{version:Iv}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(Nv(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(Nv(Rv,"Sheet1"));return e}(e),e}(e),e}const Av=[{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 i=t.cells[e];i.content&&i.content.startsWith("=")&&(i.formula=xv(i.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:i,...o}=t.figures[e].data,n=[];for(let e of i)if(e.labelCell){const t=Hi(e.dataRange),i=e.labelCell+":"+Zt(t.right,t.bottom);n.push(i)}else n.push(e.dataRange);o.dataSetsHaveTitle=Boolean(i[0].labelCell),o.dataSets=n,t.figures[e].data=o}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){var t;const i=[],o=new RegExp(re,"g");for(let n of e.sheets||[]){if(!n.name)continue;const e=n.name,s=e.replace(o,"_");let r=1,a=s;for(;i.includes(a);)a=`${s}${r}`,r++;n.name=a,i.push(a);const l=t=>{if(void 0===t)return t;let i=t.replace(e,a),o=t;for(;o!==i;)o=i,i=o.replace(e,a);return o};for(let e in n.cells){const t=n.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(l))}for(let e of n.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(l),i=l(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:i}}for(let e of n.conditionalFormats||[]){e.ranges=e.ranges.map(l);for(const i of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===(null===(t=e.rule[i])||void 0===t?void 0:t.type)&&(e.rule[i].value=l(e.rule[i].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=w,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stacked=!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 i=t.cells[e];if(i.formula){let{text:e,dependencies:t}=i.formula;for(let[i,o]of Object.entries(t)){const t=`\\${ae}${i}\\${ae}`;e=e.replace(new RegExp(t,"g"),o)}i.content=e,delete i.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let i of e.sheets||[])for(let e in i.cells||[]){const o=i.cells[e];o.format&&(o.format=st(o.format,t))}return e.formats=t,e}},{description:"Add isVisible to sheets",from:11,to:12,applyMigration(e){for(let t of e.sheets||[])t.isVisible=!0;return e}}];function Mv(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const i=[],o=[],n=e=>{if("CREATE_SHEET"===e.type)i.push(e.sheetId);else if("sheetId"in e&&!i.includes(e.sheetId))return{...e,sheetId:Rv};return e};for(const e of t)"REMOTE_REVISION"===e.type?o.push({...e,commands:e.commands.map(n)}):o.push(e);return o}(e,t),t=Ov(t,"SORT_CELLS"),t=function(e,t){var i;const o=[],n={};for(const t of e.sheets||[])null===(i=t.figures)||void 0===i||i.forEach((e=>{"chart"===e.tag&&(n[e.id]=e.data)}));for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const i of e.commands){let e=i;switch(i.type){case"CREATE_CHART":n[i.id]=i.definition;break;case"UPDATE_CHART":if(!n[i.id]){console.log(`Fix chart definition: chart with id ${i.id} not found.`);continue}const t={...n[i.id],...i.definition};e={...i,definition:t},n[i.id]=t}t.push(e)}o.push({...e,commands:t})}else o.push(e);return o}(e,t=Ov(t,"SET_DECIMAL")),t}function Ov(e,t){const i=[];for(const o of e)"REMOTE_REVISION"===o.type?i.push({...o,commands:o.commands.filter((e=>e.type!==t))}):i.push(o);return i}function Nv(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[],filterTables:[],isVisible:!0}}function _v(e="Sheet1"){return{version:Iv,sheets:[Nv(Rv,e)],entities:{},styles:{},formats:{},borders:{},revisionId:Q,uniqueFigureIds:!0}}function Fv(e,t){return{...Nv(e,t),charts:[],images:[]}}class Dv{constructor(e,t){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t}exportForExcel(e){}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 i of e){let e=i.call(this,t);Array.isArray(e)||(e=[e]);const o=e.filter((e=>0!==e));if(o.length)return o}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}Dv.getters=[];class kv extends Dv{constructor({getters:e,stateObserver:t,range:i,dispatch:o,uuidGenerator:n}){super(t,o),this.range=i,i.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=n}import(e){}export(e){}adaptRanges(e,t){}garbageCollectExternalResources(){}}class Lv extends kv{constructor(){super(...arguments),this.borders={}}allowDispatch(e){return"SET_BORDER"===e.type?this.checkBordersUnchanged(e):0}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":const t=this.borders[e.sheetId];if(t){const i=t.slice().map((e=>null==e?void 0:e.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,i)}break;case"DELETE_SHEET":const i={...this.borders};delete i[e.sheetId],this.history.update("borders",i);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_FORMATTING":if(e.border){const t=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));this.setBorders(e.sheetId,t,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){let t,i;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,i=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,i=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,i)}handleAddRows(e){let t,i;"before"===e.position?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,i=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,i=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,i)}getCellBorder({sheetId:e,col:t,row:i}){var o,n,s,r,a,l,c,h,d,u,g,p;const m={top:null===(s=null===(n=null===(o=this.borders[e])||void 0===o?void 0:o[t])||void 0===n?void 0:n[i])||void 0===s?void 0:s.horizontal,bottom:null===(l=null===(a=null===(r=this.borders[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[i+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[i])||void 0===d?void 0:d.vertical,right:null===(p=null===(g=null===(u=this.borders[e])||void 0===u?void 0:u[t+1])||void 0===g?void 0:g[i])||void 0===p?void 0:p.vertical};return m.bottom||m.left||m.right||m.top?m:null}ensureColumnBorderContinuity(e,t,i){const o=$e(t+1,i);for(let n=0;n<this.getters.getNumberRows(e);n++){const s=this.getCellBorder({sheetId:e,col:t,row:n}),r=this.getCellBorder({sheetId:e,col:i,row:n});if(s&&r){const t=this.getCommonSides(s,r);for(let i of o)this.addBorder(e,i,n,t)}}}ensureRowBorderContinuity(e,t,i){const o=$e(t+1,i);for(let n=0;n<this.getters.getNumberCols(e);n++){const s=this.getCellBorder({sheetId:e,col:n,row:t}),r=this.getCellBorder({sheetId:e,col:n,row:i});if(s&&r){const t=this.getCommonSides(s,r);for(let i of o)this.addBorder(e,n,i,t)}}}getCommonSides(e,t){const i={};for(let o of["top","bottom","left","right"])e[o]&&e[o]===t[o]&&(i[o]=e[o]);return i}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsRange(e){return this.borders[e]?$e(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,i,{moveFirstLeftBorder:o}={}){this.borders[e]&&(i<0&&this.moveBordersOfColumn(e,t,i,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>i<0?e-t:t-e)).forEach((n=>{(n===t&&o||n!==t)&&this.moveBordersOfColumn(e,n,i,"vertical"),this.moveBordersOfColumn(e,n,i,"horizontal")})))}shiftBordersVertically(e,t,i,{moveFirstTopBorder:o}={}){this.borders[e]&&(i<0&&this.moveBordersOfRow(e,t,i,"horizontal",{destructive:!1}),this.getRowsRange(e).filter((e=>e>=t)).sort(((e,t)=>i<0?e-t:t-e)).forEach((n=>{(n===t&&o||n!==t)&&this.moveBordersOfRow(e,n,i,"horizontal"),this.moveBordersOfRow(e,n,i,"vertical")})))}moveBordersOfRow(e,t,i,o,{destructive:n}={destructive:!0}){const s=this.borders[e];s&&this.getColumnsWithBorders(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=s[r])||void 0===a?void 0:a[t+i])||void 0===l?void 0:l[o],u=null===(h=null===(c=s[r])||void 0===c?void 0:c[t])||void 0===h?void 0:h[o];this.history.update("borders",e,r,t+i,o,n?u:u||d),this.history.update("borders",e,r,t,o,void 0)}))}moveBordersOfColumn(e,t,i,o,{destructive:n}={destructive:!0}){const s=this.borders[e];s&&this.getRowsRange(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=s[t+i])||void 0===a?void 0:a[r])||void 0===l?void 0:l[o],u=null===(h=null===(c=s[t])||void 0===c?void 0:c[r])||void 0===h?void 0:h[o];this.history.update("borders",e,t+i,r,o,n?u:u||d),this.history.update("borders",e,t,r,o,void 0)}))}setBorder(e,t,i,o,n=!0){var s,r,a,l,c,h,d,u,g,p,m,f,v,b,C,S;!n&&(null===(l=null===(a=null===(r=null===(s=this.borders)||void 0===s?void 0:s[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[i])||void 0===l?void 0:l.vertical)||this.history.update("borders",e,t,i,"vertical",null==o?void 0:o.left),!n&&(null===(u=null===(d=null===(h=null===(c=this.borders)||void 0===c?void 0:c[e])||void 0===h?void 0:h[t])||void 0===d?void 0:d[i])||void 0===u?void 0:u.horizontal)||this.history.update("borders",e,t,i,"horizontal",null==o?void 0:o.top),!n&&(null===(f=null===(m=null===(p=null===(g=this.borders)||void 0===g?void 0:g[e])||void 0===p?void 0:p[t+1])||void 0===m?void 0:m[i])||void 0===f?void 0:f.vertical)||this.history.update("borders",e,t+1,i,"vertical",null==o?void 0:o.right),!n&&(null===(S=null===(C=null===(b=null===(v=this.borders)||void 0===v?void 0:v[e])||void 0===b?void 0:b[t])||void 0===C?void 0:C[i+1])||void 0===S?void 0:S.horizontal)||this.history.update("borders",e,t,i+1,"horizontal",null==o?void 0:o.bottom)}clearBorders(e,t){for(let i of t){for(let t=i.top;t<=i.bottom;t++){this.history.update("borders",e,i.right+1,t,"vertical",void 0);for(let o=i.left;o<=i.right;o++)this.history.update("borders",e,o,t,void 0)}for(let t=i.left;t<=i.right;t++)this.history.update("borders",e,t,i.bottom+1,"horizontal",void 0)}}addBorder(e,t,i,o){this.setBorder(e,t,i,{...this.getCellBorder({sheetId:e,col:t,row:i}),...o})}setBorders(e,t,i){if("clear"===i)return this.clearBorders(e,t);for(let o of t){if("h"===i||"hv"===i||"all"===i)for(let t=o.top+1;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++)this.addBorder(e,i,t,{top:j});if("v"===i||"hv"===i||"all"===i)for(let t=o.top;t<=o.bottom;t++)for(let i=o.left+1;i<=o.right;i++)this.addBorder(e,i,t,{left:j});if("left"===i||"all"===i||"external"===i)for(let t=o.top;t<=o.bottom;t++)this.addBorder(e,o.left,t,{left:j});if("right"===i||"all"===i||"external"===i)for(let t=o.top;t<=o.bottom;t++)this.addBorder(e,o.right+1,t,{left:j});if("top"===i||"all"===i||"external"===i)for(let t=o.left;t<=o.right;t++)this.addBorder(e,t,o.top,{top:j});if("bottom"===i||"all"===i||"external"===i)for(let t=o.left;t<=o.right;t++)this.addBorder(e,t,o.bottom+1,{top:j})}}addBordersToMerge(e,t){const{left:i,right:o,top:n,bottom:s}=t,r=this.getCellBorder({sheetId:e,col:i,row:n}),a=this.getCellBorder({sheetId:e,col:o,row:s});this.clearBorders(e,[t]),(null==r?void 0:r.top)&&this.setBorders(e,[{...t,bottom:n}],"top"),(null==r?void 0:r.left)&&this.setBorders(e,[{...t,right:i}],"left"),((null==a?void 0:a.bottom)||(null==r?void 0:r.bottom))&&this.setBorders(e,[{...t,top:s}],"bottom"),((null==a?void 0:a.right)||(null==r?void 0:r.right))&&this.setBorders(e,[{...t,left:o}],"right")}checkBordersUnchanged(e){var t,i,o,n;const s=this.getCellBorder(e),r=!((null===(t=e.border)||void 0===t?void 0:t.bottom)||(null===(i=e.border)||void 0===i?void 0:i.left)||(null===(o=e.border)||void 0===o?void 0:o.right)||(null===(n=e.border)||void 0===n?void 0:n.top));return!s&&r||ht(s,e.border)?89:0}import(e){if(e.borders)for(let t of e.sheets)for(let[i,o]of Object.entries(t.cells))if(null==o?void 0:o.border){const n=e.borders[o.border],{col:s,row:r}=qt(i);this.setBorder(t.id,s,r,n,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Hi(e))}export(e){let t=0;const i={};function o(e){for(let[t,o]of Object.entries(i))if(ht(o,e))return parseInt(t,10);return i[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let i=0;i<t.rowNumber;i++){const n=this.getCellBorder({sheetId:t.id,col:e,row:i});if(n){const s=Zt(e,i),r=t.cells[s],a=o(n);r?r.border=a:t.cells[s]={border:a}}}e.borders=i}exportForExcel(e){this.export(e)}}Lv.getters=["getCellBorder"];class Pv extends kv{constructor(){super(...arguments),this.nextId=1,this.cells={}}adaptRanges(e,t){for(const i of Object.keys(this.cells))for(const o of Object.values(this.cells[i]||{}))if(o.isFormula)for(const n of o.dependencies)if(!t||n.sheetId===t){const t=e(n);"NONE"!==t.changeType&&this.history.update("cells",i,o.id,"dependencies",o.dependencies.indexOf(n),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":return this.checkCellOutOfSheet(e);case"CLEAR_CELL":return this.checkValidations(e,this.chainValidations(this.checkCellOutOfSheet,this.checkUselessClearCell));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.clearFormatting(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case"UPDATE_CELL":this.updateCell(e.sheetId,e.col,e.row,e);break;case"CLEAR_CELL":this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col,row:e.row,content:"",style:null,format:""})}}setFormatter(e,t,i){for(let o of t)for(let t=o.top;t<=o.bottom;t++)for(let n=o.left;n<=o.right;n++)this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,format:i})}clearFormatting(e,t){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:null,format:""})}handleAddColumnsRows(e,t){let i,o;"before"===e.position?(i=$e(e.base,e.base+e.quantity),o=e.base+e.quantity):(i=$e(e.base+1,e.base+e.quantity+1),o=e.base),t(e.sheetId,o,i)}import(e){for(let t of e.sheets)for(let i in t.cells){const o=t.cells[i],{col:n,row:s}=qt(i);if((null==o?void 0:o.content)||(null==o?void 0:o.format)||(null==o?void 0:o.style)){const i=this.importCell(t.id,o,e.styles,e.formats);this.history.update("cells",t.id,i.id,i),this.dispatch("UPDATE_CELL_POSITION",{cellId:i.id,col:n,row:s,sheetId:t.id})}}}export(e){const t={},i={};for(let o of e.sheets){const e={},n=Object.keys(this.cells[o.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const o of n){const n=this.getters.getCell(o);e[Zt(o.col,o.row)]={style:n.style?st(n.style,t):void 0,format:n.format?st(n.format,i):void 0,content:n.content||void 0}}o.cells=e}e.styles=t,e.formats=i}importCell(e,t,i,o){const n=t.style&&i[t.style]||void 0,s=t.format&&o[t.format]||void 0,r=this.getNextUid();return this.createCell(r,(null==t?void 0:t.content)||"",s,n,e)}exportForExcel(e){this.export(e)}getCells(e){return this.cells[e]||{}}getCellById(e){const t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}buildFormulaContent(e,t,i){const o=i||t.dependencies;let n=0;return rt(t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=o[n++];return this.getters.getRangeString(t,e)}return t.value})))}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t)}getCellStyle(e){var t;return(null===(t=this.getters.getCell(e))||void 0===t?void 0:t.style)||{}}zoneToXC(e,t,i=[{colFixed:!1,rowFixed:!1}]){const o=Zt((t=this.getters.expandZone(e,t)).left,t.top,i[0]),n=Zt(t.right,t.bottom,i.length>1?i[1]:i[0]),s=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),r=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=s.col===r.col&&s.row===r.row;return o==n||a?o:o+":"+n}setStyle(e,t,i){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let n=o.top;n<=o.bottom;n++){const o=this.getters.getCell({sheetId:e,col:t,row:n});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,style:i?{...null==o?void 0:o.style,...i}:void 0})}}copyColumnStyle(e,t,i){for(let o=0;o<this.getters.getNumberRows(e);o++){const n=this.getFormat(e,t,o);if(n.style||n.format)for(let t of i)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,...n})}}copyRowStyle(e,t,i){for(let o=0;o<this.getters.getNumberCols(e);o++){const n=this.getFormat(e,o,t);if(n.style||n.format)for(let t of i)this.dispatch("UPDATE_CELL",{sheetId:e,col:o,row:t,...n})}}getFormat(e,t,i){const o={},n=this.getters.getMainCellPosition({sheetId:e,col:t,row:i}),s=this.getters.getCell(n);return s&&(s.style&&(o.style=s.style),s.format&&(o.format=s.format)),o}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,i,o){const n=this.getters.getCell({sheetId:e,col:t,row:i}),s="content"in o||"formula"in o,r=s?vt(null==o?void 0:o.content):(null==n?void 0:n.content)||"";let a;a=void 0!==o.style?o.style||void 0:n?n.style:void 0;let l=("format"in o?o.format:n&&n.format)||Ti(r);if((s&&!r&&!o.formula||!s&&(!n||""===n.content))&&!a&&!l)return void(n&&(this.history.update("cells",e,n.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:i,sheetId:e})));const c=(null==n?void 0:n.id)||this.getNextUid(),h=this.createCell(c,r,l,a,e);this.history.update("cells",e,h.id,h),this.dispatch("UPDATE_CELL_POSITION",{cellId:h.id,col:t,row:i,sheetId:e})}createCell(e,t,i,o,n){if(!t.startsWith("="))return this.createLiteralCell(e,t,i,o);try{return this.createFormulaCell(e,t,i,o,n)}catch(n){return this.createErrorFormula(e,t,i,o,n)}}createLiteralCell(e,t,i,o){return{id:e,content:t,style:o,format:i,isFormula:!1}}createFormulaCell(e,t,i,o,n){const s=vf(t);return s.dependencies.length?this.createFormulaCellWithDependencies(e,s,i,o,n):{id:e,content:t,style:o,format:i,isFormula:!0,compiledFormula:s,dependencies:[]}}createFormulaCellWithDependencies(e,t,i,o,n){const s=t.dependencies.map((e=>this.getters.getRangeFromSheetXC(n,e))),r=this.buildFormulaContent.bind(this);return{id:e,get content(){return r(n,{dependencies:this.dependencies,compiledFormula:this.compiledFormula})},style:o,format:i,isFormula:!0,compiledFormula:t,dependencies:s}}createErrorFormula(e,t,i,o,n){return{id:e,content:t,style:o,format:i,isFormula:!0,compiledFormula:{dependencies:[],tokens:Fm(t),execute:function(){throw n}},dependencies:[]}}checkCellOutOfSheet(e){const{sheetId:t,col:i,row:o}=e;if(!this.getters.tryGetSheet(t))return 27;return Ji(i,o,this.getters.getSheetZone(t))?0:18}checkUselessClearCell(e){const t=this.getters.getCell(e);return t&&(t.content||t.style||t.format)?0:89}}Pv.getters=["zoneToXC","getCells","getFormulaCellContent","getCellStyle","buildFormulaContent","getCellById"];class Uv extends kv{constructor(){super(...arguments),this.charts={},this.createChart=function(e){const t=pr.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(i,o,n){const s=t.find((e=>e.match(o.type)));if(!s)throw new Error(`No builder for this chart: ${o.type}`);return s.createChart(o,n,e)}}(this.getters),this.validateChartDefinition=e=>function(e,t){const i=pr.getAll().find((e=>e.match(t.type)));if(!i)throw new Error("Unknown chart type.");return i.validateChartDefinition(e,t)}(this,e.definition)}adaptRanges(e){for(const[t,i]of Object.entries(this.charts))this.history.update("charts",t,null==i?void 0:i.updateRanges(e))}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return 0}}handle(e){var t;switch(e.type){case"CREATE_CHART":this.addFigure(e.id,e.sheetId,e.position,e.size),this.addChart(e.id,e.definition);break;case"UPDATE_CHART":this.addChart(e.id,e.definition);break;case"DUPLICATE_SHEET":{const i=this.getters.getFigures(e.sheetId);for(const o of i)if("chart"===o.tag){const i=o.id.split(ee).pop(),n=`${e.sheetIdTo}${ee}${i}`,s=null===(t=this.charts[o.id])||void 0===t?void 0:t.copyForSheetId(e.sheetIdTo);s&&this.dispatch("CREATE_CHART",{id:n,position:{x:o.x,y:o.y},size:{width:o.width,height:o.height},definition:s.getDefinition(),sheetId:e.sheetIdTo})}break}case"DELETE_FIGURE":this.history.update("charts",e.id,void 0);break;case"DELETE_SHEET":for(let t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}getContextCreationChart(e){var t;return null===(t=this.charts[e])||void 0===t?void 0:t.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){var t;const i=null===(t=this.charts[e])||void 0===t?void 0:t.type;if(!i)throw new Error("Chart not defined.");return i}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter((([,t])=>(null==t?void 0:t.sheetId)===e)).map((([e])=>e))}getChartDefinition(e){var t;const i=null===(t=this.charts[e])||void 0===t?void 0:t.getDefinition();if(!i)throw new Error(`There is no chart with the given figureId: ${e}`);return i}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)"chart"===e.tag&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){var t;if(e.sheets)for(let i of e.sheets){const e=this.getters.getFigures(i.id),o=[];for(let i of e){const e=i;if(e&&"chart"===e.tag){const i=null===(t=this.charts[e.id])||void 0===t?void 0:t.getDefinition();i&&(e.data=i,o.push(e))}else o.push(e)}i.figures=o}}exportForExcel(e){var t;for(let i of e.sheets){const e=this.getters.getFigures(i.id),o=[];for(let i of e)if(i&&"chart"===i.tag){const e=null===(t=this.charts[i.id])||void 0===t?void 0:t.getDefinitionForExcel();e&&o.push({...i,data:e})}i.charts=o}}addFigure(e,t,i={x:0,y:0},o={width:536,height:335}){if(this.getters.getFigure(t,e))return;const n={id:e,x:i.x,y:i.y,width:o.width,height:o.height,tag:"chart"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:n})}addChart(e,t){const i=this.getters.getFigureSheetId(e);i&&this.history.update("charts",e,this.createChart(e,t,i))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?85:0}checkChartExists(e){return this.getters.getFigureSheetId(e.id)?0:86}}function Vv(e){return""===e?NaN:Number(e)}Uv.getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];class zv extends kv{constructor(){super(...arguments),this.cfRules={}}loopThroughRangesOfSheet(e,t){for(const i of this.cfRules[e])for(const o of i.ranges){const n=t(o);switch(n.changeType){case"REMOVE":let t=i.ranges.slice();t.splice(i.ranges.indexOf(o),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(i),"ranges",t):this.removeConditionalFormatting(i.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(i),"ranges",i.ranges.indexOf(o),n.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){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return this.checkValidations(e,this.checkCFRule,this.checkEmptyRange);case"MOVE_CONDITIONAL_FORMAT":return this.checkValidReordering(e.cfId,e.direction,e.sheetId)}return 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 i={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(i,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"MOVE_CONDITIONAL_FORMAT":this.reorderConditionalFormatting(e.cfId,e.direction,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){var t;return(null===(t=this.cfRules[e])||void 0===t?void 0:t.map((t=>this.mapToConditionalFormat(e,t))))||[]}getRulesSelection(e,t){const i=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{i.add(e)}))})),Array.from(i)}getRulesByZone(e,t){const i=new Set;for(let o=t.top;o<=t.bottom;o++)for(let n=t.left;n<=t.right;n++){this.getRulesByCell(e,n,o).forEach((e=>{i.add(e.id)}))}return i}getRulesByCell(e,t,i){const o=[];for(let n of this.cfRules[e])for(let e of n.ranges)Ji(t,i,e.zone)&&o.push(n);return new Set(o.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e)))}}mapToConditionalFormatInternal(e,t){const i={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return i}addConditionalFormatting(e,t){const i=this.cfRules[t].slice(),o=i.findIndex((t=>t.id===e.id)),n=this.mapToConditionalFormatInternal(t,e);o>-1?i.splice(o,1,n):i.push(n),this.history.update("cfRules",t,i)}checkValidReordering(e,t,i){if(!this.cfRules[i])return 27;const o=this.cfRules[i].findIndex((t=>t.id===e));if(-1===o)return 72;const n="up"===t?o-1:o+1;return n<0||n>=this.cfRules[i].length?72:0}checkEmptyRange(e){return e.ranges.length?0:24}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 i=>{if(t.includes(i.operator)){const t=[],o=e=>void 0===e||""===e;return e>=1&&o(i.values[0])&&t.push(52),e>=2&&o(i.values[1])&&t.push(53),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 54;case"max":return 56;case"mid":return 55;case"upperInflectionPoint":return 57;case"lowerInflectionPoint":return 58}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{vf(e.value||"")}catch(e){switch(t){case"min":return 59;case"max":return 61;case"mid":return 60;case"upperInflectionPoint":return 62;case"lowerInflectionPoint":return 63}}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,i=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(i)?49:0}checkMinBiggerThanMax(e){const t=e.minimum.value,i=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&Vv(t)>=Vv(i)?48:0}checkMidBiggerThanMax(e){var t;const i=null===(t=e.midpoint)||void 0===t?void 0:t.value,o=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&Vv(i)>=Vv(o)?50:0}checkMinBiggerThanMid(e){var t;const i=e.minimum.value,o=null===(t=e.midpoint)||void 0===t?void 0:t.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&Vv(i)>=Vv(o)?51:0}removeConditionalFormatting(e,t){const i=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==i){const e=this.cfRules[t].slice();e.splice(i,1),this.history.update("cfRules",t,e)}}reorderConditionalFormatting(e,t,i){const o=this.cfRules[i].findIndex((t=>t.id===e)),n="up"===t?o-1:o+1;if(!(n<0||n>=this.cfRules[i].length)&&-1!==o&&-1!==n){const e=[...this.cfRules[i]],t=e[o];e[o]=e[n],e[n]=t,this.history.update("cfRules",i,e)}}}zv.getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];class Bv extends kv{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:i,...o}=e,n=o;this.updateFigure(i,n);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId)}}updateFigure(e,t){if("id"in t)for(const[i,o]of Object.entries(t))switch(i){case"x":case"y":void 0!==o&&this.history.update("figures",e,t.id,i,Math.max(o,0));break;case"width":case"height":void 0!==o&&this.history.update("figures",e,t.id,i,o)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){var i;return void 0===(null===(i=this.figures[e])||void 0===i?void 0:i[t])?71:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>null==t?void 0:t[e]))?83:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(ot)}getFigure(e,t){var i;return null===(i=this.figures[e])||void 0===i?void 0:i[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>{var i;return void 0!==(null===(i=this.figures[t])||void 0===i?void 0:i[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 i=void 0;t.figures.push({...e,data:i})}}exportForExcel(e){this.export(e)}}Bv.getters=["getFigures","getFigure","getFigureSheetId"];class Hv{constructor(e){this.filters=[],this.zone=e;const t=new zi;this.id=t.uuidv4();for(const i of $e(e.left,e.right+1)){const e={...this.zone,left:i,right:i};this.filters.push(new $v(t.uuidv4(),e))}}get contentZone(){if(this.zone.bottom!==this.zone.top)return{...this.zone,top:this.zone.top+1}}getFilterId(e){var t;return null===(t=this.filters.find((t=>t.col===e)))||void 0===t?void 0:t.id}clone(){return new Hv(this.zone)}}class $v{constructor(e,t){if(t.left!==t.right)throw new Error("Can only define a filter on a single column");this.id=e,this.zoneWithHeaders=t}get col(){return this.zoneWithHeaders.left}get filteredZone(){const e=this.zoneWithHeaders;if(e.bottom!==e.top)return{...e,top:e.top+1}}}class Wv extends kv{constructor(){super(...arguments),this.tables={}}allowDispatch(e){switch(e.type){case"CREATE_FILTER_TABLE":if(!go(...e.target))return 82;const t=Yi(...e.target),i=()=>this.getFilterTables(e.sheetId).some((e=>Qi(e.zone,t)))?79:0,o=()=>{const i=this.getters.getMergesInZone(e.sheetId,t);for(let e of i)if(Qi(t,e))return 81;return 0};return this.checkValidations(e,i,o);case"ADD_MERGE":for(let t of e.target)for(let i of this.getFilterTables(e.sheetId))if(Qi(i.zone,t))return 81}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break;case"DUPLICATE_SHEET":const i={};for(const t of Object.values(this.tables[e.sheetId]||{}))if(t){const e=Fe(t);i[e.id]=e}this.history.update("tables",e.sheetIdTo,i);break;case"ADD_COLUMNS_ROWS":this.onAddColumnsRows(e);break;case"REMOVE_COLUMNS_ROWS":this.onDeleteColumnsRows(e);break;case"CREATE_FILTER_TABLE":{const t=Yi(...e.target),i=this.createFilterTable(t);this.history.update("tables",e.sheetId,i.id,i);break}case"REMOVE_FILTER_TABLE":{const t={};for(const i of this.getFilterTables(e.sheetId))e.target.every((e=>!Xi(e,i.zone)))&&(t[i.id]=i);this.history.update("tables",e.sheetId,t);break}case"UPDATE_CELL":{const t=e.sheetId;for(let i of this.getFilterTables(t))this.canUpdateCellCmdExtendTable(e,i)&&this.extendTableDown(t,i);break}}}getFilters(e){return this.getFilterTables(e).map((e=>e.filters)).flat()}getFilterTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(ot):[]}getFilter(e){var t;return null===(t=this.getFilterTable(e))||void 0===t?void 0:t.filters.find((t=>t.col===e.col))}getFilterId(e){var t;return null===(t=this.getFilter(e))||void 0===t?void 0:t.id}getFilterTable({sheetId:e,col:t,row:i}){return this.getFilterTables(e).find((e=>Ji(t,i,e.zone)))}getFilterTablesInZone(e,t){return this.getFilterTables(e).filter((e=>eo(e.zone,t)))}doesZonesContainFilter(e,t){for(const i of t)for(const t of this.getFilterTables(e))if(Xi(i,t.zone))return!0;return!1}onAddColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const i=Gi(t.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),o=[];for(const i of t.filters){const t=Gi(i.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);o.push(new $v(i.id,t))}if(o.length<oo(i).numberOfCols){for(let e=i.left;e<=i.right;e++)o.find((t=>t.col===e))||o.push(new $v(this.uuidGenerator.uuidv4(),{...i,left:e,right:e}));o.sort(((e,t)=>e.col-t.col))}this.history.update("tables",e.sheetId,t.id,"zone",i),this.history.update("tables",e.sheetId,t.id,"filters",o)}}onDeleteColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){if("ROW"===e.dimension&&e.elements.includes(t.zone.top)){const i={...this.tables[e.sheetId]};delete i[t.id],this.history.update("tables",e.sheetId,i);continue}const i=ji(t.zone,"COL"===e.dimension?"left":"top",e.elements);if(i){if(Wi(i)!==Wi(t.zone)){const o=[];for(const i of t.filters){const t=ji(i.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.elements);t&&o.push(new $v(i.id,t))}this.history.update("tables",e.sheetId,t.id,"zone",i),this.history.update("tables",e.sheetId,t.id,"filters",o)}}else{const i={...this.tables[e.sheetId]};delete i[t.id],this.history.update("tables",e.sheetId,i)}}}createFilterTable(e){return new Hv(e)}extendTableDown(e,t){const i={...t.zone,bottom:t.zone.bottom+1};this.history.update("tables",e,t.id,"zone",i);for(let i=0;i<t.filters.length;i++){const o=t.filters[i],n={...o.zoneWithHeaders,bottom:o.zoneWithHeaders.bottom+1};this.history.update("tables",e,t.id,"filters",i,"zoneWithHeaders",n)}}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:i,row:o},n){var s;if(!e)return;const r=n.zone;if(!(r.bottom+1===o&&i>=r.left&&i<=r.right))return!1;for(const e of $e(r.left,r.right+1)){const i={sheetId:t,col:e,row:o};if(null===(s=this.getters.getCell(i))||void 0===s?void 0:s.content)return!1;if(this.getters.getFilter(i))return!1;if(this.getters.isInMerge(i))return!1}return!0}import(e){for(const t of e.sheets)for(const e of t.filterTables||[]){const i=this.createFilterTable(Hi(e.range));this.history.update("tables",t.id,i.id,i)}}export(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))t.filterTables.push({range:Wi(e.zone)})}exportForExcel(e){this.export(e)}}Wv.getters=["doesZonesContainFilter","getFilter","getFilters","getFilterTable","getFilterTables","getFilterTablesInZone","getFilterId"];class Gv extends kv{constructor(){super(...arguments),this.sizes={}}handle(e){var t,i;switch(e.type){case"CREATE_SHEET":{const t=this.computeSheetSizes(e.sheetId),i={COL:t.COL.map((e=>({manualSize:void 0,computedSize:at(e)}))),ROW:t.ROW.map((e=>({manualSize:void 0,computedSize:at(e)})))};this.history.update("sizes",e.sheetId,i);break}case"DUPLICATE_SHEET":for(const t of this.sizes[e.sheetId].ROW)t.computedSize();for(const t of this.sizes[e.sheetId].COL)t.computedSize();this.history.update("sizes",e.sheetIdTo,Fe(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const o={...this.sizes};delete o[e.sheetId],this.history.update("sizes",o);break;case"REMOVE_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];for(let i of[...e.elements].sort(((e,t)=>t-e)))t.splice(i,1);const i=Math.min(...e.elements);t=t.map(((t,o)=>"ROW"===e.dimension&&o>=i?{manualSize:t.manualSize,computedSize:at((()=>this.getRowTallestCellSize(e.sheetId,o)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];const i=ct(e.position,e.base),o=t[e.base],n=$e(0,e.quantity).map((()=>({manualSize:o.manualSize,computedSize:at(o.computedSize())})));t.splice(i,0,...n),t=t.map(((t,i)=>"ROW"===e.dimension&&i>e.base+e.quantity?{manualSize:t.manualSize,computedSize:at((()=>this.getRowTallestCellSize(e.sheetId,i)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"RESIZE_COLUMNS_ROWS":for(let t of e.elements)if("ROW"===e.dimension){const i=this.getRowTallestCellSize(e.sheetId,t);this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:at(i)})}else this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:at(e.size||F)});break;case"UPDATE_CELL":const n=null===(i=null===(t=this.sizes[e.sheetId])||void 0===t?void 0:t.ROW)||void 0===i?void 0:i[e.row];if(n&&!n.manualSize){const{sheetId:t,row:i}=e;this.history.update("sizes",t,"ROW",i,"computedSize",at((()=>this.getRowTallestCellSize(t,i))))}break;case"ADD_MERGE":case"REMOVE_MERGE":for(let t of e.target)for(let i of $e(t.top,t.bottom+1)){const t=this.getRowTallestCellSize(e.sheetId,i);t!==this.getRowSize(e.sheetId,i)&&this.history.update("sizes",e.sheetId,"ROW",i,"computedSize",at(t))}}}getColSize(e,t){return this.getHeaderSize(e,"COL",t)}getRowSize(e,t){return this.getHeaderSize(e,"ROW",t)}getHeaderSize(e,t,i){var o,n,s,r;return Math.round((null===(n=null===(o=this.sizes[e])||void 0===o?void 0:o[t][i])||void 0===n?void 0:n.manualSize)||(null===(r=null===(s=this.sizes[e])||void 0===s?void 0:s[t][i])||void 0===r?void 0:r.computedSize())||this.getDefaultHeaderSize(t))}computeSheetSizes(e){var t,i;const o={COL:[],ROW:[]};for(let t of $e(0,this.getters.getNumberCols(e)))o.COL.push(this.getHeaderSize(e,"COL",t));for(let n of $e(0,this.getters.getNumberRows(e))){let s=null===(i=null===(t=this.sizes[e])||void 0===t?void 0:t.ROW)||void 0===i?void 0:i[n].manualSize;if(!s){s=this.getRowTallestCellSize(e,n)}o.ROW.push(s)}return o}getDefaultHeaderSize(e){return"COL"===e?F:D}getCellHeight(e){const t=this.getters.getMerge(e);if(t&&t.bottom!==t.top)return D;return function(e){return e&&e.content?Pe(He(e.style),e.isFormula?1:e.content.split(he).length)+2*z:D}(this.getters.getCell(e))}getRowTallestCellSize(e,t){const i=this.getters.getRowCells(e,t);let o=0;for(let e=0;e<i.length;e++){const t=this.getters.getCellById(i[e]);if(!t)continue;const n=this.getters.getCellPosition(t.id),s=this.getCellHeight(n);s>o&&s>D&&(o=s)}return o<=D?D:o}import(e){for(let t of e.sheets){const e={COL:[],ROW:[]};for(let[i,o]of Object.entries(t.rows))o.size&&(e.ROW[i]=o.size);for(let[i,o]of Object.entries(t.cols))o.size&&(e.COL[i]=o.size);const i=this.computeSheetSizes(t.id);this.sizes[t.id]={COL:i.COL.map(((t,i)=>({manualSize:e.COL[i],computedSize:at(t)}))),ROW:i.ROW.map(((t,i)=>({manualSize:e.ROW[i],computedSize:at(t)})))}}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){var i,o;for(let n of e.sheets){void 0===n.rows&&(n.rows={});for(let e of $e(0,this.getters.getNumberRows(n.id)))(t||(null===(i=this.sizes[n.id].ROW[e])||void 0===i?void 0:i.manualSize))&&(n.rows[e]={...n.rows[e],size:this.getRowSize(n.id,e)});void 0===n.cols&&(n.cols={});for(let e of $e(0,this.getters.getNumberCols(n.id)))(t||(null===(o=this.sizes[n.id].COL[e])||void 0===o?void 0:o.manualSize))&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}}Gv.getters=["getRowSize","getColSize"];class qv extends kv{constructor(){super(...arguments),this.hiddenHeaders={}}allowDispatch(e){switch(e.type){case"HIDE_COLUMNS_ROWS":{if(!this.getters.tryGetSheet(e.sheetId))return 27;const t="COL"===e.dimension?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),i="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=i?67:Math.min(...e.elements)<0||Math.max(...e.elements)>i?87:0}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?8:0:27}return 0}handle(e){switch(e.type){case"CREATE_SHEET":const t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update("hiddenHeaders",e.sheetId,t);break;case"DUPLICATE_SHEET":this.history.update("hiddenHeaders",e.sheetIdTo,Fe(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let i of[...e.elements].sort(((e,t)=>t-e)))t.splice(i,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]],i=ct(e.position,e.base);t.splice(i,0,...Array(e.quantity).fill(!1)),this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"HIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}checkElementsIncludeAllVisibleHeaders(e,t,i){return dt(i,this.getAllVisibleHeaders(e,t))}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]}getHiddenColsGroups(e){const t=[[]],i=this.hiddenHeaders[e].COL;for(let e=0;e<i.length;e++){i[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],i=this.hiddenHeaders[e].ROW;for(let e=0;e<i.length;e++){i[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){return $e(0,this.hiddenHeaders[e][t].length).filter((i=>!this.hiddenHeaders[e][t][i]))}import(e){var t,i;for(let o of e.sheets){this.hiddenHeaders[o.id]={COL:[],ROW:[]};for(let e=0;e<o.rowNumber;e++)this.hiddenHeaders[o.id].ROW[e]=Boolean(null===(t=o.rows[e])||void 0===t?void 0:t.isHidden);for(let e=0;e<o.colNumber;e++)this.hiddenHeaders[o.id].COL[e]=Boolean(null===(i=o.cols[e])||void 0===i?void 0:i.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let i of e.sheets){void 0===i.rows&&(i.rows={});for(let e=0;e<this.getters.getNumberRows(i.id);e++)(t||this.hiddenHeaders[i.id].ROW[e])&&(void 0===i.rows[e]&&(i.rows[e]={}),i.rows[e].isHidden=this.hiddenHeaders[i.id].ROW[e]);void 0===i.cols&&(i.cols={});for(let e=0;e<this.getters.getNumberCols(i.id);e++)(t||this.hiddenHeaders[i.id].COL[e])&&(void 0===i.cols[e]&&(i.cols[e]={}),i.cols[e].isHidden=this.hiddenHeaders[i.id].COL[e])}}}qv.getters=["checkElementsIncludeAllVisibleHeaders","getHiddenColsGroups","getHiddenRowsGroups","isRowHiddenByUser","isColHiddenByUser"];class Zv extends kv{constructor(e){super(e),this.images={},this.syncedImages=new Set,this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?28:0}handle(e){switch(e.type){case"CREATE_IMAGE":this.addFigure(e.figureId,e.sheetId,e.position,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const i of t)if("image"===i.tag){const t=i.id.split(ee).pop(),o=`${e.sheetIdTo}${ee}${t}`,n=this.getImage(i.id);if(n){const t={width:i.width,height:i.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:o,position:{x:i.x,y:i.y},size:t,definition:Fe(n)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.id,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}garbageCollectExternalResources(){var e;const t=new Set(this.getAllImages().map((e=>e.path)));for(const i of this.syncedImages)t.has(i)||null===(e=this.fileStore)||void 0===e||e.delete(i)}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,i,o){const n={id:e,x:i.x,y:i.y,width:o.width,height:o.height,tag:"image"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:n})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter((e=>"image"===e.tag));for(const i of e)this.history.update("images",t.id,i.id,i.data),this.syncedImages.add(i.data.path)}}export(e){var t;for(const i of e.sheets){const e=i.figures.filter((e=>"image"===e.tag));for(const o of e)o.data=null===(t=this.images[i.id])||void 0===t?void 0:t[o.id]}}exportForExcel(e){for(const t of e.sheets){const e=this.getters.getFigures(t.id),i=[];for(const t of e)if("image"===(null==t?void 0:t.tag)){const e=this.getImage(t.id);e&&i.push({...t,data:Fe(e)})}t.images=i}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(ot));return e}}Zv.getters=["getImage","getImagePath","getImageSize"];class jv extends kv{constructor(){super(...arguments),this.nextId=1,this.merges={},this.mergeCellMap={}}allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;for(const i of Object.values(t).filter(ot))this.addMerge(e.sheetIdTo,i.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){const i=t?[t]:Object.keys(this.merges);for(const t of i)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(ot)}getMerge({sheetId:e,col:t,row:i}){var o;const n=this.mergeCellMap[e],s=n?t in n&&(null===(o=n[t])||void 0===o?void 0:o[i]):void 0;return s?this.getMergeById(e,s):void 0}getMergesInZone(e,t){var i;const o=this.mergeCellMap[e];if(!o)return[];const n=new Set;for(const{col:e,row:s}of so(t)){const t=null===(i=o[e])||void 0===i?void 0:i[s];t&&n.add(t)}return Array.from(n).map((t=>this.getMergeById(e,t))).filter(ot)}doesIntersectMerge(e,t){return so(t).some((({col:t,row:i})=>void 0!==this.getMerge({sheetId:e,col:t,row:i})))}doesColumnsHaveCommonMerges(e,t,i){const o=this.getters.getSheet(e);for(let n=0;n<this.getters.getNumberRows(e);n++)if(this.isInSameMerge(o.id,t,n,i,n))return!0;return!1}doesRowsHaveCommonMerges(e,t,i){const o=this.getters.getSheet(e);for(let n=0;n<=this.getters.getNumberCols(e);n++)if(this.isInSameMerge(o.id,n,t,n,i))return!0;return!1}expandZone(e,t){let{left:i,right:o,top:n,bottom:s}=t,r={left:i,right:o,top:n,bottom:s};for(let t in this.merges[e]){const i=this.getMergeById(e,parseInt(t));i&&Qi(i,r)&&(r=Yi(i,r))}return Ki(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,i,o,n){const s=this.getMerge({sheetId:e,col:t,row:i}),r=this.getMerge({sheetId:e,col:o,row:n});return!(!s||!r)&&Ki(s,r)}isInMerge({sheetId:e,col:t,row:i}){var o;const n=this.mergeCellMap[e];return!!n&&(t in n&&Boolean(null===(o=n[t])||void 0===o?void 0:o[i]))}getMainCellPosition(e){if(!this.isInMerge(e))return e;const t=this.getMerge(e).topLeft;return{sheetId:e.sheetId,col:t.col,row:t.row}}getBottomLeftCell(e){if(!this.isInMerge(e))return e;const{bottom:t,left:i}=this.getMerge(e);return{sheetId:e.sheetId,col:i,row:t}}isMergeHidden(e,t){const i=this.getters.getHiddenColsGroups(e),o=this.getters.getHiddenRowsGroups(e);for(let e of i)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of o)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const i=this.getMerge({sheetId:e,col:t.left,row:t.top});if(i)return Ki(t,i);const{numberOfCols:o,numberOfRows:n}=oo(t);return 1===o&&1===n}isMergeDestructive(e,t){let{left:i,right:o,top:n,bottom:s}=t;o=Le(o,0,this.getters.getNumberCols(e)-1),s=Le(s,0,this.getters.getNumberRows(e)-1);for(let t=n;t<=s;t++)for(let s=i;s<=o;s++)if(s!==i||t!==n){const i=this.getters.getCell({sheetId:e,col:s,row:t});if(i&&""!==i.content)return!0}return!1}getMergeById(e,t){var i;const o=null===(i=this.merges[e])||void 0===i?void 0:i[t];return void 0!==o?Xv(t,o):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;return t.some((t=>this.isMergeDestructive(e,t)))?3:0}checkOverlap({target:e}){for(const t of e)for(const i of e)if(t!==i&&Qi(t,i))return 66;return 0}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;const{xSplit:i,ySplit:o}=this.getters.getPaneDivisions(e);for(const e of t)if(e.left<i&&e.right>=i||e.top<o&&e.bottom>=o)return 76;return 0}checkMergedContentUpdate(e){const{col:t,row:i,content:o}=e;if(void 0===o)return 0;const{col:n,row:s}=this.getMainCellPosition(e);return n===t&&s===i?0:4}checkMergeExists(e){const{sheetId:t,target:i}=e;for(const e of i){const{left:i,top:o}=e,n=this.getMerge({sheetId:t,col:i,row:o});if(void 0===n||!Ki(e,n))return 5}return 0}addMerge(e,t){let{left:i,right:o,top:n,bottom:s}=t;o=Le(o,0,this.getters.getNumberCols(e)-1),s=Le(s,0,this.getters.getNumberRows(e)-1);if(Zt(i,n)===Zt(o,s))return;const r=this.getters.getCell({sheetId:e,col:i,row:n});let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,Wi({left:i,top:n,right:o,bottom:s})));let l=new Set;for(let t=n;t<=s;t++)for(let s=i;s<=o;s++){s===i&&t===n||this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,style:r?r.style:null,content:""});const o=this.getMerge({sheetId:e,col:s,row:t});o&&l.add(o.id),this.history.update("mergeCellMap",e,s,t,a)}for(let t of l){const{top:i,bottom:o,left:n,right:s}=this.getMergeById(e,t);for(let t=i;t<=o;t++)for(let i=n;i<=s;i++){const o={sheetId:e,col:i,row:t},n=this.getMerge(o);n&&n.id===a||(this.history.update("mergeCellMap",e,i,t,void 0),this.dispatch("CLEAR_CELL",o))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:i,top:o,bottom:n,right:s}=t,r=this.getMerge({sheetId:e,col:i,row:o});if(void 0!==r&&Ki(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=o;t<=n;t++)for(let o=i;o<=s;o++)this.history.update("mergeCellMap",e,o,t,void 0)}}applyRangeChangeOnSheet(e,t){const i=Object.entries(this.merges[e]||{});for(const[o,n]of i)if(n){const i=n.zone,s=t(n);switch(s.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,i);break;default:const{numberOfCols:t,numberOfRows:n}=oo(s.range.zone);1===t&&1===n?this.removeMerge(e,i):this.history.update("merges",e,parseInt(o,10),s.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:i,row:o}of so(t))this.history.update("mergeCellMap",e,i,o,t.id)}import(e){const t=e.sheets||[];for(let e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let i of t)this.addMerge(e,Hi(i))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...Yv(e))}}exportForExcel(e){this.export(e)}}function Yv(e){return Object.entries(e).map((([e,t])=>t?Xv(parseInt(e,10),t):void 0)).filter(ot).map((e=>Zt(e.left,e.top)+":"+Zt(e.right,e.bottom)))}function Xv(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}jv.getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge"];class Kv{constructor(e){this.providers=[],this.getters=e}allowDispatch(e){return"MOVE_RANGES"===e.type?1===e.target.length?0:26:0}beforeHandle(e){}handle(e){switch(e.type){case"REMOVE_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",i="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";const n=[...e.elements];n.sort(((e,t)=>t-e));const s=We(n);this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};let r=n,a="NONE";for(let e of s){const s=Math.min(...e),l=Math.max(...e);if(n.zone[t]<=s&&s<=n.zone[i]){const e=Math.min(n.zone[i],l)-s+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e)}else if(n.zone[t]>=s&&n.zone[i]<=l)a="REMOVE",r=n.clone({...this.getInvalidRange()});else if(n.zone[t]<=l&&n.zone[i]>=l){const e=l-n.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e),r=this.createAdaptedRange(r,o,"MOVE",-(n.zone[t]-s))}else s<n.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,o,a,-(l-s+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",i="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(n.zone[t]<=e.base&&e.base<n.zone[i])return{changeType:"RESIZE",range:this.createAdaptedRange(n,o,"RESIZE",e.quantity)};if(e.base<n.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(n,o,"MOVE",e.quantity)}}else{if(n.zone[t]<e.base&&e.base<=n.zone[i])return{changeType:"RESIZE",range:this.createAdaptedRange(n,o,"RESIZE",e.quantity)};if(e.base<=n.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(n,o,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId!==e.sheetId)return{changeType:"NONE"};const i=this.getters.getSheetName(e.sheetId);return{changeType:"REMOVE",range:t=t.clone({...this.getInvalidRange(),invalidSheetName:i})}}),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 i=void 0,o=e.sheetId;return{changeType:"CHANGE",range:t.clone({sheetId:o,invalidSheetName:i})}}return{changeType:"NONE"}}));break;case"MOVE_RANGES":{const t=e.target[0];this.executeOnAllRanges((i=>{if(i.sheetId!==e.sheetId||!eo(i.zone,t))return{changeType:"NONE"};const o=e.targetSheetId,n=e.col-t.left,s=e.row-t.top,r=this.createAdaptedRange(i,"both","MOVE",[n,s]),a=e.sheetId!==o||r.prefixSheet;return{changeType:"MOVE",range:r.clone({sheetId:o,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const i=e(t);return"NONE"===i.changeType||$i(i.range.zone)?i:{range:i.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,i,o){const n=ro(e.unboundedZone,t,i,o);return e.clone({zone:n})}executeOnAllRanges(e,t){const i=this.verifyRangeRemoved(e);for(const e of this.providers)e(i,t)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,i,o){const n=e.map((e=>ki.fromRange(e,this.getters)));return n.map((e=>{if(!$i(e.zone))return e;const n=e.prefixSheet?e.sheetId:o,s={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:i),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:i)};return e.clone({sheetId:n,zone:s}).orderZone()}))}getRangeFromSheetXC(e,t){if(!Pt.test(t))return new ki({sheetId:"",zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let i,o=t,n=!1;t.includes("!")&&(({xc:o,sheetName:i}=$t(t)),i&&(n=!0));const s=Bi(o),r=ki.getRangeParts(o,s),a=i&&!this.getters.getSheetIdByName(i)?i:void 0,l=this.getters.getSheetIdByName(i)||e;return new ki({prefixSheet:n,zone:s,sheetId:l,invalidSheetName:a,parts:r},this.getters.getSheetSize).orderZone()}getSelectionRangeString(e,t){const i=ki.fromRange(e,this.getters),o=this.getters.expandZone(i.sheetId,i.zone),n=i.clone({zone:{...o,bottom:i.isFullCol?void 0:o.bottom,right:i.isFullRow?void 0:o.right}});return this.getRangeString(n,t)}getRangeString(e,t){if(!e)return K;if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return K;if(e.zone.left<0||e.zone.top<0)return K;const i=ki.fromRange(e,this.getters);let o=i.sheetId!==t||i.invalidSheetName||i.prefixSheet,n="";if(o&&(n=i.invalidSheetName?i.invalidSheetName:ke(this.getters.getSheetName(i.sheetId))),o&&!n)return K;let s=this.getRangePartString(i,0);return i.parts&&2===i.parts.length&&(i.zone.top!==i.zone.bottom||i.zone.left!==i.zone.right||i.parts[0].rowFixed||i.parts[0].colFixed||i.parts[1].rowFixed||i.parts[1].colFixed)&&(s+=":",s+=this.getRangePartString(i,1)),`${o?n+"!":""}${s}`}getRangeDataFromXc(e,t){return this.getters.getRangeFromSheetXC(e,t).rangeData}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t}}getRangeFromRangeData(e){const t={prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]};return new ki(t,this.getters.getSheetSize)}getRangePartString(e,t){var i,o;const n=e.parts&&(null===(i=e.parts[t])||void 0===i?void 0:i.colFixed)?"$":"",s=Wt(0===t?e.zone.left:e.zone.right),r=e.parts&&(null===(o=e.parts[t])||void 0===o?void 0:o.rowFixed)?"$":"",a=String(0===t?e.zone.top+1:e.zone.bottom+1);let l="";return l=e.isFullCol?0===t&&e.unboundedZone.hasHeader?n+s+r+a:n+s:e.isFullRow?0===t&&e.unboundedZone.hasHeader?n+s+r+a:r+a:n+s+r+a,l}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:K}}}Kv.getters=["getRangeString","getSelectionRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData"];class Qv extends kv{constructor(){super(...arguments),this.sheetIdsMapName={},this.orderedSheetIds=[],this.sheets={},this.cellPosition={}}allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZones)(e);if(0!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?9:0;case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"MOVE_SHEET":try{const t=this.orderedSheetIds.findIndex((t=>t===e.sheetId));return this.findIndexOfTargetSheet(t,e.delta),0}catch(e){return 14}case"RENAME_SHEET":return this.isRenameAllowed(e);case"DELETE_SHEET":return this.orderedSheetIds.length>1?0:9;case"ADD_COLUMNS_ROWS":const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return e.base<0||e.base>=t?87:e.quantity<=0?88:0;case"REMOVE_COLUMNS_ROWS":{const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return Math.min(...e.elements)<0||Math.max(...e.elements)>t?87:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?8:0}case"FREEZE_ROWS":return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case"FREEZE_COLUMNS":return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);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("sheetIdsMapName",t.name,t.id);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.delta);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.name);break;case"HIDE_SHEET":this.hideSheet(e.sheetId);break;case"SHOW_SHEET":this.showSheet(e.sheetId);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e);break;case"FREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,e.quantity,"COL");break;case"FREEZE_ROWS":this.setPaneDivisions(e.sheetId,e.quantity,"ROW");break;case"UNFREEZE_ROWS":this.setPaneDivisions(e.sheetId,0,"ROW");break;case"UNFREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,0,"COL");break;case"UNFREEZE_COLUMNS_ROWS":this.setPaneDivisions(e.sheetId,0,"COL"),this.setPaneDivisions(e.sheetId,0,"ROW")}}import(e){var t,i;for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let o of e.sheets){const e=o.name||n("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:s,rowNumber:r}=this.getImportedSheetSize(o),a={id:o.id,name:e,numberOfCols:s,rows:Vi(r),areGridLinesVisible:void 0===o.areGridLinesVisible||o.areGridLinesVisible,isVisible:o.isVisible,panes:{xSplit:(null===(t=o.panes)||void 0===t?void 0:t.xSplit)||0,ySplit:(null===(i=o.panes)||void 0===i?void 0:i.ySplit)||0}};this.orderedSheetIds.push(a.id),this.sheets[a.id]=a}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(ot).map((e=>{const t=this.sheets[e],i={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},conditionalFormats:[],figures:[],filterTables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible};return(t.panes.xSplit||t.panes.ySplit)&&(i.panes=t.panes),i}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){var t;return null===(t=this.tryGetSheet(e))||void 0===t?void 0:t.name}getSheetIdByName(e){if(e){const t=De(e);for(const e in this.sheetIdsMapName)if(e.toUpperCase()===t.toUpperCase())return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}getEvaluationSheets(){return this.sheets}doesHeaderExist(e,t,i){return"COL"===t?i>=0&&i<this.getNumberCols(e):i>=0&&i<this.getNumberRows(e)}getRow(e,t){const i=this.getSheet(e).rows[t];if(!i)throw new Error(`Row ${i} not found.`);return i}getCell({sheetId:e,col:t,row:i}){var o;const n=this.tryGetSheet(e),s=null===(o=null==n?void 0:n.rows[i])||void 0===o?void 0:o.cells[t];if(void 0!==s)return this.getters.getCellById(s)}getColsZone(e,t,i){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:i}}getRowCells(e,t){var i;return Object.values(null===(i=this.getSheet(e).rows[t])||void 0===i?void 0:i.cells).filter(ot)}getRowsZone(e,t,i){return{top:t,bottom:i,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){let t=1;const i=this.orderedSheetIds.map(this.getSheetName.bind(this));let o=`${e}${t}`;for(;i.includes(o);)o=`${e}${t}`,t++;return o}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,i){const o={...this.getPaneDivisions(e)};"COL"===i?o.xSplit=t:"ROW"===i&&(o.ySplit=t),this.history.update("sheets",e,"panes",o)}checkElementsIncludeAllNonFrozenHeaders(e,t,i){const o=this.getters.getPaneDivisions(e),n="ROW"===t?o.ySplit:o.xSplit,s=this.getters.getNumberHeaders(e,t);if(!n)return!1;return dt(i,$e(n,s))}isEmpty(e,t){return so(t).map((({col:t,row:i})=>this.getCell({sheetId:e,col:t,row:i}))).every((e=>!e||""===e.content))}updateCellPosition(e){const{sheetId:t,cellId:i,col:o,row:n}=e;i?this.setNewPosition(i,t,o,n):this.clearPosition(t,o,n)}setNewPosition(e,t,i,o){const n=this.cellPosition[e];n&&this.clearPosition(t,n.col,n.row),this.history.update("cellPosition",e,{row:o,col:i,sheetId:t}),this.history.update("sheets",t,"rows",o,"cells",i,e)}clearPosition(e,t,i){var o;const n=null===(o=this.sheets[e])||void 0===o?void 0:o.rows[i].cells[t];n&&(this.history.update("cellPosition",n,void 0),this.history.update("sheets",e,"rows",i,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++){this.sheets[e].rows[o].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:o})}}createSheet(e,t,i,o,n){const s={id:e,name:t,numberOfCols:i,rows:Vi(o),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},r=this.orderedSheetIds.slice();r.splice(n,0,s.id);const a=this.sheets;return this.history.update("orderedSheetIds",r),this.history.update("sheets",Object.assign({},a,{[s.id]:s})),s}moveSheet(e,t){const i=this.orderedSheetIds.slice(),o=i.findIndex((t=>t===e)),n=i.splice(o,1);let s=this.findIndexOfTargetSheet(o,t);i.splice(s,0,n[0]),this.history.update("orderedSheetIds",i)}findIndexOfTargetSheet(e,t){for(;0!=t&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(0===t)return e;throw new Error(s("There is not enough visible sheets"))}checkSheetName(e){const{orderedSheetIds:t,sheets:i}=this,o=e.name&&e.name.trim().toLowerCase();return t.find((e=>{var t;return(null===(t=i[e])||void 0===t?void 0:t.name.toLowerCase())===o}))?11:re.test(o)?13:0}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?15:0}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?0:75}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?0:75}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let i of t)if(i.top<e.quantity&&e.quantity<=i.bottom)return 66;return 0}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let i of t)if(i.left<e.quantity&&e.quantity<=i.right)return 66;return 0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const i=e.name;this.history.update("sheets",e.id,"name",t.trim());const o=Object.assign({},this.sheetIdsMapName);o[t]=e.id,delete o[i],this.history.update("sheetIdsMapName",o)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t){const i=this.getSheet(e),o=this.getDuplicateSheetName(i.name),n=Fe(i);n.id=t,n.name=o;for(let e=0;e<=n.numberOfCols;e++)for(let t=0;t<=n.rows.length;t++)n.rows[t]&&(n.rows[t].cells[e]=void 0);const s=this.orderedSheetIds.slice(),r=s.indexOf(e);s.splice(r+1,0,n.id),this.history.update("orderedSheetIds",s),this.history.update("sheets",Object.assign({},this.sheets,{[n.id]:n}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:i}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:n.id,col:e,row:i,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIdsMapName);a[n.name]=n.id,this.history.update("sheetIdsMapName",a)}getDuplicateSheetName(e){let t=1;const i=this.orderedSheetIds.map(this.getSheetName.bind(this)),o=s("Copy of %s",e);let n=o.toString();for(;i.includes(n);)n=`${o} (${t})`,t++;return n}deleteSheet(e){const t=e.name,i=Object.assign({},this.sheets);delete i[e.id],this.history.update("sheets",i);const o=this.orderedSheetIds.slice(),n=o.indexOf(e.id);o.splice(n,1),this.history.update("orderedSheetIds",o);const s=Object.assign({},this.sheetIdsMapName);delete s[t],this.history.update("sheetIdsMapName",s)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let i of t)this.moveCellOnColumnsDeletion(e,i);const i=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",i-t.length);const o=t.filter((t=>t<e.panes.xSplit)).length;o&&this.setPaneDivisions(e.id,e.panes.xSplit-o,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(let i of We(t)){const t=i[i.length-1],o=i[0];this.moveCellOnRowsDeletion(e,t,o),this.updateRowsStructureOnDeletion(e,t,o)}const i=t.filter((t=>t<e.panes.ySplit)).length;i&&this.setPaneDivisions(e.id,e.panes.ySplit-i,"ROW")}addColumns(e,t,i,o){const n="before"===i?t:t+1;this.moveCellsOnAddition(e,n,o,"columns");const s=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",s+o),n<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+o,"COL")}addRows(e,t,i,o){const n="before"===i?t:t+1;this.addEmptyRows(e,o),this.moveCellsOnAddition(e,n,o,"rows"),n<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+o,"ROW")}moveCellOnColumnsDeletion(e,t){for(let i=0;i<e.rows.length;i++){const o=e.rows[i];for(let n in o.cells){const s=Number(n),r=o.cells[n];r&&(s===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:s,row:i}),s>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:s-1,row:i}))}}}moveCellsOnAddition(e,t,i,o){const n=[];for(let s=0;s<e.rows.length;s++){const r=e.rows[s];if("rows"!==o||s>=t)for(let a in r.cells){const l=Number(a),c=r.cells[a];c&&("rows"===o||l>=t)&&n.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c,col:l+("columns"===o?i:0),row:s+("rows"===o?i:0)})}}for(let e of n.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,i){const o=i-t+1;for(let n=0;n<e.rows.length;n++){const s=e.rows[n];if(n>=t&&n<=i)for(let t in s.cells){const i=Number(t);s.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:i,row:n})}if(n>i)for(let t in s.cells){const i=Number(t),r=s.cells[t];r&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:i,row:n-o})}}}updateRowsStructureOnDeletion(e,t,i){const o=[],n=e.rows.map((e=>e.cells)).reverse();for(let s in e.rows){const e=Number(s);e>=t&&e<=i||o.push({cells:n.pop()})}this.history.update("sheets",e.id,"rows",o)}addEmptyRows(e,t){const i=e.rows.slice();for(let e=0;e<t;e++)i.push({cells:{}});this.history.update("sheets",e.id,"rows",i)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(qt);let i=e.rowNumber,o=e.colNumber;for(let{col:e,row:n}of t)i=Math.max(i,n+1),o=Math.max(o,e+1);return{rowNumber:i,colNumber:o}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?27:"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),"ranges"in e&&Array.isArray(e.ranges)&&t.push(...e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone))),!t.every($i))return 25;if(t.length&&"sheetId"in e){const i=this.getSheetZone(e.sheetId);return t.every((e=>eo(e,i)))?0:18}return 0}}Qv.getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheetIds","getVisibleSheetIds","isSheetVisible","getEvaluationSheets","doesHeaderExist","getCell","getCellPosition","getColsZone","getRowCells","getRowsZone","getNumberCols","getNumberRows","getNumberHeaders","getGridLinesVisibility","getNextSheetName","isEmpty","getSheetSize","getSheetZone","getPaneDivisions","checkElementsIncludeAllNonFrozenHeaders"];class Jv extends Dv{constructor({getters:e,stateObserver:t,dispatch:i,uiActions:o,selection:n}){super(t,i),this.getters=e,this.ui=o,this.selection=n}drawGrid(e,t){}}Jv.layers=[];class eb extends Jv{constructor(){super(...arguments),this.customColors=new Set,this.shouldUpdateColors=!1}handle(e){switch(e.type){case"UPDATE_CELL":case"UPDATE_CHART":case"CREATE_CHART":case"ADD_CONDITIONAL_FORMAT":this.shouldUpdateColors=!0}}finalize(){if(this.shouldUpdateColors){this.shouldUpdateColors=!1;for(const e of this.getCustomColors())this.tryToAddColor(e)}}getCustomColors(){let e=[];for(const t of this.getters.getSheetIds()){const i=Object.values(this.getters.getCells(t));e=e.concat(this.getColorsFromCells(i),this.getFormattingColors(t),this.getChartColors(t))}return function(e){const t=[{leadColor:It(255,0,0),colors:[]},{leadColor:It(255,128,0),colors:[]},{leadColor:It(128,128,0),colors:[]},{leadColor:It(128,255,0),colors:[]},{leadColor:It(0,255,0),colors:[]},{leadColor:It(0,255,128),colors:[]},{leadColor:It(0,255,255),colors:[]},{leadColor:It(0,127,255),colors:[]},{leadColor:It(0,0,255),colors:[]},{leadColor:It(127,0,255),colors:[]},{leadColor:It(128,0,128),colors:[]},{leadColor:It(255,0,128),colors:[]}];for(const i of e.map(At)){let e=500,o=0;t.forEach(((t,n)=>{const s=(r=i,a=t.leadColor,Math.sqrt(Math.pow(r.r-a.r,2)+Math.pow(r.g-a.g,2)+Math.pow(r.b-a.b,2)));var r,a;e>s&&(e=s,o=n)})),t[o].colors.push(i)}return t.map((e=>e.colors.sort(((e,t)=>Ot(e).s-Ot(t).s)))).flat().map(Tt)}([...new Set([...new Set([...e,...this.customColors])].filter(yt).map(wt))]).filter((e=>!O.includes(e)))}getColorsFromCells(e){var t,i;const o=new Set;for(const n of e)(null===(t=n.style)||void 0===t?void 0:t.textColor)&&o.add(n.style.textColor),(null===(i=n.style)||void 0===i?void 0:i.fillColor)&&o.add(n.style.fillColor);return[...o]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),i=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(i.push(t.style.textColor),i.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(i.push(Et(t.minimum.color)),i.push(t.midpoint?Et(t.midpoint.color):void 0),i.push(Et(t.maximum.color)))}return i.filter(ot)}getChartColors(e){const t=this.getters.getChartIds(e).map((e=>this.getters.getChart(e)));let i=new Set;for(let e of t){if(void 0===e)continue;const t=e.getDefinition().background;switch(void 0!==t&&i.add(t),e.type){case"gauge":const t=e.sectionRule.colors;i.add(t.lowerColor),i.add(t.middleColor),i.add(t.upperColor);break;case"scorecard":const o=e;i.add(o.baselineColorDown),i.add(o.baselineColorUp)}}return[...i]}tryToAddColor(e){const t=wt(e);e&&!O.includes(t)&&this.customColors.add(t)}}eb.getters=["getCustomColors"];const tb=ig.mapping;class ib extends Jv{constructor(e){super(e),this.isUpToDate=!1,this.evaluatedCells={},this.evalContext=e.custom,this.lazyEvaluation=e.lazyEvaluation}handle(e){switch(dn.has(e.type)&&(this.isUpToDate=!1),e.type){case"UPDATE_CELL":("content"in e||"format"in e)&&(this.isUpToDate=!1);break;case"EVALUATE_CELLS":this.evaluate()}}finalize(){this.isUpToDate||(this.evaluate(),this.isUpToDate=!0)}evaluateFormula(e,t=this.getters.getActiveSheetId()){try{const i=vf(e),o=this.getCompilationParameters((e=>this.getEvaluatedCell(this.getters.getCellPosition(e.id)))),n=[];for(let e of i.dependencies)n.push(this.getters.getRangeFromSheetXC(t,e));return i.execute(n,...o).value}catch(e){return e instanceof c?e.errorType:a.GenericError}}getRangeFormattedValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.formattedValue))}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.value))}getRangeFormats(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.format))}getEvaluatedCell({sheetId:e,col:t,row:i}){var o,n,s;return void 0===this.getters.getCell({sheetId:e,col:t,row:i})?wn(""):(null===(s=null===(n=null===(o=this.evaluatedCells[e])||void 0===o?void 0:o[t])||void 0===n?void 0:n[i])||void 0===s?void 0:s.call(n))||wn("")}getEvaluatedCells(e){const t=this.getters.getCells(e)||{},i={};for(let e of Object.keys(t)){const t=this.getters.getCellPosition(e);i[e]=this.getEvaluatedCell(t)}return i}getColEvaluatedCells(e,t){var i;return Object.values((null===(i=this.evaluatedCells[e])||void 0===i?void 0:i[t])||[]).filter(ot).map((e=>e()))}getEvaluatedCellsInZone(e,t){return so(t).map((({col:t,row:i})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:i})))}setEvaluatedCell(e,t){const{col:i,row:o,sheetId:n}=this.getters.getCellPosition(e);this.evaluatedCells[n]||(this.evaluatedCells[n]={}),this.evaluatedCells[n][i]||(this.evaluatedCells[n][i]={}),this.evaluatedCells[n][i][o]=t,this.lazyEvaluation||this.evaluatedCells[n][i][o]()}*getAllCells(){for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t)yield t[e]}}evaluate(){this.evaluatedCells={};const e=new Set,t=e=>{var t,n;const s=e.id,{col:r,row:a,sheetId:l}=this.getters.getCellPosition(s),c=null===(n=null===(t=this.evaluatedCells[l])||void 0===t?void 0:t[r])||void 0===n?void 0:n[a];return c||at((()=>{try{switch(e.isFormula){case!0:return o(e);case!1:return Sn(e.content,e.format)}}catch(t){return i(t,e)}}))},i=(e,t)=>{e instanceof Error||(e=new Error(e));const i=(null==e?void 0:e.errorType)||a.GenericError,o=n[2].__lastFnCalled||"",s=new c(i,e.message.replace("[[FUNCTION_NAME]]",o),void 0!==e.logLevel?e.logLevel:l.error);return Rn(t.content,s)},o=t=>{const i=t.id;if(e.has(i))throw new d;n[2].__originCellXC=()=>{const e=n[2].getters.getCellPosition(i);return Zt(e.col,e.row)},e.add(i);const o=t.compiledFormula.execute(t.dependencies,...n);if(e.delete(i),Array.isArray(o.value))throw new Error(s("This formula depends on invalid values"));return wn(o.value,t.format||o.format)},n=this.getCompilationParameters((e=>t(e)()));for(const e of this.getAllCells())this.setEvaluatedCell(e.id,t(e))}getCompilationParameters(e){const t=Object.assign(Object.create(tb),this.evalContext,{getters:this.getters}),i=this.getters;const o=t=>{const i=e(t);if(i.type===cn.error)throw i.error;return i},n={};function r(e){if(!$i(e.zone))throw new u;if(e.invalidSheetName)throw new Error(s("Invalid sheet name: %s",e.invalidSheetName))}return[function(e,t,n,a){if(r(e),t)return{value:Wi(e.zone)};if(e.zone.bottom!==e.zone.top||e.zone.left!==e.zone.right)throw new Error(a?s("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",n.toString(),a.toString()):s("Function %s expects its parameters to be single values or single cell references, not ranges.",n.toString()));return function(e){let t;if(!i.tryGetSheet(e.sheetId))throw new Error(s("Invalid sheet name"));return t=i.getCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}),t&&""!==t.content?o(t):{value:null,format:null==t?void 0:t.format}}(e)},function(e){r(e);const s=e.sheetId,a=i.getSheetZone(s),l=Xi(e.zone,a);if(!l)return[[]];const{top:c,left:h,bottom:d,right:u}=l,g=`${s}-${c}-${h}-${d}-${u}`;if(g in n)return n[g];const p=new Array(u-h+1);for(let i=h;i<=u;i++){const n=new Array(d-c+1);for(let s=c;s<=d;s++){const r=t.getters.getCell({sheetId:e.sheetId,col:i,row:s});n[s-c]=r?o(r):void 0}p[i-h]=n}return n[g]=p,p},t]}exportForExcel(e){for(let t of e.sheets)for(const e in t.cells){const i={sheetId:t.id,...qt(e)},o=this.getters.getCell(i);if(o){const n=t.cells[e],s=this.getEvaluatedCell(i);n.value=s.value,n.isFormula=o.isFormula&&!this.isBadExpression(o.content),o.format!==s.format&&(n.computedFormat=s.format)}}}isBadExpression(e){try{return vf(e),!1}catch(e){return!0}}}ib.getters=["evaluateFormula","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getColEvaluatedCells","getEvaluatedCellsInZone"];class ob extends Jv{constructor(){super(...arguments),this.charts={},this.createRuntimeChart=function(e){const t=pr.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(i){const o=t.find((e=>e.match(i.type)));if(!o)throw new Error("No runtime builder for this chart.");return o.getChartRuntime(i,e)}}(this.getters)}handle(e){if(dn.has(e.type)||un.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type)for(const e in this.charts)this.charts[e]=void 0;switch(e.type){case"UPDATE_CHART":case"CREATE_CHART":case"DELETE_FIGURE":this.charts[e.id]=void 0;break;case"DELETE_SHEET":for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0)}}getChartRuntime(e){if(!this.charts[e]){const t=this.getters.getChart(e);if(!t)throw new Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:Rs(e)};if(!t)return{background:w,fontColor:Rs(w)};const i=t.zone.left,o=t.zone.top,n=t.sheetId,s=this.getters.getCellComputedStyle({sheetId:n,col:i,row:o}),r=s.fillColor||w;return{background:r,fontColor:s.textColor||Rs(r)}}}ob.getters=["getChartRuntime","getStyleOfSingleCellChart"];class nb extends Jv{constructor(){super(...arguments),this.isStale=!0,this.computedStyles={},this.computedIcons={},this.uuidGenerator=new zi,this.rulePredicate={CellIsRule:(e,t)=>{if(e.type===cn.error)return!1;const i=t.values.map(En);switch(t.operator){case"IsEmpty":return""===e.value.toString().trim();case"IsNotEmpty":return""!==e.value.toString().trim();case"BeginsWith":return""!==i[0]&&e.value.toString().startsWith(i[0].toString());case"EndsWith":return""!==i[0]&&e.value.toString().endsWith(i[0].toString());case"Between":return e.value>=i[0]&&e.value<=i[1];case"NotBetween":return!(e.value>=i[0]&&e.value<=i[1]);case"ContainsText":return e.value.toString().indexOf(i[0].toString())>-1;case"NotContains":return!e.value||-1==e.value.toString().indexOf(i[0].toString());case"GreaterThan":return e.value>i[0];case"GreaterThanOrEqual":return e.value>=i[0];case"LessThan":return e.value<i[0];case"LessThanOrEqual":return e.value<=i[0];case"NotEqual":return""!==i[0]&&e.value!==i[0];case"Equal":return""===i[0]||e.value===i[0];default:console.warn(s("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}}}handle(e){switch((un.has(e.type)||"UPDATE_CELL"===e.type&&"content"in e)&&(this.isStale=!0),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 i=this.getters.getActiveSheetId(),o=this.getters.getRulesByCell(i,e.originCol,e.originRow);for(const t of o)this.adaptRules(i,t,[Zt(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.origin,e.target,e.operation)}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getCellComputedStyle(e){var t;const{sheetId:i,col:o,row:n}=e,s=this.getters.getCell(e),r=this.computedStyles[i],a=r&&(null===(t=r[o])||void 0===t?void 0:t[n]),l={...null==s?void 0:s.style,...a};return this.getters.getEvaluatedCell(e).link&&!l.textColor&&(l.textColor=I),this.getters.isFilterHeader(e)&&(l.bold=!0),l}getConditionalIcon({col:e,row:t}){var i;const o=this.getters.getActiveSheetId(),n=this.computedIcons[o];return n&&(null===(i=n[e])||void 0===i?void 0:i[t])}computeStyles(){var e;const t=this.getters.getActiveSheetId();this.computedStyles[t]={},this.computedIcons[t]={};const i=this.computedStyles[t];for(let o of this.getters.getConditionalFormats(t).reverse())switch(o.rule.type){case"ColorScaleRule":for(let e of o.ranges)this.applyColorScale(e,o.rule);break;case"IconSetRule":for(let e of o.ranges)this.applyIcon(e,o.rule);break;default:for(let n of o.ranges){const s=this.getters.getRangeFromSheetXC(t,n).zone;for(let n=s.top;n<=s.bottom;n++)for(let r=s.left;r<=s.right;r++){const s=this.rulePredicate[o.rule.type];let a=this.getters.getEvaluatedCell({sheetId:t,col:r,row:n});s&&s(a,o.rule)&&(i[r]||(i[r]=[]),i[r][n]=Object.assign((null===(e=i[r])||void 0===e?void 0:e[n])||{},o.rule.style))}}}}parsePoint(e,t,i){const o=this.getters.getActiveSheetId(),n=this.getters.getEvaluatedCellsInZone(o,this.getters.getRangeFromSheetXC(o,e).zone).filter((e=>e.type===cn.number)).map((e=>e.value));switch(t.type){case"value":return"max"===i?Math.max(...n):Math.min(...n);case"number":return Number(t.value);case"percentage":const e=Math.min(...n);return e+(Math.max(...n)-e)*Number(t.value)/100;case"percentile":return ai(n,Number(t.value)/100,!0);case"formula":const o=t.value&&this.getters.evaluateFormula(t.value);return"number"==typeof o?o:null;default:return null}}applyIcon(e,t){const i=this.parsePoint(e,t.lowerInflectionPoint),o=this.parsePoint(e,t.upperInflectionPoint);if(null===i||null===o||i>o)return;const n=this.getters.getActiveSheetId(),s=this.getters.getRangeFromSheetXC(n,e).zone,r=this.computedIcons[n],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=s.top;e<=s.bottom;e++)for(let l=s.left;l<=s.right;l++){const s=this.getters.getEvaluatedCell({sheetId:n,col:l,row:e});if(s.type!==cn.number)continue;const c=this.computeIcon(s.value,o,t.upperInflectionPoint.operator,i,t.lowerInflectionPoint.operator,a);r[l]||(r[l]=[]),r[l][e]=c}}computeIcon(e,t,i,o,n,s){return"ge"===i&&e>=t||"gt"===i&&e>t?s[0]:"ge"===n&&e>=o||"gt"===n&&e>o?s[1]:s[2]}applyColorScale(e,t){var i;const o=this.parsePoint(e,t.minimum,"min"),n=t.midpoint?this.parsePoint(e,t.midpoint):null,s=this.parsePoint(e,t.maximum,"max");if(null===o||null===s||o>=s||n&&(o>=n||n>=s))return;const r=this.getters.getActiveSheetId(),a=this.getters.getRangeFromSheetXC(r,e).zone,l=this.computedStyles[r],c=[];t.midpoint&&n?(c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,n,t.minimum.color,t.midpoint.color)}),c.push({minValue:n,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(n,s,t.midpoint.color,t.maximum.color)})):c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,s,t.minimum.color,t.maximum.color)});for(let e=a.top;e<=a.bottom;e++)for(let t=a.left;t<=a.right;t++){const a=this.getters.getEvaluatedCell({sheetId:r,col:t,row:e});if(a.type===cn.number){const r=Le(a.value,o,s);let h;h=2===c.length&&n?r<=n?this.colorCell(r,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(r,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(r,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),l[t]||(l[t]=[]),l[t][e]=(null===(i=l[t])||void 0===i?void 0:i[e])||{},l[t][e].fillColor=Et(h)}}}computeColorDiffUnits(e,t,i,o){const n=t-e;return[((i>>16)%256-(o>>16)%256)/n,((i>>8)%256-(o>>8)%256)/n,(i%256-o%256)/n]}colorCell(e,t,i,o){const[n,s,r]=o;return Math.round((i>>16)%256-n*(e-t))<<16|Math.round((i>>8)%256-s*(e-t))<<8|Math.round(i%256-r*(e-t))}adaptRules(e,t,i,o){if(0===i.length&&0===o.length)return;const n=this.getters.getConditionalFormats(e),s=n.findIndex((e=>e.id===t.id));let r=[];s>-1&&(r=n[s].ranges),r=r.concat(i);const a=to(r,o);0!==a.length?this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:t.id,rule:t.rule,stopIfTrue:t.stopIfTrue},ranges:a.map((t=>this.getters.getRangeDataFromXc(e,t))),sheetId:e}):this.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:t.id,sheetId:e})}pasteCf(e,t,i){const o=Zt(t.col,t.row);for(let n of this.getters.getConditionalFormats(e.sheetId))for(let s of n.ranges)if(Ji(e.col,e.row,this.getters.getRangeFromSheetXC(e.sheetId,s).zone)){const s=n,r=[];if("CUT"===i&&r.push(Zt(e.col,e.row)),e.sheetId===t.sheetId)this.adaptRules(e.sheetId,s,[o],r);else{this.adaptRules(e.sheetId,s,[],r);const i=this.getCFToCopyTo(t.sheetId,s);this.adaptRules(t.sheetId,i,[o],[])}}}getCFToCopyTo(e,t){const i=this.getters.getConditionalFormats(e).find((e=>e.stopIfTrue===t.stopIfTrue&&ht(e.rule,t.rule)));return i||{...t,id:this.uuidGenerator.uuidv4(),ranges:[]}}}nb.getters=["getConditionalIcon","getCellComputedStyle"];class sb extends Jv{constructor(){super(...arguments),this.filterValues={},this.hiddenRows=new Set,this.isEvaluationDirty=!1}allowDispatch(e){if("UPDATE_FILTER"===e.type)if(!this.getters.getFilterId(e))return 80;return 0}handle(e){switch(e.type){case"UNDO":case"REDO":case"UPDATE_CELL":case"EVALUATE_CELLS":case"ACTIVATE_SHEET":case"REMOVE_FILTER_TABLE":case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":this.isEvaluationDirty=!0;break;case"START":for(const e of this.getters.getSheetIds()){this.filterValues[e]={};for(const t of this.getters.getFilters(e))this.filterValues[e][t.id]=[]}break;case"CREATE_SHEET":this.filterValues[e.sheetId]={};break;case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":this.updateHiddenRows();break;case"UPDATE_FILTER":this.updateFilter(e),this.updateHiddenRows();break;case"DUPLICATE_SHEET":const t={};for(const i of this.getters.getFilters(e.sheetIdTo)){const o=i.zoneWithHeaders;t[i.id]=this.getFilterValues({sheetId:e.sheetId,col:o.left,row:o.top})}this.filterValues[e.sheetIdTo]=t}}finalize(){this.isEvaluationDirty&&(this.updateHiddenRows(),this.isEvaluationDirty=!1)}isRowFiltered(e,t){return e===this.getters.getActiveSheetId()&&this.hiddenRows.has(t)}getCellBorderWithFilterBorder(e){const{sheetId:t,col:i,row:o}=e;let n;for(let e of this.getters.getFilterTables(t)){const s=e.zone;if(Ji(i,o,s)){const e=this.intersectZoneWithViewport(t,s);n={top:o===e.top?Y:void 0,bottom:o===e.bottom?Y:void 0,left:i===e.left?Y:void 0,right:i===e.right?Y:void 0}}}const s=this.getters.getCellBorder(e),r={...n,...ut(s||{})};return nt(r)?null:r}getFilterHeaders(e){const t=[];for(let i of this.getters.getFilterTables(e)){const o=i.zone;if(!o)continue;const n=o.top;for(let i=o.left;i<=o.right;i++)this.getters.isColHidden(e,i)||this.getters.isRowHidden(e,n)||t.push({col:i,row:n})}return t}getFilterValues(e){const t=this.getters.getFilterId(e),i=e.sheetId;return t&&this.filterValues[i]&&this.filterValues[i][t]||[]}isFilterHeader({sheetId:e,col:t,row:i}){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===i))}isFilterActive(e){var t,i;const o=this.getters.getFilterId(e),n=e.sheetId;return Boolean(o&&(null===(i=null===(t=this.filterValues[n])||void 0===t?void 0:t[o])||void 0===i?void 0:i.length))}intersectZoneWithViewport(e,t){return{left:this.getters.findVisibleHeader(e,"COL",t.left,t.right),right:this.getters.findVisibleHeader(e,"COL",t.right,t.left),top:this.getters.findVisibleHeader(e,"ROW",t.top,t.bottom),bottom:this.getters.findVisibleHeader(e,"ROW",t.bottom,t.top)}}updateFilter({col:e,row:t,values:i,sheetId:o}){const n=this.getters.getFilterId({sheetId:o,col:e,row:t});n&&(this.filterValues[o]||(this.filterValues[o]={}),this.filterValues[o][n]=i)}updateHiddenRows(){var e,t;const i=this.getters.getActiveSheetId(),o=this.getters.getFilters(i).sort(((e,t)=>e.zoneWithHeaders.top-t.zoneWithHeaders.top)),n=new Set;for(let s of o){if(this.getters.isRowHiddenByUser(i,s.zoneWithHeaders.top))continue;if(n.has(s.zoneWithHeaders.top))continue;const o=null===(t=null===(e=this.filterValues[i])||void 0===e?void 0:e[s.id])||void 0===t?void 0:t.map(gt);if(o&&s.filteredZone)for(let e=s.filteredZone.top;e<=s.filteredZone.bottom;e++){const t=this.getCellValueAsString(i,s.col,e);o.includes(t)&&n.add(e)}}this.hiddenRows=n}getCellValueAsString(e,t,i){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:i}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets){const e=t.id;for(const i of t.filterTables){const o=Hi(i.range),n=[],s=[];for(const i of $e(0,oo(o).numberOfCols)){const r={sheetId:t.id,col:o.left+i,row:o.top},a=this.getFilterValues(r),l=this.getters.getFilter(r);if(!l)continue;const c=l.filteredZone?so(l.filteredZone).map((t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue)):[];if(a.length){const e=c.filter((e=>e)).filter((e=>!a.includes(e)));n.push({colId:i,displayedValues:[...new Set(e)],displayBlanks:!a.includes("")&&c.some((e=>!e))})}const h={col:l.col,row:l.zoneWithHeaders.top,sheetId:e},d=this.getters.getEvaluatedCell(h).formattedValue,u=this.getUniqueColNameForExcel(i,d,s);s.push(u),t.cells[Zt(h.col,h.row)]={...t.cells[Zt(h.col,h.row)],content:u,value:u,isFormula:!1}}i.filters=n}}}getUniqueColNameForExcel(e,t,i){t||(t=`Column${e}`);let o=t,n=2;for(;i.includes(o);)o=t+String(n),n++;return o}}sb.getters=["getCellBorderWithFilterBorder","getFilterHeaders","getFilterValues","isFilterHeader","isRowFiltered","isFilterActive"];class rb{constructor(e,t,i,o,n,s){this.getters=e,this.sheetId=t,this.boundaries=i,this.viewportWidth=o.width,this.viewportHeight=o.height,this.offsetScrollbarX=s.x,this.offsetScrollbarY=s.y,this.canScrollVertically=n.canScrollVertically,this.canScrollHorizontally=n.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:i,size:o}=this.getters.getColDimensions(this.sheetId,e),{end:n,size:s}=this.getters.getRowDimensions(this.sheetId,t),r=this.searchHeaderIndex("COL",i-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,r),l=this.searchHeaderIndex("ROW",n-this.viewportHeight,0),c=this.getters.getRowSize(this.sheetId,l);let h=i-this.offsetCorrectionX;this.canScrollHorizontally&&(h+=Math.max(F,Math.min(a,this.viewportWidth-o)),h=Math.max(h,this.viewportWidth));let d=n-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(D+5,Math.min(c,this.viewportHeight-s)),d=Math.max(d,this.viewportHeight)),{width:h,height:d}}getColIndex(e,t=!1){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX,this.left,t)}getRowIndex(e,t=!1){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY,this.top,t)}adjustPosition(e){const t=this.sheetId;e||(e=this.getters.getSheetPosition(t));const i=this.getters.getMainCellPosition({sheetId:t,...e}),{col:o,row:n}=this.getters.getNextVisibleCellPosition(i);Ji(o,this.boundaries.top,this.boundaries)&&this.adjustPositionX(o),Ji(this.boundaries.left,n,this.boundaries)&&this.adjustPositionY(n)}adjustPositionX(e){const t=this.sheetId,{end:i}=this.getters.getColDimensions(t,e),o=this.getters.getNumberCols(t);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<i){let i=e;for(;this.getters.isColHidden(t,i)&&e<o;)i++;const n=this.getters.getColDimensions(t,i).end,s=this.searchHeaderIndex("COL",n-this.viewportWidth-this.offsetCorrectionX,this.boundaries.left,!0);this.offsetX=this.getters.getColDimensions(t,s).end-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX()}else if(this.left>e){let i=e;for(;this.getters.isColHidden(t,i)&&e>0;)i--;this.offsetX=this.getters.getColDimensions(t,i).start-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX()}}adjustPositionY(e){const t=this.sheetId,{end:i}=this.getters.getRowDimensions(t,e),o=this.getters.getNumberRows(t);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<i){let i=e;for(;this.getters.isRowHidden(t,i)&&e<o;)i++;const n=this.getters.getRowDimensions(t,i).end,s=this.searchHeaderIndex("ROW",n-this.viewportHeight-this.offsetCorrectionY,this.boundaries.top,!0);this.offsetY=this.getters.getRowDimensions(t,s).end-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY()}else if(this.top>e){let i=e;for(;this.getters.isRowHidden(t,i)&&e>0;)i--;this.offsetY=this.getters.getRowDimensions(t,i).start-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY()}}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getRect(e){const t=Xi(e,this.zone);if(t){return{x:this.getters.getColRowOffset("COL",this.zone.left,t.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset("ROW",this.zone.top,t.top)+this.offsetCorrectionY,width:Math.min(this.getters.getColRowOffset("COL",t.left,t.right+1),this.viewportWidth),height:Math.min(this.getters.getColRowOffset("ROW",t.top,t.bottom+1),this.viewportHeight)}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,i=0,o=!1){let n=0;const s=this.sheetId,r=this.getters.getNumberHeaders(s,e);for(let a=i;a<=r-1;a++){const i=o||"COL"!==e?a<this.top&&a>this.bottom:a<this.left&&a>this.right;if(!this.getters.isHeaderHidden(s,e,a)&&!i&&(n+="COL"===e?this.getters.getColSize(s,a):this.getters.getRowSize(s,a),n>t))return a}return-1}get zone(){return{left:this.left,right:this.right,top:this.top,bottom:this.bottom}}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetScrollbarX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetScrollbarY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){const{width:e}=this.getMaxSize();this.viewportWidth+this.offsetScrollbarX>e&&(this.offsetScrollbarX=Math.max(0,e-this.viewportWidth))}this.left=this.getColIndex(this.offsetScrollbarX,!0),this.right=this.getColIndex(this.offsetScrollbarX+this.viewportWidth,!0),-1===this.right&&(this.right=this.boundaries.right),this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){const{height:e}=this.getMaxSize();this.viewportHeight+this.offsetScrollbarY>e&&(this.offsetScrollbarY=Math.max(0,e-this.viewportHeight))}this.top=this.getRowIndex(this.offsetScrollbarY,!0),this.bottom=this.getRowIndex(this.offsetScrollbarY+this.viewportWidth,!0),-1===this.bottom&&(this.bottom=this.boundaries.bottom),this.adjustViewportZoneY()}adjustViewportZoneX(){const e=this.sheetId;this.left=this.searchHeaderIndex("COL",this.offsetScrollbarX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex("COL",this.viewportWidth,this.left)),-1===this.left&&(this.left=this.boundaries.left),-1===this.right&&(this.right=this.getters.getNumberCols(e)-1),this.offsetX=this.getters.getColDimensions(e,this.left).start-this.getters.getColDimensions(e,this.boundaries.left).start}adjustViewportZoneY(){const e=this.sheetId;this.top=this.searchHeaderIndex("ROW",this.offsetScrollbarY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex("ROW",this.viewportHeight,this.top)),-1===this.top&&(this.top=this.boundaries.top),-1===this.bottom&&(this.bottom=this.getters.getNumberRows(e)-1),this.offsetY=this.getters.getRowDimensions(e,this.top).start-this.getters.getRowDimensions(e,this.boundaries.top).start}}class ab extends Jv{constructor(){super(...arguments),this.viewports={},this.sheetViewWidth=1e3,this.sheetViewHeight=1e3,this.gridOffsetX=0,this.gridOffsetY=0,this.sheetsWithDirtyViewports=new Set}allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.checkScrollingDirection(e);case"RESIZE_SHEETVIEW":return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return 0}}handleEvent(e){switch(e.type){case"HeadersSelected":case"AlterZone":break;case"ZonesSelected":let{col:t,row:i}=ao(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const o=e.previousAnchor.zone,n=e.anchor.zone,{top:s,bottom:r,left:a,right:l}=this.getters.getActiveMainViewport();o.left===n.left&&o.right===n.right&&(t=a>t||t>l?a:t),o.top===n.top&&o.bottom===n.bottom&&(i=s>i||i>r?s:i)}const o=this.getters.getActiveSheetId();t=Math.min(t,this.getters.getNumberCols(o)-1),i=Math.min(i,this.getters.getNumberRows(o)-1),this.refreshViewport(this.getters.getActiveSheetId(),{col:t,row:i})}}handle(e){var t;switch(this.cleanViewports(),e.type){case"START":this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case"UNDO":case"REDO":this.resetSheetViews();break;case"RESIZE_SHEETVIEW":this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case"SET_VIEWPORT_OFFSET":this.setSheetViewOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const{top:i}=this.getActiveMainViewport(),o=this.getters.getActiveSheetId(),n=this.clipOffsetY(this.getters.getRowDimensions(o,i).start+this.sheetViewHeight);this.shiftVertically(n);break;case"SHIFT_VIEWPORT_UP":{const{top:e}=this.getActiveMainViewport(),t=this.getters.getActiveSheetId(),i=this.clipOffsetY(this.getters.getRowDimensions(t,e).end-this.sheetViewHeight);this.shiftVertically(i);break}case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UPDATE_FILTER":this.resetViewports(e.sheetId);break;case"UPDATE_CELL":("content"in e||"format"in e||void 0!==(null===(t=e.style)||void 0===t?void 0:t.fontSize))&&this.sheetsWithDirtyViewports.add(e.sheetId);break;case"ACTIVATE_SHEET":this.setViewports(),this.refreshViewport(e.sheetIdTo);break;case"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":this.resetViewports(this.getters.getActiveSheetId());break;case"DELETE_SHEET":this.sheetsWithDirtyViewports.delete(e.sheetId);break;case"START_EDITION":const{col:s,row:r}=this.getters.getActivePosition();this.refreshViewport(this.getters.getActiveSheetId(),{col:s,row:r})}}finalize(){for(const e of this.sheetsWithDirtyViewports)this.resetViewports(e);this.sheetsWithDirtyViewports=new Set,this.setViewports()}setViewports(){var e;const t=this.getters.getSheetIds();for(const i of t)(null===(e=this.viewports[i])||void 0===e?void 0:e.bottomRight)||this.resetViewports(i)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getColIndex(e))))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getRowIndex(e))))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getActiveMainViewport(){const e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getActiveSheetDOMScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetScrollbarX,scrollY:t.offsetScrollbarY}}getSheetViewVisibleCols(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>$e(e.left,e.right+1))).flat())].filter((t=>!this.getters.isHeaderHidden(e,"COL",t)))}getSheetViewVisibleRows(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>$e(e.top,e.bottom+1))).flat())].filter((t=>!this.getters.isHeaderHidden(e,"ROW",t)))}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:i,ySplit:o}=this.getters.getPaneDivisions(e);let{width:n,height:s}=t.getMaxSize();return{x:this.getters.getColDimensions(e,i).start,y:this.getters.getRowDimensions(e,o).start,width:n,height:s}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:i}=this.getMainViewportRect(),o=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-o.viewportWidth+1),maxOffsetY:Math.max(0,i-o.viewportHeight+1)}}getColRowOffsetInViewport(e,t,i){const o=this.getters.getActiveSheetId(),n=this.getters.getSheetViewVisibleCols(),s=this.getters.getSheetViewVisibleRows();if(i<t)return-this.getColRowOffsetInViewport(e,i,t);let r=0;const a="COL"===e?n:s;for(let n=t;n<i;n++)a.includes(n)&&(r+="COL"===e?this.getters.getColSize(o,n):this.getters.getRowSize(o,n));return r}isVisibleInViewport({sheetId:e,col:t,row:i}){return this.getSubViewports(e).some((e=>e.isVisible(t,i)))}getEdgeScrollCol(e,t,i){let o=!1,n=0,s=0;const{xSplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(o=!0,s=Kt(e-a),n=1):e<l&&i>=l&&c>0?(o=!0,s=Kt(l-e),n=-1):r&&t<l&&e>l&&(o=!0,s=Kt(e),n="reset"),{canEdgeScroll:o,direction:n,delay:s}}getEdgeScrollRow(e,t,i){let o=!1,n=0,s=0;const{ySplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(o=!0,s=Kt(e-a),n=1):e<l&&i>=l&&c>0?(o=!0,s=Kt(l-e),n=-1):r&&t<l&&e>l&&(o=!0,s=Kt(e),n="reset"),{canEdgeScroll:o,direction:n,delay:s}}getVisibleRect(e){const t=this.getters.getActiveSheetId(),i=this.getSubViewports(t).map((t=>t.getRect(e))).filter(ot);if(0===i.length)return{x:0,y:0,width:0,height:0};const o=Math.min(...i.map((e=>e.x))),n=Math.min(...i.map((e=>e.y))),s=Math.max(...i.map((e=>e.x+e.width)))-o,r=Math.max(...i.map((e=>e.y+e.height)))-n;return{x:o+this.gridOffsetX,y:n+this.gridOffsetY,width:s,height:r}}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,i).start}}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(ot)}checkPositiveDimension(e){return e.width<0||e.height<0?69:0}checkValuesAreDifferent(e){const{height:t,width:i}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===i&&e.height===t?77:0}checkScrollingDirection({offsetX:e,offsetY:t}){const i=this.getMainInternalViewport(this.getters.getActiveSheetId());return!i.canScrollHorizontally&&e>0||!i.canScrollVertically&&t>0?70:0}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e=this.getters.getSheetIds();for(let t of Object.keys(this.viewports))e.includes(t)||delete this.viewports[t]}resetSheetViews(){for(let e of Object.keys(this.viewports)){const t=this.getters.getSheetPosition(e);this.resetViewports(e);const i=this.getSubViewports(e);Object.values(i).forEach((e=>{e.adjustPosition(t)}))}}resizeSheetView(e,t,i=0,o=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=i,this.gridOffsetY=o,this.recomputeViewports()}recomputeViewports(){for(let e of Object.keys(this.viewports))this.resetViewports(e)}setSheetViewOffset(e,t){const i=this.getters.getActiveSheetId(),{maxOffsetX:o,maxOffsetY:n}=this.getMaximumSheetOffset();Object.values(this.getSubViewports(i)).forEach((i=>i.setViewportOffset(Le(e,0,o),Le(t,0,n))))}clipOffsetY(e){const{height:t}=this.getMainViewportRect(),i=t-this.sheetViewHeight;return e=Math.min(e,i),e=Math.max(e,0)}getViewportOffset(e){var t,i;return{x:(null===(t=this.viewports[e])||void 0===t?void 0:t.bottomRight.offsetScrollbarX)||0,y:(null===(i=this.viewports[e])||void 0===i?void 0:i.bottomRight.offsetScrollbarY)||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e),o=this.getters.getNumberCols(e),n=this.getters.getNumberRows(e),s=this.getters.getColRowOffset("COL",0,t,e),r=this.getters.getColRowOffset("ROW",0,i,e),{xRatio:a,yRatio:l}=this.getFrozenSheetViewRatio(e),c=a<1,h=l<1,d=this.getViewportOffset(e),u={topLeft:i&&t&&new rb(this.getters,e,{left:0,right:t-1,top:0,bottom:i-1},{width:s,height:r},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:i&&new rb(this.getters,e,{left:t,right:o-1,top:0,bottom:i-1},{width:this.sheetViewWidth-s,height:r},{canScrollHorizontally:c,canScrollVertically:!1},{x:c?d.x:0,y:0})||void 0,bottomLeft:t&&new rb(this.getters,e,{left:0,right:t-1,top:i,bottom:n-1},{width:s,height:this.sheetViewHeight-r},{canScrollHorizontally:!1,canScrollVertically:h},{x:0,y:h?d.y:0})||void 0,bottomRight:new rb(this.getters,e,{left:t,right:o-1,top:i,bottom:n-1},{width:this.sheetViewWidth-s,height:this.sheetViewHeight-r},{canScrollHorizontally:c,canScrollVertically:h},{x:c?d.x:0,y:h?d.y:0})};this.viewports[e]=u}refreshViewport(e,t){Object.values(this.getSubViewports(e)).forEach((e=>{e.adjustViewportZone(),e.adjustPosition(t)}))}shiftVertically(e){const{top:t}=this.getActiveMainViewport(),{scrollX:i}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(i,e);const{anchor:o}=this.getters.getSelection(),n=this.getActiveMainViewport().top-t;this.selection.selectCell(o.cell.col,o.cell.row+n)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],i=this.getters.getFigures(e),{scrollX:o,scrollY:n}=this.getActiveSheetScrollInfo(),{x:s,y:r}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of i)e.x>=s&&(e.x+e.width<=s+o||e.x>=a+o+s)||e.y>=r&&(e.y+e.height<=r+n||e.y>=l+n+r)||t.push(e);return t}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e),o=this.getters.getColDimensions(e,t).start,n=this.getters.getRowDimensions(e,i).start;return{xRatio:o/(this.sheetViewWidth+this.gridOffsetX),yRatio:n/(this.sheetViewHeight+this.gridOffsetY)}}}ab.getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getActiveSheetDOMScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio"];class lb{constructor(e,t,i){this.index=0,this.cells=e,this.getters=t,this.direction=i}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:i,tooltip:o}=An.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:i,tooltip:o,origin:{col:e.data.col,row:e.data.row}}}}class cb extends Jv{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:Le(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:Le(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:46;case"AUTOFILL_AUTO":const i=this.getters.getSelectedZone();return i.top===i.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||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),i=this.autofillZone;switch(this.direction){case"down":for(let o=t.left;o<=t.right;o++){const n=[];for(let e=t.top;e<=t.bottom;e++)n.push(Zt(o,e));const s=this.createGenerator(n);for(let t=i.top;t<=i.bottom;t++)this.computeNewCell(s,o,t,e)}break;case"up":for(let o=t.left;o<=t.right;o++){const n=[];for(let e=t.bottom;e>=t.top;e--)n.push(Zt(o,e));const s=this.createGenerator(n);for(let t=i.bottom;t>=i.top;t--)this.computeNewCell(s,o,t,e)}break;case"left":for(let o=t.top;o<=t.bottom;o++){const n=[];for(let e=t.right;e>=t.left;e--)n.push(Zt(e,o));const s=this.createGenerator(n);for(let t=i.right;t>=i.left;t--)this.computeNewCell(s,t,o,e)}break;case"right":for(let o=t.top;o<=t.bottom;o++){const n=[];for(let e=t.left;e<=t.right;e++)n.push(Zt(e,o));const s=this.createGenerator(n);for(let t=i.left;t<=i.right;t++)this.computeNewCell(s,t,o,e)}}e&&(this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0)}select(e,t){const i=this.getters.getSelectedZone();if(Ji(e,t,i))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,i.top-1,i.left,i.right),this.steps=i.top-t;break;case"down":this.saveZone(i.bottom+1,t,i.left,i.right),this.steps=t-i.bottom;break;case"left":this.saveZone(i.top,i.bottom,e,i.left-1),this.steps=i.left-e;break;case"right":this.saveZone(i.top,i.bottom,i.right+1,e),this.steps=e-i.right}this.autofill(!1)}}autofillAuto(){var e,t;const i=this.getters.getSelectedZone(),o=this.getters.getActiveSheetId();let n=i.left,s=i.bottom;if(n>0){let t={sheetId:o,col:n-1,row:s};for(;this.getters.getEvaluatedCell(t).type!==cn.empty||(null===(e=this.getters.getCell(t))||void 0===e?void 0:e.content);)s+=1,t={sheetId:o,col:n-1,row:s}}if(s===i.bottom&&(n=i.right,n<=this.getters.getNumberCols(o))){let e={sheetId:o,col:n+1,row:s};for(;this.getters.getEvaluatedCell(e).type!==cn.empty||(null===(t=this.getters.getCell(e))||void 0===t?void 0:t.content);)s+=1,e={sheetId:o,col:n+1,row:s}}s!==i.bottom&&(this.select(i.left,s-1),this.autofill(!0))}computeNewCell(e,t,i,o){const{cellData:n,tooltip:s,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=n;this.tooltip=s,o&&this.dispatch("AUTOFILL_CELL",{originCol:r.col,originRow:r.row,col:t,row:i,content:a,style:l,border:c,format:h})}getRule(e,t){const i=Mn.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((i=>i.condition(e,t)));return i&&i.generateRule(e,t)}createGenerator(e){const t=[],i=[],o=this.getters.getActiveSheetId();for(let t of e){const{col:e,row:n}=qt(t),s=this.getters.getCell({sheetId:o,col:e,row:n});i.push({col:e,row:n,cell:s,sheetId:o})}const n=i.map((e=>e.cell));for(let e of i){let i={type:"COPY_MODIFIER"};if(e&&e.cell){i=this.getRule(e.cell,n)||i}const o=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:o},rule:i})}return new lb(t,this.getters,this.direction)}saveZone(e,t,i,o){this.autofillZone={top:e,bottom:t,left:i,right:o}}getDirection(e,t){const i=this.getters.getSelectedZone(),o={up:{number:i.top-t,value:"up"},down:{number:t-i.bottom,value:"down"},left:{number:i.left-e,value:"left"},right:{number:e-i.right,value:"right"}};if(1===Object.values(o).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(o).find((e=>e.number>0?1:0)).value;const n=o.up.number>0?"up":"down",s=o.left.number>0?"left":"right";return Math.abs(o[n].number)>=Math.abs(o[s].number)?o[n].value:o[s].value}autoFillMerge(e,t,i,o){const n=this.getters.getActiveSheetId(),s={sheetId:n,col:i,row:o},r={sheetId:n,col:e,row:t};if(this.getters.isInMerge(s)&&!this.getters.isInMerge(r)){const e=this.getters.getMerge(s);e&&this.dispatch("REMOVE_MERGE",{sheetId:n,target:[e]})}const a=this.getters.getMerge(r);(null==a?void 0:a.topLeft.col)===e&&(null==a?void 0:a.topLeft.row)===t&&this.dispatch("ADD_MERGE",{sheetId:n,target:[{top:o,bottom:o+a.bottom-a.top,left:i,right:i+a.right-a.left}]})}drawGrid(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:i}=e,{x:o,y:n,width:s,height:r}=this.getters.getVisibleRect(this.autofillZone);s>0&&r>0&&(t.strokeStyle="black",t.lineWidth=i,t.setLineDash([3]),t.strokeRect(o,n,s,r),t.setLineDash([]))}}cb.layers=[5],cb.getters=["getAutofillTooltip"];class hb extends Jv{handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:i}=this.getters.getSelection();for(const o of t){const t=this.getAutomaticSums(e,o,i.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,i){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,i):this.sumData(e,t)}sumData(e,t){const i=this.dimensionsToSum(e,t),o=this.sumDimensions(e,t,i).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return i.has("ROW")&&i.has("COL")&&o.push(this.sumTotal(t)),o}sumAdjacentData(e,t,i){const{col:o,row:n}=Ji(i.col,i.row,t)?i:{col:t.left,row:t.top},s=this.findAdjacentData(e,o,n);return s?this.getters.isSingleCellOrMerge(e,t)||no(Yi(s,t))?[{position:{col:o,row:n},zone:s}]:this.sumDimensions(e,Yi(s,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,i){const o=this.getters.getSheet(e),n=this.getters.getMainCellPosition({sheetId:e,col:t,row:i}),s=this.findSuitableZoneToSum(o,n.col,n.row);if(s)return this.getters.expandZone(e,s)}findSuitableZoneToSum(e,t,i){const o=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:i-1}),n=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:i});if(this.isNumber(n)&&!this.isNumber(o))return this.findHorizontalZone(e,t,i);const s=this.findVerticalZone(e,t,i);if(this.isZoneValid(s))return s;const r=this.findHorizontalZone(e,t,i);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,i){const o={top:0,bottom:i-1,left:t,right:t},n=this.reduceZoneStart(e,o,o.bottom);return{...o,top:n}}findHorizontalZone(e,t,i){const o={top:i,bottom:i,left:0,right:t-1},n=this.reduceZoneStart(e,o,o.right);return{...o,left:n}}reduceZoneStart(e,t,i){const o=this.getters.getEvaluatedCellsInZone(e.id,t),n=$e(i,-1,-1),s=n.filter((e=>o[e]&&!o[e].isAutoSummable)),r=Math.max(...s),a=We(n.filter((e=>this.isNumber(o[e]))))[0]||[];return Math.max(...a)<r?1/0:Math.min(...a)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){var t;return e.type===cn.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(X))}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 i=new Set;return no(t)?(i.add(1===oo(t).numberOfCols?"COL":"ROW"),i):(this.lastColIsEmpty(e,t)&&i.add("ROW"),this.lastRowIsEmpty(e,t)&&i.add("COL"),0===i.size&&i.add("COL"),i)}sumDimensions(e,t,i){return[...i.has("COL")?this.sumColumns(t,e):[],...i.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:i}=e;return{position:{col:i,row:t},zone:{...e,top:t,right:i-1}}}sumColumns(e,t){const i=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,i.bottom-1)},so(i).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const i=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,i.right-1)},so(i).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const i of t){const{col:t,row:o}=i.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:`=SUM(${this.getters.zoneToXC(e,i.zone)})`})}}nextEmptyRow(e,t){let i=t.bottom+1;const{left:o,right:n}=t;for(;!this.getters.isEmpty(e,{bottom:i,top:i,left:o,right:n});)i++;return{...t,top:i,bottom:i}}nextEmptyCol(e,t){let i=t.right+1;const{top:o,bottom:n}=t;for(;!this.getters.isEmpty(e,{left:i,right:i,top:o,bottom:n});)i++;return{...t,left:i,right:i}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}hb.getters=["getAutomaticSums"];class db extends Jv{allowDispatch(e){if("OPEN_CELL_POPOVER"===e.type){try{us.get(e.popoverType)}catch(e){return 73}return 0}return 0}handle(e){switch(e.type){case"ACTIVATE_SHEET":case"CLOSE_CELL_POPOVER":this.persistentPopover=void 0;break;case"OPEN_CELL_POPOVER":this.persistentPopover={col:e.col,row:e.row,sheetId:this.getters.getActiveSheetId(),type:e.popoverType}}}getCellPopover({col:e,row:t}){var i,o;const n=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=null===(o=(i=us.get(this.persistentPopover.type)).onOpen)||void 0===o?void 0:o.call(i,e,this.getters);return(null==t?void 0:t.isOpen)?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}if(void 0===e||void 0===t||!this.getters.isVisibleInViewport({sheetId:n,col:e,row:t}))return{isOpen:!1};const s=this.getters.getMainCellPosition({sheetId:n,col:e,row:t}),r=us.getAll().map((e=>{var t;return null===(t=e.onHover)||void 0===t?void 0:t.call(e,s,this.getters)})).find((e=>null==e?void 0:e.isOpen));return(null==r?void 0:r.isOpen)?{...r,anchorRect:this.computePopoverAnchorRect(s)}:{isOpen:!1}}hasOpenedPopover(){return void 0!==this.persistentPopover}getPersistentPopoverTypeAtPosition({col:e,row:t}){if(this.persistentPopover&&this.persistentPopover.col===e&&this.persistentPopover.row===t)return this.persistentPopover.type}computePopoverAnchorRect({col:e,row:t}){const i=this.getters.getActiveSheetId(),o=this.getters.getMerge({sheetId:i,col:e,row:t});return o?this.getters.getVisibleRect(o):this.getters.getVisibleRect(co({col:e,row:t}))}}db.getters=["getCellPopover","getPersistentPopoverTypeAtPosition","hasOpenedPopover"];var ub;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(ub||(ub={}));class gb extends Jv{constructor(){super(...arguments),this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1},this.toSearch="",this.isSearchDirty=!1}handle(e){switch(e.type){case"UPDATE_SEARCH":this.updateSearch(e.toSearch,e.searchOptions);break;case"CLEAR_SEARCH":this.clearSearch();break;case"SELECT_SEARCH_PREVIOUS_MATCH":this.selectNextCell(ub.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(ub.next);break;case"REPLACE_SEARCH":this.replace(e.replaceWith);break;case"REPLACE_ALL_SEARCH":this.replaceAll(e.replaceWith);break;case"UNDO":case"REDO":case"REMOVE_FILTER_TABLE":case"UPDATE_FILTER":case"REMOVE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"EVALUATE_CELLS":case"UPDATE_CELL":this.isSearchDirty=!0;break;case"ACTIVATE_SHEET":this.refreshSearch()}}finalize(){this.isSearchDirty&&(this.refreshSearch(),this.isSearchDirty=!1)}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(ub.current)}updateRegex(){let e=_e(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),i=[];if(this.toSearch)for(const o of Object.values(t)){const{col:t,row:n}=this.getters.getCellPosition(o.id),s=this.getters.isColHidden(e,t),r=this.getters.isRowHidden(e,n);if(!s&&!r&&(o&&this.currentSearchRegex&&this.currentSearchRegex.test(this.getSearchableString({sheetId:e,col:t,row:n})))){const e={col:t,row:n,selected:!1};i.push(e)}}return i.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 i;i=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,i=(i%t.length+t.length)%t.length,this.selectedMatchIndex=i,this.selection.selectCell(t[i].col,t[i].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}}replaceMatch(e,t){if(!this.currentSearchRegex)return;const i=this.getters.getActiveSheetId(),o=this.getters.getCell({sheetId:i,...e}),{col:n,row:s}=e;if((null==o?void 0:o.isFormula)&&!this.searchOptions.searchFormulas)return;const r=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),a=this.getSearchableString({sheetId:i,col:n,row:s}).replace(r,t);this.dispatch("UPDATE_CELL",{sheetId:i,col:n,row:s,content:a})}replace(e){if(null===this.selectedMatchIndex)return;const t=this.searchMatches[this.selectedMatchIndex];this.replaceMatch(t,e),this.selectNextCell(ub.next)}replaceAll(e){const t=this.searchMatches.length;for(let i=0;i<t;i++)this.replaceMatch(this.searchMatches[i],e)}getSearchableString(e){const t=this.getters.getCell(e);return this.searchOptions.searchFormulas&&(null==t?void 0:t.isFormula)?t.content:this.getters.getEvaluatedCell(e).formattedValue}drawGrid(e){const{ctx:t}=e,i=this.getters.getActiveSheetId();for(const e of this.searchMatches){const o=this.getters.getMerge({sheetId:i,col:e.col,row:e.row}),n=o?o.left:e.col,s=o?o.right:e.col,r=o?o.top:e.row,a=o?o.bottom:e.row,{x:l,y:c,width:h,height:d}=this.getters.getVisibleRect({top:r,left:n,right:s,bottom:a});h>0&&d>0&&(t.fillStyle="#8B008B33",t.fillRect(l,c,h,d),e.selected&&(t.strokeStyle="#8B008B",t.strokeRect(l,c,h,d)))}}}gb.layers=[3],gb.getters=["getSearchMatches","getCurrentSelectedMatchIndex"];class pb extends Jv{isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,i){return"COL"===t?this.isColHidden(e,i):this.isRowHidden(e,i)}getNextVisibleCellPosition({sheetId:e,col:t,row:i}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",i,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,i,o){if(i<=o)for(let n=i;n<=o;n++)if(this.getters.doesHeaderExist(e,t,n)&&!this.isHeaderHidden(e,t,n))return n;if(i>o)for(let n=i;n>=o;n--)if(this.getters.doesHeaderExist(e,t,n)&&!this.isHeaderHidden(e,t,n))return n}findLastVisibleColRowIndex(e,t,{last:i,first:o}){return $e(i,o,-1).find((i=>!this.isHeaderHidden(e,t,i)))||o}findFirstVisibleColRowIndex(e,t){const i=this.getters.getNumberHeaders(e,t);for(let o=0;o<i;o++){if("COL"===t&&!this.isColHidden(e,o))return o;if("ROW"===t&&!this.isRowHidden(e,o))return o}}exportForExcel(e){for(const t of e.sheets)for(const[e,i]of Object.entries(t.rows)){const o=this.isRowHidden(t.id,Number(e));i.isHidden=o}}}pb.getters=["getNextVisibleCellPosition","findVisibleHeader","findLastVisibleColRowIndex","findFirstVisibleColRowIndex","isRowHidden","isColHidden","isHeaderHidden"];class mb extends Jv{getHighlights(){return this.prepareHighlights(this.getters.getComposerHighlights().concat(this.getters.getSelectionInputHighlights()))}prepareHighlights(e){return e.filter((e=>e.zone.top>=0&&e.zone.left>=0&&e.zone.bottom<this.getters.getNumberRows(e.sheetId)&&e.zone.right<this.getters.getNumberCols(e.sheetId))).map((e=>{const{numberOfRows:t,numberOfCols:i}=oo(e.zone),o=t*i==1?this.getters.expandZone(e.sheetId,e.zone):e.zone;return{...e,zone:o}}))}drawGrid(e){const{ctx:t,thinLineWidth:i}=e,o=this.getters.getActiveSheetId(),n=3*i;t.lineWidth=n;const s=this.getHighlights();for(let e of s.filter(((e,t)=>s.findIndex((t=>Ki(t.zone,e.zone)&&t.sheetId===o))===t))){const{x:i,y:o,width:s,height:r}=this.getters.getVisibleRect(e.zone);s>0&&r>0&&(t.strokeStyle=e.color,t.strokeRect(i+n/2,o+n/2,s-n,r-n),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(i+n,o+n,s-2*n,r-2*n))}}}mb.layers=[1],mb.getters=["getHighlights"];class fb extends Jv{constructor(){super(...arguments),this.boxes=[]}getColDimensionsInViewport(e,t){const i=Math.min(...this.getters.getSheetViewVisibleCols()),o=this.getters.getColRowOffsetInViewport("COL",i,t),n=this.getters.getColSize(e,t);return{start:o,size:n,end:o+(this.getters.isColHidden(e,t)?0:n)}}getRowDimensionsInViewport(e,t){const i=Math.min(...this.getters.getSheetViewVisibleRows()),o=this.getters.getColRowOffsetInViewport("ROW",i,t),n=this.getters.getRowSize(e,t);return{start:o,size:n,end:o+(this.getters.isRowHidden(e,t)?0:n)}}getHeaderOffset(e,t,i){let o=this.getters.getColRowOffsetInViewport(e,t,i);return this.getters.isDashboard()||(o+="ROW"===e?N:_),o}drawGrid(e,t){switch(t){case 0:this.boxes=this.getGridBoxes(),this.drawBackground(e),this.drawOverflowingCellBackground(e),this.drawCellBackground(e),this.drawBorders(e),this.drawTexts(e),this.drawIcon(e),this.drawFrozenPanes(e);break;case 7:this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawBackground(e){const{ctx:t,thinLineWidth:i}=e,{width:o,height:n}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,o+m,n+m);const s=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),r=s?.1*i:0;if(s)for(const e of this.boxes)t.strokeStyle="#E2E3E3",t.lineWidth=i,t.strokeRect(e.x+r,e.y+r,e.width-2*r,e.height-2*r)}drawCellBackground(e){const{ctx:t}=e;for(const e of this.boxes){let i=e.style;i.fillColor&&"#ffffff"!==i.fillColor&&(t.fillStyle=i.fillColor||"#ffffff",t.fillRect(e.x,e.y,e.width,e.height)),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())}}drawOverflowingCellBackground(e){var t,i;const{ctx:o,thinLineWidth:n}=e;for(const e of this.boxes)if(e.content&&e.isOverflow){const s=e.content.align||"left";let r,a;const l=e.y+n/2,c=e.height-n,h=Math.min((null===(t=e.clipRect)||void 0===t?void 0:t.width)||1/0,e.content.width);"left"===s?(r=e.x+n/2,a=h-2*n):"right"===s?(r=e.x+e.width-n/2,a=2*n-h):(r=((null===(i=e.clipRect)||void 0===i?void 0:i.x)||e.x+e.width/2-e.content.width/2)+n/2,a=h-2*n),o.fillStyle="#ffffff",o.fillRect(r,l,a,c)}}drawBorders(e){const{ctx:t,thinLineWidth:i}=e;for(let e of this.boxes){const t=e.border;if(t){const{x:i,y:n,width:s,height:r}=e;t.left&&o(t.left,i,n,i,n+r),t.top&&o(t.top,i,n,i+s,n),t.right&&o(t.right,i+s,n,i+s,n+r),t.bottom&&o(t.bottom,i,n+r,i+s,n+r)}}function o([e,o],n,s,r,a){t.strokeStyle=o,t.lineWidth=("thin"===e?2:3)*i,t.beginPath(),t.moveTo(n,s),t.lineTo(r,a),t.stroke()}}drawTexts(e){const{ctx:t,thinLineWidth:i}=e;let o;t.textBaseline="top";for(let e of this.boxes)if(e.content){const n=e.style||{},s=e.content.align||"left",r=Be(n);r!==o&&(o=r,t.font=r),t.fillStyle=n.textColor||"#000";let a=e.x;if(a+="left"===s?V+(e.image?e.image.size+U:0):"right"===s?e.width-V-(e.isFilterHeader?20:0):e.width/2,t.textAlign=s,e.clipRect){t.save(),t.beginPath();const{x:i,y:o,width:n,height:s}=e.clipRect;t.rect(i,o,n,s),t.clip()}const l=He(n),c=e.content.textLines.length;let h=this.computeTextYCoordinate(e,l,c);for(let o of e.content.textLines){if(t.fillText(o,Math.round(a),Math.round(h)),n.strikethrough||n.underline){const e=Ue(t,o,n);let r=a;"right"===s?r-=e:"center"===s&&(r-=e/2),n.strikethrough&&t.fillRect(r,h+l/2,e,2.6*i),n.underline&&t.fillRect(r,h+l+1,e,1.3*i)}h+=V+l}e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const i=e.image.image;if(e.image.clipIcon){t.save(),t.beginPath();const{x:i,y:o,width:n,height:s}=e.image.clipIcon;t.rect(i,o,n,s),t.clip()}const o=e.image.size,n=this.computeTextYCoordinate(e,o);t.drawImage(i,e.x+U,n,o,o),e.image.clipIcon&&t.restore()}}computeTextYCoordinate(e,t,i=1){const o=e.y+1,n=Pe(t,i),s=e.height>n+2*V,r=e.verticalAlign||"middle";if(s){if("middle"===r)return o+(e.height-n)/2;if("bottom"===r)return o+e.height-n-V}return o+V}drawHeaders(e){const{ctx:t,thinLineWidth:i}=e,o=this.getters.getSheetViewVisibleCols(),n=o[0],s=o[o.length-1],r=this.getters.getSheetViewVisibleRows(),a=r[0],l=r[r.length-1],{width:c,height:h}=this.getters.getSheetViewDimensionWithHeaders(),d=this.getters.getSelectedZones(),u=function(e){const t=new Set;for(let i of e)for(let e of $e(i.left,i.right+1))t.add(e);return t}(d),g=function(e){const t=new Set;for(let i of e)for(let e of $e(i.top,i.bottom+1))t.add(e);return t}(d),p=this.getters.getActiveSheetId(),m=this.getters.getNumberCols(p),f=this.getters.getNumberRows(p),E=this.getters.getActiveCols(),w=this.getters.getActiveRows();t.font=`400 11px ${Z}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=i,t.strokeStyle="#333";for(let e=n;e<=s;e++){const i={left:e,right:e,top:0,bottom:f-1},{x:o,width:n}=this.getters.getVisibleRect(i),s=this.getters.doesZonesContainFilter(p,[i]),r=E.has(e),a=u.has(e);t.fillStyle=r?s?R:C:a?s?A:b:s?T:v,t.fillRect(o,0,n,N)}for(let e=a;e<=l;e++){const i={top:e,bottom:e,left:0,right:m-1},{y:o,height:n}=this.getters.getVisibleRect(i),s=this.getters.doesZonesContainFilter(p,[i]),r=w.has(e),a=g.has(e);t.fillStyle=r?s?R:C:a?s?A:b:s?T:v,t.fillRect(0,o,_,n)}t.beginPath(),t.moveTo(_,0),t.lineTo(_,h),t.moveTo(0,N),t.lineTo(c,N),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(const e of o){const i=this.getters.getColSize(p,e),o=Wt(e);t.fillStyle=E.has(e)?"#fff":S;let s=this.getHeaderOffset("COL",n,e);t.fillText(o,s+i/2,13),t.moveTo(s+i,0),t.lineTo(s+i,N)}for(const e of r){const i=this.getters.getRowSize(p,e);t.fillStyle=w.has(e)?"#fff":S;let o=this.getHeaderOffset("ROW",a,e);t.fillText(String(e+1),24,o+i/2),t.moveTo(0,o+i),t.lineTo(_,o+i)}t.stroke()}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:i}=e,{x:o,y:n}=this.getters.getMainViewportCoordinates(),s=this.getters.isDashboard()?0:_,r=this.getters.isDashboard()?0:N;t.lineWidth=6*i,t.strokeStyle="#BCBCBC",t.beginPath(),o&&(t.moveTo(s+o,0),t.lineTo(s+o,r)),n&&(t.moveTo(0,r+n),t.lineTo(s,r+n)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:i}=e,{x:o,y:n}=this.getters.getMainViewportCoordinates(),s=this.getters.getSheetViewVisibleCols(),r=s[0],a=s[s.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:r,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:_,u=this.getters.isDashboard()?0:N;t.lineWidth=6*i,t.strokeStyle="#DADFE8",t.beginPath(),o&&(t.moveTo(d+o,u),t.lineTo(d+o,h.height+u)),n&&(t.moveTo(d,u+n),t.lineTo(h.width+d,u+n)),t.stroke()}findNextEmptyCol(e,t,i){const o=this.getters.getActiveSheetId();let n=e;for(;n<t;){const e={sheetId:o,col:n+1,row:i},t=this.getters.getEvaluatedCell(e),s=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==cn.empty||this.getters.isInMerge(e)||(null==s?void 0:s.left))return n;n++}return n}findPreviousEmptyCol(e,t,i){const o=this.getters.getActiveSheetId();let n=e;for(;n>t;){const e={sheetId:o,col:n-1,row:i},t=this.getters.getEvaluatedCell(e),s=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==cn.empty||this.getters.isInMerge(e)||(null==s?void 0:s.right))return n;n--}return n}computeCellAlignment(e,t){const i=this.getters.getCell(e);if((null==i?void 0:i.isFormula)&&this.getters.shouldShowFormulas())return"left";const{align:o}=this.getters.getCellStyle(e),n=this.getters.getEvaluatedCell(e);return t&&n.type===cn.number?"center"!==o?"left":o:o||n.defaultAlign}createZoneBox(e,t,i){const{left:o,right:n}=i,s=t.left,r=t.top,a={sheetId:e,col:s,row:r},c=this.getters.getEvaluatedCell(a),h=this.getters.shouldShowFormulas(),{x:d,y:u,width:g,height:p}=this.getters.getVisibleRect(t),{verticalAlign:m}=this.getters.getCellStyle(a),f={x:d,y:u,width:g,height:p,border:this.getters.getCellBorderWithFilterBorder(a)||void 0,style:this.getters.getCellComputedStyle(a),verticalAlign:m};if(c.type===cn.empty)return f;const v=this.getters.getConditionalIcon(a),b=He(f.style),C=v?U+b:0;v&&(f.image={type:"icon",size:b,clipIcon:{x:f.x,y:f.y,width:Math.min(C,g),height:p},image:Mg[v].img}),f.isFilterHeader=this.getters.isFilterHeader(a);const S=f.isFilterHeader?19:0,E=this.getters.getCellComputedStyle(a),w=E.wrapping||"overflow",y="wrap"!==w||h?void 0:g-2*V,x=this.getters.getCellMultiLineText(a,y),I=Math.max(...x.map((e=>this.getters.getTextWidth(e,E)+V))),R=C+I+S,T=this.computeCellAlignment(a,R>g);f.content={textLines:x,width:"overflow"===w?I:g,align:T},c.type===cn.error&&c.error.logLevel>l.silent&&(f.error=c.error.message);const A=R>g||b>p;if(v||f.isFilterHeader)f.clipRect={x:f.x+C,y:f.y,width:Math.max(0,g-C-S),height:p};else if(A&&"overflow"===w){let e,i;switch(this.getters.isInMerge(a)?(e=this.getters.getMerge(a).right,i=s):(e=this.findNextEmptyCol(s,n,r),i=this.findPreviousEmptyCol(s,o,r),f.isOverflow=!0),T){case"left":{const i=co({col:e,row:r}),{x:o,y:n,width:s,height:a}=this.getters.getVisibleRect(Yi(t,i));(s<R||b>a||x.length>1)&&(f.clipRect={x:o,y:n,width:s,height:a});break}case"right":{const e=co({col:i,row:r}),{x:o,y:n,width:s,height:a}=this.getters.getVisibleRect(Yi(t,e));(s<R||b>a||x.length>1)&&(f.clipRect={x:o,y:n,width:s,height:a});break}case"center":{const o={...t,left:i,right:e},{x:n,y:s,height:r,width:a}=this.getters.getVisibleRect(o),l=R/2,c=f.x+f.width/2;if(n+a<c+l||n>c-l||b>r||x.length>1){const e=n>c-l?n:c-l,t=n+a-e;f.clipRect={x:e,y:s,width:t,height:r}}break}}}else("clip"===w||"wrap"===w||x.length>1)&&(f.clipRect={x:f.x,y:f.y,width:g,height:p});return f}getGridBoxes(){const e=[],t=this.getters.getSheetViewVisibleCols(),i=t[0],o=t[t.length-1],n=this.getters.getSheetViewVisibleRows(),s={left:i,right:o,top:n[0],bottom:n[n.length-1]},r=this.getters.getActiveSheetId();for(const i of n)for(const o of t){const t={sheetId:r,col:o,row:i};this.getters.isInMerge(t)||e.push(this.createZoneBox(r,co(t),s))}for(const t of this.getters.getMerges(r))if(!this.getters.isMergeHidden(r,t)&&Qi(t,s)){const i=this.createZoneBox(r,t,s),o=this.getters.getCellBorder({sheetId:r,col:t.right,row:t.bottom});i.border={...i.border,bottom:o?o.bottom:void 0,right:o?o.right:void 0},i.isMerge=!0,e.push(i)}return e}}fb.layers=[0,7],fb.getters=["getColDimensionsInViewport","getRowDimensionsInViewport"];class vb extends Jv{constructor(e,t,i){if(i&&t.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");super(e),this.inputHasSingleRange=i,this.ranges=[],this.focusedRangeIndex=null,this.willAddNewRange=!1,this.insertNewRange(0,t),this.activeSheet=this.getters.getActiveSheetId(),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}handleEvent(e){const t=Wi(e.anchor.zone),i=this.activeSheet,o=this.getters.getActiveSheetId(),n=this.getters.getSheetName(o);this.add([o===i?t:`${ke(n)}!${t}`])}handle(e){switch(e.type){case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"FOCUS_RANGE":this.focus(this.getIndex(e.rangeId));break;case"CHANGE_RANGE":{const t=this.getIndex(e.rangeId);if(null!==t&&this.focusedRangeIndex!==t&&this.focus(t),null!==t){const i=e.value.replace(/^,+/,"").split(",").map((e=>e.trim()));this.setRange(t,i)}break}case"ADD_EMPTY_RANGE":this.insertNewRange(this.ranges.length,[""]),this.focusLast();break;case"REMOVE_RANGE":const t=this.getIndex(e.rangeId);null!==t&&this.removeRange(t);break;case"STOP_SELECTION_INPUT":this.willAddNewRange=!1;break;case"PREPARE_SELECTION_INPUT_EXPANSION":{const e=this.focusedRangeIndex;null===e||this.inputHasSingleRange||(this.willAddNewRange=""!==this.ranges[e].xc.trim());break}case"ACTIVATE_SHEET":if(e.sheetIdFrom!==e.sheetIdTo){const{col:t,row:i}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),o=this.getters.expandZone(e.sheetIdTo,co({col:t,row:i}));this.selection.resetAnchor(this,{cell:{col:t,row:i},zone:o})}}}getSelectionInputValue(){return this.cleanInputs(this.ranges.map((e=>e.xc?e.xc:"")))}getSelectionInputHighlights(){return this.ranges.map((e=>this.inputToHighlights(e))).flat()}focus(e){this.focusedRangeIndex=e}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null}add(e){null!==this.focusedRangeIndex&&0!==e.length&&(this.willAddNewRange?(this.insertNewRange(this.ranges.length,e),this.focusLast(),this.willAddNewRange=!1):this.setRange(this.focusedRangeIndex,e))}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){const i=Math.max(0,...this.ranges.map((e=>Number(e.id))));this.ranges.splice(e,0,...t.map(((e,t)=>({xc:e,id:i+t+1,color:St[(i+t)%St.length]}))))}setRange(e,t){const[,...i]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,i),i.length&&this.focus(e+i.length)}removeRange(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const i=this.cleanInputs([e]).filter((e=>this.getters.isRangeValid(e))).filter((e=>this.shouldBeHighlighted(this.activeSheet,e)));return i.map((e=>{const{sheetName:i}=$t(e);return{zone:this.getters.getRangeFromSheetXC(this.activeSheet,e).zone,sheetId:i&&this.getters.getSheetIdByName(i)||this.activeSheet,color:t}}))}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:i}=$t(t),o=this.getters.getSheetIdByName(i),n=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(o===n||void 0===o&&n===e)}getIndex(e){const t=this.ranges.findIndex((t=>t.id===e));return t>=0?t:null}}vb.layers=[1],vb.getters=[];class bb extends Jv{get currentInput(){return this.focusedInputId?this.inputs[this.focusedInputId]:null}constructor(e){super(e),this.config=e,this.inputs={},this.focusedInputId=null}allowDispatch(e){var t,i;switch(e.type){case"FOCUS_RANGE":case"CHANGE_RANGE":case"ADD_EMPTY_RANGE":case"REMOVE_RANGE":if(!this.inputs[e.id])return 31}switch(e.type){case"FOCUS_RANGE":const o=null===(t=this.currentInput)||void 0===t?void 0:t.getIndex(e.rangeId);if(this.focusedInputId===e.id&&(null===(i=this.currentInput)||void 0===i?void 0:i.focusedRangeIndex)===o)return 29;break;case"ADD_EMPTY_RANGE":const n=this.inputs[e.id];if(n.inputHasSingleRange&&1===n.ranges.length)return 30;break;case"CHANGE_RANGE":if(this.inputs[e.id].inputHasSingleRange&&e.value.split(",").length>1)return 30;break}return 0}handle(e){var t;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];break;case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"ADD_EMPTY_RANGE":case"REMOVE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id];this.selection.capture(t,{cell:{col:0,row:0},zone:co({col:0,row:0})},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}break;case"FOCUS_RANGE":case"CHANGE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id],i=t.ranges.find((t=>t.id===e.rangeId)),o=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(o,(null==i?void 0:i.xc)||"A1").zone;this.selection.capture(t,{cell:{col:n.left,row:n.top},zone:n},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}}null===(t=this.currentInput)||void 0===t||t.handle(e)}getSelectionInput(e){return this.inputs[e]?this.inputs[e].ranges.map(((t,i)=>Object.assign({},t,{color:this.focusedInputId===e&&null!==this.inputs[e].focusedRangeIndex&&this.isRangeValid(t.xc)?t.color:null,isFocused:this.focusedInputId===e&&this.inputs[e].focusedRangeIndex===i}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:i}=$t(e);return null!==t.match(Pt)&&(!i||void 0!==this.getters.getSheetIdByName(i))}getSelectionInputValue(e){return this.inputs[e].getSelectionInputValue()}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].getSelectionInputHighlights():[]}initInput(e,t,i=!1){if(this.inputs[e]=new vb(this.config,t,i),0===t.length){const t=this.inputs[e],i={zone:co({col:0,row:0}),cell:{col:0,row:0}};this.selection.capture(t,i,{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e}}unfocus(){this.selection.release(this.currentInput),this.focusedInputId=null}}bb.layers=[1],bb.getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];class Cb{constructor(){this.subscriptions={}}on(e,t,i){if(!i)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:i})}trigger(e,t){const i=this.subscriptions[e]||[];for(let e=0,o=i.length;e<o;e++){const o=i[e];o.callback.call(o.owner,t)}}off(e,t){const i=this.subscriptions[e];i&&(this.subscriptions[e]=i.filter((e=>e.owner!==t)))}clear(){this.subscriptions={}}}function Sb(e,t){return{...e,definition:Rr(e.definition,t)}}function Eb(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let i=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(let t of e)i>t&&i--}if("ADD_COLUMNS_ROWS"===t.type){i=i>("before"===t.position?t.base-1:t.base)?i+t.quantity:i}return i>0?{...e,quantity:i}:void 0}rg.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],Sb),rg.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],Sb),rg.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const i=t.sheetId;if(e.targetSheetId===i||e.sheetId===i)return;return e})),rg.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),rg.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){var i;if(e.name===t.name)return{...e,name:(null===(i=e.name)||void 0===i?void 0:i.match(/\d+/))?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),rg.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE","CREATE_FILTER_TABLE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const i=[];for(const o of e.target)for(const e of t.target)Qi(o,e)||i.push({...o});if(i.length)return{...e,target:i};return})),rg.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],Eb),rg.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],Eb),rg.addTransformation("CREATE_FILTER_TABLE",["CREATE_FILTER_TABLE","ADD_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;for(const i of e.target)for(const e of t.target)if(Qi(e,i))return;return e}));const wb=[{match:function(e){return"sheetId"in e},fn:Ib},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const i=Ib(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;const o=[];for(const i of e.target){const e=ms(i,t);e&&o.push(e)}if(!o.length)return"IGNORE_COMMAND";return{...e,target:o}}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const i=Ib(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const i="COL"===t.dimension?"col":"row";let o=e[i];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(o))return"IGNORE_COMMAND";for(let t of e)o>=t&&o--}"ADD_COLUMNS_ROWS"===t.type&&(o>t.base||o===t.base&&"before"===t.position)&&(o+=t.quantity);return{...e,[i]:o}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const i of t.target){if(!(e.col===i.left&&e.row===i.top)&&Ji(e.col,e.row,i))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e},fn:function(e,t){const i=Ib(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const i="ADD_COLUMNS_ROWS"===e.type,o=i?"base":"elements";let n=i?[e[o]]:e[o];if("REMOVE_COLUMNS_ROWS"===t.type&&(n=n.map((e=>{if(t.elements.includes(e))return;const i=t.elements.sort(((e,t)=>t-e));for(let t of i)e>t&&e--;return e})).filter(ot)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;n=n.map((i=>i>e?i+t.quantity:i))}if(n.length){let t=n;return i&&(t=n[0]),{...e,[o]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}},{match:function(e){return"ranges"in e},fn:function(e,t){const i=[],o="DELETE_SHEET"===t.type&&t.sheetId;for(const n of e.ranges)if(n._sheetId!==t.sheetId)i.push({...n,_zone:n._zone});else{const e=ms(n._zone,t);e&&o!==n._sheetId&&i.push({...n,_zone:e})}if(!i.length)return"IGNORE_COMMAND";return{...e,ranges:i}}}];function yb(e,t){const i=rg.getTransformation(e.type,t.type);return i?i(e,t):function(e,t){for(const{match:i,fn:o}of wb)if(i(e)){const i=o(e,t);if("SKIP_TRANSFORMATION"===i)continue;if("IGNORE_COMMAND"===i)return;e=i}return e}(e,t)}function xb(e,t){let i=[...e];for(const e of t)i=i.map((t=>yb(t,e))).filter(ot);return i}function Ib(e,t){const i="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===i?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class Rb{constructor(e,t,i,o){this._commands=[],this._changes=[],this.id=e,this.clientId=t,this._commands=[...i],this._changes=o?[...o]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class Tb extends Error{}class Ab extends Cb{constructor(e,t,i=Q){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=i,this.clients={},this.clientId="local",this.pendingMessages=[],this.waitingAck=!1,this.waitingUndoRedoAck=!1,this.isReplayingInitialRevisions=!1,this.processedRevisions=new Set,this.uuidGenerator=new zi,this.debouncedMove=function(e,t,i){let o;return function(){const n=this,s=arguments,r=i&&!o;clearTimeout(o),o=setTimeout((function(){o=null,i||e.apply(n,s)}),t),r&&e.apply(n,s)}}(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t){if(!e.length||!t.length||!this.canApplyOptimisticUpdate())return;const i=new Rb(this.uuidGenerator.uuidv4(),this.clientId,e,t);this.revisions.append(i.id,i),this.trigger("new-local-state-update",{id:i.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:i.id,clientId:i.clientId,commands:i.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_UNDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_REDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:"local",name:"local"},this.clientId="local"),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this))}loadInitialMessages(e){this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1}leave(){delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}snapshot(e){const t=this.uuidGenerator.uuidv4();this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){const e=this.clients[this.clientId];if(!e)throw new Tb("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(ot))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}_move(e){var t;if(!this.clients[this.clientId])return;const i=null===(t=this.clients[this.clientId])||void 0===t?void 0:t.position;if((null==i?void 0:i.col)===e.col&&i.row===e.row&&i.sheetId===e.sheetId)return;const o=i?"CLIENT_MOVED":"CLIENT_JOINED",n=this.getClient();this.clients[this.clientId]={...n,position:e},this.transportService.sendMessage({type:o,version:1,client:{...n,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:i}=e,o=new Rb(e.nextRevisionId,t,i);if(o.clientId!==this.clientId){this.revisions.insert(o.id,o,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:xb(i,t)})}break;case"SNAPSHOT_CREATED":{const t=new Rb(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){if("CLIENT_MOVED"===e.type&&e.client.id===this.clientId)return!0;switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter((({type:e})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const Mb=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];class Ob extends Jv{constructor(){super(...arguments),this.availableColors=new Set(Mb),this.colors={}}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}chooseNewColor(){0===this.availableColors.size&&(this.availableColors=new Set(Mb));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 Tb)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const i of this.getters.getConnectedClients())if(i.id!==this.getters.getClient().id&&i.position&&i.position.sheetId===e&&this.isPositionValid(i.position)){const e=i.position;this.colors[i.id]||(this.colors[i.id]=this.chooseNewColor());const o=this.colors[i.id];t.push({...i,position:e,color:o})}return t}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:i}=e,o=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:n,col:s}=e.position,r=this.getters.expandZone(o,{top:n,bottom:n,left:s,right:s}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);if(c<=0||h<=0)continue;const d=e.color,u=`${d}10`;t.fillStyle=u,t.lineWidth=4*i,t.strokeStyle=d,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,h),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,h),t.font=`bold ${q+1}px ${Z}`}}}Ob.getters=["getClientsToDisplay"],Ob.layers=[6];class Nb extends Jv{allowDispatch(e){if("SORT_CELLS"===e.type){if(!Ji(e.col,e.row,e.zone))throw new Error(s("The anchor must be part of the provided zone"));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return 0}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;return so(t).some((({col:t,row:i})=>!this.getters.isInMerge({sheetId:e,col:t,row:i})))?64:0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const i=this.getters.getMerges(e).filter((e=>Qi(e,t))),o=oo(i[0]);let[n,s]=[o.numberOfCols,o.numberOfRows];return i.every((e=>{let[t,i]=[e.right-e.left+1,e.bottom-e.top+1];return t===n&&i===s}))?0:64}expand(e,t){const{left:i,right:o,top:n,bottom:s}=this.getters.expandZone(e,t);return{left:Math.max(0,i),right:Math.min(this.getters.getNumberCols(e)-1,o),top:Math.max(0,n),bottom:Math.min(this.getters.getNumberRows(e)-1,s)}}checkExpandedValues(e,t){const i=this.expand(e,t);let o;if(this.getters.doesIntersectMerge(e,i)){const{left:t,right:n,top:s,bottom:r}=i;for(let i=t;i<=n;i++)for(let t=s;t<=r;t++){const{col:n,row:s}=this.getters.getMainCellPosition({sheetId:e,col:i,row:t});if(o=this.getters.getEvaluatedCell({sheetId:e,col:n,row:s}),o.formattedValue)return!0}}else for(let t of this.getters.getEvaluatedCellsInZone(e,i))if(t.formattedValue)return!0;return!1}getContiguousZone(e,t){let i,{top:o,bottom:n,left:s,right:r}=t,a=!1;for(;!a;)a=!0,o>0&&(i=this.checkExpandedValues(e,{left:s-1,right:r+1,top:o-1,bottom:o-1}),i&&(a=!1,o--)),s>0&&(i=this.checkExpandedValues(e,{left:s-1,right:s-1,top:o-1,bottom:n+1}),i&&(a=!1,s--)),r<this.getters.getNumberCols(e)-1&&(i=this.checkExpandedValues(e,{left:r+1,right:r+1,top:o-1,bottom:n+1}),i&&(a=!1,r++)),n<this.getters.getNumberRows(e)-1&&(i=this.checkExpandedValues(e,{left:s-1,right:r+1,top:n+1,bottom:n+1}),i&&(a=!1,n++));return{left:s,right:r,top:o,bottom:n}}hasHeader(e,t){if(1===t[0].length)return!1;let i=t.map((t=>t.map((({col:t,row:i})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:i}).type))));return i[0][0]===cn.empty&&(i=i.slice(1)),!i.some((e=>e[0]===cn.empty))&&!!i.some((e=>e[1]!==cn.empty&&e[0]!==e[1]))}sortZone(e,t,i,o,n){const[s,r]=this.mainCellsSteps(e,i);let a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},i),c=this.mainCells(e,i);!n.sortHeaders&&this.hasHeader(e,c)&&(l.top+=r),c=this.mainCells(e,l);const h=function(e,t,i){const o=e.map(((e,t)=>({index:t,type:e.type,value:e.value})));let n=o.filter((e=>e.type===cn.empty)),s=o.filter((e=>e.type!==cn.empty));i&&(s.push(...n.map((e=>({...e,type:cn.number,value:0})))),n=[]);const r="descending"===t?-1:1;return s.sort(((e,t)=>{let i=Ar.indexOf(e.type)-Ar.indexOf(t.type);return 0===i&&(i=e.type===cn.text||e.type===cn.error?e.value.localeCompare(t.value):e.value-t.value),r*i})).concat(n)}(c[a-l.left].map((e=>this.getters.getEvaluatedCell(e))),o,Boolean(n.emptyCellAsZero)),d=h.map((e=>e.index)),[u,g]=[c.length,c[0].length],p=[];for(let e=0;e<u;e++)for(let t=0;t<g;t++){let{col:i,row:o,sheetId:n}=c[e][d[t]];const a=this.getters.getCell({sheetId:n,col:i,row:o});let h=l.left+e*s,u=l.top+t*r,g={sheetId:n,col:h,row:u,content:""};if(a){let e=a.content;if(a.isFormula){const t=u-this.getters.getCellPosition(a.id).row,i=this.getters.createAdaptedRanges(a.dependencies,0,t,n);e=this.getters.buildFormulaContent(n,a,i)}g.style=a.style,g.content=e,g.format=a.format}p.push(g)}p.forEach((e=>this.dispatch("UPDATE_CELL",e)))}mainCellsSteps(e,t){const i=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[i?i.right-i.left+1:1,i?i.bottom-i.top+1:1]}mainCells(e,t){const[i,o]=this.mainCellsSteps(e,t),n=[],s=$e(t.left,t.right+1,i),r=$e(t.top,t.bottom+1,o);for(const t of s){const i=[];n.push(i);for(const o of r)i.push({sheetId:e,col:t,row:o})}return n}}Nb.getters=["getContiguousZone"];class _b extends Jv{constructor(){super(...arguments),this.showFormulas=!1}handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}_b.getters=["shouldShowFormulas"];class Fb extends Jv{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}allowDispatch(e){switch(e.type){case"AUTORESIZE_ROWS":case"AUTORESIZE_COLUMNS":try{this.getters.getSheet(e.sheetId);break}catch(e){return 27}}return 0}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){const i=this.getColMaxWidth(e.sheetId,t);0!==i&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:i,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":for(let t of e.rows)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"ROW",size:null,sheetId:e.sheetId})}}getCellWidth(e){const t=this.getCellText(e),i=this.getters.getCellComputedStyle(e),o=t.split(he);let n=Math.max(...o.map((e=>this.getTextWidth(e,i))));this.getters.getConditionalIcon(e)&&(n+=function(e){return He(e)+2*U}(this.getters.getCellStyle(e)));if(this.getters.isFilterHeader(e)&&(n+=20),n>0&&(n+=2*B,"wrap"===this.getters.getCellStyle(e).wrapping)){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,n)}return n}getTextWidth(e,t){return Ue(this.ctx,e,t)}getCellText(e,t=!1){const i=this.getters.getCell(e);return t&&(null==i?void 0:i.isFormula)?i.content:this.getters.getEvaluatedCell(e).formattedValue}getCellMultiLineText(e,t){const i=this.getters.getCellStyle(e),o=this.getters.getCellText(e,this.getters.shouldShowFormulas()),n=[];for(const e of o.split("\n")){const o=e.split(" ");if(!t){n.push(e);continue}let s="",r=t;for(let e of o){const o=this.splitWordToSpecificWidth(this.ctx,e,t,i),a=o.pop(),l=Ue(this.ctx,a,i);if(o.length)""!==s&&(n.push(s),s="",r=t),o.forEach((e=>{n.push(e)})),s=a,r=t-l;else{const e=""===s?a:" "+a,o=Ue(this.ctx,e,i);o<=r?(s+=e,r-=o):(n.push(s),s=a,r=t-l)}}""!==s&&n.push(s)}return n}getColDimensions(e,t){const i=this.getColRowOffset("COL",0,t,e),o=this.getters.getColSize(e,t);return{start:i,size:o,end:i+(this.getters.isColHidden(e,t)?0:o)}}getRowDimensions(e,t){const i=this.getColRowOffset("ROW",0,t,e),o=this.getters.getRowSize(e,t);return{start:i,size:o,end:i+(this.getters.isRowHidden(e,t)?0:o)}}getColRowOffset(e,t,i,o=this.getters.getActiveSheetId()){if(i<t)return-this.getColRowOffset(e,i,t);let n=0;for(let s=t;s<i;s++)this.getters.isHeaderHidden(o,e,s)||(n+="COL"===e?this.getters.getColSize(o,s):this.getters.getRowSize(o,s));return n}getColMaxWidth(e,t){const i=so(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,...i)}splitWordToSpecificWidth(e,t,i,o){if(Ue(e,t,o)<=i)return[t];const n=[];let s="";for(let r of t){Ue(e,s+r,o)>i?(n.push(s),s=r):s+=r}return n.push(s),n}}Fb.getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getColDimensions","getRowDimensions","getColRowOffset"];class Db{constructor(e,t,i,o){this.getters=t,this.dispatch=i,this.selection=o,this.operation=e,this.sheetId=t.getActiveSheetId()}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0}addMissingDimensions(e,t,i,o){const n=this.getters.getActiveSheetId(),s=t+o-this.getters.getNumberRows(n);s>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(n)-1,sheetId:n,quantity:s,position:"after"});const r=e+i-this.getters.getNumberCols(n);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(n)-1,sheetId:n,quantity:r,position:"after"})}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class kb extends Db{constructor(e,t,i,o,n){if(super(t,i,o,n),!e.length)return this.cells=[[]],this.zones=[],void(this.copiedTables=[]);const s=new Set(e.map((e=>e.left))),r=new Set(e.map((e=>e.right))),a=new Set(e.map((e=>e.top))),l=new Set(e.map((e=>e.bottom))),c=1===a.size&&1===l.size||1===s.size&&1===r.size?function(e){return e.reduce(((e,t)=>{const i=e.length;for(let o=0;o<i;o++)if(Qi(e[o],t))return e[o]=Yi(e[o],t),e;return e[i]=t,e}),[])}(e):[e[e.length-1]],h=c.map((e=>so(e))).flat(),d=[...new Set(h.map((e=>e.col)))].sort(((e,t)=>e-t)),u=[...new Set(h.map((e=>e.row)))].sort(((e,t)=>e-t)),g=[],p=i.getActiveSheetId();for(let e of u){let t=[];for(let o of d){const n={col:o,row:e,sheetId:p};t.push({cell:i.getCell(n),style:i.getCellComputedStyle(n),evaluatedCell:i.getEvaluatedCell(n),border:i.getCellBorder(n)||void 0,position:n})}g.push(t)}const m=[];for(const t of e)for(const e of this.getters.getFilterTablesInZone(p,t)){const t=[];for(const i of $e(e.zone.left,e.zone.right+1))t.push(this.getters.getFilterValues({sheetId:p,col:i,row:e.zone.top}));m.push({filtersValues:t,zone:e.zone})}this.cells=g,this.zones=c,this.copiedTables=m}isCutAllowed(e){return 1!==e.length?19:0}isPasteAllowed(e,t){const i=this.getters.getActiveSheetId();if("CUT"===this.operation&&void 0!==(null==t?void 0:t.pasteOption))return 21;if(e.length>1&&(this.cells.length>1||this.cells[0].length>1))return 20;const o=this.cells.length,n=this.cells[0].length;for(let t of this.getPasteZones(e))if(this.getters.doesIntersectMerge(i,t)&&(e.length>1||!this.getters.isSingleCellOrMerge(i,e[0])||o*n!=1))return 2;const{xSplit:s,ySplit:r}=this.getters.getPaneDivisions(i);for(const t of this.getPasteZones(e))if(t.left<s&&t.right>=s||t.top<r&&t.bottom>=r)return 76;return 0}paste(e,t){"COPY"===this.operation?this.pasteFromCopy(e,t):this.pasteFromCut(e,t);const i=this.cells.length,o=this.cells[0].length,n="CUT"===this.operation;(null==t?void 0:t.selectTarget)&&this.selectPastedZone(o,i,n,e)}pasteFromCopy(e,t){if(1===e.length){const i=this.cells.length,o=this.cells[0].length,n=this.pastedZones(e,o,i);for(const e of n)this.pasteZone(e.left,e.top,t)}else for(const i of e)for(let e=i.left;e<=i.right;e++)for(let o=i.top;o<=i.bottom;o++)this.pasteZone(e,o,t);void 0===(null==t?void 0:t.pasteOption)&&this.pasteCopiedTables(e)}pasteFromCut(e,t){this.clearClippedZones();const i=e[0];this.pasteZone(i.left,i.top,t),this.dispatch("MOVE_RANGES",{target:this.zones,sheetId:this.sheetId,targetSheetId:this.getters.getActiveSheetId(),col:i.left,row:i.top});for(const e of this.copiedTables)this.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.sheetId,target:[e.zone]});this.pasteCopiedTables(e)}pastedZones(e,t,i){const o=e[0],n=Math.max(1,Math.floor((o.right+1-o.left)/t)),s=Math.max(1,Math.floor((o.bottom+1-o.top)/i)),r=[];for(let e=0;e<n;e++)for(let n=0;n<s;n++){const s=o.top+n*i,a=o.left+e*t;r.push({left:a,top:s,bottom:s+i-1,right:a+t-1})}return r}getPasteZones(e){const t=this.cells;if(!t.length||!t[0].length)return e;const i=[],o=t.length,n=t[0].length,s=e[e.length-1],r=s.left,a=s.top,l=Math.max(1,Math.floor((s.right+1-r)/n)),c=Math.max(1,Math.floor((s.bottom+1-a)/o));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)i.push({left:r,top:a,right:r-1+e*n,bottom:a-1+t*o});return i}selectPastedZone(e,t,i,o){const n=o[0],s=n.left,r=n.top;if(t>1||e>1||i){const n=this.pastedZones(o,e,t),a=i?n[0]:Yi(...n);this.selection.selectZone({cell:{col:s,row:r},zone:a})}}clearClippedZones(){for(const e of this.cells)for(const t of e)t.cell&&this.dispatch("CLEAR_CELL",t.position);this.dispatch("CLEAR_FORMATTING",{sheetId:this.sheetId,target:this.zones})}pasteZone(e,t,i){const o=this.cells.length,n=this.cells[0].length,s="onlyValue"!==(null==i?void 0:i.pasteOption)&&(null==i?void 0:i.shouldPasteCF),r=this.getters.getActiveSheetId();this.addMissingDimensions(n,o,e,t);for(let a=0;a<o;a++){const o=this.cells[a];for(let l=0;l<n;l++){const n=o[l],c={col:e+l,row:t+a,sheetId:r};"CUT"!==this.operation&&this.pasteMergeIfExist(n.position,c),this.pasteCell(n,c,this.operation,i),s&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:n.position,target:c,operation:this.operation})}}}pasteCell(e,t,i,o){const{sheetId:n,col:s,row:r}=t,a=this.getters.getEvaluatedCell(t);if("onlyValue"!==(null==o?void 0:o.pasteOption)){const i=this.getters.getCellBorder(t),o=e.border,a={top:(null==i?void 0:i.top)||(null==o?void 0:o.top),bottom:(null==i?void 0:i.bottom)||(null==o?void 0:o.bottom),left:(null==i?void 0:i.left)||(null==o?void 0:o.left),right:(null==i?void 0:i.right)||(null==o?void 0:o.right)};this.dispatch("SET_BORDER",{sheetId:n,col:s,row:r,border:a})}if(e.cell){if("onlyFormat"===(null==o?void 0:o.pasteOption))return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.evaluatedCell.format});if("onlyValue"===(null==o?void 0:o.pasteOption)){const i=fi(e.evaluatedCell.value);return void this.dispatch("UPDATE_CELL",{...t,content:i})}let a=e.cell.content;if(e.cell.isFormula&&"COPY"===i){const t=s-e.position.col,o=r-e.position.row;a=this.getUpdatedContent(n,e.cell,t,o,i)}this.dispatch("UPDATE_CELL",{...t,content:a,style:e.cell.style||null,format:e.cell.format})}else a&&("onlyValue"===(null==o?void 0:o.pasteOption)?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===(null==o?void 0:o.pasteOption)?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,i,o,n){const s=this.getters.createAdaptedRanges(t.dependencies,i,o,e);return this.getters.buildFormulaContent(e,t,s)}pasteMergeIfExist(e,t){let{sheetId:i,col:o,row:n}=e;const{col:s,row:r}=this.getters.getMainCellPosition(e);if(s===o&&r===n){const s=this.getters.getMerge(e);if(!s)return;({sheetId:i,col:o,row:n}=t),this.dispatch("ADD_MERGE",{sheetId:i,force:!0,target:[{left:o,top:n,right:o+s.right-s.left,bottom:n+s.bottom-s.top}]})}}pasteCopiedTables(e){const t=this.getters.getActiveSheetId(),i=e[0],o=this.zones[0],n=[i.left-o.left,i.top-o.top];for(const e of this.copiedTables){const i=ro(e.zone,"both","MOVE",n);this.dispatch("CREATE_FILTER_TABLE",{sheetId:t,target:[i]});for(const o of $e(0,e.filtersValues.length))this.dispatch("UPDATE_FILTER",{sheetId:t,col:i.left+o,row:i.top,values:e.filtersValues[o]})}}getClipboardContent(){return{[hn.PlainText]:this.getPlainTextContent(),[hn.Html]:this.getHTMLContent()}}getPlainTextContent(){return this.cells.map((e=>e.map((e=>e.cell?this.getters.getCellText(e.position,this.getters.shouldShowFormulas()):"")).join("\t"))).join("\n")||"\t"}getHTMLContent(){if(1==this.cells.length&&1==this.cells[0].length)return this.getters.getCellText(this.cells[0][0].position);let e='<table border="1" style="border-collapse:collapse">';for(const t of this.cells){e+="<tr>";for(const i of t){e+=`<td style="${Eo(Co(i.style))}">`+iv(this.getters.getCellText(i.position))+"</td>"}e+="</tr>"}return e+="</table>",e}isColRowDirtyingClipboard(e,t){if(!this.zones)return!1;for(let i of this.zones){if("COL"===t&&e<=i.right)return!0;if("ROW"===t&&e<=i.bottom)return!0}return!1}drawClipboard(e){const{ctx:t,thinLineWidth:i}=e;if(this.sheetId===this.getters.getActiveSheetId()&&this.zones&&this.zones.length){t.setLineDash([8,5]),t.strokeStyle=E,t.lineWidth=3.3*i;for(const e of this.zones){const{x:i,y:o,width:n,height:s}=this.getters.getVisibleRect(e);n>0&&s>0&&t.strokeRect(i,o,n,s)}}}}class Lb{constructor(e,t,i){this.operation=e,this.getters=t,this.dispatch=i,this.sheetId=t.getActiveSheetId();const o=t.getSelectedFigureId();if(!o)throw new Error("No figure selected");const n=t.getFigure(this.sheetId,o);if(!n)throw new Error(`No figure for the given id: ${o}`);switch(this.copiedFigure={...n},n.tag){case"chart":this.copiedFigureContent=new Pb(i,t,this.sheetId,o);break;case"image":this.copiedFigureContent=new Ub(i,t,this.sheetId,o);break;default:throw new Error(`Unknow tag '${n.tag}' for the given figure id: ${o}`)}}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0===e.length?74:void 0!==(null==t?void 0:t.pasteOption)?22:0}paste(e){const t=this.getters.getActiveSheetId(),i={x:this.getters.getColDimensions(t,e[0].left).start,y:this.getters.getRowDimensions(t,e[0].top).start},o={height:this.copiedFigure.height,width:this.copiedFigure.width},n=(new zi).uuidv4();this.copiedFigureContent.paste(t,n,i,o),"CUT"===this.operation&&this.dispatch("DELETE_FIGURE",{sheetId:this.copiedFigureContent.sheetId,id:this.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{id:n})}getClipboardContent(){return{[hn.PlainText]:"\t"}}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class Pb{constructor(e,t,i,o){this.dispatch=e,this.sheetId=i;const n=t.getChart(o);if(!n)throw new Error(`No chart for the given id: ${o}`);this.copiedChart=n.copyInSheetId(i)}paste(e,t,i,o){const n=this.copiedChart.copyInSheetId(e);this.dispatch("CREATE_CHART",{id:t,sheetId:e,position:i,size:o,definition:n.getDefinition()})}}class Ub{constructor(e,t,i,o){this.dispatch=e,this.sheetId=i;const n=t.getImage(o);this.copiedImage=Fe(n)}paste(e,t,i,o){const n=Fe(this.copiedImage);this.dispatch("CREATE_IMAGE",{figureId:t,sheetId:e,position:i,size:o,definition:n})}}class Vb extends Db{constructor(e,t,i,o){super("COPY",t,i,o),this.values=e.replace(/\r/g,"").split("\n").map((e=>e.split("\t")))}isPasteAllowed(e,t){const i=this.getters.getActiveSheetId(),o=this.getPasteZone(e);return this.getters.doesIntersectMerge(i,o)?2:0}paste(e){const t=this.values,i=this.getPasteZone(e),{left:o,top:n}=i,{numberOfCols:s,numberOfRows:r}=oo(i),a=this.getters.getActiveSheetId();this.addMissingDimensions(s,r,o,n);for(let e=0;e<t.length;e++)for(let i=0;i<t[e].length;i++)this.dispatch("UPDATE_CELL",{row:n+e,col:o+i,content:t[e][i],sheetId:a});const l={left:o,top:n,right:o+s-1,bottom:n+r-1};this.selection.selectZone({cell:{col:o,row:n},zone:l})}getClipboardContent(){return{[hn.PlainText]:this.values.map((e=>e.join("\t"))).join("\n")}}getPasteZone(e){const t=this.values.length,i=Math.max(...this.values.map((e=>e.length))),{left:o,top:n}=e[0];return{top:n,left:o,bottom:n+t-1,right:o+i-1}}}class zb extends Jv{constructor(){super(...arguments),this.status="invisible",this._isPaintingFormat=!1}allowDispatch(e){switch(e.type){case"CUT":const t=this.getters.getSelectedZones();return this.getClipboardState(t,e.type).isCutAllowed(t);case"PASTE":if(!this.state)return 23;const i=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);return this.state.isPasteAllowed(e.target,{pasteOption:i});case"PASTE_FROM_OS_CLIPBOARD":return new Vb(e.text,this.getters,this.dispatch,this.selection).isPasteAllowed(e.target);case"INSERT_CELL":{const{cut:t,paste:i}=this.getInsertCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(i)}case"DELETE_CELL":{const{cut:t,paste:i}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(i)}}return 0}handle(e){var t,i;switch(e.type){case"COPY":case"CUT":const o=this.getters.getSelectedZones();this.state=this.getClipboardState(o,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const n=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1,this.state.paste(e.target,{pasteOption:n,shouldPasteCF:!0,selectTarget:!0}),"CUT"===this.state.operation&&(this.state=void 0),this.status="invisible";break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:i}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!$i(t[0])){for(const{col:t,row:i}of so(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:i,sheetId:this.getters.getActiveSheetId()});break}this.getClipboardStateForCopyCells(t,"CUT").paste(i);break}case"INSERT_CELL":{const{cut:t,paste:i}=this.getInsertCellsTargets(e.zone,e.shiftDimension);this.getClipboardStateForCopyCells(t,"CUT").paste(i);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(t=this.state)||void 0===t?void 0:t.operation))return;this.state.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===(i=this.state)||void 0===i?void 0:i.operation))return;for(let t of e.elements){if(this.state.isColRowDirtyingClipboard(t,e.dimension)){this.state=void 0;break}}this.status="invisible";break;case"PASTE_FROM_OS_CLIPBOARD":new Vb(e.text,this.getters,this.dispatch,this.selection).paste(e.target),this.status="invisible";break;case"ACTIVATE_PAINT_FORMAT":{const e=this.getters.getSelectedZones();this.state=this.getClipboardStateForCopyCells(e,"COPY"),this._isPaintingFormat=!0,this.status="visible";break}default:mn(e)&&(this.status="invisible")}}getClipboardContent(){var e;return(null===(e=this.state)||void 0===e?void 0:e.getClipboardContent())||{[hn.PlainText]:"\t"}}getClipboardTextContent(){var e;return(null===(e=this.state)||void 0===e?void 0:e.getClipboardContent()[hn.PlainText])||"\t"}isCutOperation(){return!!this.state&&"CUT"===this.state.operation}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const i=this.getters.getActiveSheetId();let o;return o="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(i)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(i)-1},{cut:[o],paste:[e]}}getInsertCellsTargets(e,t){const i=this.getters.getActiveSheetId();let o,n;return"COL"===t?(o={...e,right:this.getters.getNumberCols(i)-1},n={...e,left:e.right+1,right:e.right+1}):(o={...e,bottom:this.getters.getNumberRows(i)-1},n={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(i)-1}),{cut:[o],paste:[n]}}getClipboardStateForCopyCells(e,t){return new kb(e,t,this.getters,this.dispatch,this.selection)}getClipboardState(e,t){return this.getters.getSelectedFigureId()?new Lb(t,this.getters,this.dispatch):new kb(e,t,this.getters,this.dispatch,this.selection)}drawGrid(e){"visible"===this.status&&this.state&&this.state.drawClipboard(e)}}function Bb(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:i}=$t(e.value),[o,n]=t.split(":"),s=i?`${ke(i)}!`:"",r=Hb(o),a=n?`:${Hb(n)}`:"";return{...e,value:s+r+a}}function Hb(e){switch(function(e){if(function(e){return e.startsWith("$")&&e.length>1&&e.slice(1).includes("$")}(e))return"colrow";if(function(e){return e.startsWith("$")}(e))return"col";if(function(e){return e.includes("$",1)}(e))return"row";return"none"}(e)){case"none":e=$b(e,"colrow");break;case"colrow":e=$b(e,"row");break;case"row":e=$b(e,"col");break;case"col":e=$b(e,"none")}return e}function $b(e,t){let i;switch(e=e.replace(/\$/g,""),t){case"col":return"$"+e;case"row":return i=e.search(/[0-9]/),e.slice(0,i)+"$"+e.slice(i);case"colrow":return i=e.search(/[0-9]/),-1===i||0===i?"$"+e:"$"+(e=e.slice(0,i)+"$"+e.slice(i));case"none":return e}}zb.layers=[2],zb.getters=["getClipboardContent","getClipboardTextContent","isCutOperation","isPaintingFormat"];const Wb=s("The cell you are trying to edit has been deleted.");class Gb extends Jv{constructor(){super(...arguments),this.col=0,this.row=0,this.mode="inactive",this.sheetId="",this.currentContent="",this.currentTokens=[],this.selectionStart=0,this.selectionEnd=0,this.selectionInitialStart=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=e.text||this.getComposerContent(this.getters.getActivePosition());return this.validateSelection(t.length,e.selection.start,e.selection.end)}return 0;default:return 0}}handleEvent(e){if("selecting"===this.mode)if("newAnchor"===e.mode)this.insertSelectedRange(e.anchor.zone);else this.replaceSelectedRanges(e.anchor.zone)}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":"inactive"!==this.mode&&e.text?this.setContent(e.text,e.selection):this.startEdition(e.text,e.selection),this.updateRangeColor();break;case"STOP_EDITION":e.cancel?(this.cancelEditionAndActivateSheet(),this.resetContent()):this.stopEdition(),this.colorIndexByRange={};break;case"SET_CURRENT_CONTENT":this.setContent(e.content,e.selection,!0),this.updateRangeColor();break;case"REPLACE_COMPOSER_CURSOR_SELECTION":this.replaceSelection(e.text);break;case"SELECT_FIGURE":this.cancelEditionAndActivateSheet(),this.resetContent();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.getters.getRangeFromRangeData(e.range),i=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((e=>{const{xc:i,sheetName:o}=$t(e.value),n=o||this.getters.getSheetName(this.sheetId),s=this.getters.getActiveSheetId();if(this.getters.getSheetName(s)!==n)return!1;const r=this.getters.getRangeFromSheetXC(s,i);return Ki(this.getters.expandZone(s,r.zone),t.zone)}));this.previousRef=i.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=i.start;break;case"CHANGE_HIGHLIGHT":const o=this.getters.getRangeFromRangeData(e.range),n=this.getRangeReference(o,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(n),this.previousRef=n,this.selectionStart=this.currentContent.length,this.selectionEnd=this.currentContent.length;break;case"ACTIVATE_SHEET":if(this.currentContent.startsWith("=")||(this.cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){const t=this.getters.getActivePosition(),{col:i,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),n=this.getters.expandZone(e.sheetIdTo,co({col:i,row:o}));this.selection.resetAnchor(this,{cell:{col:i,row:o},zone:n})}break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheetId)||"inactive"===this.mode||(this.sheetId=this.getters.getActiveSheetId(),this.cancelEditionAndActivateSheet(),this.resetContent(),this.ui.notifyUI({type:"ERROR",text:Wb}));break;case"CYCLE_EDITION_REFERENCES":this.cycleReferences()}}getEditionMode(){return this.mode}getCurrentContent(){return"inactive"===this.mode?this.getComposerContent(this.getters.getActivePosition()):this.currentContent}getEditionSheet(){return this.sheetId}getComposerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}getCurrentEditedCell(){return{sheetId:this.sheetId,col:this.col,row:this.row}}isSelectingForComposer(){return"selecting"===this.mode}showSelectionIndicator(){return this.isSelectingForComposer()&&this.canStartComposerRangeSelection()}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((i=>i.start<=e&&i.end>=t))}cycleReferences(){const e=this.getTokensInSelection(),t=e.filter((e=>"REFERENCE"===e.type));if(0===t.length)return;const i=e.map(Bb).map((e=>e.value)).join(""),o=this.currentContent,n=e[0].start,s=e[e.length-1].end,r=o.slice(0,n)+i+o.slice(s),a=r.length-o.length,l={start:t[0].start,end:t[t.length-1].end+a};1===t.length&&this.selectionStart===this.selectionEnd&&(l.start=l.end),this.dispatch("SET_CURRENT_CONTENT",{content:r,selection:l})}validateSelection(e,t,i){return t>=0&&t<=e&&i>=0&&i<=e?0:47}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:Wb});const{top:t,left:i}=Zi({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=i,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:Wb});const{top:t,left:i}=Zi({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=i,this.row=t}onAddElements(e){const{top:t,left:i}=qi({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=i,this.row=t}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=co({col:this.col,row:this.row});this.selection.resetAnchor(this,{cell:{col:this.col,row:this.row},zone:e})}this.mode="selecting",this.selectionInitialStart=this.selectionStart}startEdition(e,t){var i;const o=this.getters.getActiveCell();e&&(null===(i=o.format)||void 0===i?void 0:i.includes("%"))&&ni(e)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const{col:n,row:s,sheetId:r}=this.getters.getActivePosition();this.col=n,this.sheetId=r,this.row=s,this.initialContent=this.getComposerContent({sheetId:r,col:n,row:s}),this.mode="editing",this.setContent(e||this.initialContent,t),this.colorIndexByRange={};const a=co({col:this.col,row:this.row});this.selection.capture(this,{cell:{col:this.col,row:this.row},zone:a},{handleEvent:this.handleEvent.bind(this),release:()=>{this.stopEdition()}})}stopEdition(){if("inactive"!==this.mode){this.cancelEditionAndActivateSheet();const e=this.col,t=this.row;let i=this.currentContent;if(!(this.initialContent!==i))return;if(i){const o=this.getters.getActiveSheetId(),n=this.getters.getEvaluatedCell({sheetId:o,col:this.col,row:this.row});if(i.startsWith("=")){const e=this.currentTokens.filter((e=>"LEFT_PAREN"===e.type)).length,t=this.currentTokens.filter((e=>"RIGHT_PAREN"===e.type)).length,o=e-t;o>0&&(i+=rt(new Array(o).fill(")")))}else n.link&&(i=Ke(i,n.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,col:e,row:t,content:i})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,content:"",col:e,row:t});this.setContent("")}}cancelEditionAndActivateSheet(){if("inactive"===this.mode)return;this.cancelEdition();this.getters.getActiveSheetId()!==this.sheetId&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}getComposerContent(e){const t=this.getters.getCell(e);if(null==t?void 0:t.isFormula)return t.content;const{format:i,value:o,type:n,formattedValue:s}=this.getters.getEvaluatedCell(e);switch(n){case cn.text:case cn.empty:return o;case cn.boolean:return s;case cn.error:return(null==t?void 0:t.content)||"";case cn.number:return i&&wi(i)?s:this.numberComposerContent(o,i)}}numberComposerContent(e,t){return(null==t?void 0:t.includes("%"))?100*e+"%":function(e){const{integerDigits:t,decimalDigits:i}=Ci(e,20);return i?`${t}.${i}`:t}(e)}cancelEdition(){"inactive"!==this.mode&&(this.mode="inactive",this.selection.release(this))}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,i){const o=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(o||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?bf(e):[],this.currentTokens.length>100&&i&&this.ui.notifyUI({type:"ERROR",text:s("This formula has over 100 parts. It can't be processed properly, consider splitting it into multiple cells")})),this.canStartComposerRangeSelection()&&this.startComposerRangeSelection()}insertSelectedRange(e){const t=Math.min(this.selectionStart,this.selectionEnd),i=this.getZoneReference(e);this.canStartComposerRangeSelection()?(this.insertText(i,t),this.selectionInitialStart=t):(this.insertText(","+i,t),this.selectionInitialStart=t+1)}replaceSelectedRanges(e){const t=this.getZoneReference(e);this.replaceText(t,this.selectionInitialStart,this.selectionEnd)}getZoneReference(e,t=[{colFixed:!1,rowFixed:!1}]){const i=this.getters.getActiveSheetId();let o=this.getters.zoneToXC(i,e,t);if(this.getters.getEditionSheet()!==this.getters.getActiveSheetId()){o=`${ke(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${o}`}return o}getRangeReference(e,t=[{colFixed:!1,rowFixed:!1}]){let i=[...t];1===t.length&&uo(e.zone)>1?i.push({...t[0]}):2===t.length&&1===uo(e.zone)&&i.pop();const o=e.clone({parts:i});return this.getters.getSelectionRangeString(o,this.getters.getEditionSheet())}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),i=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,i)}replaceText(e,t,i){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(i,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const i=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),o=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:i,selection:{start:o,end:o}})}updateRangeColor(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return;const e=this.getters.getEditionSheet(),t=this.getReferencedRanges().map((t=>this.getters.getRangeString(t,e))),i={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(i[e]=this.colorIndexByRange[e]);const o=new Set(Object.values(i));let n=0;const s=()=>{for(;o.has(n);)n++;return o.add(n),n};for(const e of t){const t=e in i?i[e]:s();i[e]=t}this.colorIndexByRange=i}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=this.getters.getEditionSheet(),t=e=>{const t=this.colorIndexByRange[e];return St[t%St.length]};return this.getReferencedRanges().map((i=>{const o=this.getters.getRangeString(i,e);return{zone:i.zone,color:t(o),sheetId:i.sheetId}}))}getReferencedRanges(){const e=this.getters.getEditionSheet();return this.currentTokens.filter((e=>"REFERENCE"===e.type)).map((t=>this.getters.getRangeFromSheetXC(e,t.value))).filter((e=>!e.invalidSheetName&&!e.invalidXc))}canStartComposerRangeSelection(){if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(!e)return!1;const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let i=t,o=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(o.type)||Nm.includes(o.value);){if("SPACE"!==o.type||i<1)return!1;i--,o=this.currentTokens[i]}for(i=t+1,o=this.currentTokens[i];o&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(o.type);){if("SPACE"!==o.type)return!1;i++,o=this.currentTokens[i]}return!0}return!1}getTokensInSelection(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return this.currentTokens.filter((i=>i.start<=e&&i.end>=e||i.start>=e&&i.start<t))}}Gb.getters=["getEditionMode","isSelectingForComposer","showSelectionIndicator","getCurrentContent","getEditionSheet","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights","getCurrentEditedCell"];const qb=[{name:s("Sum"),types:[cn.number],compute:e=>bl.compute([e])},{name:s("Avg"),types:[cn.number],compute:e=>Ml.compute([e])},{name:s("Min"),types:[cn.number],compute:e=>ql.compute([e])},{name:s("Max"),types:[cn.number],compute:e=>Hl.compute([e])},{name:s("Count"),types:[cn.number,cn.text,cn.boolean,cn.error],compute:e=>Pl.compute([e])},{name:s("Count Numbers"),types:[cn.number,cn.text,cn.boolean,cn.error],compute:e=>Ll.compute([e])}];class Zb extends Jv{constructor(e){super(e),this.gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]},this.selectedFigureId=null,this.sheetsData={},this.activeSheet=null,this.moveClient=e.moveClient}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{this.getters.getSheet(e.sheetIdTo);break}catch(e){return 27}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return 0}handleEvent(e){const t=e.anchor;let i=[];switch(e.mode){case"overrideSelection":i=[t.zone];break;case"updateAnchor":i=[...this.gridSelection.zones];const o=i.findIndex((t=>Ki(t,e.previousAnchor.zone)));o>=0&&(i[o]=t.zone);break;case"newAnchor":i=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,i),this.selection.resetDefaultAnchor(this,Fe(this.gridSelection.anchor));const{col:o,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:o,row:n}),this.selectedFigureId=null}handle(e){switch(e.type){case"START_EDITION":case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.dispatch("ACTIVATE_SHEET",{sheetIdTo:t,sheetIdFrom:t});const{col:i,row:o}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(i,o),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case"ACTIVATE_SHEET":if(this.getters.isSheetVisible(e.sheetIdTo)||this.dispatch("SHOW_SHEET",{sheetId:e.sheetIdTo}),this.setActiveSheet(e.sheetIdTo),this.sheetsData[e.sheetIdFrom]={gridSelection:Fe(this.gridSelection)},e.sheetIdTo in this.sheetsData)Object.assign(this,this.sheetsData[e.sheetIdTo]),this.selection.resetDefaultAnchor(this,Fe(this.gridSelection.anchor));else{const{col:t,row:i}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0});this.selectCell(t,i)}break;case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:i,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:i,row:o})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:i,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:i,row:o})}break}case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"SELECT_FIGURE":this.selectedFigureId=e.id;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":const n=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of n)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:Fe(t)}}if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:i})}const s=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(s,e))),this.gridSelection.anchor.zone=this.getters.expandZone(s,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones)}this.selection.resetDefaultAnchor(this,Fe(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){const e=new Set;for(let t of this.gridSelection.zones)if(0===t.top&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let i=t.left;i<=t.right;i++)e.add(i);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(let i of this.gridSelection.zones)if(0===i.left&&i.right===this.getters.getNumberCols(t)-1)for(let t=i.top;t<=i.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return Fe(this.gridSelection.zones)}getSelectedZone(){return Fe(this.gridSelection.anchor.zone)}getSelection(){return Fe(this.gridSelection)}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{const t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}getStatisticFnResults(){const e=this.getters.getActiveSheetId(),t=new Set;for(const i of this.gridSelection.zones)for(const{col:o,row:n}of so(i)){if(this.getters.isRowHidden(e,n)||this.getters.isColHidden(e,o))continue;const i=this.getters.getEvaluatedCell({sheetId:e,col:o,row:n});i.type!==cn.empty&&t.add(i)}let i=new Set,o=[];for(let e of t)i.add(e.type),o.push(e.value);let n={};for(let e of qb){let t;e.types.some((e=>i.has(e)))&&(t=e.compute(o)),n[e.name]=t}return n}getAggregate(){let e=0,t=0;const i=this.getters.getActiveSheetId(),o=this.gridSelection.zones.map(so).flat();for(const{col:n,row:s}of o){const o=this.getters.getEvaluatedCell({sheetId:i,col:n,row:s});o.type===cn.number&&(t++,e+=o.value)}return t<2?null:fi(e)}isSelected(e){return!!this.getters.getSelectedZones().find((t=>Ki(t,e)))}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 i=[];const o="COL"===e?"left":"top",n="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[n]-e[o]+1},((t,i)=>e[o]+i));i=i.concat(t)}return[...new Set(i)].sort()}setSelectionMixin(e,t){const{anchor:i,zones:o}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=i,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,i)=>t===i.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(o)}selectCell(e,t){const i=this.getters.getActiveSheetId(),o=this.getters.expandZone(i,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:o,cell:{col:e,row:t}},[o])}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){const t=this.getters.getSheetIds(),i=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[i]})}onColumnsRemoved(e){const{cell:t,zone:i}=this.gridSelection.anchor,o=Zi(i,"left",[...e.elements]);let n={left:t.col,right:t.col,top:t.row,bottom:t.row};n=Zi(n,"left",[...e.elements]);const s={cell:{col:n.left,row:n.top},zone:o};this.setSelectionMixin(s,[o])}onRowsRemoved(e){const{cell:t,zone:i}=this.gridSelection.anchor,o=Zi(i,"top",[...e.elements]);let n={left:t.col,right:t.col,top:t.row,bottom:t.row};n=Zi(n,"top",[...e.elements]);const s={cell:{col:n.left,row:n.top},zone:o};this.setSelectionMixin(s,[o])}onAddElements(e){const t=qi(this.gridSelection.anchor.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),i={cell:{col:t.left,row:t.top},zone:t};this.setSelectionMixin(i,[t])}onMoveElements(e){const t=e.elements.length;this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:e.position});const i="COL"===e.dimension,o=e.elements[0],n=e.elements[t-1],s=e.base<o,r=s&&i?t:0,a=s&&!i?t:0,l=[{left:i?o+r:0,right:i?n+r:this.getters.getNumberCols(e.sheetId)-1,top:i?0:o+a,bottom:i?this.getters.getNumberRows(e.sheetId)-1:n+a}],c=new kb(l,"CUT",this.getters,this.dispatch,this.selection),h=s?e.base:e.base+1,d=[{left:i?h:0,right:i?h+t-1:this.getters.getNumberCols(e.sheetId)-1,top:i?0:h,bottom:i?this.getters.getNumberRows(e.sheetId)-1:h+t-1}];c.paste(d,{selectTarget:!0});const u=s?e.elements.map((e=>e+t)):e.elements;let g=e.base;for(const t of u){const i="COL"===e.dimension?this.getters.getColSize(e.sheetId,t):this.getters.getRowSize(e.sheetId,t);this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:i,elements:[g]}),g+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:u})}isMoveElementAllowed(e){const t="COL"===e.dimension,i=e.elements[0],o=e.elements[e.elements.length-1],n=e.sheetId,s=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(s(n,i-1,i)||s(n,o,o+1)||s(n,e.base-1,e.base))return 2;const r=[e.base,...e.elements],a=t?this.getters.getNumberCols(n):this.getters.getNumberRows(n);return r.some((e=>e<0||e>=a))?87:0}clipSelection(e,t){const i=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:Le(e.left,0,i),right:Le(e.right,0,i),top:Le(e.top,0,o),bottom:Le(e.bottom,0,o)}))),anchor:{cell:{col:Le(t.anchor.cell.col,0,i),row:Le(t.anchor.cell.row,0,o)},zone:{left:Le(t.anchor.zone.left,0,i),right:Le(t.anchor.zone.right,0,i),top:Le(t.anchor.zone.top,0,o),bottom:Le(t.anchor.zone.bottom,0,o)}}}}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:i}=e,o=this.getSelectedZones();t.fillStyle="#f3f7fe";const n=1===o.length&&o[0].left===o[0].right&&o[0].top===o[0].bottom;t.fillStyle=n?"#f3f7fe":"#e9f0ff",t.strokeStyle=E,t.lineWidth=1.5*i;for(const e of o){const{x:i,y:o,width:n,height:s}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(i,o,n,s),t.globalCompositeOperation="source-over",t.strokeRect(i,o,n,s)}t.globalCompositeOperation="source-over";const s=this.getActivePosition();let r;t.strokeStyle=E,t.lineWidth=3*i,r=this.getters.isInMerge(s)?this.getters.getMerge(s):co(s);const{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);c>0&&h>0&&t.strokeRect(a,l,c,h)}}Zb.layers=[6],Zb.getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getStatisticFnResults","getAggregate","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSelected","getElementsFromSelection","isGridSelectionActive"];const jb=(new Ro).add("sheet",Qv).add("header visibility",qv).add("filters",Wv).add("cell",Pv).add("merge",jv).add("headerSize",Gv).add("borders",Lv).add("conditional formatting",zv).add("figures",Bv).add("chart",Uv).add("image",Zv),Yb=(new Ro).add("ui_sheet",Fb).add("header_visibility_ui",pb).add("ui_options",_b).add("selectionInputManager",bb).add("highlight",mb).add("grid renderer",fb).add("autofill",cb).add("find_and_replace",gb).add("sort",Nb).add("automatic_sum",hb).add("format",class extends Jv{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,i){for(const o of t)for(const t of so(o)){const o=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==o){const n=Mi(o,i);this.dispatch("SET_FORMATTING",{sheetId:e,target:[co(t)],format:n})}}}getCellNumberFormat(e){var t;for(const i of[e]){const e=this.getters.getEvaluatedCell(i);if(e.type===cn.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(X)))return e.format||Ri(e.value)}}}).add("cell_popovers",db).add("selection_multiuser",Ob),Xb=(new Ro).add("selection",Zb).add("clipboard",zb).add("edition",Gb),Kb=(new Ro).add("evaluation",ib).add("evaluation_filter",sb).add("evaluation_chart",ob).add("evaluation_cf",nb).add("viewport",ab).add("custom_colors",eb),Qb=new Ro;Qb.add("link",{condition:(e,t)=>!!t.model.getters.getEvaluatedCell(e).link,action:(e,t)=>Fo(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});class Jb{constructor(e){this.fileStore=e}async requestImage(){const e=await this.getImageFromUser(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageSize(t),mimetype:e.type}}getImageFromUser(){return new Promise(((e,t)=>{const i=document.createElement("input");i.setAttribute("type","file"),i.setAttribute("accept","image/*"),i.addEventListener("change",(async()=>{null===i.files||1!=i.files.length?t():e(i.files[0])})),i.click()}))}getImageSize(e){return new Promise(((t,i)=>{const o=new Image;o.src=e,o.addEventListener("load",(()=>{const e={width:o.width,height:o.height};t(e)})),o.addEventListener("error",i)}))}}const eC=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];vo`
1401
1401
  .o-ripple {
1402
1402
  z-index: 1;
1403
1403
  }
@@ -1899,7 +1899,7 @@
1899
1899
  }
1900
1900
  }
1901
1901
  }
1902
- `;class fC extends t.Component{constructor(){super(...arguments),this.commonFormats=gC,this.customFormats=pC,this.currentFormatName="automatic",this.style={},this.state=t.useState({menuState:{isOpen:!1,position:null,menuItems:[]},activeTool:""}),this.isSelectingMenu=!1,this.openedEl=null,this.inMerge=!1,this.cannotMerge=!1,this.undoTool=!1,this.redoTool=!1,this.paintFormatTool=!1,this.fillColor="#ffffff",this.textColor="#000000",this.menus=[]}get dropdownStyle(){return`max-height:${this.props.dropdownMaxHeight}px`}setup(){t.useExternalListener(window,"click",this.onExternalClick),t.onWillStart((()=>this.updateCellState())),t.onWillUpdateProps((()=>this.updateCellState()))}get topbarComponents(){return Lg.getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}toggleStyle(e){zr(this.env,{[e]:!this.style[e]})}toggleFormat(e){const t=gC.find((t=>t.name===e)),i=t&&t.value||"";Vr(this.env,i)}toggleHorizontalAlign(e){zr(this.env,{align:e}),this.onClick()}toggleVerticalAlign(e){zr(this.env,{verticalAlign:e}),this.onClick()}toggleTextWrapping(e){zr(this.env,{wrapping:e}),this.onClick()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.openMenu(e,t)}toggleDropdownTool(e,t){const i=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=i?"":e,this.openedEl=i?null:t.target}toggleContextMenu(e,t){this.state.menuState.isOpen?this.closeMenus():this.openMenu(e,t)}openMenu(e,t){const{left:i,top:o,height:n}=t.target.getBoundingClientRect();this.state.menuState.isOpen=!0,this.state.menuState.position={x:i,y:o+n},this.state.menuState.menuItems=e.children(this.env),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.env.model.dispatch("STOP_EDITION")}closeMenus(){this.state.activeTool="",this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){const e=this.env.model.getters.getSelectedZones(),{col:t,row:i,sheetId:o}=this.env.model.getters.getActivePosition();this.inMerge=!1;const{top:n,left:s,right:r,bottom:a}=this.env.model.getters.getSelectedZone(),{xSplit:l,ySplit:c}=this.env.model.getters.getPaneDivisions(o);if(this.cannotMerge=e.length>1||n===a&&s===r||s<l&&l<=r||n<c&&c<=a,!this.cannotMerge){const n=this.env.model.getters.expandZone(o,co({col:t,row:i}));this.inMerge=Ki(e[0],n)}this.undoTool=this.env.model.getters.canUndo(),this.redoTool=this.env.model.getters.canRedo(),this.paintFormatTool=this.env.model.getters.isPaintingFormat();const h=this.env.model.getters.getActiveCell();if(h.format){const e=this.commonFormats.find((e=>e.value===h.format));this.currentFormatName=e?e.name:""}else this.currentFormatName="automatic";this.style={...this.env.model.getters.getCurrentStyle()},this.style.align=this.style.align||h.defaultAlign,this.fillColor=this.style.fillColor||"#ffffff",this.textColor=this.style.textColor||"#000000",this.menus=ng.getMenuItems()}getMenuName(e){return e.name(this.env)}toggleMerge(){if(this.cannotMerge)return;const e=this.env.model.getters.getSelectedZones(),t=[e[e.length-1]],i=this.env.model.getters.getActiveSheetId();this.inMerge?this.env.model.dispatch("REMOVE_MERGE",{sheetId:i,target:t}):function(e,t,i){const o=e.model.dispatch("ADD_MERGE",{sheetId:t,target:i});o.isCancelledBecause(80)?e.raiseError(hC.MergeInFilter):o.isCancelledBecause(3)&&e.askConfirmation(hC.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:i,force:!0})}))}(this.env,i,t)}setColor(e,t){zr(this.env,{[e]:t}),this.onClick()}setBorder(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),border:e}),this.onClick()}setFormat(e,t){t?this.openCustomFormatSidePanel(e):this.toggleFormat(e),this.onClick()}openCustomFormatSidePanel(e){const t=pC.find((t=>t.name===e)),i=t&&t.sidePanel||"";this.env.openSidePanel(i)}setDecimal(e){this.env.model.dispatch("SET_DECIMAL",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),step:e})}paintFormat(){this.env.model.dispatch("ACTIVATE_PAINT_FORMAT",{target:this.env.model.getters.getSelectedZones()})}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}doAction(e){e(this.env),this.closeMenus()}undo(){this.env.model.dispatch("REQUEST_UNDO")}redo(){this.env.model.dispatch("REQUEST_REDO")}get selectionContainsFilter(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones();return this.env.model.getters.doesZonesContainFilter(e,t)}get cannotCreateFilter(){return!go(...this.env.model.getters.getSelectedZones())}createFilter(){if(this.cannotCreateFilter)return;this.env.model.selection.selectTableAroundSelection();const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones();_r(this.env,e,t)}removeFilter(){this.env.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}}fC.template="o-spreadsheet-TopBar",fC.components={ColorPickerWidget:vg,Menu:is,TopBarComposer:dC,FontSizeEditor:uC},fC.props={onClick:Function,focusComposer:String,onComposerContentFocused:Function,dropdownMaxHeight:Number};class vC{constructor(e){this.clipboard=e}async write(e){var t;try{null===(t=this.clipboard)||void 0===t||t.write(this.getClipboardItems(e))}catch(e){}}async writeText(e){var t;try{null===(t=this.clipboard)||void 0===t||t.writeText(e)}catch(e){}}async readText(){let e;try{e=await navigator.permissions.query({name:"clipboard-read"})}catch(e){}try{return{status:"ok",content:await this.clipboard.readText()}}catch(t){return{status:"denied"===(null==e?void 0:e.state)?"permissionDenied":"notImplemented"}}}getClipboardItems(e){return[new ClipboardItem({[hn.PlainText]:this.getBlob(e,hn.PlainText),[hn.Html]:this.getBlob(e,hn.Html)})]}getBlob(e,t){return new Blob([e[t]||""],{type:t})}}vo`
1902
+ `;class fC extends t.Component{constructor(){super(...arguments),this.commonFormats=gC,this.customFormats=pC,this.currentFormatName="automatic",this.style={},this.state=t.useState({menuState:{isOpen:!1,position:null,menuItems:[]},activeTool:""}),this.isSelectingMenu=!1,this.openedEl=null,this.inMerge=!1,this.cannotMerge=!1,this.undoTool=!1,this.redoTool=!1,this.paintFormatTool=!1,this.fillColor="#ffffff",this.textColor="#000000",this.menus=[]}get dropdownStyle(){return`max-height:${this.props.dropdownMaxHeight}px`}setup(){t.useExternalListener(window,"click",this.onExternalClick),t.onWillStart((()=>this.updateCellState())),t.onWillUpdateProps((()=>this.updateCellState()))}get topbarComponents(){return Lg.getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}toggleStyle(e){zr(this.env,{[e]:!this.style[e]})}toggleFormat(e){const t=gC.find((t=>t.name===e)),i=t&&t.value||"";Vr(this.env,i)}toggleHorizontalAlign(e){zr(this.env,{align:e}),this.onClick()}toggleVerticalAlign(e){zr(this.env,{verticalAlign:e}),this.onClick()}toggleTextWrapping(e){zr(this.env,{wrapping:e}),this.onClick()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.openMenu(e,t)}toggleDropdownTool(e,t){const i=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=i?"":e,this.openedEl=i?null:t.target}toggleContextMenu(e,t){this.state.menuState.isOpen?this.closeMenus():this.openMenu(e,t)}openMenu(e,t){const{left:i,top:o,height:n}=t.target.getBoundingClientRect();this.state.menuState.isOpen=!0,this.state.menuState.position={x:i,y:o+n},this.state.menuState.menuItems=e.children(this.env),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.env.model.dispatch("STOP_EDITION")}closeMenus(){this.state.activeTool="",this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){const e=this.env.model.getters.getSelectedZones(),{col:t,row:i,sheetId:o}=this.env.model.getters.getActivePosition();this.inMerge=!1;const{top:n,left:s,right:r,bottom:a}=this.env.model.getters.getSelectedZone(),{xSplit:l,ySplit:c}=this.env.model.getters.getPaneDivisions(o);if(this.cannotMerge=e.length>1||n===a&&s===r||s<l&&l<=r||n<c&&c<=a,!this.cannotMerge){const n=this.env.model.getters.expandZone(o,co({col:t,row:i}));this.inMerge=Ki(e[0],n)}this.undoTool=this.env.model.getters.canUndo(),this.redoTool=this.env.model.getters.canRedo(),this.paintFormatTool=this.env.model.getters.isPaintingFormat();const h=this.env.model.getters.getActiveCell();if(h.format){const e=this.commonFormats.find((e=>e.value===h.format));this.currentFormatName=e?e.name:""}else this.currentFormatName="automatic";this.style={...this.env.model.getters.getCurrentStyle()},this.style.align=this.style.align||h.defaultAlign,this.fillColor=this.style.fillColor||"#ffffff",this.textColor=this.style.textColor||"#000000",this.menus=ng.getMenuItems()}getMenuName(e){return e.name(this.env)}toggleMerge(){if(this.cannotMerge)return;const e=this.env.model.getters.getSelectedZones(),t=[e[e.length-1]],i=this.env.model.getters.getActiveSheetId();this.inMerge?this.env.model.dispatch("REMOVE_MERGE",{sheetId:i,target:t}):function(e,t,i){const o=e.model.dispatch("ADD_MERGE",{sheetId:t,target:i});o.isCancelledBecause(81)?e.raiseError(hC.MergeInFilter):o.isCancelledBecause(3)&&e.askConfirmation(hC.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:i,force:!0})}))}(this.env,i,t)}setColor(e,t){zr(this.env,{[e]:t}),this.onClick()}setBorder(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),border:e}),this.onClick()}setFormat(e,t){t?this.openCustomFormatSidePanel(e):this.toggleFormat(e),this.onClick()}openCustomFormatSidePanel(e){const t=pC.find((t=>t.name===e)),i=t&&t.sidePanel||"";this.env.openSidePanel(i)}setDecimal(e){this.env.model.dispatch("SET_DECIMAL",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),step:e})}paintFormat(){this.env.model.dispatch("ACTIVATE_PAINT_FORMAT",{target:this.env.model.getters.getSelectedZones()})}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}doAction(e){e(this.env),this.closeMenus()}undo(){this.env.model.dispatch("REQUEST_UNDO")}redo(){this.env.model.dispatch("REQUEST_REDO")}get selectionContainsFilter(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones();return this.env.model.getters.doesZonesContainFilter(e,t)}get cannotCreateFilter(){return!go(...this.env.model.getters.getSelectedZones())}createFilter(){if(this.cannotCreateFilter)return;this.env.model.selection.selectTableAroundSelection();const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones();_r(this.env,e,t)}removeFilter(){this.env.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}}fC.template="o-spreadsheet-TopBar",fC.components={ColorPickerWidget:vg,Menu:is,TopBarComposer:dC,FontSizeEditor:uC},fC.props={onClick:Function,focusComposer:String,onComposerContentFocused:Function,dropdownMaxHeight:Number};class vC{constructor(e){this.clipboard=e}async write(e){var t;try{null===(t=this.clipboard)||void 0===t||t.write(this.getClipboardItems(e))}catch(e){}}async writeText(e){var t;try{null===(t=this.clipboard)||void 0===t||t.writeText(e)}catch(e){}}async readText(){let e;try{e=await navigator.permissions.query({name:"clipboard-read"})}catch(e){}try{return{status:"ok",content:await this.clipboard.readText()}}catch(t){return{status:"denied"===(null==e?void 0:e.state)?"permissionDenied":"notImplemented"}}}getClipboardItems(e){return[new ClipboardItem({[hn.PlainText]:this.getBlob(e,hn.PlainText),[hn.Html]:this.getBlob(e,hn.Html)})]}getBlob(e,t){return new Blob([e[t]||""],{type:t})}}vo`
1903
1903
  .o-spreadsheet {
1904
1904
  position: relative;
1905
1905
  display: grid;
@@ -1972,7 +1972,7 @@
1972
1972
  outline: none;
1973
1973
  }
1974
1974
  }
1975
- `;class bC extends t.Component{constructor(){super(...arguments),this.isViewportTooSmall=!1}get model(){return this.props.model}getStyle(){return this.env.isDashboard()?"grid-template-rows: auto;":"grid-template-rows: 63px auto 37px"}setup(){this.sidePanel=t.useState({isOpen:!1,panelProps:{}}),this.composer=t.useState({topBarFocus:"inactive",gridFocusMode:"inactive"}),this.keyDownMapping={"CTRL+H":()=>this.toggleSidePanel("FindAndReplace",{}),"CTRL+F":()=>this.toggleSidePanel("FindAndReplace",{})};const e=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:e?new Jb(e):void 0,loadCurrencies:this.model.config.external.loadCurrencies,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.openSidePanel.bind(this),toggleSidePanel:this.toggleSidePanel.bind(this),_t:bC._t,clipboard:this.env.clipboard||new vC(navigator.clipboard),startCellEdition:e=>this.onGridComposerCellFocused(e)}),t.useExternalListener(window,"resize",(()=>this.render(!0))),t.useExternalListener(window,"beforeunload",this.unbindModelEvents.bind(this)),this.bindModelEvents(),t.onMounted((()=>{this.checkViewportSize()})),t.onWillUnmount((()=>this.unbindModelEvents())),t.onPatched((()=>{this.checkViewportSize()}))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}bindModelEvents(){this.model.on("update",this,(()=>this.render(!0))),this.model.on("notify-ui",this,this.onNotifyUI)}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.env.notifyUser({text:s("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),tag:"viewportTooSmall"}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}onNotifyUI(e){if("ERROR"===e.type)this.env.raiseError(e.text)}openSidePanel(e,t){this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.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()}onKeydown(e){let t="";Zn(e)&&(t+="CTRL+"),t+=e.key.toUpperCase();let i=this.keyDownMapping[t];if(i)return e.preventDefault(),e.stopPropagation(),void i()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}||{}))}onGridComposerContentFocused(){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent({}))}onGridComposerCellFocused(e,t){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent({content:e,selection:t}||{}))}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})}get gridHeight(){const{height:e}=this.env.model.getters.getSheetViewDimension();return e}}bC.template="o-spreadsheet-Spreadsheet",bC.components={TopBar:fC,Grid:wp,BottomBar:rC,SidePanel:cC,SpreadsheetDashboard:lC},bC._t=e=>e,bC.props={model:Object};class CC{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))}}function SC(e){return xr.get(e.type)(e)}function EC(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class wC{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 i of this.operations){if(i.id===e)return e;if(i.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 i=this.buildTransformation.with(e.data),{before:o,operation:n,after:s}=this.locateOperation(t);this.operations=[...o,n,e,...s.map((e=>e.transformed(i)))]}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 wC(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:i}=this.locateOperation(e);this.operations=t.concat([i])}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 yC{constructor(e,t){this.id=e,this.data=t}transformed(e){return new xC(this.id,at((()=>e(this.data))))}}class xC{constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new xC(this.id,this.lazyData.map(e))}}class IC{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new IC(function*(e,t){for(const i of e)if(yield i,i.operation.id===t)return}(this.operations,e))}stopBefore(e){return new IC(function*(e,t){for(const i of e){if(i.operation.id===t)return;yield i}}(this.operations,e))}startAfter(e){return new IC(function*(e,t){let i=!0;for(const o of e)i||(yield o),o.operation.id===t&&(i=!1)}(this.operations,e))}}class RC{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 IC(Ge(this._execution(e),this._execution(e)))}revertedExecution(e){return new IC(Ge(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){var i;const o=e.getLastOperationId()||(null===(i=this.previousBranch(e))||void 0===i?void 0:i.getLastOperationId());e.append(t),o&&this.insertPrevious(e,t,o)}insertOperationAfter(e,t,i){e.insert(t,i),this.updateNextWith(e,t,i),this.insertPrevious(e,t,i)}undo(e,t){const i=this.buildTransformation.without(t.data),o=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const n=e.fork(t.id);o&&this.branchingOperationIds.set(n,o),this.insertBranchAfter(e,n),this.transform(n,i)}redo(e){const t=this.nextBranch(e);if(!t)return;const i=this.nextBranch(t);this.removeBranchFromTree(t);const o=this.branchingOperationIds.get(t);o?this.branchingOperationIds.set(e,o):this.branchingOperationIds.delete(e),i&&this.rebaseUp(i)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const i of this.revertedExecution(e))if(i.operation.id===t)return i;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!t||!i)return;const o=this.buildTransformation.without(i.data),n=t.fork(i.id);this.branchingOperationIds.set(n,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,n),n.transform(o);const s=this.nextBranch(n);s&&this.rebaseUp(s)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const i=this.branches.findIndex((t=>t===e));this.branches.splice(i+1,0,t)}updateNextWith(e,t,i){const o=this.branchingOperationIds.get(e),n=this.nextBranch(e);if(o&&n)if(e.getFirstOperationAmong(i,o)===o){const s=this.addToNextBranch(e,n,o,t,i);this.updateNextWith(n,s,i)}else{const e=this.buildTransformation.with(t.data);this.transform(n,e)}}addToNextBranch(e,t,i,o,n){let s=o;return n===i?(s=this.getTransformedOperation(e,i,o),t.prepend(s)):t.contains(n)?(s=this.getTransformedOperation(e,i,o),t.insert(s,n)):t.append(o),s}getTransformedOperation(e,t,i){const o=e.getOperation(t),n=this.buildTransformation.without(o.data);return i.transformed(n)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const i=this.nextBranch(e);i&&this.transform(i,t)}insertPrevious(e,t,i){const{previousBranch:o,branchingOperation:n}=this.findPreviousBranchingOperation(e);if(!o||!n)return;const s=this.buildTransformation.with(n.data),r=e.fork(i);r.transform(s),o.cutAfter(i),o.appendBranch(r);const a=t.transformed(s);this.insertPrevious(o,a,i)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const i=this.branchingOperationIds.get(t);return i?{previousBranch:t,branchingOperation:t.getOperation(i)}:{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 i=!!t;const o=e.getOperations();for(let n=o.length-1;n>=0;n--){const s=o[n];s.id===t&&(i=!1),i||(yield{operation:s,branch:e,isCancelled:!this.shouldExecute(e,s)})}const n=this.previousBranch(e);yield*n?this._revertedExecution(n):[]}*_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 TC{constructor(e,t,i,o,n){this.applyOperation=t,this.revertOperation=i,this.buildEmpty=o,this.buildTransformation=n,this.HEAD_BRANCH=new wC(this.buildTransformation),this.tree=new RC(n,this.HEAD_BRANCH);const s=new yC(e,o(e));this.tree.insertOperationLast(this.HEAD_BRANCH,s),this.HEAD_OPERATION=s}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const i=new yC(e,t),o=this.tree.getLastBranch();this.tree.insertOperationLast(o,i),this.HEAD_BRANCH=o,this.HEAD_OPERATION=i}insert(e,t,i){const o=new yC(e,t);this.revertTo(i),this.tree.insertOperationAfter(this.HEAD_BRANCH,o,i),this.fastForward()}undo(e,t,i){const{branch:o,operation:n}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(o,n),this.fastForward(),this.insert(t,this.buildEmpty(t),i)}redo(e,t,i){const{branch:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(o),this.fastForward(),this.insert(t,this.buildEmpty(t),i)}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:i,isCancelled:o}of e)o||this.revertOperation(i.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:i,isCancelled:o}of e)o||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=i}}function AC(e,t,i){return new TC(e,(e=>{const o=e.commands.slice(),{changes:n}=t((()=>{for(const e of o)i(e)}));e.setChanges(n)}),(e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){MC(t.changes[e],"before")}}([e])),(e=>new Rb(e,"empty",[],[])),{with:e=>t=>new Rb(t.id,t.clientId,xb(t.commands,e.commands)),without:e=>t=>new Rb(t.id,t.clientId,xb(t.commands,e.commands.map(SC).flat()))})}function MC(e,t){let i=e.path[0];const o=e.path[e.path.length-1];for(let t=1;t<e.path.slice(0,-1).length;t++){const o=e.path[t];if(void 0===i[o]){const n=e.path[t+1];i[o]=EC(n)}i=i[o]}void 0===e[t]?delete i[o]:i[o]=e[t]}class OC extends t.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 NC{constructor(){this.observers=[]}registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.push({owner:e,callbacks:t})}capture(e,t){var i,o,n;if(this.observers.find((t=>t.owner===e)))throw new Error("You are already subscribed forever");(null===(i=this.mainSubscription)||void 0===i?void 0:i.owner)&&this.mainSubscription.owner!==e&&(null===(n=(o=this.mainSubscription.callbacks).release)||void 0===n||n.call(o)),this.mainSubscription={owner:e,callbacks:t}}release(e){var t;(null===(t=this.mainSubscription)||void 0===t?void 0:t.owner)!==e||this.observers.find((t=>t.owner===e))||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){var e,t,i;this.mainSubscription!==this.defaultSubscription&&(null===(i=null===(e=this.mainSubscription)||void 0===e?void 0:(t=e.callbacks).release)||void 0===i||i.call(t),this.mainSubscription=this.defaultSubscription)}isListening(e){var t;return(null===(t=this.mainSubscription)||void 0===t?void 0:t.owner)===e}send(e){var t;null===(t=this.mainSubscription)||void 0===t||t.callbacks.handleEvent(e),[...this.observers].forEach((t=>t.callbacks.handleEvent(e)))}}class _C{constructor(e){this.getters=e,this.stream=new NC,this.anchor={cell:{col:0,row:0},zone:co({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,i){this.stream.capture(e,i),this.anchor=t}registerAsDefault(e,t,i){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,i),this.defaultAnchor=t,this.capture(e,t,i)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}selectZone(e){return this.modifyAnchor(e,"overrideSelection","ZonesSelected")}modifyAnchor(e,t,i){const o=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(o,e.zone)},this.processEvent({type:i,anchor:e,mode:t})}selectCell(e,t){const i=co({col:e,row:t});return this.selectZone({zone:i,cell:{col:e,row:t}})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new fn(83);const{col:i,row:o}=this.getNextAvailablePosition(e,t);return this.selectCell(i,o)}setAnchorCorner(e,t){const i=this.getters.getActiveSheetId(),{col:o,row:n}=this.anchor.cell,s={left:Math.min(o,e),top:Math.min(n,t),right:Math.max(o,e),bottom:Math.max(n,t)},r={zone:this.getters.expandZone(i,s),cell:{col:o,row:n}};return this.processEvent({type:"AlterZone",mode:"updateAnchor",anchor:r})}addCellToSelection(e,t){const i=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:i,col:e,row:t}));const o=this.getters.expandZone(i,co({col:e,row:t}));return this.processEvent({type:"ZonesSelected",anchor:{zone:o,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new fn(83);const i=this.getters.getActiveSheetId(),o=this.anchor,{col:n,row:s}=o.cell,{left:r,right:a,top:l,bottom:c}=o.zone,h=this.getStartingPosition(e);let[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return fn.Success;let g=o.zone;const p=e=>{e=lo(e);const{left:t,right:o,top:n,bottom:s}=this.getters.expandZone(i,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(i)-1,o),top:Math.max(0,n),bottom:Math.min(this.getters.getNumberRows(i)-1,s)}},{col:m,row:f}=this.getReferencePosition();let v=0;for(;null!==g;){if(v++,d<0){const e=this.getNextAvailableCol(d,a-(v-1),f);g=m<=a-v?p({top:l,left:r,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,r+(v-1),f);g=r+v<=m?p({top:l,left:e,bottom:c,right:a}):null}if(u<0){const e=this.getNextAvailableRow(u,m,c-(v-1));g=f<=c-v?p({top:l,left:r,bottom:e,right:a}):null}if(u>0){const e=this.getNextAvailableRow(u,m,l+(v-1));g=l+v<=f?p({top:e,left:r,bottom:c,right:a}):null}if(g=g?lo(g):g,g&&!Ki(g,o.zone))return this.processEvent({type:"ZonesSelected",mode:"updateAnchor",anchor:{zone:g,cell:{col:n,row:s}}})}g=p(Yi({top:s,bottom:s,left:n,right:n},lo({top:this.getNextAvailableRow(u,m,l),left:this.getNextAvailableCol(d,r,f),bottom:this.getNextAvailableRow(u,m,c),right:this.getNextAvailableCol(d,a,f)})));const b={zone:g,cell:{col:n,row:s}};return this.processEvent({type:"ZonesSelected",anchor:b,mode:"updateAnchor"})}selectColumn(e,t){const i=this.getters.getActiveSheetId(),o=this.getters.getNumberRows(i)-1;let n={left:e,right:e,top:0,bottom:o};const s=this.getters.findFirstVisibleColRowIndex(i,"ROW");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=e,a=s;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),n=Yi(n,{left:r,right:r,top:s,bottom:o})}return this.processEvent({type:"HeadersSelected",anchor:{zone:n,cell:{col:r,row:a}},mode:t})}selectRow(e,t){const i=this.getters.getActiveSheetId(),o=this.getters.getNumberCols(i)-1;let n={top:e,bottom:e,left:0,right:o};const s=this.getters.findFirstVisibleColRowIndex(i,"COL");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=s,a=e;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),n=Yi(n,{left:s,right:o,top:a,bottom:a})}return this.processEvent({type:"HeadersSelected",anchor:{zone:n,cell:{col:r,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(Ki(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:co(t.cell)},"updateAnchor","AlterZone");const i=this.expandZoneToTable(t.zone);return ht(i,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:i},"updateAnchor","AlterZone")}selectTableAroundSelection(){const e=this.expandZoneToTable(this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:e},"updateAnchor","AlterZone")}selectAll(){const e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({type:"HeadersSelected",mode:"overrideSelection",anchor:{zone:t,cell:this.anchor.cell}})}isListening(e){return this.stream.isListening(e)}processEvent(e){const t={...e,previousAnchor:Fe(this.anchor)},i=this.checkEventAnchorZone(t);return 0!==i?new fn(i):(this.anchor=t.anchor,this.stream.send(t),fn.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:i}=e;if(!Ji(t.col,t.row,i))return 16;const{left:o,right:n,top:s,bottom:r}=i,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",o,n);return void 0===this.getters.findVisibleHeader(a,"ROW",s,r)||void 0===l?17:0}checkAnchorZoneOrThrow(e){if(16===this.checkAnchorZone(e))throw new Error(n("The provided anchor is invalid. The cell must be part of the zone."))}getNextAvailablePosition(e,t=1){const{col:i,row:o}=this.anchor.cell,n=this.deltaToTarget({col:i,row:o},e,t);return{col:this.getNextAvailableCol(n[0],i,o),row:this.getNextAvailableRow(n[1],i,o)}}getNextAvailableCol(e,t,i){const o=this.getters.getActiveSheetId(),n={col:t,row:i};return this.getNextAvailableHeader(e,"COL",t,n,(e=>this.getters.isInSameMerge(o,t,i,e,i)))}getNextAvailableRow(e,t,i){const o=this.getters.getActiveSheetId(),n={col:t,row:i};return this.getNextAvailableHeader(e,"ROW",i,n,(e=>this.getters.isInSameMerge(o,t,i,t,e)))}getNextAvailableHeader(e,t,i,o,n){const s=this.getters.getActiveSheetId();if(0===e)return i;const r=Math.sign(e);let a=i+e;for(;n(a);)a+=r;for(;this.getters.isHeaderHidden(s,t,a);)a+=r;return a<0||a>this.getters.getNumberHeaders(s,t)-1?this.getters.isHeaderHidden(s,t,i)?this.getNextAvailableHeader(-r,t,i,o,n):i:a}getReferencePosition(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:i,right:o,top:n,bottom:s}=t.zone,{col:r,row:a}=t.cell;return{col:this.getters.isColHidden(e,r)&&this.getters.findVisibleHeader(e,"COL",i,o)||r,row:this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",n,s)||a}}deltaToTarget(e,t,i){switch(t){case"up":return"end"!==i?[0,-i]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==i?[0,i]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==i?[-i,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==i?[i,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:i}=this.getPosition();const o=this.anchor.zone;switch(e){case"down":case"up":i=i===o.top?o.bottom:o.top;break;case"left":case"right":t=t===o.right?o.left:o.right}return{col:t,row:i}}getEndOfCluster(e,t,i){const o=this.getters.getActiveSheet();let n=e;const s=this.getNextCellPosition(e,t,i);let r=this.isCellEmpty(n,o.id)||this.isCellEmpty(s,o.id)?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(n,t,i);if(n.col===e.col&&n.row===e.row)break;const s=this.isCellEmpty(e,o.id);if("endOfCluster"===r&&s)break;if("nextCluster"===r&&!s){n=e;break}n=e}return"cols"===t?n.col:n.row}isCellEmpty({col:e,row:t},i=this.getters.getActiveSheetId()){const o=this.getters.getMainCellPosition({sheetId:i,col:e,row:t});return this.getters.getEvaluatedCell(o).type===cn.empty}getNextCellPosition(e,t,i){const o="cols"===t?"col":"row",n={...e},s="cols"===t?this.getNextAvailableCol(i,n.col,n.row):this.getNextAvailableRow(i,n.col,n.row);return n[o]=s,{col:n.col,row:n.row}}getPosition(){return{...this.anchor.cell}}expandZoneToTable(e){const t=e=>{for(const t of $e(e.left,e.right+1)){if(!this.isCellEmpty({col:t,row:e.top-1}))return{...e,top:e.top-1};if(!this.isCellEmpty({col:t,row:e.bottom+1}))return{...e,bottom:e.bottom+1}}for(const t of $e(e.top,e.bottom+1)){if(!this.isCellEmpty({col:e.left-1,row:t}))return{...e,left:e.left-1};if(!this.isCellEmpty({col:e.right+1,row:t}))return{...e,right:e.right+1}}return e};let i=!1,o=e;do{i=!1;const e=t(o);Ki(o,e)||(i=!0,o=e)}while(i);return o}}class FC{constructor(){this.changes=[],this.commands=[]}recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop();let i=e[0],o=e[e.length-1];const n=e.length-2;for(let t=1;t<=n;t++){const o=e[t];if(void 0===i[o]){const n=e[t+1];i[o]=EC(n)}i=i[o]}i[o]!==t&&(this.changes.push({path:e,before:i[o],after:t}),void 0===t?delete i[o]:i[o]=t)}}const DC=17781237,kC=88853993;function LC(e,t,i){const o=[["xmlns:r",_p],["xmlns:a",Ap],["xmlns:c",Mp]],n=PC({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let s=av``;e.data.title&&(s=av`
1975
+ `;class bC extends t.Component{constructor(){super(...arguments),this.isViewportTooSmall=!1}get model(){return this.props.model}getStyle(){return this.env.isDashboard()?"grid-template-rows: auto;":"grid-template-rows: 63px auto 37px"}setup(){this.sidePanel=t.useState({isOpen:!1,panelProps:{}}),this.composer=t.useState({topBarFocus:"inactive",gridFocusMode:"inactive"}),this.keyDownMapping={"CTRL+H":()=>this.toggleSidePanel("FindAndReplace",{}),"CTRL+F":()=>this.toggleSidePanel("FindAndReplace",{})};const e=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:e?new Jb(e):void 0,loadCurrencies:this.model.config.external.loadCurrencies,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.openSidePanel.bind(this),toggleSidePanel:this.toggleSidePanel.bind(this),_t:bC._t,clipboard:this.env.clipboard||new vC(navigator.clipboard),startCellEdition:e=>this.onGridComposerCellFocused(e)}),t.useExternalListener(window,"resize",(()=>this.render(!0))),t.useExternalListener(window,"beforeunload",this.unbindModelEvents.bind(this)),this.bindModelEvents(),t.onMounted((()=>{this.checkViewportSize()})),t.onWillUnmount((()=>this.unbindModelEvents())),t.onPatched((()=>{this.checkViewportSize()}))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}bindModelEvents(){this.model.on("update",this,(()=>this.render(!0))),this.model.on("notify-ui",this,this.onNotifyUI)}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.env.notifyUser({text:s("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),tag:"viewportTooSmall"}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}onNotifyUI(e){if("ERROR"===e.type)this.env.raiseError(e.text)}openSidePanel(e,t){this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.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()}onKeydown(e){let t="";Zn(e)&&(t+="CTRL+"),t+=e.key.toUpperCase();let i=this.keyDownMapping[t];if(i)return e.preventDefault(),e.stopPropagation(),void i()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}||{}))}onGridComposerContentFocused(){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent({}))}onGridComposerCellFocused(e,t){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent({content:e,selection:t}||{}))}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})}get gridHeight(){const{height:e}=this.env.model.getters.getSheetViewDimension();return e}}bC.template="o-spreadsheet-Spreadsheet",bC.components={TopBar:fC,Grid:wp,BottomBar:rC,SidePanel:cC,SpreadsheetDashboard:lC},bC._t=e=>e,bC.props={model:Object};class CC{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))}}function SC(e){return xr.get(e.type)(e)}function EC(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class wC{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 i of this.operations){if(i.id===e)return e;if(i.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 i=this.buildTransformation.with(e.data),{before:o,operation:n,after:s}=this.locateOperation(t);this.operations=[...o,n,e,...s.map((e=>e.transformed(i)))]}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 wC(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:i}=this.locateOperation(e);this.operations=t.concat([i])}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 yC{constructor(e,t){this.id=e,this.data=t}transformed(e){return new xC(this.id,at((()=>e(this.data))))}}class xC{constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new xC(this.id,this.lazyData.map(e))}}class IC{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new IC(function*(e,t){for(const i of e)if(yield i,i.operation.id===t)return}(this.operations,e))}stopBefore(e){return new IC(function*(e,t){for(const i of e){if(i.operation.id===t)return;yield i}}(this.operations,e))}startAfter(e){return new IC(function*(e,t){let i=!0;for(const o of e)i||(yield o),o.operation.id===t&&(i=!1)}(this.operations,e))}}class RC{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 IC(Ge(this._execution(e),this._execution(e)))}revertedExecution(e){return new IC(Ge(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){var i;const o=e.getLastOperationId()||(null===(i=this.previousBranch(e))||void 0===i?void 0:i.getLastOperationId());e.append(t),o&&this.insertPrevious(e,t,o)}insertOperationAfter(e,t,i){e.insert(t,i),this.updateNextWith(e,t,i),this.insertPrevious(e,t,i)}undo(e,t){const i=this.buildTransformation.without(t.data),o=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const n=e.fork(t.id);o&&this.branchingOperationIds.set(n,o),this.insertBranchAfter(e,n),this.transform(n,i)}redo(e){const t=this.nextBranch(e);if(!t)return;const i=this.nextBranch(t);this.removeBranchFromTree(t);const o=this.branchingOperationIds.get(t);o?this.branchingOperationIds.set(e,o):this.branchingOperationIds.delete(e),i&&this.rebaseUp(i)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const i of this.revertedExecution(e))if(i.operation.id===t)return i;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!t||!i)return;const o=this.buildTransformation.without(i.data),n=t.fork(i.id);this.branchingOperationIds.set(n,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,n),n.transform(o);const s=this.nextBranch(n);s&&this.rebaseUp(s)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const i=this.branches.findIndex((t=>t===e));this.branches.splice(i+1,0,t)}updateNextWith(e,t,i){const o=this.branchingOperationIds.get(e),n=this.nextBranch(e);if(o&&n)if(e.getFirstOperationAmong(i,o)===o){const s=this.addToNextBranch(e,n,o,t,i);this.updateNextWith(n,s,i)}else{const e=this.buildTransformation.with(t.data);this.transform(n,e)}}addToNextBranch(e,t,i,o,n){let s=o;return n===i?(s=this.getTransformedOperation(e,i,o),t.prepend(s)):t.contains(n)?(s=this.getTransformedOperation(e,i,o),t.insert(s,n)):t.append(o),s}getTransformedOperation(e,t,i){const o=e.getOperation(t),n=this.buildTransformation.without(o.data);return i.transformed(n)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const i=this.nextBranch(e);i&&this.transform(i,t)}insertPrevious(e,t,i){const{previousBranch:o,branchingOperation:n}=this.findPreviousBranchingOperation(e);if(!o||!n)return;const s=this.buildTransformation.with(n.data),r=e.fork(i);r.transform(s),o.cutAfter(i),o.appendBranch(r);const a=t.transformed(s);this.insertPrevious(o,a,i)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const i=this.branchingOperationIds.get(t);return i?{previousBranch:t,branchingOperation:t.getOperation(i)}:{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 i=!!t;const o=e.getOperations();for(let n=o.length-1;n>=0;n--){const s=o[n];s.id===t&&(i=!1),i||(yield{operation:s,branch:e,isCancelled:!this.shouldExecute(e,s)})}const n=this.previousBranch(e);yield*n?this._revertedExecution(n):[]}*_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 TC{constructor(e,t,i,o,n){this.applyOperation=t,this.revertOperation=i,this.buildEmpty=o,this.buildTransformation=n,this.HEAD_BRANCH=new wC(this.buildTransformation),this.tree=new RC(n,this.HEAD_BRANCH);const s=new yC(e,o(e));this.tree.insertOperationLast(this.HEAD_BRANCH,s),this.HEAD_OPERATION=s}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const i=new yC(e,t),o=this.tree.getLastBranch();this.tree.insertOperationLast(o,i),this.HEAD_BRANCH=o,this.HEAD_OPERATION=i}insert(e,t,i){const o=new yC(e,t);this.revertTo(i),this.tree.insertOperationAfter(this.HEAD_BRANCH,o,i),this.fastForward()}undo(e,t,i){const{branch:o,operation:n}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(o,n),this.fastForward(),this.insert(t,this.buildEmpty(t),i)}redo(e,t,i){const{branch:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(o),this.fastForward(),this.insert(t,this.buildEmpty(t),i)}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:i,isCancelled:o}of e)o||this.revertOperation(i.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:i,isCancelled:o}of e)o||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=i}}function AC(e,t,i){return new TC(e,(e=>{const o=e.commands.slice(),{changes:n}=t((()=>{for(const e of o)i(e)}));e.setChanges(n)}),(e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){MC(t.changes[e],"before")}}([e])),(e=>new Rb(e,"empty",[],[])),{with:e=>t=>new Rb(t.id,t.clientId,xb(t.commands,e.commands)),without:e=>t=>new Rb(t.id,t.clientId,xb(t.commands,e.commands.map(SC).flat()))})}function MC(e,t){let i=e.path[0];const o=e.path[e.path.length-1];for(let t=1;t<e.path.slice(0,-1).length;t++){const o=e.path[t];if(void 0===i[o]){const n=e.path[t+1];i[o]=EC(n)}i=i[o]}void 0===e[t]?delete i[o]:i[o]=e[t]}class OC extends t.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 NC{constructor(){this.observers=[]}registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.push({owner:e,callbacks:t})}capture(e,t){var i,o,n;if(this.observers.find((t=>t.owner===e)))throw new Error("You are already subscribed forever");(null===(i=this.mainSubscription)||void 0===i?void 0:i.owner)&&this.mainSubscription.owner!==e&&(null===(n=(o=this.mainSubscription.callbacks).release)||void 0===n||n.call(o)),this.mainSubscription={owner:e,callbacks:t}}release(e){var t;(null===(t=this.mainSubscription)||void 0===t?void 0:t.owner)!==e||this.observers.find((t=>t.owner===e))||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){var e,t,i;this.mainSubscription!==this.defaultSubscription&&(null===(i=null===(e=this.mainSubscription)||void 0===e?void 0:(t=e.callbacks).release)||void 0===i||i.call(t),this.mainSubscription=this.defaultSubscription)}isListening(e){var t;return(null===(t=this.mainSubscription)||void 0===t?void 0:t.owner)===e}send(e){var t;null===(t=this.mainSubscription)||void 0===t||t.callbacks.handleEvent(e),[...this.observers].forEach((t=>t.callbacks.handleEvent(e)))}}class _C{constructor(e){this.getters=e,this.stream=new NC,this.anchor={cell:{col:0,row:0},zone:co({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,i){this.stream.capture(e,i),this.anchor=t}registerAsDefault(e,t,i){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,i),this.defaultAnchor=t,this.capture(e,t,i)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}selectZone(e){return this.modifyAnchor(e,"overrideSelection","ZonesSelected")}modifyAnchor(e,t,i){const o=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(o,e.zone)},this.processEvent({type:i,anchor:e,mode:t})}selectCell(e,t){const i=co({col:e,row:t});return this.selectZone({zone:i,cell:{col:e,row:t}})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new fn(84);const{col:i,row:o}=this.getNextAvailablePosition(e,t);return this.selectCell(i,o)}setAnchorCorner(e,t){const i=this.getters.getActiveSheetId(),{col:o,row:n}=this.anchor.cell,s={left:Math.min(o,e),top:Math.min(n,t),right:Math.max(o,e),bottom:Math.max(n,t)},r={zone:this.getters.expandZone(i,s),cell:{col:o,row:n}};return this.processEvent({type:"AlterZone",mode:"updateAnchor",anchor:r})}addCellToSelection(e,t){const i=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:i,col:e,row:t}));const o=this.getters.expandZone(i,co({col:e,row:t}));return this.processEvent({type:"ZonesSelected",anchor:{zone:o,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new fn(84);const i=this.getters.getActiveSheetId(),o=this.anchor,{col:n,row:s}=o.cell,{left:r,right:a,top:l,bottom:c}=o.zone,h=this.getStartingPosition(e);let[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return fn.Success;let g=o.zone;const p=e=>{e=lo(e);const{left:t,right:o,top:n,bottom:s}=this.getters.expandZone(i,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(i)-1,o),top:Math.max(0,n),bottom:Math.min(this.getters.getNumberRows(i)-1,s)}},{col:m,row:f}=this.getReferencePosition();let v=0;for(;null!==g;){if(v++,d<0){const e=this.getNextAvailableCol(d,a-(v-1),f);g=m<=a-v?p({top:l,left:r,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,r+(v-1),f);g=r+v<=m?p({top:l,left:e,bottom:c,right:a}):null}if(u<0){const e=this.getNextAvailableRow(u,m,c-(v-1));g=f<=c-v?p({top:l,left:r,bottom:e,right:a}):null}if(u>0){const e=this.getNextAvailableRow(u,m,l+(v-1));g=l+v<=f?p({top:e,left:r,bottom:c,right:a}):null}if(g=g?lo(g):g,g&&!Ki(g,o.zone))return this.processEvent({type:"ZonesSelected",mode:"updateAnchor",anchor:{zone:g,cell:{col:n,row:s}}})}g=p(Yi({top:s,bottom:s,left:n,right:n},lo({top:this.getNextAvailableRow(u,m,l),left:this.getNextAvailableCol(d,r,f),bottom:this.getNextAvailableRow(u,m,c),right:this.getNextAvailableCol(d,a,f)})));const b={zone:g,cell:{col:n,row:s}};return this.processEvent({type:"ZonesSelected",anchor:b,mode:"updateAnchor"})}selectColumn(e,t){const i=this.getters.getActiveSheetId(),o=this.getters.getNumberRows(i)-1;let n={left:e,right:e,top:0,bottom:o};const s=this.getters.findFirstVisibleColRowIndex(i,"ROW");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=e,a=s;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),n=Yi(n,{left:r,right:r,top:s,bottom:o})}return this.processEvent({type:"HeadersSelected",anchor:{zone:n,cell:{col:r,row:a}},mode:t})}selectRow(e,t){const i=this.getters.getActiveSheetId(),o=this.getters.getNumberCols(i)-1;let n={top:e,bottom:e,left:0,right:o};const s=this.getters.findFirstVisibleColRowIndex(i,"COL");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=s,a=e;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),n=Yi(n,{left:s,right:o,top:a,bottom:a})}return this.processEvent({type:"HeadersSelected",anchor:{zone:n,cell:{col:r,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(Ki(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:co(t.cell)},"updateAnchor","AlterZone");const i=this.expandZoneToTable(t.zone);return ht(i,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:i},"updateAnchor","AlterZone")}selectTableAroundSelection(){const e=this.expandZoneToTable(this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:e},"updateAnchor","AlterZone")}selectAll(){const e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({type:"HeadersSelected",mode:"overrideSelection",anchor:{zone:t,cell:this.anchor.cell}})}isListening(e){return this.stream.isListening(e)}processEvent(e){const t={...e,previousAnchor:Fe(this.anchor)},i=this.checkEventAnchorZone(t);return 0!==i?new fn(i):(this.anchor=t.anchor,this.stream.send(t),fn.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:i}=e;if(!Ji(t.col,t.row,i))return 16;const{left:o,right:n,top:s,bottom:r}=i,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",o,n);return void 0===this.getters.findVisibleHeader(a,"ROW",s,r)||void 0===l?17:0}checkAnchorZoneOrThrow(e){if(16===this.checkAnchorZone(e))throw new Error(n("The provided anchor is invalid. The cell must be part of the zone."))}getNextAvailablePosition(e,t=1){const{col:i,row:o}=this.anchor.cell,n=this.deltaToTarget({col:i,row:o},e,t);return{col:this.getNextAvailableCol(n[0],i,o),row:this.getNextAvailableRow(n[1],i,o)}}getNextAvailableCol(e,t,i){const o=this.getters.getActiveSheetId(),n={col:t,row:i};return this.getNextAvailableHeader(e,"COL",t,n,(e=>this.getters.isInSameMerge(o,t,i,e,i)))}getNextAvailableRow(e,t,i){const o=this.getters.getActiveSheetId(),n={col:t,row:i};return this.getNextAvailableHeader(e,"ROW",i,n,(e=>this.getters.isInSameMerge(o,t,i,t,e)))}getNextAvailableHeader(e,t,i,o,n){const s=this.getters.getActiveSheetId();if(0===e)return i;const r=Math.sign(e);let a=i+e;for(;n(a);)a+=r;for(;this.getters.isHeaderHidden(s,t,a);)a+=r;return a<0||a>this.getters.getNumberHeaders(s,t)-1?this.getters.isHeaderHidden(s,t,i)?this.getNextAvailableHeader(-r,t,i,o,n):i:a}getReferencePosition(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:i,right:o,top:n,bottom:s}=t.zone,{col:r,row:a}=t.cell;return{col:this.getters.isColHidden(e,r)&&this.getters.findVisibleHeader(e,"COL",i,o)||r,row:this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",n,s)||a}}deltaToTarget(e,t,i){switch(t){case"up":return"end"!==i?[0,-i]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==i?[0,i]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==i?[-i,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==i?[i,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:i}=this.getPosition();const o=this.anchor.zone;switch(e){case"down":case"up":i=i===o.top?o.bottom:o.top;break;case"left":case"right":t=t===o.right?o.left:o.right}return{col:t,row:i}}getEndOfCluster(e,t,i){const o=this.getters.getActiveSheet();let n=e;const s=this.getNextCellPosition(e,t,i);let r=this.isCellEmpty(n,o.id)||this.isCellEmpty(s,o.id)?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(n,t,i);if(n.col===e.col&&n.row===e.row)break;const s=this.isCellEmpty(e,o.id);if("endOfCluster"===r&&s)break;if("nextCluster"===r&&!s){n=e;break}n=e}return"cols"===t?n.col:n.row}isCellEmpty({col:e,row:t},i=this.getters.getActiveSheetId()){const o=this.getters.getMainCellPosition({sheetId:i,col:e,row:t});return this.getters.getEvaluatedCell(o).type===cn.empty}getNextCellPosition(e,t,i){const o="cols"===t?"col":"row",n={...e},s="cols"===t?this.getNextAvailableCol(i,n.col,n.row):this.getNextAvailableRow(i,n.col,n.row);return n[o]=s,{col:n.col,row:n.row}}getPosition(){return{...this.anchor.cell}}expandZoneToTable(e){const t=e=>{for(const t of $e(e.left,e.right+1)){if(!this.isCellEmpty({col:t,row:e.top-1}))return{...e,top:e.top-1};if(!this.isCellEmpty({col:t,row:e.bottom+1}))return{...e,bottom:e.bottom+1}}for(const t of $e(e.top,e.bottom+1)){if(!this.isCellEmpty({col:e.left-1,row:t}))return{...e,left:e.left-1};if(!this.isCellEmpty({col:e.right+1,row:t}))return{...e,right:e.right+1}}return e};let i=!1,o=e;do{i=!1;const e=t(o);Ki(o,e)||(i=!0,o=e)}while(i);return o}}class FC{constructor(){this.changes=[],this.commands=[]}recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop();let i=e[0],o=e[e.length-1];const n=e.length-2;for(let t=1;t<=n;t++){const o=e[t];if(void 0===i[o]){const n=e[t+1];i[o]=EC(n)}i=i[o]}i[o]!==t&&(this.changes.push({path:e,before:i[o],after:t}),void 0===t?delete i[o]:i[o]=t)}}const DC=17781237,kC=88853993;function LC(e,t,i){const o=[["xmlns:r",_p],["xmlns:a",Ap],["xmlns:c",Mp]],n=PC({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let s=av``;e.data.title&&(s=av`
1976
1976
  <c:title>
1977
1977
  ${VC(e.data.title,e.data.fontColor)}
1978
1978
  <c:overlay val="0" />
@@ -2455,4 +2455,4 @@
2455
2455
  <tableParts count="${e.filterTables.length}">
2456
2456
  ${rv(a)}
2457
2457
  </tableParts>
2458
- `}var SS;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(SS||(SS={}));const ES={},wS={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:N,HEADER_WIDTH:_,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:F,DEFAULT_CELL_HEIGHT:D,SCROLLBAR_WIDTH:k},yS={autofillModifiersRegistry:An,autofillRulesRegistry:Mn,cellMenuRegistry:ga,colMenuRegistry:pa,linkMenuRegistry:cs,functionRegistry:ig,featurePluginRegistry:Yb,statefulUIPluginRegistry:Xb,coreViewsPluginRegistry:Kb,corePluginRegistry:jb,rowMenuRegistry:ma,sidePanelRegistry:kg,figureRegistry:Sr,chartSidePanelComponentRegistry:Rg,chartComponentRegistry:mr,chartRegistry:pr,topbarMenuRegistry:ng,topbarComponentRegistry:Lg,clickableCellRegistry:Qb,otRegistry:rg,inverseCommandRegistry:xr,urlRegistry:Ao,cellPopoverRegistry:us},xS={arg:ba,toBoolean:Wo,toJsDate:Go,toNumber:Uo,toString:zo,toXC:Zt,toZone:Hi,toCartesian:qt,numberToLetters:Wt,UuidGenerator:zi,formatValue:fi,computeTextWidth:Ue,createEmptyWorkbookData:_v,createEmptySheet:Nv,createEmptyExcelSheet:Fv,getDefaultChartJsRuntime:Hs,chartFontColor:Rs,ChartColors:Is,EvaluationError:c,CellErrorLevel:l,getFillingMode:qs,rgbaToHex:Tt,colorToRGBA:At,positionToZone:co,isDefined:ot,lazy:at},IS={isMarkdownLink:Ye,parseMarkdownLink:Qe,markdownLink:Ke,openLink:Fo,urlRepresentation:_o},RS={ChartPanel:Tg,ChartFigure:vr,ChartJsComponent:po,Grid:wp,GridOverlay:rp,ScorecardChart:yo,LineConfigPanel:wg,LineBarPieDesignPanel:bg,BarConfigPanel:ug,LineBarPieConfigPanel:dg,GaugeChartConfigPanel:Sg,GaugeChartDesignPanel:Eg,ScorecardChartConfigPanel:xg,ScorecardChartDesignPanel:Ig,FigureComponent:Pg};e.AbstractChart=ps,e.CorePlugin=kv,e.DATETIME_FORMAT=X,e.DispatchResult=fn,e.EvaluationError=c,e.Model=class extends Cb{constructor(e={},i={},o=[],n=new zi,s=!0){super(),this.corePlugins=[],this.featurePlugins=[],this.statefulUIPlugins=[],this.coreViewsPlugins=[],this.isReplayingCommand=!1,this.renderers=[],this.status=0,this.handlers=[],this.coreHandlers=[],this.dispatch=(e,t)=>{const i={...t,type:e};let o=this.status;if(this.getters.isReadonly()&&(n=i,!gn.has(n.type)))return new fn(67);var n;if(!this.session.canApplyOptimisticUpdate())return new fn(64);switch(o){case 0:const t=this.checkDispatchAllowed(i);if(!t.isSuccessful)return t;this.status=1;const{changes:o,commands:n}=this.state.recordChanges((()=>{mn(i)&&this.state.addCommand(i),this.dispatchToHandlers(this.handlers,i),this.finalize()}));this.session.save(n,o),this.status=0,this.trigger("update");break;case 1:if(mn(i)){const e=this.checkDispatchAllowed(i);if(!e.isSuccessful)return e;this.state.addCommand(i)}this.dispatchToHandlers(this.handlers,i);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(mn(i))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,i)}return fn.Success},this.dispatchFromCorePlugin=(e,t)=>{const i={...t,type:e},o=this.status;this.status=2;const n=this.isReplayingCommand?[this.range,...this.corePlugins,...this.coreViewsPlugins]:this.handlers;return this.dispatchToHandlers(n,i),this.status=o,fn.Success},o=Mv(e,o);const r=Tv(e,s);this.state=new FC,this.uuidGenerator=n,this.config=this.setupConfig(i),this.session=this.setupSession(r.revisionId),this.history=new OC(this.dispatchFromCorePlugin,this.session),this.coreGetters={},this.range=new Kv(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getSelectionRangeString=this.range.getSelectionRangeString.bind(this.range),this.getters={isReadonly:()=>"readonly"===this.config.mode||"dashboard"===this.config.mode,isDashboard:()=>"dashboard"===this.config.mode,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.uuidGenerator.setIsFastStrategy(!0),this.selection=new _C(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of jb.getAll())this.setupCorePlugin(e,r);Object.assign(this.getters,this.coreGetters);for(let e of Xb.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t)}for(let e of Kb.getAll()){const t=this.setupUiPlugin(e);this.coreViewsPlugins.push(t),this.handlers.push(t),this.coreHandlers.push(t)}for(let e of Yb.getAll()){const t=this.setupUiPlugin(e);this.featurePlugins.push(t),this.handlers.push(t)}this.uuidGenerator.setIsFastStrategy(!1),this.handlers.push(this.history),this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.session.loadInitialMessages(o),this.joinSession(),i.snapshotRequested&&(this.session.snapshot(this.exportData()),this.garbageCollectExternalResources()),t.markRaw(this)}joinSession(){this.session.join(this.config.client)}leaveSession(){this.session.leave()}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(let i of e.getters){if(!(i in t))throw new Error(`Invalid getter name: ${i} for plugin ${t.constructor}`);if(i in this.getters)throw new Error(`Getter "${i}" is already defined.`);this.getters[i]=t[i].bind(t)}const i=e.layers.map((e=>[t,e]));return this.renderers.push(...i),this.renderers.sort(((e,t)=>e[1]-t[1])),t}setupCorePlugin(e,t){const i=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in i))throw new Error(`Invalid getter name: ${t} for plugin ${i.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=i[t].bind(i)}i.import(t),this.corePlugins.push(i),this.coreHandlers.push(i),this.handlers.push(i)}onRemoteRevisionReceived({commands:e}){for(let t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new Ab(AC(e,this.state.recordChanges.bind(this.state),(e=>{this.checkDispatchAllowed(e).isSuccessful&&(this.isReplayingCommand=!0,this.dispatchToHandlers([this.range,...this.corePlugins,...this.coreViewsPlugins],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:s("Anonymous").toString()},i=e.transportService||new CC;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:e.external||{},transportService:i,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),lazyEvaluation:!("lazyEvaluation"in e)||e.lazyEvaluation}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,uuidGenerator:this.uuidGenerator,custom:this.config.custom,external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,lazyEvaluation:this.config.lazyEvaluation}}checkDispatchAllowed(e){const t=this.handlers.map((t=>t.allowDispatch(e)));return t.some((e=>0!==e))?new fn(t.flat()):fn.Success}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0}dispatchToHandlers(e,t){t=Fe(t);for(const i of e)i.beforeHandle(t);for(const i of e)i.handle(t)}drawGrid(e){for(let[t,i]of this.renderers)e.ctx.save(),t.drawGrid(e,i),e.ctx.restore()}exportData(){let e=_v();for(let t of this.handlers)t instanceof kv&&t.export(e);return e.revisionId=this.session.getRevisionId()||Q,e=Fe(e),e}updateMode(e){"normal"!==e&&this.dispatch("STOP_EDITION",{cancel:!0}),this.config.mode=e,this.trigger("update")}exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={..._v(),sheets:[Fv(Rv,"Sheet1")]};for(let t of this.handlers)t instanceof Dv&&t.exportForExcel(e);return e=Fe(e),bS(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.Registry=Ro,e.Revision=Rb,e.SPREADSHEET_DIMENSIONS=wS,e.Spreadsheet=bC,e.UIPlugin=Jv,e.__info__=ES,e.addFunction=function(e,t){ig.add(e,t)},e.astToFormula=nf,e.compile=vf,e.components=RS,e.convertAstNodes=of,e.coreTypes=pn,e.findCellInNewZone=ao,e.functionCache=ff,e.helpers=xS,e.invalidateEvaluationCommands=dn,e.links=IS,e.load=Tv,e.parse=ef,e.readonlyAllowedCommands=gn,e.registries=yS,e.setTranslationMethod=function(e){i=e},e.tokenize=Fm,Object.defineProperty(e,"__esModule",{value:!0}),ES.version="16.2.28",ES.date="2024-01-17T10:24:07.951Z",ES.hash="16cee48"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
2458
+ `}var SS;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(SS||(SS={}));const ES={},wS={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:N,HEADER_WIDTH:_,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:F,DEFAULT_CELL_HEIGHT:D,SCROLLBAR_WIDTH:k},yS={autofillModifiersRegistry:An,autofillRulesRegistry:Mn,cellMenuRegistry:ga,colMenuRegistry:pa,linkMenuRegistry:cs,functionRegistry:ig,featurePluginRegistry:Yb,statefulUIPluginRegistry:Xb,coreViewsPluginRegistry:Kb,corePluginRegistry:jb,rowMenuRegistry:ma,sidePanelRegistry:kg,figureRegistry:Sr,chartSidePanelComponentRegistry:Rg,chartComponentRegistry:mr,chartRegistry:pr,topbarMenuRegistry:ng,topbarComponentRegistry:Lg,clickableCellRegistry:Qb,otRegistry:rg,inverseCommandRegistry:xr,urlRegistry:Ao,cellPopoverRegistry:us},xS={arg:ba,toBoolean:Wo,toJsDate:Go,toNumber:Uo,toString:zo,toXC:Zt,toZone:Hi,toCartesian:qt,numberToLetters:Wt,UuidGenerator:zi,formatValue:fi,computeTextWidth:Ue,createEmptyWorkbookData:_v,createEmptySheet:Nv,createEmptyExcelSheet:Fv,getDefaultChartJsRuntime:Hs,chartFontColor:Rs,ChartColors:Is,EvaluationError:c,CellErrorLevel:l,getFillingMode:qs,rgbaToHex:Tt,colorToRGBA:At,positionToZone:co,isDefined:ot,lazy:at},IS={isMarkdownLink:Ye,parseMarkdownLink:Qe,markdownLink:Ke,openLink:Fo,urlRepresentation:_o},RS={ChartPanel:Tg,ChartFigure:vr,ChartJsComponent:po,Grid:wp,GridOverlay:rp,ScorecardChart:yo,LineConfigPanel:wg,LineBarPieDesignPanel:bg,BarConfigPanel:ug,LineBarPieConfigPanel:dg,GaugeChartConfigPanel:Sg,GaugeChartDesignPanel:Eg,ScorecardChartConfigPanel:xg,ScorecardChartDesignPanel:Ig,FigureComponent:Pg};e.AbstractChart=ps,e.CorePlugin=kv,e.DATETIME_FORMAT=X,e.DispatchResult=fn,e.EvaluationError=c,e.Model=class extends Cb{constructor(e={},i={},o=[],n=new zi,s=!0){super(),this.corePlugins=[],this.featurePlugins=[],this.statefulUIPlugins=[],this.coreViewsPlugins=[],this.isReplayingCommand=!1,this.renderers=[],this.status=0,this.handlers=[],this.coreHandlers=[],this.dispatch=(e,t)=>{const i={...t,type:e};let o=this.status;if(this.getters.isReadonly()&&(n=i,!gn.has(n.type)))return new fn(68);var n;if(!this.session.canApplyOptimisticUpdate())return new fn(65);switch(o){case 0:const t=this.checkDispatchAllowed(i);if(!t.isSuccessful)return t;this.status=1;const{changes:o,commands:n}=this.state.recordChanges((()=>{mn(i)&&this.state.addCommand(i),this.dispatchToHandlers(this.handlers,i),this.finalize()}));this.session.save(n,o),this.status=0,this.trigger("update");break;case 1:if(mn(i)){const e=this.checkDispatchAllowed(i);if(!e.isSuccessful)return e;this.state.addCommand(i)}this.dispatchToHandlers(this.handlers,i);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(mn(i))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,i)}return fn.Success},this.dispatchFromCorePlugin=(e,t)=>{const i={...t,type:e},o=this.status;this.status=2;const n=this.isReplayingCommand?[this.range,...this.corePlugins,...this.coreViewsPlugins]:this.handlers;return this.dispatchToHandlers(n,i),this.status=o,fn.Success},o=Mv(e,o);const r=Tv(e,s);this.state=new FC,this.uuidGenerator=n,this.config=this.setupConfig(i),this.session=this.setupSession(r.revisionId),this.history=new OC(this.dispatchFromCorePlugin,this.session),this.coreGetters={},this.range=new Kv(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getSelectionRangeString=this.range.getSelectionRangeString.bind(this.range),this.getters={isReadonly:()=>"readonly"===this.config.mode||"dashboard"===this.config.mode,isDashboard:()=>"dashboard"===this.config.mode,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.uuidGenerator.setIsFastStrategy(!0),this.selection=new _C(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of jb.getAll())this.setupCorePlugin(e,r);Object.assign(this.getters,this.coreGetters);for(let e of Xb.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t)}for(let e of Kb.getAll()){const t=this.setupUiPlugin(e);this.coreViewsPlugins.push(t),this.handlers.push(t),this.coreHandlers.push(t)}for(let e of Yb.getAll()){const t=this.setupUiPlugin(e);this.featurePlugins.push(t),this.handlers.push(t)}this.uuidGenerator.setIsFastStrategy(!1),this.handlers.push(this.history),this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.session.loadInitialMessages(o),this.joinSession(),i.snapshotRequested&&(this.session.snapshot(this.exportData()),this.garbageCollectExternalResources()),t.markRaw(this)}joinSession(){this.session.join(this.config.client)}leaveSession(){this.session.leave()}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(let i of e.getters){if(!(i in t))throw new Error(`Invalid getter name: ${i} for plugin ${t.constructor}`);if(i in this.getters)throw new Error(`Getter "${i}" is already defined.`);this.getters[i]=t[i].bind(t)}const i=e.layers.map((e=>[t,e]));return this.renderers.push(...i),this.renderers.sort(((e,t)=>e[1]-t[1])),t}setupCorePlugin(e,t){const i=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in i))throw new Error(`Invalid getter name: ${t} for plugin ${i.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=i[t].bind(i)}i.import(t),this.corePlugins.push(i),this.coreHandlers.push(i),this.handlers.push(i)}onRemoteRevisionReceived({commands:e}){for(let t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new Ab(AC(e,this.state.recordChanges.bind(this.state),(e=>{this.checkDispatchAllowed(e).isSuccessful&&(this.isReplayingCommand=!0,this.dispatchToHandlers([this.range,...this.corePlugins,...this.coreViewsPlugins],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:s("Anonymous").toString()},i=e.transportService||new CC;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:e.external||{},transportService:i,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),lazyEvaluation:!("lazyEvaluation"in e)||e.lazyEvaluation}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,uuidGenerator:this.uuidGenerator,custom:this.config.custom,external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,lazyEvaluation:this.config.lazyEvaluation}}checkDispatchAllowed(e){const t=this.handlers.map((t=>t.allowDispatch(e)));return t.some((e=>0!==e))?new fn(t.flat()):fn.Success}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0}dispatchToHandlers(e,t){t=Fe(t);for(const i of e)i.beforeHandle(t);for(const i of e)i.handle(t)}drawGrid(e){for(let[t,i]of this.renderers)e.ctx.save(),t.drawGrid(e,i),e.ctx.restore()}exportData(){let e=_v();for(let t of this.handlers)t instanceof kv&&t.export(e);return e.revisionId=this.session.getRevisionId()||Q,e=Fe(e),e}updateMode(e){"normal"!==e&&this.dispatch("STOP_EDITION",{cancel:!0}),this.config.mode=e,this.trigger("update")}exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={..._v(),sheets:[Fv(Rv,"Sheet1")]};for(let t of this.handlers)t instanceof Dv&&t.exportForExcel(e);return e=Fe(e),bS(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.Registry=Ro,e.Revision=Rb,e.SPREADSHEET_DIMENSIONS=wS,e.Spreadsheet=bC,e.UIPlugin=Jv,e.__info__=ES,e.addFunction=function(e,t){ig.add(e,t)},e.astToFormula=nf,e.compile=vf,e.components=RS,e.convertAstNodes=of,e.coreTypes=pn,e.findCellInNewZone=ao,e.functionCache=ff,e.helpers=xS,e.invalidateEvaluationCommands=dn,e.links=IS,e.load=Tv,e.parse=ef,e.readonlyAllowedCommands=gn,e.registries=yS,e.setTranslationMethod=function(e){i=e},e.tokenize=Fm,Object.defineProperty(e,"__esModule",{value:!0}),ES.version="16.2.29",ES.date="2024-01-29T13:49:36.240Z",ES.hash="27b2ec1"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);