@odoo/o-spreadsheet 16.3.38 → 16.3.40
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 o=e=>e;function i(e,...t){if(1===t.length&&"object"==typeof t[0]){const o=t[0];e=e.replace(/\%\(?([^\)]+)\)s/g,((e,t)=>o[t]))}else t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));return e}const s=function(e,...t){return i(o(e),...t)},n=function(e,...t){return new r(e,t)};class r extends String{values;constructor(e,t){super(e),this.values=t}valueOf(){const e=super.valueOf();return i(o(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{errorType;logLevel;constructor(e,t,o=l.error){super(t),this.errorType=e,this.logLevel=o}}class h extends c{constructor(e){super(a.BadExpression,e)}}class d extends c{constructor(){super(a.CircularDependency,n("Circular reference"))}}class u extends c{constructor(){super(a.InvalidReference,n("Invalid reference"))}}class g extends c{constructor(e){super(a.NotAvailable,e||n("Data not available"),e?l.error:l.silent)}}class p extends c{constructor(e){super(a.UnknownFunction,n('Unknown function: "%s"',e))}}const m=.5,f="#f5f5f5",b="#F8F9FA",v="#E8EAED",S="#595959",C="#666666",E="#3266ca",w="#FFFFFF",x="#EBEBEB",y="#CACACA",I=11982760,R="#01666b",T="#188038",A="#E6F4EA",O="#CEEAD6",M="#E0E2E4",N="#4A4F59",_=["#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"],F=26,D=48,L=96,k=23,P=15,U=18,V=14,z=4,B=4,H=3,$=B,W=17,G=250,q="400",Z=10,j="'Roboto', arial",Y="bottom",X="thin",K="#000000",Q={style:"thin",color:T},J=a.InvalidReference,ee="START_REVISION",te=1,oe=20,ie="??",se="difference",ne="#00A04A",re="#DC6965",ae=.4,le=["'","*","?","/","\\","[","]"],ce=/'|\*|\?|\/|\\|\[|\]/,he="|",de=n("Invalid expression");var ue;!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.FigureAnchor=1e3]="FigureAnchor",e[e.FigureSnapLine=1001]="FigureSnapLine"}(ue||(ue={}));let ge=0;function pe(){return ge}const me="\n",fe=[6,7,8,9,10,11,12,14,18,24,36];class be{jsDate;constructor(e,t,o,i=0,s=0,n=0){this.jsDate=new Date(Date.UTC(e,t,o,i,s,n,0))}static fromTimestamp(e){const t=new Date(e);return new be(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())}static now(){const e=new Date;return new be(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds())}toString(){return this.jsDate.toString()}toLocaleDateString(){return this.jsDate.toLocaleDateString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}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 ve=new be(1899,11,30),Se=864e5,Ce=2e3,Ee=be.now().getFullYear(),we=be.fromTimestamp(0).getTime()-ve.getTime(),xe=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,ye=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,Ie=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/,Re={};function Te(e){if(e in Re)return Re[e];const t=function(e){let t;e=e.trim();const o=e.match(Ie);if(o){if(t=function(e){if(e=e.trim(),Ie.test(e)){const t=/AM/i.test(e),o=/PM/i.test(e),i=(t||o?e.substring(0,e.length-2).trim():e).split(/:/),s=i.length>=2,n=3===i.length;let r=Number(i[0]),a=s?Number(i[1]):0,l=n?Number(i[2]):0,c=n?"hh:mm:ss":"hh:mm";if(t||o)c+=" a";else if(!s)return null;r>=12&&t?r-=12:r<12&&o&&(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 be(1899,11,30,r,a,l)}}return null}(o[0]),null===t)return null;e=e.replace(o[0],"").trim()}let i;const s=e.match(xe),n=e.match(ye);if(s||n){let t;if(s?(t=s[0],i=Ae(t,"mdy")):(t=n[0],i=Ae(t,"ymd")),null===i)return null;e=e.replace(t,"").trim()}if(""!==e||!i&&!t)return null;if(i&&t)return{value:i.value+t.value,format:i.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new be(i.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,i.jsDate.getMonth()+t.jsDate.getMonth()-11,i.jsDate.getDate()+t.jsDate.getDate()-30,i.jsDate.getHours()+t.jsDate.getHours(),i.jsDate.getMinutes()+t.jsDate.getMinutes(),i.jsDate.getSeconds()+t.jsDate.getSeconds())};return i||t}(e);return Re[e]=t,t}function Ae(e,t){const o="mdy"===t;if(o||"ymd"===t){const t=e.split(/\/|-|\s/),i=o?0:1,s=o?1:2,n=o?2:0,r=Number(t[i]),a=Number(t[s]),l=2===t[i].length&&r<10||2===t[s].length&&a<10,c=t[n]?function(e){const t=Number(e);switch(e.length){case 1:return Ce+t;case 2:return Ce+(Ce+t>Ee+10?-100:0)+t;case 3:case 4:return t}return 0}(t[n]):Ee,h=new be(c,r-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==r-1||h.getDate()!==a)return null;const u=h.getTime()-ve.getTime();let g=l?`mm${d}dd`:`m${d}d`;return t[n]&&(g=o?g+d+"yyyy":"yyyy"+d+g),{value:Math.round(u/Se),format:g,jsDate:h}}return null}function Oe(e){const t=Math.trunc(e);let o=be.fromTimestamp(t*Se-we),i=e-t;i=i<0?1+i:i;const s=Math.round(24*i),n=Math.round(24*(i-s/24)*60),r=Math.round(24*(i-s/24-n/24/60)*60*60);return o.setHours(s),o.setMinutes(n),o.setSeconds(r),o}function Me(e){const t=e.getTime()-ve.getTime();return Math.round(t/Se)}function Ne(e){return new be(e.getFullYear(),e.getMonth()+1,0).getDate()}function _e(e){return Ne(e)===e.getDate()}function Fe(e,t,o){const i=e.getFullYear(),s=e.getMonth(),n=e.getDate(),r=new be(i,s+t,1);return o&&n===Ne(e)||n>Ne(r)?r.setDate(Ne(r)):r.setDate(n),r}function De(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function Le(e,t,o){if(e===t)return 0;if(e>t){const o=t;t=e,e=o}const i=Oe(e),s=Oe(t);let n=i.getDate(),r=s.getDate();const a=i.getMonth(),l=s.getMonth(),c=i.getFullYear(),h=s.getFullYear();let d=0,u=0;switch(o){case 0:31===n&&(n=30),30===n&&31===r&&(r=30),1===a&&n===(De(c)?29:28)&&(n=30,1===l&&r===(De(h)?29:28)&&(r=30)),d=c+(30*a+n)/360,u=h+(30*l+r)/360;break;case 1:let o=365;const i=c===h;if(!i&&!(c+1===h)||!i&&a<l||!i&&a===l&&n<r){let e=0,t=0;for(let o=c;o<=h;o++)e++,t+=De(o)?366:365;o=t/e}else i?De(c)&&(o=366):(De(c)&&a<2&&(o=366),De(h)&&(l>1||1===l&&29===r)&&(o=366));d=e/o,u=t/o;break;case 2:d=e/360,u=t/360;break;case 3:d=e/365,u=t/365;break;case 4:31===n&&(n=30),31===r&&(r=30),d=c+(30*a+n)/360,u=h+(30*l+r)/360}return u-d}function ke(e,t){const o=12*(t.getFullYear()-e.getFullYear())+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?o-1:o}function Pe(e,t){const o=e.getTime(),i=t.getTime();return Math.floor((i-o)/Se)}function Ue(e,t){const o=t.getFullYear()-e.getFullYear(),i=e.getMonth(),s=t.getMonth(),n=e.getDate(),r=t.getDate();return s>i||s===i&&r>=n?o:o-1}function Ve(e){return'"'===e[0]&&(e=e.slice(1)),'"'===e[e.length-1]&&"\\"!==e[e.length-2]?e.slice(0,e.length-1):e}function ze(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Be(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&&e?.constructor===Object}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");for(const o in e)t[o]=Be(e[o]);return t;case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function He(e){return e.startsWith("'")&&(e=e.slice(1,-1).replace(/''/g,"'")),e}function $e(e){return e.match(/\w/g)?.length!==e.length&&(e=`'${e}'`),e}function We(e,t,o){return e<t?t:e>o?o:e}function Ge(e,t=1){return t*(e+B)-B}function qe(e,t,o){const i=Ye(o);if(Ze[i]||(Ze[i]={}),void 0===Ze[i][t]){e.save(),e.font=i;const o=e.measureText(t).width;e.restore(),Ze[i][t]=o}return Ze[i][t]}const Ze={};function je(e){return Math.round(96*e/72)}function Ye(e){return`${e.italic?"italic ":""}${e.bold?"bold":q} ${Xe(e)}px ${j}`}function Xe(e){return je(e?.fontSize||Z)}function Ke(e,t,o=1){if(t<=e&&o>0)return[];if(0===o)throw new Error("range() step must not be zero");const i=Math.ceil(Math.abs((t-e)/o)),s=Array(i);for(let t=0;t<i;t++)s[t]=e+t*o;return s}function Qe(e){return e.reduce(((e,t,o,i)=>{if(1===Math.abs(t-i[o-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*Je(e,t){t.next();for(const o of e){const e=t.next();yield{...o,next:e.done?void 0:e.value}}}function et(e){return null!==Te(e)}const tt=/^\[(.+)\]\((.+)\)$/,ot=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function it(e){return tt.test(e)}function st(e){return ot.test(e)}function nt(e,t){return`[${e}](${t})`}function rt(e){const t=e.match(tt)||[],o=t[1],i=t[2];if(!o||!i)throw new Error(`Could not parse markdown link ${e}.`);return{label:o,url:i}}const at="o-spreadsheet://";function lt(e){return e.startsWith(at)}function ct(e){return`${at}${e}`}function ht(e){if(e.startsWith(at))return e.substr(at.length);throw new Error(`${e} is not a valid sheet link`)}function dt(e){return void 0!==e}function ut(e){return void 0===e||Object.values(e).every((e=>"object"==typeof e?ut(e):!e))}function gt(e,t){for(let[o,i]of Object.entries(t))if(vt(i,e))return parseInt(o,10);const o=Object.keys(t),i=0===o.length?0:Rt(o.map((e=>parseInt(e,10))));return t[i+1]=e,i+1}function pt(e){let t="";for(let o=0,i=e.length;o<i;o++)t+=e[o];return t}function mt(e){let t,o=!1;const i=()=>(o||(t=e instanceof Function?e():e,o=!0),t);return i.map=e=>mt((()=>e(i()))),i}function ft(e,t){let o=e.slice(t).find((e=>e));return o||(o=e.slice(0,t).reverse().find((e=>e))),o||""}function bt(e,t){return"after"===e?t+1:t}function vt(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;if(typeof e!=typeof t)return!1;if("object"!=typeof e)return!1;const o=new Set;Object.keys(e).forEach((e=>o.add(e))),Object.keys(t).forEach((e=>o.add(e)));for(let i of o){if(typeof e[i]!=typeof e[i])return!1;if("object"==typeof e[i]){if(!vt(e[i],t[i]))return!1}else if(e[i]!==t[i])return!1}return!0}function St(e,t){return t.every((t=>e.includes(t)))}function Ct(e){const t={...e};return Object.keys(t).forEach((e=>!t[e]&&delete t[e])),t}function Et(e){return e?e.toLowerCase():""}const wt=[" ","\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))],xt=new RegExp(wt.join("|"),"g"),yt=/\r\n|\r|\n/g;function It(e){return e?e=(e=e.replace(xt," ")).replace(yt,me):""}function Rt(e){let t=e.length;if(t<1e5)return Math.max(...e);let o=-1/0;for(;t--;)o=e[t]>o?e[t]:o;return o}function Tt(e){let t=e.length;if(t<1e5)return Math.min(...e);let o=1/0;for(;t--;)o=e[t]<o?e[t]:o;return o}const At=/rgba?\(|\s+|\)/gi,Ot=/^#([A-F\d]{2}){3,4}$/,Mt=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function Nt(e){return _t(e.toString(16).padStart(6,"0"))}function _t(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(At,"").split(",");let o=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");o=Math.round(255*(e||1))}const i=t.map((e=>parseInt(e,10)));255!==o&&i.push(o);return"#"+pt(i.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}`),!Ot.test(t))throw new Error(`invalid color input: ${e}`);return t}function Ft(e){try{return _t(e),!0}catch(e){return!1}}const Dt=e=>e>=0&&e<=255;function Lt(e,t,o,i=1){if(!Dt(e)||!Dt(t)||!Dt(o)||i<0||i>1)throw new Error(`Invalid RGBA values ${[e,t,o,i]}`);return{a:i,b:o,g:t,r:e}}function kt(e){let{r:t,g:o,b:i}=Ut(e);t/=255,o/=255,i/=255;const s=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*s(t)+.7152*s(o)+.0722*s(i)}function Pt(e){let t=e.r.toString(16),o=e.g.toString(16),i=e.b.toString(16),s=Math.round(255*e.a).toString(16);return 1==t.length&&(t="0"+t),1==o.length&&(o="0"+o),1==i.length&&(i="0"+i),1==s.length&&(s="0"+s),"ff"===s&&(s=""),("#"+t+o+i+s).toUpperCase()}function Ut(e){let t,o,i,s;if(7===(e=_t(e)).length)t=parseInt(e[1]+e[2],16),o=parseInt(e[3]+e[4],16),i=parseInt(e[5]+e[6],16),s=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),o=parseInt(e[3]+e[4],16),i=parseInt(e[5]+e[6],16),s=parseInt(e[7]+e[8],16)}return s=+(s/255).toFixed(3),{a:s,r:t,g:o,b:i}}function Vt(e){(e={...e}).s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,o=t*(1-Math.abs(e.h/60%2-1)),i=e.l-t/2,s=0,n=0,r=0;return 0<=e.h&&e.h<60?(s=t,n=o,r=0):60<=e.h&&e.h<120?(s=o,n=t,r=0):120<=e.h&&e.h<180?(s=0,n=t,r=o):180<=e.h&&e.h<240?(s=0,n=o,r=t):240<=e.h&&e.h<300?(s=o,n=0,r=t):300<=e.h&&e.h<360&&(s=t,n=0,r=o),s=Math.round(255*(s+i)),n=Math.round(255*(n+i)),r=Math.round(255*(r+i)),{a:e.a,r:s,g:n,b:r}}function zt(e){const t=e.r/255,o=e.g/255,i=e.b/255;let s=Math.min(t,o,i),n=Math.max(t,o,i),r=n-s,a=0,l=0,c=0;return a=0==r?0:n==t?(o-i)/r%6:n==o?(i-t)/r+2:(t-o)/r+4,a=Math.round(60*a),a<0&&(a+=360),c=(n+s)/2,l=0==r?0:r/(1-Math.abs(2*c-1)),l=+(100*l).toFixed(1),c=+(100*c).toFixed(1),{a:e.a,h:a,s:l,l:c}}function Bt(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Bt(Math.floor(e/26)-1)+Bt(e%26)}const Ht={};for(const e of"ABCDEFGHIJKLMNOPQRSTUVWXYZ"){const t=e.charCodeAt(0)-64;Ht[e]=t,Ht[e.toLowerCase()]=t}function $t(e){let t=-1;let o=1;for(let i=e.length-1;i>=0;i--){t+=Ht[e[i]]*o,o*=26}return t}function Wt(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function Gt(e){return e>="0"&&e<="9"}function qt(e){let t;e=e.trim();for(let o=0;o<e.length;o++){const i=e[o];if(!t){if("$"===i&&0===o||Wt(i))continue;t=o}if(!Gt(i)){if("$"===i&&o===t)continue;throw new Error(`Invalid cell description: ${e}`)}}if(!t||t===e.length)throw new Error(`Invalid cell description: ${e}`);const o="$"===e[0]?e.slice(1,t):e.slice(0,t),i="$"===e[t]?e.slice(t+1):e.slice(t);if(o.length<1||o.length>3||i.length<1||i.length>7)throw new Error(`Invalid cell description: ${e}`);const s=$t(o),n=Number(i)-1;if(isNaN(n))throw new Error(`Invalid cell description: ${e}`);return{col:s,row:n}}function Zt(e,t,o={colFixed:!1,rowFixed:!1}){return(o.colFixed?"$":"")+Bt(e)+(o.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*%)?",eo="(\\s*-)?",to="(\\s*[\\$€])?",oo="^(("+[eo+to+Jt,eo+Jt+to,to+eo+Jt].join(")|(")+"))$",io=new RegExp(oo,"i");function so(e){return!!e&&io.test(e.trim())}const no=/[,\$€]+/g;function ro(e){e=e.replace(no,"");let t=Number(e);return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}function ao(e,t,o){const i=[...e].sort(((e,t)=>e-t));let s=(i.length+(o?-1:1))*t;if(o||s--,Number.isInteger(s))return i[s];const n=Math.ceil(s),r=Math.floor(s);return i[n]*(s-r)+i[r]*(n-s)}const lo=20,co=11,ho=/(\d+?)(?=(\d{3})+(?!\d)|$)/g,uo=/0/g,go={0:n("January"),1:n("February"),2:n("March"),3:n("April"),4:n("May"),5:n("June"),6:n("July"),7:n("August"),8:n("September"),9:n("October"),10:n("November"),11:n("December")},po={0:n("Sunday"),1:n("Monday"),2:n("Tuesday"),3:n("Wednesday"),4:n("Thursday"),5:n("Friday"),6:n("Saturday")},mo={};function fo(e){let t=mo[e];return void 0===t&&(t=function(e){if(""===e)throw new Error("A format cannot be empty");let t=0,o=[];for(;t<e.length;){let i;if("["===e.charAt(t)){if("$"!==e.charAt(t+1))throw new Error(`Currency formats have to be prefixed by a $: ${e}`);if(i=e.substring(t+1).indexOf("]")+t+2,0===i)throw new Error(`Invalid currency brackets format: ${e}`);const s=e.substring(t+2,i-1);if(s.includes("["))throw new Error(`Invalid currency format: ${e}`);o.push({type:"STRING",format:s})}else{const s=e.substring(t).indexOf("[");i=s>-1?s+t:e.length;const n=e.substring(t,i);xo(n)?o.push({type:"DATE",format:n}):o.push({type:"NUMBER",format:Do(n)})}t=i}return o}(e),mo[e]=t),t}function bo(e,t){switch(typeof e){case"string":return e.includes('\\"')?e.replace(/\\"/g,'"'):e;case"boolean":return e?"TRUE":"FALSE";case"number":t||(t=Ao(e));return function(e,t){if("DATE"===t[0].type)return Io(e,t[0].format);let o=e<0?"-":"";for(let i of t)switch(i.type){case"NUMBER":o+=vo(Math.abs(e),i.format);break;case"STRING":o+=i.format}return o}(e,fo(t));case"object":return"0"}}function vo(e,t){t.isPercent&&(e*=100),e/=t.magnitude;let o=0;void 0!==t.decimalPart&&(o=t.decimalPart.length);const{integerDigits:i,decimalDigits:s}=Co(e,o);let n=function(e,t,o){const i="0"===e?"":e;let s=i;const n=t.length-i.length;if(n>0){const e=(t.substring(0,n).match(uo)||[]).length;s="0".repeat(e)+s}o&&(s=s.match(ho)?.join(",")||s);return s}(i,t.integerPart,t.thousandsSeparator);return void 0!==t.decimalPart&&(n+="."+function(e,t){let o=e;if(t.length-e.length>0){const i=(t.substring(e.length,t.length+1).match(uo)||[]).length;o+="0".repeat(i)}return o}(s||"",t.decimalPart)),t.isPercent&&(n+="%"),n}const So=[];function Co(e,t=lo){const o=e.toString();if(o.includes("e"))return function(e,t=lo){let o=So[t];o||(o=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),So[t]=o);const[i,s]=o.format(e).split(".");return{integerDigits:i,decimalDigits:s}}(e,t);if(Number.isInteger(e))return{integerDigits:o,decimalDigits:void 0};const i=o.indexOf(".");let s=o.substring(0,i),n=o.substring(i+1);if(0===t)return Number(n[0])>=5&&(s=(Number(s)+1).toString()),{integerDigits:s,decimalDigits:void 0};if(n.length>t){const{integerDigits:e,decimalDigits:o}=function(e,t){let o="0",i=e,s=e.slice(0,t);const n=t;if(Number(e[n])<5)return{integerDigits:o,decimalDigits:s};const r=s.match(wo)?.[0]||"",a=(Number(s)+1).toString(),l=s.slice(r.length),c=a.length>l.length;c&&!r?(o="1",i=void 0):i=c?r.slice(0,-1)+a:r+a;return{integerDigits:o,decimalDigits:i}}(n,t);n=o,"0"!==e&&(s=(Number(s)+Number(e)).toString())}return{integerDigits:s,decimalDigits:Eo(n||"")}}function Eo(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const wo=/^0+/;function xo(e){if(!yo.has(e[0]))return!1;try{return Io(1,e),!0}catch(e){return!1}}const yo=new Set(["h","m","y","d"]);function Io(e,t){const o=Oe(e),i=t.indexOf("h");let s="",n="";return i>0?(s=Ro(o,t.substring(0,i-1)),n=To(o,t.substring(i))):0===i?n=To(o,t):i<0&&(s=Ro(o,t)),s+(s&&n?" ":"")+n}function Ro(e,t){const o=t.match(/\/|-|\s/)?.[0];return(o?t.split(o):[t]).map((o=>{switch(o){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return po[e.getDay()].slice(0,3);case"dddd":return po[e.getDay()];case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return go[e.getMonth()].slice(0,3);case"mmmm":return go[e.getMonth()];case"mmmmm":return go[e.getMonth()].slice(0,1);case"yy":const o=String(e.getFullYear()).replace("-","").padStart(2,"0");return o.slice(o.length-2);case"yyyy":return e.getFullYear();default:throw new Error(`invalid format: ${t}`)}})).join(o)}function To(e,t){let o=t.split(/:|\s/);const i=e.getHours(),s="a"===o[o.length-1];let n=i,r="";return s&&(n=0===n?12:n>12?n-12:n,r=i>=12?" PM":" AM",o.pop()),o.map((o=>{switch(o){case"hhhh":return Math.floor((e.getTime()-ve.getTime())/36e5).toString();case"hh":return n.toString().padStart(2,"0");case"mm":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");default:throw new Error(`invalid format: ${t}`)}})).join(":")+r}function Ao(e){let{integerDigits:t,decimalDigits:o}=Co(e);if(!o)return"0";const i=t.replace("-","").length;if(i+2>co)return"0";const s=co-i-1;return({decimalDigits:o}=Co(e,Math.min(s,o.length))),o?"0."+"0".repeat(o.length):"0"}function Oo(e){if(et(e)){return Te(e).format}if(!so(e))return;const t=e.includes(".")?"0.00":"0",o=e.match(/[\$€]/);if(o){const i=e.match(/[\d]/),s="[$"+o.values().next().value+"]";return i.index<o.index?"#,##"+t+s:s+"#,##"+t}return e.includes("%")?t+"%":void 0}function Mo(e,t,o){const i=fo(e||"#,##0"),s=[];for(let e=0;e<i.length;e++){const n=i[e];if("NUMBER"!==n.type){s.push(n);continue}s.push({...n,format:{...n.format,magnitude:t,decimalPart:void 0}}),s.push({type:"STRING",format:o});const r=i[e+1];"STRING"===r?.type&&["k","m","b"].includes(r.format)&&e++}return ko(s)}function No(e,t){const o=fo(e).map((e=>"NUMBER"===e.type?{...e,format:_o(e.format,t)}:e)),i=ko(o);return mo[i]=o,i}function _o(e,t){const o={...e},i=Math.sign(t),s=o.decimalPart?.length||0,n=Math.min(Math.max(0,s+i),lo);return o.decimalPart="0".repeat(n),""===o.decimalPart&&delete o.decimalPart,o}const Fo=/,*?$/;function Do(e){if(function(e){return Boolean(e.replace(Lo,""))}(e=e.trim()))throw new Error(`Invalid number format: ${e}`);const t=e.includes("%"),o=e.match(Fo)?.[0]||"",i=o?1e3**o.length:1;let s=e.slice(0,e.length-(o.length||0));const n=s.includes(",");if(/\..*,/.test(s))throw new Error("A format can't contain ',' symbol in the decimal part");s=s.replace("%","").replace(",","");const r=s.match(/[\%|,]/);if(r)throw new Error(`A format can only contain a single '${r[0]}' symbol`);const[a,l]=s.split(".");if(l&&l.length>20)throw new Error("A format can't contain more than 20 decimal places");return void 0!==l?{integerPart:a,isPercent:t,thousandsSeparator:n,decimalPart:l,magnitude:i}:{integerPart:a,isPercent:t,thousandsSeparator:n,magnitude:i}}const Lo=/[,#0.%]/g;function ko(e){let t="";for(let o of e){let e;switch(o.type){case"NUMBER":const t=o.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=`[$${o.format}]`;break;case"DATE":e=o.format}t+=e}return t}const Po=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),Uo=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),Vo=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),zo=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),Bo=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),Ho=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),$o=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[Po.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 Wo(e){return Bo.test(e)}function Go(e){return Ho.test(e)}function qo(e){return Vo.test(e)}function Zo(e){return zo.test(e)}function jo(e){return Uo.test(e)}function Yo(e){const t=e.split("!"),o=t.pop();return{sheetName:He(t.join("!"))||void 0,xc:o}}class Xo{getSheetSize;_zone;parts;invalidXc;prefixSheet=!1;sheetId;invalidSheetName;constructor(e,t){this.getSheetSize=t,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 Xo?e:new Xo(e,t.getSheetSize)}get unboundedZone(){return this._zone}get zone(){const{left:e,top:t,bottom:o,right:i}=this._zone;if(void 0!==i&&void 0!==o)return this._zone;if(void 0===o&&void 0!==i)return{right:i,top:t,left:e,bottom:this.getSheetSize(this.sheetId).numberOfRows-1};if(void 0===i&&void 0!==o)return{bottom:o,left:e,top:t,right:this.getSheetSize(this.sheetId).numberOfCols-1};throw new Error(n("Bad zone format"))}static getRangeParts(e,t){const o=e.split(":").map((e=>{const t=Go(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}})),i=void 0===t.bottom,s=void 0===t.right;return i&&(o[0].rowFixed=o[0].rowFixed||o[1].rowFixed,o[1].rowFixed=o[0].rowFixed||o[1].rowFixed),s&&(o[0].colFixed=o[0].colFixed||o[1].colFixed,o[1].colFixed=o[0].colFixed||o[1].colFixed),o}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(){const e={...this._zone};let t=this.parts;if(void 0!==e.right&&e.right<e.left){let o=e.right;e.right=e.left,e.left=o,t=[{colFixed:t[1]?.colFixed||!1,rowFixed:t[0]?.rowFixed||!1},{colFixed:t[0]?.colFixed||!1,rowFixed:t[1]?.rowFixed||!1}]}if(void 0!==e.bottom&&e.bottom<e.top){let o=e.bottom;e.bottom=e.top,e.top=o,t=[{colFixed:t[0]?.colFixed||!1,rowFixed:t[1]?.rowFixed||!1},{colFixed:t[1]?.colFixed||!1,rowFixed:t[0]?.rowFixed||!1}]}return this.clone({zone:e,parts:t})}clone(e){return new Xo({zone:e?.zone?e.zone:{...this._zone},sheetId: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:e?.parts?e.parts:this.parts.map((e=>({rowFixed:e.rowFixed,colFixed:e.colFixed}))),prefixSheet:e?.prefixSheet?e.prefixSheet:this.prefixSheet},this.getSheetSize)}}function Ko(e,t,o){const i=o.sheetId===e?t:o.sheetId;return o.clone({sheetId:i})}function Qo(e,t,o){if(!o)return;const i=e.getRangeFromSheetXC(t,o);return i.invalidSheetName||i.invalidXc?void 0:i}function Jo(e,t,o){const i=[];return t.forEach((t=>{const s=function(e,t){e=e.toLocaleLowerCase();let o=0,i=0,s=(t=t.toLocaleLowerCase()).length,n=0;for(let r=0;r<s;r++)t[r]===e[n]?(n++,i+=100+i-r/200):i=0,o+=i;return n===e.length?o:0}(e,o(t));s>0&&i.push({score:s,elem:t})})),i.sort(((e,t)=>t.score-e.score)),i.map((e=>e.elem))}function ei(e){const t=[];for(let o=0;o<e;o++){const e={cells:{}};t.push(e)}return t}class ti{isFastIdStrategy=!1;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 oi(e){const t=function(e){let t,o,i,s,n;e.includes("!")&&(e=e.split("!").at(-1)),e.includes("$")&&(e=e.replace(/\$/g,"")),t=e.includes(":")?e.split(":").map((e=>e.trim())):[e.trim()];let r=!1,a=!1,l=!1;const c=t[0],h=t[1]&&t[1];if(Wo(c))s=n=$t(c),o=i=0,r=!0;else if(Go(c))o=i=parseInt(c,10)-1,s=n=0,a=!0;else{const e=qt(c);s=n=e.col,o=i=e.row,l=!0}if(2===t.length)if(Wo(h))n=$t(h),r=!0;else if(Go(h))i=parseInt(h,10)-1,a=!0;else{const e=qt(h);n=e.col,i=e.row,o=r?i:o,s=a?n:s,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:o,left:s,bottom:r?void 0:i,right:a?void 0:n};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 ii(e){const t=oi(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function si(e){const{bottom:t,top:o,left:i,right:s}=e;return!(void 0!==t&&isNaN(t)||isNaN(o)||isNaN(i)||void 0!==s&&isNaN(s))&&((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 ni(e){const{top:t,bottom:o,left:i,right:s}=e,r="hasHeader"in e&&e.hasHeader,a=t===o&&i===s;if(void 0===o&&void 0!==s)return 0!==t||r?`${Zt(i,t)}:${Bt(s)}`:`${Bt(i)}:${Bt(s)}`;if(void 0===s&&void 0!==o)return 0!==i||r?`${Zt(i,t)}:${o+1}`:`${t+1}:${o+1}`;if(void 0!==o&&void 0!==s)return a?Zt(i,t):`${Zt(i,t)}:${Zt(s,o)}`;throw new Error(n("Bad zone format"))}function ri(e,t,o,i,s){const n="left"===t?"columns":"rows",r="before"===i?o-1:o,a=e["left"===t?"right":"bottom"];return e[t]<=r&&a&&a>r?Ei(e,n,"RESIZE",s):r<e[t]?Ei(e,n,"MOVE",s):{...e}}function ai(e,t,o,i,s){const n="left"===t?"columns":"rows",r="before"===i?o-1:o,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?Ei(e,n,"RESIZE",s):r<e[t]?Ei(e,n,"MOVE",s):{...e}}function li(e,t,o){const i="left"===t?"right":"bottom";let s=e[t],n=e[i];for(let r of o.sort(((e,t)=>t-e)))e[t]>r&&(s--,n--),e[t]<r&&e[i]>=r&&n--;return{...e,[t]:s,[i]:n}}function ci(e,t,o){const i="left"===t?"right":"bottom";let s=e[t],n=e[i];const r=e[i];for(let i of o.sort(((e,t)=>t-e)))e[t]>i&&(s--,void 0!==n&&n--),void 0!==r&&void 0!==n&&e[t]<=i&&r>=i&&n--;if(!(void 0!==n&&s>n))return{...e,[t]:s,[i]:n}}function hi(...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 di(e,t){if(gi(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 ui(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function gi(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function pi(e,t,o){const{left:i,right:s,top:n,bottom:r}=o;return e>=i&&e<=s&&t>=n&&t<=r}function mi(e,t){return ui(hi(t,e),t)}function fi(e,t){const o=e.map(oi),i=t.map(ii),s=Math.max(...o.concat(i).map((e=>e.bottom||0))),n=Math.max(...o.concat(i).map((e=>e.right||0))),r=o.map((e=>({...e,bottom:void 0===e.bottom?s+1:e.bottom,right:void 0===e.right?n+1:e.right}))),a=i.map((e=>({...e,bottom:void 0===e.bottom?s+1:e.bottom,right:void 0===e.right?n+1:e.right}))),l=function(e,t){const o=new Set(t.map((({col:e,row:t})=>`${e}-${t}`)));return e.filter((({col:e,row:t})=>!o.has(`${e}-${t}`)))}(r.map(Ci).flat(),a.map(Ci).flat()),c=function(e){if(0===e.length)return[];const[t,...o]=[...e].sort(((e,t)=>e.row-t.row)).sort(((e,t)=>e.col-t.col)),i=[];let s=yi(t);for(const{col:e,row:t}of o)if(!pi(e,t,s))if(e===s.left&&t===s.bottom+1){const e=s.bottom+1;s={...s,bottom:e}}else i.push(s),s=yi({col:e,row:t});return[...i,s]}(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=[],o=bi(e),i=(e,t)=>e.top===t.top&&e.bottom===t.bottom&&e.right+1===t.left;for(;o.length;){const e=o.reduce(((e,t)=>i(e,t)?hi(e,t):e),o.shift());t.push(e)}return bi(t)}(c).map((e=>({...e,bottom:e.bottom===s+1?void 0:e.bottom,right:e.right===n+1?void 0:e.right}))).map(ni)}function bi(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(),o=[];for(;0!==t.length;){const e=t.shift();t.some((t=>mi(e,t)))||o.push(e)}return o.reverse()}function vi(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function Si(e){const{numberOfCols:t,numberOfRows:o}=vi(e);return 1===t||1===o}function Ci(e){const t=[],[o,i]=[e.right,e.left].sort(((e,t)=>e-t)),[s,n]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of Ke(o,i+1))for(const o of Ke(s,n+1))t.push({col:e,row:o});return t}function Ei(e,t,o,i){const s="both"===t?i[0]:"columns"===t?i:0,n="both"===t?i[1]:"rows"===t?i:0,r="hasHeader"in e&&e.hasHeader;let a;a=!function(e){return void 0===e.bottom}(e)||r?!(Ii(e)&&!r)||"columns"!==t:"rows"!==t;const l={...e};return a&&"MOVE"===o&&(l.left+=s,l.top+=n),void 0!==l.right&&(l.right+=s),void 0!==l.bottom&&(l.bottom+=n),l}function wi(e,t){let o,i;const{left:s,right:n,top:r,bottom:a}=e,{left:l,right:c,top:h,bottom:d}=t;return o=l!=s?l:c!=n?c:l,i=h!=r?h:d!=a?d:h,{col:o,row:i}}function xi(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 yi(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function Ii(e){return void 0===e.right}function Ri(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function Ti(...e){return e.length<2||1===fi(e.map(ni),[]).length}class Ai extends t.Component{static template="o-spreadsheet-ChartJsComponent";canvas=t.useRef("graphContainer");chart;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;vt(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){const t=e.chartJsConfig;t.data&&t.data.datasets?(this.chart.data=t.data,t.options?.title&&(this.chart.config.options.title=t.options.title),t.options&&"valueLabel"in t.options&&t.options?.valueLabel&&(this.chart.config.options.valueLabel=t.options.valueLabel)):this.chart.data.datasets=void 0,this.chart.config.options.tooltips=t.options?.tooltips,this.chart.config.options.legend=t.options?.legend,this.chart.config.options.scales=t.options?.scales,this.chart.update({duration:0})}}Ai.props={figure:Object};const Oi={};let Mi=0;function Ni(e,...t){const o="__sheet__"+Mi++;return function(e,t){const o=document.createElement("style");o.textContent=function(e){const t=e.split(/(\{|\}|;)/).map((e=>e.trim())),o=[],i=[];let s=[];function n(e,t){const i=[];for(const s of o[e]){let r=t&&t+" "+s||s;r.includes("&")&&(r=s.replace(/&/g,t||"")),e<o.length-1&&(r=n(e+1,r)),i.push(r)}return i.join(", ")}function r(){s.length&&(i.push(n(0)+" {"),i.push(...s),i.push("}"),s=[])}for(;t.length;){let e=t.shift();"}"===e?(r(),o.pop()):("{"===t[0]&&(r(),o.push(e.split(/\s*,\s*/)),t.shift()),";"===t[0]&&s.push(" "+e+";"))}return i.join("\n")}(t),Oi[e]=o}(o,String.raw(e,...t)),function(e){const t=Oi[e];t.setAttribute("component",e),document.head.appendChild(t)}(o),o}function _i({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function Fi(e){const t=Di(e);return e?(e.fillColor&&(t.background=e.fillColor),t):t}function Di(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 o=e.strikethrough?"line-through":"";o=e.underline?o+" underline":o,t["text-decoration"]=o}return e.textColor&&(t.color=e.textColor),t}function Li(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>`${e}:${t};`)).join(" ")}const ki=1.2;Ni`
|
|
1
|
+
!function(e,t){"use strict";let o=e=>e;function i(e,...t){if(1===t.length&&"object"==typeof t[0]){const o=t[0];e=e.replace(/\%\(?([^\)]+)\)s/g,((e,t)=>o[t]))}else t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));return e}const s=function(e,...t){return i(o(e),...t)},n=function(e,...t){return new r(e,t)};class r extends String{values;constructor(e,t){super(e),this.values=t}valueOf(){const e=super.valueOf();return i(o(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{errorType;logLevel;constructor(e,t,o=l.error){super(t),this.errorType=e,this.logLevel=o}}class h extends c{constructor(e){super(a.BadExpression,e)}}class d extends c{constructor(){super(a.CircularDependency,n("Circular reference"))}}class u extends c{constructor(){super(a.InvalidReference,n("Invalid reference"))}}class g extends c{constructor(e){super(a.NotAvailable,e||n("Data not available"),e?l.error:l.silent)}}class p extends c{constructor(e){super(a.UnknownFunction,n('Unknown function: "%s"',e))}}const m=.5,f="#f5f5f5",b="#F8F9FA",v="#E8EAED",S="#595959",C="#666666",E="#3266ca",w="#FFFFFF",x="#EBEBEB",y="#CACACA",I=11982760,R="#01666b",T="#188038",A="#E6F4EA",O="#CEEAD6",M="#E0E2E4",N="#4A4F59",_=["#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"],F=26,D=48,L=96,P=23,k=15,U=18,V=14,z=4,B=4,H=3,$=B,W=17,G=250,q="400",Z=10,j="'Roboto', arial",Y="bottom",X="thin",K="#000000",Q={style:"thin",color:T},J=a.InvalidReference,ee="START_REVISION",te=1,oe=20,ie="??",se="difference",ne="#00A04A",re="#DC6965",ae=.4,le=["'","*","?","/","\\","[","]"],ce=/'|\*|\?|\/|\\|\[|\]/,he="|",de=n("Invalid expression");var ue;!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.FigureAnchor=1e3]="FigureAnchor",e[e.FigureSnapLine=1001]="FigureSnapLine"}(ue||(ue={}));let ge=0;function pe(){return ge}const me="\n",fe=[6,7,8,9,10,11,12,14,18,24,36];class be{jsDate;constructor(e,t,o,i=0,s=0,n=0){this.jsDate=new Date(Date.UTC(e,t,o,i,s,n,0))}static fromTimestamp(e){const t=new Date(e);return new be(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())}static now(){const e=new Date;return new be(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds())}toString(){return this.jsDate.toString()}toLocaleDateString(){return this.jsDate.toLocaleDateString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}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 ve=new be(1899,11,30),Se=864e5,Ce=2e3,Ee=be.now().getFullYear(),we=be.fromTimestamp(0).getTime()-ve.getTime(),xe=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,ye=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,Ie=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/,Re={};function Te(e){if(e in Re)return Re[e];const t=function(e){let t;e=e.trim();const o=e.match(Ie);if(o){if(t=function(e){if(e=e.trim(),Ie.test(e)){const t=/AM/i.test(e),o=/PM/i.test(e),i=(t||o?e.substring(0,e.length-2).trim():e).split(/:/),s=i.length>=2,n=3===i.length;let r=Number(i[0]),a=s?Number(i[1]):0,l=n?Number(i[2]):0,c=n?"hh:mm:ss":"hh:mm";if(t||o)c+=" a";else if(!s)return null;r>=12&&t?r-=12:r<12&&o&&(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 be(1899,11,30,r,a,l)}}return null}(o[0]),null===t)return null;e=e.replace(o[0],"").trim()}let i;const s=e.match(xe),n=e.match(ye);if(s||n){let t;if(s?(t=s[0],i=Ae(t,"mdy")):(t=n[0],i=Ae(t,"ymd")),null===i)return null;e=e.replace(t,"").trim()}if(""!==e||!i&&!t)return null;if(i&&t)return{value:i.value+t.value,format:i.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new be(i.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,i.jsDate.getMonth()+t.jsDate.getMonth()-11,i.jsDate.getDate()+t.jsDate.getDate()-30,i.jsDate.getHours()+t.jsDate.getHours(),i.jsDate.getMinutes()+t.jsDate.getMinutes(),i.jsDate.getSeconds()+t.jsDate.getSeconds())};return i||t}(e);return Re[e]=t,t}function Ae(e,t){const o="mdy"===t;if(o||"ymd"===t){const t=e.split(/\/|-|\s/),i=o?0:1,s=o?1:2,n=o?2:0,r=Number(t[i]),a=Number(t[s]),l=2===t[i].length&&r<10||2===t[s].length&&a<10,c=t[n]?function(e){const t=Number(e);switch(e.length){case 1:return Ce+t;case 2:return Ce+(Ce+t>Ee+10?-100:0)+t;case 3:case 4:return t}return 0}(t[n]):Ee,h=new be(c,r-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==r-1||h.getDate()!==a)return null;const u=h.getTime()-ve.getTime();let g=l?`mm${d}dd`:`m${d}d`;return t[n]&&(g=o?g+d+"yyyy":"yyyy"+d+g),{value:Math.round(u/Se),format:g,jsDate:h}}return null}function Oe(e){const t=Math.trunc(e);let o=be.fromTimestamp(t*Se-we),i=e-t;i=i<0?1+i:i;const s=Math.round(24*i),n=Math.round(24*(i-s/24)*60),r=Math.round(24*(i-s/24-n/24/60)*60*60);return o.setHours(s),o.setMinutes(n),o.setSeconds(r),o}function Me(e){const t=e.getTime()-ve.getTime();return Math.round(t/Se)}function Ne(e){return new be(e.getFullYear(),e.getMonth()+1,0).getDate()}function _e(e){return Ne(e)===e.getDate()}function Fe(e,t,o){const i=e.getFullYear(),s=e.getMonth(),n=e.getDate(),r=new be(i,s+t,1);return o&&n===Ne(e)||n>Ne(r)?r.setDate(Ne(r)):r.setDate(n),r}function De(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function Le(e,t,o){if(e===t)return 0;if(e>t){const o=t;t=e,e=o}const i=Oe(e),s=Oe(t);let n=i.getDate(),r=s.getDate();const a=i.getMonth(),l=s.getMonth(),c=i.getFullYear(),h=s.getFullYear();let d=0,u=0;switch(o){case 0:31===n&&(n=30),30===n&&31===r&&(r=30),1===a&&n===(De(c)?29:28)&&(n=30,1===l&&r===(De(h)?29:28)&&(r=30)),d=c+(30*a+n)/360,u=h+(30*l+r)/360;break;case 1:let o=365;const i=c===h;if(!i&&!(c+1===h)||!i&&a<l||!i&&a===l&&n<r){let e=0,t=0;for(let o=c;o<=h;o++)e++,t+=De(o)?366:365;o=t/e}else i?De(c)&&(o=366):(De(c)&&a<2&&(o=366),De(h)&&(l>1||1===l&&29===r)&&(o=366));d=e/o,u=t/o;break;case 2:d=e/360,u=t/360;break;case 3:d=e/365,u=t/365;break;case 4:31===n&&(n=30),31===r&&(r=30),d=c+(30*a+n)/360,u=h+(30*l+r)/360}return u-d}function Pe(e,t){const o=12*(t.getFullYear()-e.getFullYear())+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?o-1:o}function ke(e,t){const o=e.getTime(),i=t.getTime();return Math.floor((i-o)/Se)}function Ue(e,t){const o=t.getFullYear()-e.getFullYear(),i=e.getMonth(),s=t.getMonth(),n=e.getDate(),r=t.getDate();return s>i||s===i&&r>=n?o:o-1}function Ve(e){return'"'===e[0]&&(e=e.slice(1)),'"'===e[e.length-1]&&"\\"!==e[e.length-2]?e.slice(0,e.length-1):e}function ze(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Be(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&&e?.constructor===Object}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");for(const o in e)t[o]=Be(e[o]);return t;case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function He(e){return e.startsWith("'")&&(e=e.slice(1,-1).replace(/''/g,"'")),e}function $e(e){return e.match(/\w/g)?.length!==e.length&&(e=`'${e}'`),e}function We(e,t,o){return e<t?t:e>o?o:e}function Ge(e,t=1){return t*(e+B)-B}function qe(e,t,o){const i=Ye(o);if(Ze[i]||(Ze[i]={}),void 0===Ze[i][t]){e.save(),e.font=i;const o=e.measureText(t).width;e.restore(),Ze[i][t]=o}return Ze[i][t]}const Ze={};function je(e){return Math.round(96*e/72)}function Ye(e){return`${e.italic?"italic ":""}${e.bold?"bold":q} ${Xe(e)}px ${j}`}function Xe(e){return je(e?.fontSize||Z)}function Ke(e,t,o=1){if(t<=e&&o>0)return[];if(0===o)throw new Error("range() step must not be zero");const i=Math.ceil(Math.abs((t-e)/o)),s=Array(i);for(let t=0;t<i;t++)s[t]=e+t*o;return s}function Qe(e){return e.reduce(((e,t,o,i)=>{if(1===Math.abs(t-i[o-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*Je(e,t){t.next();for(const o of e){const e=t.next();yield{...o,next:e.done?void 0:e.value}}}function et(e){return null!==Te(e)}const tt=/^\[(.+)\]\((.+)\)$/,ot=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function it(e){return tt.test(e)}function st(e){return ot.test(e)}function nt(e,t){return`[${e}](${t})`}function rt(e){const t=e.match(tt)||[],o=t[1],i=t[2];if(!o||!i)throw new Error(`Could not parse markdown link ${e}.`);return{label:o,url:i}}const at="o-spreadsheet://";function lt(e){return e.startsWith(at)}function ct(e){return`${at}${e}`}function ht(e){if(e.startsWith(at))return e.substr(at.length);throw new Error(`${e} is not a valid sheet link`)}function dt(e){return void 0!==e}function ut(e){return void 0===e||Object.values(e).every((e=>"object"==typeof e?ut(e):!e))}function gt(e,t){for(let[o,i]of Object.entries(t))if(vt(i,e))return parseInt(o,10);const o=Object.keys(t),i=0===o.length?0:Rt(o.map((e=>parseInt(e,10))));return t[i+1]=e,i+1}function pt(e){let t="";for(let o=0,i=e.length;o<i;o++)t+=e[o];return t}function mt(e){let t,o=!1;const i=()=>(o||(t=e instanceof Function?e():e,o=!0),t);return i.map=e=>mt((()=>e(i()))),i}function ft(e,t){let o=e.slice(t).find((e=>e));return o||(o=e.slice(0,t).reverse().find((e=>e))),o||""}function bt(e,t){return"after"===e?t+1:t}function vt(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;if(typeof e!=typeof t)return!1;if("object"!=typeof e)return!1;const o=new Set;Object.keys(e).forEach((e=>o.add(e))),Object.keys(t).forEach((e=>o.add(e)));for(let i of o){if(typeof e[i]!=typeof e[i])return!1;if("object"==typeof e[i]){if(!vt(e[i],t[i]))return!1}else if(e[i]!==t[i])return!1}return!0}function St(e,t){return t.every((t=>e.includes(t)))}function Ct(e){const t={...e};return Object.keys(t).forEach((e=>!t[e]&&delete t[e])),t}function Et(e){return e?e.toLowerCase():""}const wt=[" ","\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))],xt=new RegExp(wt.join("|"),"g"),yt=/\r\n|\r|\n/g;function It(e){return e?e=(e=e.replace(xt," ")).replace(yt,me):""}function Rt(e){let t=e.length;if(t<1e5)return Math.max(...e);let o=-1/0;for(;t--;)o=e[t]>o?e[t]:o;return o}function Tt(e){let t=e.length;if(t<1e5)return Math.min(...e);let o=1/0;for(;t--;)o=e[t]<o?e[t]:o;return o}const At=/rgba?\(|\s+|\)/gi,Ot=/^#([A-F\d]{2}){3,4}$/,Mt=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function Nt(e){return _t(e.toString(16).padStart(6,"0"))}function _t(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(At,"").split(",");let o=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");o=Math.round(255*(e||1))}const i=t.map((e=>parseInt(e,10)));255!==o&&i.push(o);return"#"+pt(i.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}`),!Ot.test(t))throw new Error(`invalid color input: ${e}`);return t}function Ft(e){try{return _t(e),!0}catch(e){return!1}}const Dt=e=>e>=0&&e<=255;function Lt(e,t,o,i=1){if(!Dt(e)||!Dt(t)||!Dt(o)||i<0||i>1)throw new Error(`Invalid RGBA values ${[e,t,o,i]}`);return{a:i,b:o,g:t,r:e}}function Pt(e){let{r:t,g:o,b:i}=Ut(e);t/=255,o/=255,i/=255;const s=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*s(t)+.7152*s(o)+.0722*s(i)}function kt(e){let t=e.r.toString(16),o=e.g.toString(16),i=e.b.toString(16),s=Math.round(255*e.a).toString(16);return 1==t.length&&(t="0"+t),1==o.length&&(o="0"+o),1==i.length&&(i="0"+i),1==s.length&&(s="0"+s),"ff"===s&&(s=""),("#"+t+o+i+s).toUpperCase()}function Ut(e){let t,o,i,s;if(7===(e=_t(e)).length)t=parseInt(e[1]+e[2],16),o=parseInt(e[3]+e[4],16),i=parseInt(e[5]+e[6],16),s=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),o=parseInt(e[3]+e[4],16),i=parseInt(e[5]+e[6],16),s=parseInt(e[7]+e[8],16)}return s=+(s/255).toFixed(3),{a:s,r:t,g:o,b:i}}function Vt(e){(e={...e}).s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,o=t*(1-Math.abs(e.h/60%2-1)),i=e.l-t/2,s=0,n=0,r=0;return 0<=e.h&&e.h<60?(s=t,n=o,r=0):60<=e.h&&e.h<120?(s=o,n=t,r=0):120<=e.h&&e.h<180?(s=0,n=t,r=o):180<=e.h&&e.h<240?(s=0,n=o,r=t):240<=e.h&&e.h<300?(s=o,n=0,r=t):300<=e.h&&e.h<360&&(s=t,n=0,r=o),s=Math.round(255*(s+i)),n=Math.round(255*(n+i)),r=Math.round(255*(r+i)),{a:e.a,r:s,g:n,b:r}}function zt(e){const t=e.r/255,o=e.g/255,i=e.b/255;let s=Math.min(t,o,i),n=Math.max(t,o,i),r=n-s,a=0,l=0,c=0;return a=0==r?0:n==t?(o-i)/r%6:n==o?(i-t)/r+2:(t-o)/r+4,a=Math.round(60*a),a<0&&(a+=360),c=(n+s)/2,l=0==r?0:r/(1-Math.abs(2*c-1)),l=+(100*l).toFixed(1),c=+(100*c).toFixed(1),{a:e.a,h:a,s:l,l:c}}function Bt(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Bt(Math.floor(e/26)-1)+Bt(e%26)}const Ht={};for(const e of"ABCDEFGHIJKLMNOPQRSTUVWXYZ"){const t=e.charCodeAt(0)-64;Ht[e]=t,Ht[e.toLowerCase()]=t}function $t(e){let t=-1;let o=1;for(let i=e.length-1;i>=0;i--){t+=Ht[e[i]]*o,o*=26}return t}function Wt(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function Gt(e){return e>="0"&&e<="9"}function qt(e){let t;e=e.trim();for(let o=0;o<e.length;o++){const i=e[o];if(!t){if("$"===i&&0===o||Wt(i))continue;t=o}if(!Gt(i)){if("$"===i&&o===t)continue;throw new Error(`Invalid cell description: ${e}`)}}if(!t||t===e.length)throw new Error(`Invalid cell description: ${e}`);const o="$"===e[0]?e.slice(1,t):e.slice(0,t),i="$"===e[t]?e.slice(t+1):e.slice(t);if(o.length<1||o.length>3||i.length<1||i.length>7)throw new Error(`Invalid cell description: ${e}`);const s=$t(o),n=Number(i)-1;if(isNaN(n))throw new Error(`Invalid cell description: ${e}`);return{col:s,row:n}}function Zt(e,t,o={colFixed:!1,rowFixed:!1}){return(o.colFixed?"$":"")+Bt(e)+(o.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*%)?",eo="(\\s*-)?",to="(\\s*[\\$€])?",oo="^(("+[eo+to+Jt,eo+Jt+to,to+eo+Jt].join(")|(")+"))$",io=new RegExp(oo,"i");function so(e){return!!e&&io.test(e.trim())}const no=/[,\$€]+/g;function ro(e){e=e.replace(no,"");let t=Number(e);return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}function ao(e,t,o){const i=[...e].sort(((e,t)=>e-t));let s=(i.length+(o?-1:1))*t;if(o||s--,Number.isInteger(s))return i[s];const n=Math.ceil(s),r=Math.floor(s);return i[n]*(s-r)+i[r]*(n-s)}const lo=20,co=11,ho=/(\d+?)(?=(\d{3})+(?!\d)|$)/g,uo=/0/g,go={0:n("January"),1:n("February"),2:n("March"),3:n("April"),4:n("May"),5:n("June"),6:n("July"),7:n("August"),8:n("September"),9:n("October"),10:n("November"),11:n("December")},po={0:n("Sunday"),1:n("Monday"),2:n("Tuesday"),3:n("Wednesday"),4:n("Thursday"),5:n("Friday"),6:n("Saturday")},mo={};function fo(e){let t=mo[e];return void 0===t&&(t=function(e){if(""===e)throw new Error("A format cannot be empty");let t=0,o=[];for(;t<e.length;){let i;if("["===e.charAt(t)){if("$"!==e.charAt(t+1))throw new Error(`Currency formats have to be prefixed by a $: ${e}`);if(i=e.substring(t+1).indexOf("]")+t+2,0===i)throw new Error(`Invalid currency brackets format: ${e}`);const s=e.substring(t+2,i-1);if(s.includes("["))throw new Error(`Invalid currency format: ${e}`);o.push({type:"STRING",format:s})}else{const s=e.substring(t).indexOf("[");i=s>-1?s+t:e.length;const n=e.substring(t,i);xo(n)?o.push({type:"DATE",format:n}):o.push({type:"NUMBER",format:Do(n)})}t=i}return o}(e),mo[e]=t),t}function bo(e,t){switch(typeof e){case"string":return e.includes('\\"')?e.replace(/\\"/g,'"'):e;case"boolean":return e?"TRUE":"FALSE";case"number":t||(t=Ao(e));return function(e,t){if("DATE"===t[0].type)return Io(e,t[0].format);let o=e<0?"-":"";for(let i of t)switch(i.type){case"NUMBER":o+=vo(Math.abs(e),i.format);break;case"STRING":o+=i.format}return o}(e,fo(t));case"object":return"0"}}function vo(e,t){t.isPercent&&(e*=100),e/=t.magnitude;let o=0;void 0!==t.decimalPart&&(o=t.decimalPart.length);const{integerDigits:i,decimalDigits:s}=Co(e,o);let n=function(e,t,o){const i="0"===e?"":e;let s=i;const n=t.length-i.length;if(n>0){const e=(t.substring(0,n).match(uo)||[]).length;s="0".repeat(e)+s}o&&(s=s.match(ho)?.join(",")||s);return s}(i,t.integerPart,t.thousandsSeparator);return void 0!==t.decimalPart&&(n+="."+function(e,t){let o=e;if(t.length-e.length>0){const i=(t.substring(e.length,t.length+1).match(uo)||[]).length;o+="0".repeat(i)}return o}(s||"",t.decimalPart)),t.isPercent&&(n+="%"),n}const So=[];function Co(e,t=lo){const o=e.toString();if(o.includes("e"))return function(e,t=lo){let o=So[t];o||(o=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),So[t]=o);const[i,s]=o.format(e).split(".");return{integerDigits:i,decimalDigits:s}}(e,t);if(Number.isInteger(e))return{integerDigits:o,decimalDigits:void 0};const i=o.indexOf(".");let s=o.substring(0,i),n=o.substring(i+1);if(0===t)return Number(n[0])>=5&&(s=(Number(s)+1).toString()),{integerDigits:s,decimalDigits:void 0};if(n.length>t){const{integerDigits:e,decimalDigits:o}=function(e,t){let o="0",i=e,s=e.slice(0,t);const n=t;if(Number(e[n])<5)return{integerDigits:o,decimalDigits:s};const r=s.match(wo)?.[0]||"",a=(Number(s)+1).toString(),l=s.slice(r.length),c=a.length>l.length;c&&!r?(o="1",i=void 0):i=c?r.slice(0,-1)+a:r+a;return{integerDigits:o,decimalDigits:i}}(n,t);n=o,"0"!==e&&(s=(Number(s)+Number(e)).toString())}return{integerDigits:s,decimalDigits:Eo(n||"")}}function Eo(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const wo=/^0+/;function xo(e){if(!yo.has(e[0]))return!1;try{return Io(1,e),!0}catch(e){return!1}}const yo=new Set(["h","m","y","d"]);function Io(e,t){const o=Oe(e),i=t.indexOf("h");let s="",n="";return i>0?(s=Ro(o,t.substring(0,i-1)),n=To(o,t.substring(i))):0===i?n=To(o,t):i<0&&(s=Ro(o,t)),s+(s&&n?" ":"")+n}function Ro(e,t){const o=t.match(/\/|-|\s/)?.[0];return(o?t.split(o):[t]).map((o=>{switch(o){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return po[e.getDay()].slice(0,3);case"dddd":return po[e.getDay()];case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return go[e.getMonth()].slice(0,3);case"mmmm":return go[e.getMonth()];case"mmmmm":return go[e.getMonth()].slice(0,1);case"yy":const o=String(e.getFullYear()).replace("-","").padStart(2,"0");return o.slice(o.length-2);case"yyyy":return e.getFullYear();default:throw new Error(`invalid format: ${t}`)}})).join(o)}function To(e,t){let o=t.split(/:|\s/);const i=e.getHours(),s="a"===o[o.length-1];let n=i,r="";return s&&(n=0===n?12:n>12?n-12:n,r=i>=12?" PM":" AM",o.pop()),o.map((o=>{switch(o){case"hhhh":return Math.floor((e.getTime()-ve.getTime())/36e5).toString();case"hh":return n.toString().padStart(2,"0");case"mm":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");default:throw new Error(`invalid format: ${t}`)}})).join(":")+r}function Ao(e){let{integerDigits:t,decimalDigits:o}=Co(e);if(!o)return"0";const i=t.replace("-","").length;if(i+2>co)return"0";const s=co-i-1;return({decimalDigits:o}=Co(e,Math.min(s,o.length))),o?"0."+"0".repeat(o.length):"0"}function Oo(e){if(et(e)){return Te(e).format}if(!so(e))return;const t=e.includes(".")?"0.00":"0",o=e.match(/[\$€]/);if(o){const i=e.match(/[\d]/),s="[$"+o.values().next().value+"]";return i.index<o.index?"#,##"+t+s:s+"#,##"+t}return e.includes("%")?t+"%":void 0}function Mo(e,t,o){const i=fo(e||"#,##0"),s=[];for(let e=0;e<i.length;e++){const n=i[e];if("NUMBER"!==n.type){s.push(n);continue}s.push({...n,format:{...n.format,magnitude:t,decimalPart:void 0}}),s.push({type:"STRING",format:o});const r=i[e+1];"STRING"===r?.type&&["k","m","b"].includes(r.format)&&e++}return Po(s)}function No(e,t){const o=fo(e).map((e=>"NUMBER"===e.type?{...e,format:_o(e.format,t)}:e)),i=Po(o);return mo[i]=o,i}function _o(e,t){const o={...e},i=Math.sign(t),s=o.decimalPart?.length||0,n=Math.min(Math.max(0,s+i),lo);return o.decimalPart="0".repeat(n),""===o.decimalPart&&delete o.decimalPart,o}const Fo=/,*?$/;function Do(e){if(function(e){return Boolean(e.replace(Lo,""))}(e=e.trim()))throw new Error(`Invalid number format: ${e}`);const t=e.includes("%"),o=e.match(Fo)?.[0]||"",i=o?1e3**o.length:1;let s=e.slice(0,e.length-(o.length||0));const n=s.includes(",");if(/\..*,/.test(s))throw new Error("A format can't contain ',' symbol in the decimal part");s=s.replace("%","").replace(",","");const r=s.match(/[\%|,]/);if(r)throw new Error(`A format can only contain a single '${r[0]}' symbol`);const[a,l]=s.split(".");if(l&&l.length>20)throw new Error("A format can't contain more than 20 decimal places");return void 0!==l?{integerPart:a,isPercent:t,thousandsSeparator:n,decimalPart:l,magnitude:i}:{integerPart:a,isPercent:t,thousandsSeparator:n,magnitude:i}}const Lo=/[,#0.%]/g;function Po(e){let t="";for(let o of e){let e;switch(o.type){case"NUMBER":const t=o.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=`[$${o.format}]`;break;case"DATE":e=o.format}t+=e}return t}const ko=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),Uo=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),Vo=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),zo=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),Bo=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),Ho=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),$o=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[ko.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 Wo(e){return Bo.test(e)}function Go(e){return Ho.test(e)}function qo(e){return Vo.test(e)}function Zo(e){return zo.test(e)}function jo(e){return Uo.test(e)}function Yo(e){const t=e.split("!"),o=t.pop();return{sheetName:He(t.join("!"))||void 0,xc:o}}class Xo{getSheetSize;_zone;parts;invalidXc;prefixSheet=!1;sheetId;invalidSheetName;constructor(e,t){this.getSheetSize=t,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 Xo?e:new Xo(e,t.getSheetSize)}get unboundedZone(){return this._zone}get zone(){const{left:e,top:t,bottom:o,right:i}=this._zone;if(void 0!==i&&void 0!==o)return this._zone;if(void 0===o&&void 0!==i)return{right:i,top:t,left:e,bottom:this.getSheetSize(this.sheetId).numberOfRows-1};if(void 0===i&&void 0!==o)return{bottom:o,left:e,top:t,right:this.getSheetSize(this.sheetId).numberOfCols-1};throw new Error(n("Bad zone format"))}static getRangeParts(e,t){const o=e.split(":").map((e=>{const t=Go(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}})),i=void 0===t.bottom,s=void 0===t.right;return i&&(o[0].rowFixed=o[0].rowFixed||o[1].rowFixed,o[1].rowFixed=o[0].rowFixed||o[1].rowFixed),s&&(o[0].colFixed=o[0].colFixed||o[1].colFixed,o[1].colFixed=o[0].colFixed||o[1].colFixed),o}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(){const e={...this._zone};let t=this.parts;if(void 0!==e.right&&e.right<e.left){let o=e.right;e.right=e.left,e.left=o,t=[{colFixed:t[1]?.colFixed||!1,rowFixed:t[0]?.rowFixed||!1},{colFixed:t[0]?.colFixed||!1,rowFixed:t[1]?.rowFixed||!1}]}if(void 0!==e.bottom&&e.bottom<e.top){let o=e.bottom;e.bottom=e.top,e.top=o,t=[{colFixed:t[0]?.colFixed||!1,rowFixed:t[1]?.rowFixed||!1},{colFixed:t[1]?.colFixed||!1,rowFixed:t[0]?.rowFixed||!1}]}return this.clone({zone:e,parts:t})}clone(e){return new Xo({zone:e?.zone?e.zone:{...this._zone},sheetId: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:e?.parts?e.parts:this.parts.map((e=>({rowFixed:e.rowFixed,colFixed:e.colFixed}))),prefixSheet:e?.prefixSheet?e.prefixSheet:this.prefixSheet},this.getSheetSize)}}function Ko(e,t,o){const i=o.sheetId===e?t:o.sheetId;return o.clone({sheetId:i})}function Qo(e,t,o){if(!o)return;const i=e.getRangeFromSheetXC(t,o);return i.invalidSheetName||i.invalidXc?void 0:i}function Jo(e,t,o){const i=[];return t.forEach((t=>{const s=function(e,t){e=e.toLocaleLowerCase();let o=0,i=0,s=(t=t.toLocaleLowerCase()).length,n=0;for(let r=0;r<s;r++)t[r]===e[n]?(n++,i+=100+i-r/200):i=0,o+=i;return n===e.length?o:0}(e,o(t));s>0&&i.push({score:s,elem:t})})),i.sort(((e,t)=>t.score-e.score)),i.map((e=>e.elem))}function ei(e){const t=[];for(let o=0;o<e;o++){const e={cells:{}};t.push(e)}return t}class ti{isFastIdStrategy=!1;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 oi(e){const t=function(e){let t,o,i,s,n;e.includes("!")&&(e=e.split("!").at(-1)),e.includes("$")&&(e=e.replace(/\$/g,"")),t=e.includes(":")?e.split(":").map((e=>e.trim())):[e.trim()];let r=!1,a=!1,l=!1;const c=t[0],h=t[1]&&t[1];if(Wo(c))s=n=$t(c),o=i=0,r=!0;else if(Go(c))o=i=parseInt(c,10)-1,s=n=0,a=!0;else{const e=qt(c);s=n=e.col,o=i=e.row,l=!0}if(2===t.length)if(Wo(h))n=$t(h),r=!0;else if(Go(h))i=parseInt(h,10)-1,a=!0;else{const e=qt(h);n=e.col,i=e.row,o=r?i:o,s=a?n:s,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:o,left:s,bottom:r?void 0:i,right:a?void 0:n};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 ii(e){const t=oi(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function si(e){const{bottom:t,top:o,left:i,right:s}=e;return!(void 0!==t&&isNaN(t)||isNaN(o)||isNaN(i)||void 0!==s&&isNaN(s))&&((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 ni(e){const{top:t,bottom:o,left:i,right:s}=e,r="hasHeader"in e&&e.hasHeader,a=t===o&&i===s;if(void 0===o&&void 0!==s)return 0!==t||r?`${Zt(i,t)}:${Bt(s)}`:`${Bt(i)}:${Bt(s)}`;if(void 0===s&&void 0!==o)return 0!==i||r?`${Zt(i,t)}:${o+1}`:`${t+1}:${o+1}`;if(void 0!==o&&void 0!==s)return a?Zt(i,t):`${Zt(i,t)}:${Zt(s,o)}`;throw new Error(n("Bad zone format"))}function ri(e,t,o,i,s){const n="left"===t?"columns":"rows",r="before"===i?o-1:o,a=e["left"===t?"right":"bottom"];return e[t]<=r&&a&&a>r?Ei(e,n,"RESIZE",s):r<e[t]?Ei(e,n,"MOVE",s):{...e}}function ai(e,t,o,i,s){const n="left"===t?"columns":"rows",r="before"===i?o-1:o,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?Ei(e,n,"RESIZE",s):r<e[t]?Ei(e,n,"MOVE",s):{...e}}function li(e,t,o){const i="left"===t?"right":"bottom";let s=e[t],n=e[i];for(let r of o.sort(((e,t)=>t-e)))e[t]>r&&(s--,n--),e[t]<r&&e[i]>=r&&n--;return{...e,[t]:s,[i]:n}}function ci(e,t,o){const i="left"===t?"right":"bottom";let s=e[t],n=e[i];const r=e[i];for(let i of o.sort(((e,t)=>t-e)))e[t]>i&&(s--,void 0!==n&&n--),void 0!==r&&void 0!==n&&e[t]<=i&&r>=i&&n--;if(!(void 0!==n&&s>n))return{...e,[t]:s,[i]:n}}function hi(...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 di(e,t){if(gi(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 ui(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function gi(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function pi(e,t,o){const{left:i,right:s,top:n,bottom:r}=o;return e>=i&&e<=s&&t>=n&&t<=r}function mi(e,t){return ui(hi(t,e),t)}function fi(e,t){const o=e.map(oi),i=t.map(ii),s=Math.max(...o.concat(i).map((e=>e.bottom||0))),n=Math.max(...o.concat(i).map((e=>e.right||0))),r=o.map((e=>({...e,bottom:void 0===e.bottom?s+1:e.bottom,right:void 0===e.right?n+1:e.right}))),a=i.map((e=>({...e,bottom:void 0===e.bottom?s+1:e.bottom,right:void 0===e.right?n+1:e.right}))),l=function(e,t){const o=new Set(t.map((({col:e,row:t})=>`${e}-${t}`)));return e.filter((({col:e,row:t})=>!o.has(`${e}-${t}`)))}(r.map(Ci).flat(),a.map(Ci).flat()),c=function(e){if(0===e.length)return[];const[t,...o]=[...e].sort(((e,t)=>e.row-t.row)).sort(((e,t)=>e.col-t.col)),i=[];let s=yi(t);for(const{col:e,row:t}of o)if(!pi(e,t,s))if(e===s.left&&t===s.bottom+1){const e=s.bottom+1;s={...s,bottom:e}}else i.push(s),s=yi({col:e,row:t});return[...i,s]}(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=[],o=bi(e),i=(e,t)=>e.top===t.top&&e.bottom===t.bottom&&e.right+1===t.left;for(;o.length;){const e=o.reduce(((e,t)=>i(e,t)?hi(e,t):e),o.shift());t.push(e)}return bi(t)}(c).map((e=>({...e,bottom:e.bottom===s+1?void 0:e.bottom,right:e.right===n+1?void 0:e.right}))).map(ni)}function bi(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(),o=[];for(;0!==t.length;){const e=t.shift();t.some((t=>mi(e,t)))||o.push(e)}return o.reverse()}function vi(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function Si(e){const{numberOfCols:t,numberOfRows:o}=vi(e);return 1===t||1===o}function Ci(e){const t=[],[o,i]=[e.right,e.left].sort(((e,t)=>e-t)),[s,n]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of Ke(o,i+1))for(const o of Ke(s,n+1))t.push({col:e,row:o});return t}function Ei(e,t,o,i){const s="both"===t?i[0]:"columns"===t?i:0,n="both"===t?i[1]:"rows"===t?i:0,r="hasHeader"in e&&e.hasHeader;let a;a=!function(e){return void 0===e.bottom}(e)||r?!(Ii(e)&&!r)||"columns"!==t:"rows"!==t;const l={...e};return a&&"MOVE"===o&&(l.left+=s,l.top+=n),void 0!==l.right&&(l.right+=s),void 0!==l.bottom&&(l.bottom+=n),l}function wi(e,t){let o,i;const{left:s,right:n,top:r,bottom:a}=e,{left:l,right:c,top:h,bottom:d}=t;return o=l!=s?l:c!=n?c:l,i=h!=r?h:d!=a?d:h,{col:o,row:i}}function xi(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 yi(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function Ii(e){return void 0===e.right}function Ri(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function Ti(...e){return e.length<2||1===fi(e.map(ni),[]).length}class Ai extends t.Component{static template="o-spreadsheet-ChartJsComponent";canvas=t.useRef("graphContainer");chart;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;vt(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){const t=e.chartJsConfig;t.data&&t.data.datasets?(this.chart.data=t.data,t.options?.title&&(this.chart.config.options.title=t.options.title),t.options&&"valueLabel"in t.options&&t.options?.valueLabel&&(this.chart.config.options.valueLabel=t.options.valueLabel)):this.chart.data.datasets=void 0,this.chart.config.options.tooltips=t.options?.tooltips,this.chart.config.options.legend=t.options?.legend,this.chart.config.options.scales=t.options?.scales,this.chart.update({duration:0})}}Ai.props={figure:Object};const Oi={};let Mi=0;function Ni(e,...t){const o="__sheet__"+Mi++;return function(e,t){const o=document.createElement("style");o.textContent=function(e){const t=e.split(/(\{|\}|;)/).map((e=>e.trim())),o=[],i=[];let s=[];function n(e,t){const i=[];for(const s of o[e]){let r=t&&t+" "+s||s;r.includes("&")&&(r=s.replace(/&/g,t||"")),e<o.length-1&&(r=n(e+1,r)),i.push(r)}return i.join(", ")}function r(){s.length&&(i.push(n(0)+" {"),i.push(...s),i.push("}"),s=[])}for(;t.length;){let e=t.shift();"}"===e?(r(),o.pop()):("{"===t[0]&&(r(),o.push(e.split(/\s*,\s*/)),t.shift()),";"===t[0]&&s.push(" "+e+";"))}return i.join("\n")}(t),Oi[e]=o}(o,String.raw(e,...t)),function(e){const t=Oi[e];t.setAttribute("component",e),document.head.appendChild(t)}(o),o}function _i({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function Fi(e){const t=Di(e);return e?(e.fillColor&&(t.background=e.fillColor),t):t}function Di(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 o=e.strikethrough?"line-through":"";o=e.underline?o+" underline":o,t["text-decoration"]=o}return e.textColor&&(t.color=e.textColor),t}function Li(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>`${e}:${t};`)).join(" ")}const Pi=1.2;Ni`
|
|
2
2
|
div.o-scorecard {
|
|
3
3
|
font-family: ${j};
|
|
4
4
|
user-select: none;
|
|
@@ -17,15 +17,15 @@
|
|
|
17
17
|
|
|
18
18
|
.o-title-text {
|
|
19
19
|
text-align: left;
|
|
20
|
-
height: ${
|
|
21
|
-
line-height: ${
|
|
20
|
+
height: ${Pi+"em"};
|
|
21
|
+
line-height: ${Pi+"em"};
|
|
22
22
|
overflow: hidden;
|
|
23
23
|
white-space: nowrap;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
.o-key-text {
|
|
27
|
-
line-height: ${
|
|
28
|
-
height: ${
|
|
27
|
+
line-height: ${Pi+"em"};
|
|
28
|
+
height: ${Pi+"em"};
|
|
29
29
|
overflow: hidden;
|
|
30
30
|
white-space: nowrap;
|
|
31
31
|
}
|
|
@@ -40,8 +40,8 @@
|
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
.o-baseline-text {
|
|
43
|
-
line-height: ${
|
|
44
|
-
height: ${
|
|
43
|
+
line-height: ${Pi+"em"};
|
|
44
|
+
height: ${Pi+"em"};
|
|
45
45
|
overflow: hidden;
|
|
46
46
|
white-space: nowrap;
|
|
47
47
|
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
|
-
`;class Pi extends t.Component{static template="o-spreadsheet-ScorecardChart";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 kt(this.backgroundColor)>.3?"#525252":"#C8C8C8"}get figure(){return this.props.figure}get chartStyle(){return Li({padding:`${this.chartPadding}px`,background:this.backgroundColor})}get chartContentStyle(){return Li({height:`${this.getDrawableHeight()}px`})}get chartPadding(){return.02*this.props.figure.width}getTextStyles(){const e=.96*this.props.figure.width,t=this.getWidestElement(),o=t.getElementMaxFontSize(this.getDrawableHeight(),this);let i=function(e,t,o,i=.25){let s=1;if(o(s)>e)return s;if(o(t)<e)return t;let n=(s+t)/2,r=o(n),a=0;for(;Math.abs(r-e)>i&&a<20;)r>=e?t=(s+t)/2:s=(s+t)/2,n=(s+t)/2,r=o(n),a++;return n}(e,o,(e=>t.getElementWidth(e,this.ctx,this)))/o;const s=(new Vi).getElementMaxFontSize(this.getDrawableHeight(),this)*i,n=(new Ui).getElementMaxFontSize(this.getDrawableHeight(),this)*i;return{titleStyle:this.getTextStyle({fontSize:18,color:this.secondaryFontColor}),keyStyle:this.getTextStyle({fontSize:s,cellStyle:this.runtime.keyValueStyle,color:this.primaryFontColor}),baselineStyle:this.getTextStyle({fontSize:n}),baselineValueStyle:this.getTextStyle({fontSize:n,cellStyle:this.runtime.baselineStyle,color:this.runtime.baselineColor||this.secondaryFontColor}),baselineDescrStyle:this.getTextStyle({fontSize:.9*n,color:this.secondaryFontColor})}}getTextStyle(e){const t=Di(e.cellStyle);return t["font-size"]=`${e.fontSize}px`,t.display="inline-block",!t.color&&e.color&&(t.color=e.color),Li(t)}getDrawableHeight(){const e=2*this.chartPadding;let t=this.props.figure.height-e;return t-=this.title?18*ki:0,t}getWidestElement(){const e=new Ui,t=new Vi;return e.getElementWidth(.35,this.ctx,this)>t.getElementWidth(.65,this.ctx,this)?e:t}}class Ui{getElementWidth(e,t,o){if(!o.runtime)return 0;const i=o.baseline,s="neutral"!==o.baselineArrowDirection?"A "+i:i;t.font=`${e}px ${j}`;let n=t.measureText(s).width;return t.font=`${.9*e}px ${j}`,n+=t.measureText(o.baselineDescr).width,n}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.35*e:0)/ki}}class Vi{getElementWidth(e,t,o){if(!o.runtime)return 0;const i=o.keyValue||"";return t.font=`${e}px ${j}`,t.measureText(i).width}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.65*e:e)/ki}}Pi.props={figure:Object};class zi{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 Bi(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const Hi=new zi;function $i(e,t){return{url:e=Bi(e),label:t||e,isExternal:!0,isUrlEditable:!0}}Hi.add("sheet_URL",{match:e=>lt(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){const o=ht(e);return t.tryGetSheetName(o)||n("Invalid sheet")},open(e,t){const o=ht(e);t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:o})},sequence:0});const Wi={createLink:$i,match:e=>st(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function Gi(e){return Hi.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((t=>t.match(e)))||Wi}function qi(e,t){return Gi(e.url).urlRepresentation(e.url,t)}function Zi(e,t){Gi(e.url).open(e.url,t)}function ji(e){if("string"==typeof e){if(it(e)){const{label:t,url:o}=rt(e);return Gi(o).createLink(o,t)}return st(e)?$i(e):void 0}}const Yi=["number","string","boolean","undefined"];function Xi(e,t){if(!e())throw new Error(t)}const Ki=e=>n("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function Qi(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(so(e)||""===e)return ro(e);const t=Te(e);if(t)return t.value;throw new Error(Ki(e));default:return 0}}function Ji(e){if(""===e)throw new Error(Ki(e));return Qi(e)}function es(e){return Math.trunc(Ji(e))}function ts(e){Xi((()=>e>=1),n("The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.",e.toString()))}function os(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}const is=function(e){const t=new Map,o=e.name?e.name+" (memoized)":"memoized";return{[o]:(...o)=>(t.has(o[0])||t.set(o[0],e(...o)),t.get(o[0]))}[o]}((function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}));function ss(e){return"string"==typeof e?is(e):e}const ns=e=>n("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function rs(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(ns(e))}return!1;case"number":return!!e;default:return!1}}function as(e){return Oe(Qi(e))}function ls(e,t,o){for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let s=0;s<o;s++)for(let o=0;o<e;o++)t(i[o][s])}else o(i)}function cs(e,t){ls(e,t,t)}function hs(e,t){ls(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(Ji(e))}))}function ds(e,t,o,i){let s=i;for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let n=0;n<o;n++)for(let o=0;o<e;o++)s=t(s,i[o][n])}else s=o(s,i);return s}function us(e,t,o){return ds(e,t,t,o)}function gs(e,t,o){return ds(e,((e,o)=>"number"==typeof o?t(e,o):e),((e,o)=>t(e,Ji(o))),o)}function ps(e,t,o){return ds(e,((e,o)=>null!=o?t(e,"number"==typeof o?o:"boolean"==typeof o?Qi(o):0):e),((e,o)=>t(e,Qi(o))),o)}function ms(e,t){return function(e,t,o){for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let s=0;s<o;s++)for(let o=0;o<e;o++)if(!t(i[o][s]))return}else if(!o(i))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(ns(e));return rs(e)}(e))))}function fs(e,t){let o,i,s=e.substring(0,2);"<="===s||">="===s||"<>"===s?(o=s,i=e.substring(2)):(s=e.substring(0,1),"<"===s||">"===s||"="===s?(o=s,i=e.substring(1)):(o="=",i=e)),so(i)?i=Qi(i):"TRUE"!==i&&"FALSE"!==i||(i=rs(i));const n={operator:o,operand:i};return"string"==typeof i&&(t&&(i+="*"),n.regexp=function(e){let t="",o="";for(let i of e)"?"===i&&"~"!==o?t+=".":"*"===i&&"~"!==o?t+=".*":("*"!==i&&"?"!==i||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(i)&&(t+="\\"),t+=i),o=i;return new RegExp("^"+t+"$","i")}(i)),n}function bs(e,t){const{operator:o,operand:i}=t;if(void 0===e||void 0===i)return!1;if("number"==typeof i&&"="===o)return os(e)===os(i);if("<>"===o||"="===o){let s;return s=typeof e==typeof i&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===i),"="===o?s:!s}if(typeof e==typeof i)switch(o){case"<":return e<i;case">":return e>i;case"<=":return e<=i;case">=":return e>=i}return!1}function vs(e,t,o=!1){const i=e.length;if(i%2==1)throw new Error(n("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const s=e[0].length,r=e[0][0].length;let a=[];for(let t=0;t<i-1;t+=2){const i=e[t];if(!Array.isArray(i)||i.length!==s||i[0].length!==r)throw new Error(n("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=os(e[t+1]);a.push(fs(l,o))}for(let o=0;o<s;o++)for(let s=0;s<r;s++){let n=!0;for(let t=0;t<i-1;t+=2){if(n=bs(e[t][o][s],a[t/2]),!n)break}n&&t(o,s)}}function Ss(e,t){return ss(e[0][t])}function Cs(e,t){return ss(e[t][0])}function Es(e,t,o,i,s,n){if(null==t)return-1;const r=typeof t;let a,l,c,h,d,u,g=0,p=s-1;for(;p-g>=0;){for(c=Math.floor((g+p)/2),h=c,d=n(e,h),u=typeof d;g<h&&r!==u;)h--,d=n(e,h),u=typeof d;u===r&&void 0!==d?("strict"===o&&d===t?(a=d,l=h):"nextSmaller"===o&&d<=t?(void 0===a||a<d||a===d&&"asc"===i&&l<h||a===d&&"desc"===i&&l>h)&&(a=d,l=h):"nextGreater"===o&&d>=t&&(void 0===a||a>d||a===d&&"asc"===i&&l<h||a===d&&"desc"===i&&l>h)&&(a=d,l=h),"asc"===i&&d>t||"desc"===i&&d<=t?p=h-1:g=c+1):g=c+1}return void 0!==l?l:-1}function ws(e,t,o,i,s,n=!1){if(null==t)return-1;const r=n?(e,t)=>s(e,i-t-1):s;let a,l=-1;for(let s=0;s<i;s++){const c=r(e,s);if(c===t)return n?i-s-1:s;"nextSmaller"===o?(!a&&xs(t,c)>=0||xs(t,c)>=0&&xs(c,a)>0)&&(a=c,l=s):"nextGreater"===o&&(!a&&xs(t,c)<=0||xs(t,c)<=0&&xs(c,a)<0)&&(a=c,l=s)}return n?i-l-1:l}function xs(e,t){let o=Yi.indexOf(typeof e)-Yi.indexOf(typeof t);return 0===o&&("string"==typeof e&&"string"==typeof t?o=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?o=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(o=Number(e)-Number(t))),o}var ys,Is;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(ys||(ys={})),function(e){e.PlainText="text/plain",e.Html="text/html"}(Is||(Is={}));const Rs=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),Ts=new Set([...Rs,"DUPLICATE_SHEET","EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT"]),As=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"]),Os=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","SET_ZONE_BORDERS","CREATE_CHART","UPDATE_CHART","CREATE_FILTER_TABLE","REMOVE_FILTER_TABLE","CREATE_IMAGE"]);function Ms(e){return Os.has(e.type)}class Ns{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new Ns}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var _s;e.CommandResult=void 0,(_s=e.CommandResult||(e.CommandResult={}))[_s.Success=0]="Success",_s[_s.CancelledForUnknownReason=1]="CancelledForUnknownReason",_s[_s.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",_s[_s.MergeIsDestructive=3]="MergeIsDestructive",_s[_s.CellIsMerged=4]="CellIsMerged",_s[_s.InvalidTarget=5]="InvalidTarget",_s[_s.EmptyUndoStack=6]="EmptyUndoStack",_s[_s.EmptyRedoStack=7]="EmptyRedoStack",_s[_s.NotEnoughElements=8]="NotEnoughElements",_s[_s.NotEnoughSheets=9]="NotEnoughSheets",_s[_s.MissingSheetName=10]="MissingSheetName",_s[_s.DuplicatedSheetName=11]="DuplicatedSheetName",_s[_s.DuplicatedSheetId=12]="DuplicatedSheetId",_s[_s.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",_s[_s.WrongSheetMove=14]="WrongSheetMove",_s[_s.WrongSheetPosition=15]="WrongSheetPosition",_s[_s.InvalidAnchorZone=16]="InvalidAnchorZone",_s[_s.SelectionOutOfBound=17]="SelectionOutOfBound",_s[_s.TargetOutOfSheet=18]="TargetOutOfSheet",_s[_s.WrongCutSelection=19]="WrongCutSelection",_s[_s.WrongPasteSelection=20]="WrongPasteSelection",_s[_s.WrongPasteOption=21]="WrongPasteOption",_s[_s.WrongFigurePasteOption=22]="WrongFigurePasteOption",_s[_s.EmptyClipboard=23]="EmptyClipboard",_s[_s.EmptyRange=24]="EmptyRange",_s[_s.InvalidRange=25]="InvalidRange",_s[_s.InvalidZones=26]="InvalidZones",_s[_s.InvalidSheetId=27]="InvalidSheetId",_s[_s.InvalidFigureId=28]="InvalidFigureId",_s[_s.InputAlreadyFocused=29]="InputAlreadyFocused",_s[_s.MaximumRangesReached=30]="MaximumRangesReached",_s[_s.InvalidInputId=31]="InvalidInputId",_s[_s.InvalidChartDefinition=32]="InvalidChartDefinition",_s[_s.InvalidDataSet=33]="InvalidDataSet",_s[_s.InvalidLabelRange=34]="InvalidLabelRange",_s[_s.InvalidScorecardKeyValue=35]="InvalidScorecardKeyValue",_s[_s.InvalidScorecardBaseline=36]="InvalidScorecardBaseline",_s[_s.InvalidGaugeDataRange=37]="InvalidGaugeDataRange",_s[_s.EmptyGaugeRangeMin=38]="EmptyGaugeRangeMin",_s[_s.GaugeRangeMinNaN=39]="GaugeRangeMinNaN",_s[_s.EmptyGaugeRangeMax=40]="EmptyGaugeRangeMax",_s[_s.GaugeRangeMaxNaN=41]="GaugeRangeMaxNaN",_s[_s.GaugeRangeMinBiggerThanRangeMax=42]="GaugeRangeMinBiggerThanRangeMax",_s[_s.GaugeLowerInflectionPointNaN=43]="GaugeLowerInflectionPointNaN",_s[_s.GaugeUpperInflectionPointNaN=44]="GaugeUpperInflectionPointNaN",_s[_s.GaugeLowerBiggerThanUpper=45]="GaugeLowerBiggerThanUpper",_s[_s.InvalidAutofillSelection=46]="InvalidAutofillSelection",_s[_s.WrongComposerSelection=47]="WrongComposerSelection",_s[_s.MinBiggerThanMax=48]="MinBiggerThanMax",_s[_s.LowerBiggerThanUpper=49]="LowerBiggerThanUpper",_s[_s.MidBiggerThanMax=50]="MidBiggerThanMax",_s[_s.MinBiggerThanMid=51]="MinBiggerThanMid",_s[_s.FirstArgMissing=52]="FirstArgMissing",_s[_s.SecondArgMissing=53]="SecondArgMissing",_s[_s.MinNaN=54]="MinNaN",_s[_s.MidNaN=55]="MidNaN",_s[_s.MaxNaN=56]="MaxNaN",_s[_s.ValueUpperInflectionNaN=57]="ValueUpperInflectionNaN",_s[_s.ValueLowerInflectionNaN=58]="ValueLowerInflectionNaN",_s[_s.MinInvalidFormula=59]="MinInvalidFormula",_s[_s.MidInvalidFormula=60]="MidInvalidFormula",_s[_s.MaxInvalidFormula=61]="MaxInvalidFormula",_s[_s.ValueUpperInvalidFormula=62]="ValueUpperInvalidFormula",_s[_s.ValueLowerInvalidFormula=63]="ValueLowerInvalidFormula",_s[_s.InvalidSortZone=64]="InvalidSortZone",_s[_s.WaitingSessionConfirmation=65]="WaitingSessionConfirmation",_s[_s.MergeOverlap=66]="MergeOverlap",_s[_s.TooManyHiddenElements=67]="TooManyHiddenElements",_s[_s.Readonly=68]="Readonly",_s[_s.InvalidViewportSize=69]="InvalidViewportSize",_s[_s.InvalidScrollingDirection=70]="InvalidScrollingDirection",_s[_s.FigureDoesNotExist=71]="FigureDoesNotExist",_s[_s.InvalidConditionalFormatId=72]="InvalidConditionalFormatId",_s[_s.InvalidCellPopover=73]="InvalidCellPopover",_s[_s.EmptyTarget=74]="EmptyTarget",_s[_s.InvalidFreezeQuantity=75]="InvalidFreezeQuantity",_s[_s.FrozenPaneOverlap=76]="FrozenPaneOverlap",_s[_s.ValuesNotChanged=77]="ValuesNotChanged",_s[_s.InvalidFilterZone=78]="InvalidFilterZone",_s[_s.FilterOverlap=79]="FilterOverlap",_s[_s.FilterNotFound=80]="FilterNotFound",_s[_s.MergeInFilter=81]="MergeInFilter",_s[_s.NonContinuousTargets=82]="NonContinuousTargets",_s[_s.DuplicatedFigureId=83]="DuplicatedFigureId",_s[_s.InvalidSelectionStep=84]="InvalidSelectionStep",_s[_s.DuplicatedChartId=85]="DuplicatedChartId",_s[_s.ChartDoesNotExist=86]="ChartDoesNotExist",_s[_s.InvalidHeaderIndex=87]="InvalidHeaderIndex",_s[_s.InvalidQuantity=88]="InvalidQuantity",_s[_s.MoreThanOneColumnSelected=89]="MoreThanOneColumnSelected",_s[_s.EmptySplitSeparator=90]="EmptySplitSeparator",_s[_s.SplitWillOverwriteContent=91]="SplitWillOverwriteContent",_s[_s.NoSplitSeparatorInSelection=92]="NoSplitSeparatorInSelection",_s[_s.NoActiveSheet=93]="NoActiveSheet",_s[_s.NoChanges=94]="NoChanges";const Fs=["thin","medium","thick","dashed","dotted"];var Ds,Ls;function ks(e,t){return Us(Ps(e||""),t)}function Ps(e){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);return so(e)||et(e)?Qi(e):function(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}(e)?"TRUE"===e.toUpperCase():e}function Us(e,t){const o=ji(e);return o?{...Vs(Ps(o.label),t||Oo(o.label)),link:o}:Vs(e,t)}function Vs(e,t){try{for(const o of $s){const i=o(e,t);if(i)return i}return function(e,t){return{type:ys.text,value:e,format:t,isAutoSummable:!0,defaultAlign:"left",formattedValue:bo(e,t)}}((e||"").toString(),t)}catch(t){return Hs((e||"").toString(),new c(a.GenericError,t.message||de))}}function zs(e,t){return{type:ys.number,value:e||0,format:t,isAutoSummable:!0,defaultAlign:"right",formattedValue:bo(e,t)}}!function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(Ds||(Ds={})),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"}(Ls||(Ls={}));const Bs={type:ys.empty,value:"",format:void 0,isAutoSummable:!0,defaultAlign:"left",formattedValue:""};function Hs(e,t){return{type:ys.error,value:t.errorType,error:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:t.errorType}}const $s=[function(e,t){if(""===e)return function(e){return void 0===e?Bs:{type:ys.empty,value:"",format:e,isAutoSummable:!0,defaultAlign:"left",formattedValue:""}}(t)},function(e,t){if(t&&"number"==typeof e&&xo(t))return function(e,t){const o=bo(e,t);return{type:ys.number,value:e,format:t,isAutoSummable:!1,defaultAlign:"right",formattedValue:o}}(e,t)},function(e,t){return"number"==typeof e?zs(e,t):null===e?zs(0,t):void 0},function(e,t){if("boolean"==typeof e)return function(e,t){const o=e?"TRUE":"FALSE";return{type:ys.boolean,value:e,format:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:o}}(e,t)}],Ws=new zi;Ws.add("ALPHANUMERIC_INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;const o=`${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:o},tooltip:{props:{content:o}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;const o=e.current.toString(),i=bo(e.current,t.cell?.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:i}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,o)=>{const i=t.cell?.content||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i},tooltip:i?{props:{content:ks(t.cell?.content,t.cell?.format).formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,o,i)=>{e.current+=e.increment;let s=0,n=0;switch(i){case"up":s=0,n=-e.current;break;case"down":s=0,n=e.current;break;case"left":s=-e.current,n=0;break;case"right":s=e.current,n=0}const r=t.cell;if(!r||!r.isFormula)return{cellData:{}};const a=t.sheetId,l=o.createAdaptedRanges(r.dependencies,s,n,a),c=o.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 Gs=new zi,qs=/(\d+)$/,Zs=/^(.*\D+)/,js=/^(.*\D+)(\d+)$/;function Ys(e,t,o){let i=[],s=!1;for(let n of t){n===e&&(s=!0);const t=n?.isFormula?void 0:ks(n?.content);if(t&&o(t))i.push(t);else{if(s)return i;i=[]}}return i}function Xs(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let o=e[0];for(let i=1;i<e.length;i++){const s=e[i];t.push(s-o),o=s}return t.reduce(((e,t)=>e+t),0)/t.length}(e)*e.length),t}Gs.add("simple_value_copy",{condition:(e,t)=>!(1!==t.length||e.isFormula||e.format&&xo(e.format)),generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&ks(e.content).type===ys.text&&js.test(e.content),generateRule:(e,t)=>{const o=parseInt(e.content.match(qs)[0]),i=e.content.match(Zs)[0],s=e.content.length-i.length,n=Ys(e,t,(e=>e.type===ys.text&&js.test(e.value))).filter((e=>i===e.value.toString().match(Zs)[0])).map((e=>parseInt(e.value.toString().match(qs)[0]))),r=Xs(n);return{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:i,current:o,increment:r,numberPostfixLength:s}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&ks(e.content).type===ys.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&&ks(e.content).type===ys.number,generateRule:(e,t)=>{const o=Xs(Ys(e,t,(e=>e.type===ys.number)).map((e=>Number(e.value)))),i=ks(e.content);return{type:"INCREMENT_MODIFIER",increment:o,current:i.type===ys.number?i.value:0}},sequence:40});Ni`
|
|
53
|
+
`;class ki extends t.Component{static template="o-spreadsheet-ScorecardChart";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 Pt(this.backgroundColor)>.3?"#525252":"#C8C8C8"}get figure(){return this.props.figure}get chartStyle(){return Li({padding:`${this.chartPadding}px`,background:this.backgroundColor})}get chartContentStyle(){return Li({height:`${this.getDrawableHeight()}px`})}get chartPadding(){return.02*this.props.figure.width}getTextStyles(){const e=.96*this.props.figure.width,t=this.getWidestElement(),o=t.getElementMaxFontSize(this.getDrawableHeight(),this);let i=function(e,t,o,i=.25){let s=1;if(o(s)>e)return s;if(o(t)<e)return t;let n=(s+t)/2,r=o(n),a=0;for(;Math.abs(r-e)>i&&a<20;)r>=e?t=(s+t)/2:s=(s+t)/2,n=(s+t)/2,r=o(n),a++;return n}(e,o,(e=>t.getElementWidth(e,this.ctx,this)))/o;const s=(new Vi).getElementMaxFontSize(this.getDrawableHeight(),this)*i,n=(new Ui).getElementMaxFontSize(this.getDrawableHeight(),this)*i;return{titleStyle:this.getTextStyle({fontSize:18,color:this.secondaryFontColor}),keyStyle:this.getTextStyle({fontSize:s,cellStyle:this.runtime.keyValueStyle,color:this.primaryFontColor}),baselineStyle:this.getTextStyle({fontSize:n}),baselineValueStyle:this.getTextStyle({fontSize:n,cellStyle:this.runtime.baselineStyle,color:this.runtime.baselineColor||this.secondaryFontColor}),baselineDescrStyle:this.getTextStyle({fontSize:.9*n,color:this.secondaryFontColor})}}getTextStyle(e){const t=Di(e.cellStyle);return t["font-size"]=`${e.fontSize}px`,t.display="inline-block",!t.color&&e.color&&(t.color=e.color),Li(t)}getDrawableHeight(){const e=2*this.chartPadding;let t=this.props.figure.height-e;return t-=this.title?18*Pi:0,t}getWidestElement(){const e=new Ui,t=new Vi;return e.getElementWidth(.35,this.ctx,this)>t.getElementWidth(.65,this.ctx,this)?e:t}}class Ui{getElementWidth(e,t,o){if(!o.runtime)return 0;const i=o.baseline,s="neutral"!==o.baselineArrowDirection?"A "+i:i;t.font=`${e}px ${j}`;let n=t.measureText(s).width;return t.font=`${.9*e}px ${j}`,n+=t.measureText(o.baselineDescr).width,n}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.35*e:0)/Pi}}class Vi{getElementWidth(e,t,o){if(!o.runtime)return 0;const i=o.keyValue||"";return t.font=`${e}px ${j}`,t.measureText(i).width}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.65*e:e)/Pi}}ki.props={figure:Object};class zi{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 Bi(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const Hi=new zi;function $i(e,t){return{url:e=Bi(e),label:t||e,isExternal:!0,isUrlEditable:!0}}Hi.add("sheet_URL",{match:e=>lt(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){const o=ht(e);return t.tryGetSheetName(o)||n("Invalid sheet")},open(e,t){const o=ht(e);t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:o})},sequence:0});const Wi={createLink:$i,match:e=>st(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function Gi(e){return Hi.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((t=>t.match(e)))||Wi}function qi(e,t){return Gi(e.url).urlRepresentation(e.url,t)}function Zi(e,t){Gi(e.url).open(e.url,t)}function ji(e){if("string"==typeof e){if(it(e)){const{label:t,url:o}=rt(e);return Gi(o).createLink(o,t)}return st(e)?$i(e):void 0}}const Yi=["number","string","boolean","undefined"];function Xi(e,t){if(!e())throw new Error(t)}const Ki=e=>n("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function Qi(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(so(e)||""===e)return ro(e);const t=Te(e);if(t)return t.value;throw new Error(Ki(e));default:return 0}}function Ji(e){if(""===e)throw new Error(Ki(e));return Qi(e)}function es(e){return Math.trunc(Ji(e))}function ts(e){Xi((()=>e>=1),n("The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.",e.toString()))}function os(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}const is=function(e){const t=new Map,o=e.name?e.name+" (memoized)":"memoized";return{[o]:(...o)=>(t.has(o[0])||t.set(o[0],e(...o)),t.get(o[0]))}[o]}((function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}));function ss(e){return"string"==typeof e?is(e):e}const ns=e=>n("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function rs(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(ns(e))}return!1;case"number":return!!e;default:return!1}}function as(e){return Oe(Qi(e))}function ls(e,t,o){for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let s=0;s<o;s++)for(let o=0;o<e;o++)t(i[o][s])}else o(i)}function cs(e,t){ls(e,t,t)}function hs(e,t){ls(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(Ji(e))}))}function ds(e,t,o,i){let s=i;for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let n=0;n<o;n++)for(let o=0;o<e;o++)s=t(s,i[o][n])}else s=o(s,i);return s}function us(e,t,o){return ds(e,t,t,o)}function gs(e,t,o){return ds(e,((e,o)=>"number"==typeof o?t(e,o):e),((e,o)=>t(e,Ji(o))),o)}function ps(e,t,o){return ds(e,((e,o)=>null!=o?t(e,"number"==typeof o?o:"boolean"==typeof o?Qi(o):0):e),((e,o)=>t(e,Qi(o))),o)}function ms(e,t){return function(e,t,o){for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let s=0;s<o;s++)for(let o=0;o<e;o++)if(!t(i[o][s]))return}else if(!o(i))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(ns(e));return rs(e)}(e))))}function fs(e,t){let o,i,s=e.substring(0,2);"<="===s||">="===s||"<>"===s?(o=s,i=e.substring(2)):(s=e.substring(0,1),"<"===s||">"===s||"="===s?(o=s,i=e.substring(1)):(o="=",i=e)),so(i)?i=Qi(i):"TRUE"!==i&&"FALSE"!==i||(i=rs(i));const n={operator:o,operand:i};return"string"==typeof i&&(t&&(i+="*"),n.regexp=function(e){let t="",o="";for(let i of e)"?"===i&&"~"!==o?t+=".":"*"===i&&"~"!==o?t+=".*":("*"!==i&&"?"!==i||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(i)&&(t+="\\"),t+=i),o=i;return new RegExp("^"+t+"$","i")}(i)),n}function bs(e,t){const{operator:o,operand:i}=t;if(void 0===e||void 0===i)return!1;if("number"==typeof i&&"="===o)return os(e)===os(i);if("<>"===o||"="===o){let s;return s=typeof e==typeof i&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===i),"="===o?s:!s}if(typeof e==typeof i)switch(o){case"<":return e<i;case">":return e>i;case"<=":return e<=i;case">=":return e>=i}return!1}function vs(e,t,o=!1){const i=e.length;if(i%2==1)throw new Error(n("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const s=e[0].length,r=e[0][0].length;let a=[];for(let t=0;t<i-1;t+=2){const i=e[t];if(!Array.isArray(i)||i.length!==s||i[0].length!==r)throw new Error(n("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=os(e[t+1]);a.push(fs(l,o))}for(let o=0;o<s;o++)for(let s=0;s<r;s++){let n=!0;for(let t=0;t<i-1;t+=2){if(n=bs(e[t][o][s],a[t/2]),!n)break}n&&t(o,s)}}function Ss(e,t){return ss(e[0][t])}function Cs(e,t){return ss(e[t][0])}function Es(e,t,o,i,s,n){if(null==t)return-1;const r=typeof t;let a,l,c,h,d,u,g=0,p=s-1;for(;p-g>=0;){for(c=Math.floor((g+p)/2),h=c,d=n(e,h),u=typeof d;g<h&&r!==u;)h--,d=n(e,h),u=typeof d;u===r&&void 0!==d?("strict"===o&&d===t?(a=d,l=h):"nextSmaller"===o&&d<=t?(void 0===a||a<d||a===d&&"asc"===i&&l<h||a===d&&"desc"===i&&l>h)&&(a=d,l=h):"nextGreater"===o&&d>=t&&(void 0===a||a>d||a===d&&"asc"===i&&l<h||a===d&&"desc"===i&&l>h)&&(a=d,l=h),"asc"===i&&d>t||"desc"===i&&d<=t?p=h-1:g=c+1):g=c+1}return void 0!==l?l:-1}function ws(e,t,o,i,s,n=!1){if(null==t)return-1;const r=n?(e,t)=>s(e,i-t-1):s;let a,l=-1;for(let s=0;s<i;s++){const c=r(e,s);if(c===t)return n?i-s-1:s;"nextSmaller"===o?(!a&&xs(t,c)>=0||xs(t,c)>=0&&xs(c,a)>0)&&(a=c,l=s):"nextGreater"===o&&(!a&&xs(t,c)<=0||xs(t,c)<=0&&xs(c,a)<0)&&(a=c,l=s)}return n?i-l-1:l}function xs(e,t){let o=Yi.indexOf(typeof e)-Yi.indexOf(typeof t);return 0===o&&("string"==typeof e&&"string"==typeof t?o=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?o=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(o=Number(e)-Number(t))),o}var ys,Is;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(ys||(ys={})),function(e){e.PlainText="text/plain",e.Html="text/html"}(Is||(Is={}));const Rs=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),Ts=new Set([...Rs,"DUPLICATE_SHEET","EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT"]),As=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"]),Os=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","SET_ZONE_BORDERS","CREATE_CHART","UPDATE_CHART","CREATE_FILTER_TABLE","REMOVE_FILTER_TABLE","CREATE_IMAGE"]);function Ms(e){return Os.has(e.type)}class Ns{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new Ns}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var _s;e.CommandResult=void 0,(_s=e.CommandResult||(e.CommandResult={}))[_s.Success=0]="Success",_s[_s.CancelledForUnknownReason=1]="CancelledForUnknownReason",_s[_s.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",_s[_s.MergeIsDestructive=3]="MergeIsDestructive",_s[_s.CellIsMerged=4]="CellIsMerged",_s[_s.InvalidTarget=5]="InvalidTarget",_s[_s.EmptyUndoStack=6]="EmptyUndoStack",_s[_s.EmptyRedoStack=7]="EmptyRedoStack",_s[_s.NotEnoughElements=8]="NotEnoughElements",_s[_s.NotEnoughSheets=9]="NotEnoughSheets",_s[_s.MissingSheetName=10]="MissingSheetName",_s[_s.DuplicatedSheetName=11]="DuplicatedSheetName",_s[_s.DuplicatedSheetId=12]="DuplicatedSheetId",_s[_s.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",_s[_s.WrongSheetMove=14]="WrongSheetMove",_s[_s.WrongSheetPosition=15]="WrongSheetPosition",_s[_s.InvalidAnchorZone=16]="InvalidAnchorZone",_s[_s.SelectionOutOfBound=17]="SelectionOutOfBound",_s[_s.TargetOutOfSheet=18]="TargetOutOfSheet",_s[_s.WrongCutSelection=19]="WrongCutSelection",_s[_s.WrongPasteSelection=20]="WrongPasteSelection",_s[_s.WrongPasteOption=21]="WrongPasteOption",_s[_s.WrongFigurePasteOption=22]="WrongFigurePasteOption",_s[_s.EmptyClipboard=23]="EmptyClipboard",_s[_s.EmptyRange=24]="EmptyRange",_s[_s.InvalidRange=25]="InvalidRange",_s[_s.InvalidZones=26]="InvalidZones",_s[_s.InvalidSheetId=27]="InvalidSheetId",_s[_s.InvalidFigureId=28]="InvalidFigureId",_s[_s.InputAlreadyFocused=29]="InputAlreadyFocused",_s[_s.MaximumRangesReached=30]="MaximumRangesReached",_s[_s.InvalidInputId=31]="InvalidInputId",_s[_s.InvalidChartDefinition=32]="InvalidChartDefinition",_s[_s.InvalidDataSet=33]="InvalidDataSet",_s[_s.InvalidLabelRange=34]="InvalidLabelRange",_s[_s.InvalidScorecardKeyValue=35]="InvalidScorecardKeyValue",_s[_s.InvalidScorecardBaseline=36]="InvalidScorecardBaseline",_s[_s.InvalidGaugeDataRange=37]="InvalidGaugeDataRange",_s[_s.EmptyGaugeRangeMin=38]="EmptyGaugeRangeMin",_s[_s.GaugeRangeMinNaN=39]="GaugeRangeMinNaN",_s[_s.EmptyGaugeRangeMax=40]="EmptyGaugeRangeMax",_s[_s.GaugeRangeMaxNaN=41]="GaugeRangeMaxNaN",_s[_s.GaugeRangeMinBiggerThanRangeMax=42]="GaugeRangeMinBiggerThanRangeMax",_s[_s.GaugeLowerInflectionPointNaN=43]="GaugeLowerInflectionPointNaN",_s[_s.GaugeUpperInflectionPointNaN=44]="GaugeUpperInflectionPointNaN",_s[_s.GaugeLowerBiggerThanUpper=45]="GaugeLowerBiggerThanUpper",_s[_s.InvalidAutofillSelection=46]="InvalidAutofillSelection",_s[_s.WrongComposerSelection=47]="WrongComposerSelection",_s[_s.MinBiggerThanMax=48]="MinBiggerThanMax",_s[_s.LowerBiggerThanUpper=49]="LowerBiggerThanUpper",_s[_s.MidBiggerThanMax=50]="MidBiggerThanMax",_s[_s.MinBiggerThanMid=51]="MinBiggerThanMid",_s[_s.FirstArgMissing=52]="FirstArgMissing",_s[_s.SecondArgMissing=53]="SecondArgMissing",_s[_s.MinNaN=54]="MinNaN",_s[_s.MidNaN=55]="MidNaN",_s[_s.MaxNaN=56]="MaxNaN",_s[_s.ValueUpperInflectionNaN=57]="ValueUpperInflectionNaN",_s[_s.ValueLowerInflectionNaN=58]="ValueLowerInflectionNaN",_s[_s.MinInvalidFormula=59]="MinInvalidFormula",_s[_s.MidInvalidFormula=60]="MidInvalidFormula",_s[_s.MaxInvalidFormula=61]="MaxInvalidFormula",_s[_s.ValueUpperInvalidFormula=62]="ValueUpperInvalidFormula",_s[_s.ValueLowerInvalidFormula=63]="ValueLowerInvalidFormula",_s[_s.InvalidSortZone=64]="InvalidSortZone",_s[_s.WaitingSessionConfirmation=65]="WaitingSessionConfirmation",_s[_s.MergeOverlap=66]="MergeOverlap",_s[_s.TooManyHiddenElements=67]="TooManyHiddenElements",_s[_s.Readonly=68]="Readonly",_s[_s.InvalidViewportSize=69]="InvalidViewportSize",_s[_s.InvalidScrollingDirection=70]="InvalidScrollingDirection",_s[_s.FigureDoesNotExist=71]="FigureDoesNotExist",_s[_s.InvalidConditionalFormatId=72]="InvalidConditionalFormatId",_s[_s.InvalidCellPopover=73]="InvalidCellPopover",_s[_s.EmptyTarget=74]="EmptyTarget",_s[_s.InvalidFreezeQuantity=75]="InvalidFreezeQuantity",_s[_s.FrozenPaneOverlap=76]="FrozenPaneOverlap",_s[_s.ValuesNotChanged=77]="ValuesNotChanged",_s[_s.InvalidFilterZone=78]="InvalidFilterZone",_s[_s.FilterOverlap=79]="FilterOverlap",_s[_s.FilterNotFound=80]="FilterNotFound",_s[_s.MergeInFilter=81]="MergeInFilter",_s[_s.NonContinuousTargets=82]="NonContinuousTargets",_s[_s.DuplicatedFigureId=83]="DuplicatedFigureId",_s[_s.InvalidSelectionStep=84]="InvalidSelectionStep",_s[_s.DuplicatedChartId=85]="DuplicatedChartId",_s[_s.ChartDoesNotExist=86]="ChartDoesNotExist",_s[_s.InvalidHeaderIndex=87]="InvalidHeaderIndex",_s[_s.InvalidQuantity=88]="InvalidQuantity",_s[_s.MoreThanOneColumnSelected=89]="MoreThanOneColumnSelected",_s[_s.EmptySplitSeparator=90]="EmptySplitSeparator",_s[_s.SplitWillOverwriteContent=91]="SplitWillOverwriteContent",_s[_s.NoSplitSeparatorInSelection=92]="NoSplitSeparatorInSelection",_s[_s.NoActiveSheet=93]="NoActiveSheet",_s[_s.NoChanges=94]="NoChanges";const Fs=["thin","medium","thick","dashed","dotted"];var Ds,Ls;function Ps(e,t){return Us(ks(e||""),t)}function ks(e){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);return so(e)||et(e)?Qi(e):function(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}(e)?"TRUE"===e.toUpperCase():e}function Us(e,t){const o=ji(e);return o?{...Vs(ks(o.label),t||Oo(o.label)),link:o}:Vs(e,t)}function Vs(e,t){try{for(const o of $s){const i=o(e,t);if(i)return i}return function(e,t){return{type:ys.text,value:e,format:t,isAutoSummable:!0,defaultAlign:"left",formattedValue:bo(e,t)}}((e||"").toString(),t)}catch(t){return Hs((e||"").toString(),new c(a.GenericError,t.message||de))}}function zs(e,t){return{type:ys.number,value:e||0,format:t,isAutoSummable:!0,defaultAlign:"right",formattedValue:bo(e,t)}}!function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(Ds||(Ds={})),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"}(Ls||(Ls={}));const Bs={type:ys.empty,value:"",format:void 0,isAutoSummable:!0,defaultAlign:"left",formattedValue:""};function Hs(e,t){return{type:ys.error,value:t.errorType,error:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:t.errorType}}const $s=[function(e,t){if(""===e)return function(e){return void 0===e?Bs:{type:ys.empty,value:"",format:e,isAutoSummable:!0,defaultAlign:"left",formattedValue:""}}(t)},function(e,t){if(t&&"number"==typeof e&&xo(t))return function(e,t){const o=bo(e,t);return{type:ys.number,value:e,format:t,isAutoSummable:!1,defaultAlign:"right",formattedValue:o}}(e,t)},function(e,t){return"number"==typeof e?zs(e,t):null===e?zs(0,t):void 0},function(e,t){if("boolean"==typeof e)return function(e,t){const o=e?"TRUE":"FALSE";return{type:ys.boolean,value:e,format:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:o}}(e,t)}],Ws=new zi;Ws.add("ALPHANUMERIC_INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;const o=`${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:o},tooltip:{props:{content:o}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;const o=e.current.toString(),i=bo(e.current,t.cell?.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:i}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,o)=>{const i=t.cell?.content||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i},tooltip:i?{props:{content:Ps(t.cell?.content,t.cell?.format).formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,o,i)=>{e.current+=e.increment;let s=0,n=0;switch(i){case"up":s=0,n=-e.current;break;case"down":s=0,n=e.current;break;case"left":s=-e.current,n=0;break;case"right":s=e.current,n=0}const r=t.cell;if(!r||!r.isFormula)return{cellData:{}};const a=t.sheetId,l=o.createAdaptedRanges(r.dependencies,s,n,a),c=o.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 Gs=new zi,qs=/(\d+)$/,Zs=/^(.*\D+)/,js=/^(.*\D+)(\d+)$/;function Ys(e,t,o){let i=[],s=!1;for(let n of t){n===e&&(s=!0);const t=n?.isFormula?void 0:Ps(n?.content);if(t&&o(t))i.push(t);else{if(s)return i;i=[]}}return i}function Xs(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let o=e[0];for(let i=1;i<e.length;i++){const s=e[i];t.push(s-o),o=s}return t.reduce(((e,t)=>e+t),0)/t.length}(e)*e.length),t}Gs.add("simple_value_copy",{condition:(e,t)=>!(1!==t.length||e.isFormula||e.format&&xo(e.format)),generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&Ps(e.content).type===ys.text&&js.test(e.content),generateRule:(e,t)=>{const o=parseInt(e.content.match(qs)[0]),i=e.content.match(Zs)[0],s=e.content.length-i.length,n=Ys(e,t,(e=>e.type===ys.text&&js.test(e.value))).filter((e=>i===e.value.toString().match(Zs)[0])).map((e=>parseInt(e.value.toString().match(qs)[0]))),r=Xs(n);return{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:i,current:o,increment:r,numberPostfixLength:s}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&Ps(e.content).type===ys.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&&Ps(e.content).type===ys.number,generateRule:(e,t)=>{const o=Xs(Ys(e,t,(e=>e.type===ys.number)).map((e=>Number(e.value)))),i=Ps(e.content);return{type:"INCREMENT_MODIFIER",increment:o,current:i.type===ys.number?i.value:0}},sequence:40});Ni`
|
|
54
54
|
.o-error-tooltip {
|
|
55
55
|
font-size: 13px;
|
|
56
56
|
background-color: white;
|
|
@@ -172,7 +172,7 @@
|
|
|
172
172
|
width: fit-content;
|
|
173
173
|
height: fit-content;
|
|
174
174
|
}
|
|
175
|
-
`;class vn extends t.Component{static template="o-spreadsheet-Popover";static defaultProps={positioning:"BottomLeft",verticalOffset:0,onMouseWheel:()=>{},onPopoverMoved:()=>{},onPopoverHidden:()=>{},zIndex:ue.Popover};popoverRef=t.useRef("popover");currentPosition=void 0;currentDisplayValue=void 0;spreadsheetRect=gn();containerRect;setup(){this.containerRect=function(){const e=t.useState({x:0,y:0,width:0,height:0}),o=t.useComponent(),i=gn();function s(){const t=o.env,s="getPopoverContainerRect"in t?t.getPopoverContainerRect():i;e.x=s.x,e.y=s.y,e.width=s.width,e.height=s.height}return s(),t.onMounted(s),t.onPatched(s),e}(),t.useEffect((()=>{if(!this.containerRect)throw new Error("Popover container is not defined");const e=this.popoverRef.el,t=mn(this.props.anchorRect,this.containerRect),o=t?"block":"none";if("none"!==this.currentDisplayValue&&"none"===o&&this.props.onPopoverHidden?.(),e.style.display=o,this.currentDisplayValue=o,!t)return;const i={width:this.props.maxWidth,height:this.props.maxHeight}
|
|
175
|
+
`;class vn extends t.Component{static template="o-spreadsheet-Popover";static defaultProps={positioning:"BottomLeft",verticalOffset:0,onMouseWheel:()=>{},onPopoverMoved:()=>{},onPopoverHidden:()=>{},zIndex:ue.Popover};popoverRef=t.useRef("popover");currentPosition=void 0;currentDisplayValue=void 0;spreadsheetRect=gn();containerRect;setup(){this.containerRect=function(){const e=t.useState({x:0,y:0,width:0,height:0}),o=t.useComponent(),i=gn();function s(){const t=o.env,s="getPopoverContainerRect"in t?t.getPopoverContainerRect():i;e.x=s.x,e.y=s.y,e.width=s.width,e.height=s.height}return s(),t.onMounted(s),t.onPatched(s),e}(),t.useEffect((()=>{if(!this.containerRect)throw new Error("Popover container is not defined");const e=this.popoverRef.el,t=mn(this.props.anchorRect,this.containerRect),o=t?"block":"none";if("none"!==this.currentDisplayValue&&"none"===o&&this.props.onPopoverHidden?.(),e.style.display=o,this.currentDisplayValue=o,!t)return;const i={width:this.props.maxWidth,height:this.props.maxHeight};let s={width:e.getBoundingClientRect().width,height:e.getBoundingClientRect().height};const n=this.spreadsheetRect,r="BottomLeft"===this.props.positioning?new Cn(t,this.containerRect,i,n):new En(t,this.containerRect,i,n);e.style["max-height"]=r.getMaxHeight(s.height)+"px",e.style["max-width"]=r.getMaxWidth(s.width)+"px",s={width:e.getBoundingClientRect().width,height:e.getBoundingClientRect().height};let a=r.getCss(s,this.props.verticalOffset);for(const t of Object.keys(a))e.style[t]=a[t];const l=r.getCurrentPosition(s);this.currentPosition&&l!==this.currentPosition&&this.props.onPopoverMoved?.(),this.currentPosition=l}))}get popoverStyle(){return Li({"z-index":`${this.props.zIndex}`})}}vn.props={anchorRect:Object,containerRect:{type:Object,optional:!0},positioning:{type:String,optional:!0},maxWidth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},verticalOffset:{type:Number,optional:!0},onMouseWheel:{type:Function,optional:!0},onPopoverHidden:{type:Function,optional:!0},onPopoverMoved:{type:Function,optional:!0},zIndex:{type:Number,optional:!0},slots:Object};class Sn{anchorRect;containerRect;propsMaxSize;spreadsheetOffset;constructor(e,t,o,i){this.anchorRect=e,this.containerRect=t,this.propsMaxSize=o,this.spreadsheetOffset=i}shouldRenderAtBottom(e){return e<=this.availableHeightDown||this.availableHeightDown>=this.availableHeightUp}shouldRenderAtRight(e){return e<=this.availableWidthRight||this.availableWidthRight>=this.availableWidthLeft}getMaxHeight(e){const t=this.shouldRenderAtBottom(e)?this.availableHeightDown:this.availableHeightUp;return this.propsMaxSize.height?Math.min(t,this.propsMaxSize.height):t}getMaxWidth(e){const t=this.shouldRenderAtRight(e)?this.availableWidthRight:this.availableWidthLeft;return this.propsMaxSize.width?Math.min(t,this.propsMaxSize.width):t}getCss(e,t){const o=this.getMaxHeight(e.height),i=this.getMaxWidth(e.width),s=Math.min(o,e.height),n=Math.min(i,e.width),r=this.shouldRenderAtBottom(e.height),a=this.shouldRenderAtRight(e.width);t=r?t:-t;return{top:this.getTopCoordinate(s,r)-this.spreadsheetOffset.y-t+"px",left:this.getLeftCoordinate(n,a)-this.spreadsheetOffset.x+"px"}}getCurrentPosition(e){const t=this.shouldRenderAtBottom(e.height),o=this.shouldRenderAtRight(e.width);return t&&o?"BottomRight":t&&!o?"BottomLeft":!t&&o?"TopRight":"TopLeft"}}class Cn extends Sn{get availableHeightUp(){return this.anchorRect.y-this.containerRect.y}get availableHeightDown(){return this.containerRect.height-this.availableHeightUp-this.anchorRect.height}get availableWidthRight(){return this.containerRect.x+this.containerRect.width-this.anchorRect.x}get availableWidthLeft(){return this.anchorRect.x+this.anchorRect.width-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y+this.anchorRect.height:this.anchorRect.y-e}getLeftCoordinate(e,t){return t?this.anchorRect.x:this.anchorRect.x+this.anchorRect.width-e}}class En extends Sn{get availableHeightUp(){return this.anchorRect.y+this.anchorRect.height-this.containerRect.y}get availableHeightDown(){return this.containerRect.y+this.containerRect.height-this.anchorRect.y}get availableWidthRight(){return this.containerRect.width-this.anchorRect.width-this.availableWidthLeft}get availableWidthLeft(){return this.anchorRect.x-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y:this.anchorRect.y+this.anchorRect.height-e}getLeftCoordinate(e,t){return t?this.anchorRect.x+this.anchorRect.width:this.anchorRect.x-e}}Ni`
|
|
176
176
|
.o-menu {
|
|
177
177
|
background-color: white;
|
|
178
178
|
padding: ${6}px 0px;
|
|
@@ -271,7 +271,7 @@
|
|
|
271
271
|
cursor: pointer;
|
|
272
272
|
color: #000;
|
|
273
273
|
}
|
|
274
|
-
`;class xn extends t.Component{static components={Menu:wn};static template="o-spreadsheet-LinkDisplay";get cell(){const{col:e,row:t}=this.props.cellPosition,o=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t})}get link(){if(this.cell.link)return this.cell.link;const{col:e,row:t}=this.props.cellPosition;throw new Error(`LinkDisplay Component can only be used with link cells. ${Zt(e,t)} is not a link.`)}getUrlRepresentation(e){return qi(e,this.env.model.getters)}openLink(){Zi(this.link,this.env)}edit(){const{col:e,row:t}=this.props.cellPosition;this.env.model.dispatch("OPEN_CELL_POPOVER",{col:e,row:t,popoverType:"LinkEditor"})}unlink(){const e=this.env.model.getters.getActiveSheetId(),{col:t,row:o}=this.props.cellPosition,i=this.env.model.getters.getCellComputedStyle({sheetId:e,col:t,row:o}),s=i?.textColor===R?void 0:i?.textColor;this.env.model.dispatch("UPDATE_CELL",{col:t,row:o,sheetId:e,content:this.link.label,style:{...i,textColor:s,underline:void 0}})}}const yn={onHover:(e,t)=>{const o=t.getEvaluatedCell(e);return!t.isDashboard()&&o.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:xn,props:{cellPosition:e},cellCorner:"BottomLeft"}:{isOpen:!1}}};xn.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const In={name:n("Link sheet"),children:[e=>e.model.getters.getSheetIds().map((t=>e.model.getters.getSheet(t))).map((e=>({id:e.id,name:e.name,execute:()=>nt(e.name,ct(e.id))})))]},Rn={name:n("Delete"),isVisible:e=>e.model.getters.getSheetIds().length>1,execute:e=>e.askConfirmation(n("Are you sure you want to delete this sheet ?"),(()=>{e.model.dispatch("DELETE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})}))},Tn={name:n("Duplicate"),execute:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.uuidGenerator.uuidv4();e.model.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:o}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})}},An=e=>({name:n("Rename"),execute:e.renameSheetCallback}),On={name:n("Move right"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getVisibleSheetIds();return o.indexOf(t)!==o.length-1},execute:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:1})},Mn={name:n("Move left"),isVisible:e=>{const t=e.model.getters.getActiveSheetId();return e.model.getters.getVisibleSheetIds()[0]!==t},execute:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:-1})},Nn={name:n("Hide sheet"),isVisible:e=>1!==e.model.getters.getVisibleSheetIds().length,execute:e=>e.model.dispatch("HIDE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})};function _n(e){return e.map(Dn).sort(((e,t)=>e.sequence-t.sequence))}const Fn=new ti;function Dn(e){const t=e.name,o=e.children;return{id:e.id||Fn.uuidv4(),name:"function"==typeof t?t:()=>t,isVisible:e.isVisible?e.isVisible:()=>!0,isEnabled:e.isEnabled?e.isEnabled:()=>!0,isActive:e.isActive,execute:e.execute,children:o?e=>o.map((t=>"function"==typeof t?t(e):t)).flat().map(Dn):()=>[],isReadonlyAllowed:e.isReadonlyAllowed||!1,separator:e.separator||!1,icon:e.icon||"",description:e.description||"",textColor:e.textColor,sequence:e.sequence||0}}class Ln extends zi{add(e,t){return void 0===t.id&&(t.id=e),this.content[e]=t,this}addChild(e,t,o){"function"!=typeof o&&void 0===o.id&&(o.id=e);const i=t.splice(0,1)[0];let s=this.content[i];if(!s)throw new Error(`Path ${i+":"+t.join(":")} not found`);for(let e of t){const o=s.children;if(!o||"function"==typeof o)throw new Error(`${e} is either not a node or it's dynamically computed`);if(s=o.find((t=>t.id===e)),!s)throw new Error(`Path ${i+":"+t.join(":")} not found`)}return s.children||(s.children=[]),s.children.push(o),this}getMenuItems(){return _n(this.getAll())}}const
|
|
274
|
+
`;class xn extends t.Component{static components={Menu:wn};static template="o-spreadsheet-LinkDisplay";get cell(){const{col:e,row:t}=this.props.cellPosition,o=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t})}get link(){if(this.cell.link)return this.cell.link;const{col:e,row:t}=this.props.cellPosition;throw new Error(`LinkDisplay Component can only be used with link cells. ${Zt(e,t)} is not a link.`)}getUrlRepresentation(e){return qi(e,this.env.model.getters)}openLink(){Zi(this.link,this.env)}edit(){const{col:e,row:t}=this.props.cellPosition;this.env.model.dispatch("OPEN_CELL_POPOVER",{col:e,row:t,popoverType:"LinkEditor"})}unlink(){const e=this.env.model.getters.getActiveSheetId(),{col:t,row:o}=this.props.cellPosition,i=this.env.model.getters.getCellComputedStyle({sheetId:e,col:t,row:o}),s=i?.textColor===R?void 0:i?.textColor;this.env.model.dispatch("UPDATE_CELL",{col:t,row:o,sheetId:e,content:this.link.label,style:{...i,textColor:s,underline:void 0}})}}const yn={onHover:(e,t)=>{const o=t.getEvaluatedCell(e);return!t.isDashboard()&&o.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:xn,props:{cellPosition:e},cellCorner:"BottomLeft"}:{isOpen:!1}}};xn.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const In={name:n("Link sheet"),children:[e=>e.model.getters.getSheetIds().map((t=>e.model.getters.getSheet(t))).map((e=>({id:e.id,name:e.name,execute:()=>nt(e.name,ct(e.id))})))]},Rn={name:n("Delete"),isVisible:e=>e.model.getters.getSheetIds().length>1,execute:e=>e.askConfirmation(n("Are you sure you want to delete this sheet ?"),(()=>{e.model.dispatch("DELETE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})}))},Tn={name:n("Duplicate"),execute:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.uuidGenerator.uuidv4();e.model.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:o}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})}},An=e=>({name:n("Rename"),execute:e.renameSheetCallback}),On={name:n("Move right"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getVisibleSheetIds();return o.indexOf(t)!==o.length-1},execute:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:1})},Mn={name:n("Move left"),isVisible:e=>{const t=e.model.getters.getActiveSheetId();return e.model.getters.getVisibleSheetIds()[0]!==t},execute:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:-1})},Nn={name:n("Hide sheet"),isVisible:e=>1!==e.model.getters.getVisibleSheetIds().length,execute:e=>e.model.dispatch("HIDE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})};function _n(e){return e.map(Dn).sort(((e,t)=>e.sequence-t.sequence))}const Fn=new ti;function Dn(e){const t=e.name,o=e.children;return{id:e.id||Fn.uuidv4(),name:"function"==typeof t?t:()=>t,isVisible:e.isVisible?e.isVisible:()=>!0,isEnabled:e.isEnabled?e.isEnabled:()=>!0,isActive:e.isActive,execute:e.execute,children:o?e=>o.map((t=>"function"==typeof t?t(e):t)).flat().map(Dn):()=>[],isReadonlyAllowed:e.isReadonlyAllowed||!1,separator:e.separator||!1,icon:e.icon||"",description:e.description||"",textColor:e.textColor,sequence:e.sequence||0}}class Ln extends zi{add(e,t){return void 0===t.id&&(t.id=e),this.content[e]=t,this}addChild(e,t,o){"function"!=typeof o&&void 0===o.id&&(o.id=e);const i=t.splice(0,1)[0];let s=this.content[i];if(!s)throw new Error(`Path ${i+":"+t.join(":")} not found`);for(let e of t){const o=s.children;if(!o||"function"==typeof o)throw new Error(`${e} is either not a node or it's dynamically computed`);if(s=o.find((t=>t.id===e)),!s)throw new Error(`Path ${i+":"+t.join(":")} not found`)}return s.children||(s.children=[]),s.children.push(o),this}getMenuItems(){return _n(this.getAll())}}const Pn=new Ln;Pn.add("sheet",{...In,sequence:10});Ni`
|
|
275
275
|
.o-link-editor {
|
|
276
276
|
font-size: 13px;
|
|
277
277
|
background-color: white;
|
|
@@ -344,13 +344,13 @@
|
|
|
344
344
|
}
|
|
345
345
|
}
|
|
346
346
|
}
|
|
347
|
-
`;class Pn extends t.Component{static template="o-spreadsheet-LinkEditor";static components={Menu:wn};menuItems=kn.getMenuItems();link=t.useState(this.defaultState);menu=t.useState({isOpen:!1});linkEditorRef=t.useRef("linkEditor");position=pn(this.linkEditorRef);urlInput=t.useRef("urlInput");setup(){t.onMounted((()=>this.urlInput.el?.focus()))}get defaultState(){const{col:e,row:t}=this.props.cellPosition,o=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t});return i.link?{url:i.link.url,label:i.formattedValue,isUrlEditable:i.link.isUrlEditable}:{label:i.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,o=ji(t);o&&(this.link.url=o.url,this.link.label=o.label,this.link.isUrlEditable=o.isUrlEditable)}getUrlRepresentation(e){return qi(e,this.env.model.getters)}openMenu(){this.menu.isOpen=!0}removeLink(){this.link.url="",this.link.isUrlEditable=!0}save(){const{col:e,row:t}=this.props.cellPosition,o=this.link.label||this.link.url;this.env.model.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:this.env.model.getters.getActiveSheetId(),content:nt(o,this.link.url)}),this.props.onClosed?.()}cancel(){this.props.onClosed?.()}onKeyDown(e){switch(e.key){case"Enter":this.link.url&&this.save(),e.stopPropagation(),e.preventDefault();break;case"Escape":this.cancel(),e.stopPropagation()}}}const Un={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:Pn,cellCorner:"BottomLeft"})};Pn.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const Vn=new zi;function zn(e){return 8===(e=_t(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}Vn.add("ErrorToolTip",Qs).add("LinkCell",yn).add("LinkEditor",Un).add("FilterMenu",on);class Bn{sheetId;title;getters;constructor(e,t,o){this.title=e.title,this.sheetId=t,this.getters=o}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 Hn(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?ci(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?ri(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}function $n(e,t,o,i){let s=!1;const n=[];for(let i in o){let r=o[i];if(r.labelCell){const e=qn(r.labelCell,t);r.labelCell!==e&&(s=!0,r={...r,labelCell:e})}const a=qn(r.dataRange,t);void 0===a||e.getRangeString(a,a.sheetId)===J?(s=!0,r=void 0):a!==r.dataRange&&(s=!0,r={...r,dataRange:a}),n[i]=r}let r=i;const a=qn(r,t);a!==r&&(s=!0,r=a);return{isStale:s,dataSets:n.filter(dt),labelRange:r}}function Wn(e,t,o){return o.map((o=>({dataRange:Ko(e,t,o.dataRange),labelCell:o.labelCell?Ko(e,t,o.labelCell):void 0})))}function Gn(e,t,o){return o?Ko(e,t,o):void 0}function qn(e,t){if(!e)return;const o=t(e);switch(o.changeType){case"NONE":return e;case"REMOVE":return;default:return o.range}}function Zn(e,t,o,i){const s=[];for(const n of t){const t=e.getRangeFromSheetXC(o,n),{unboundedZone:r,sheetId:a,invalidSheetName:l,invalidXc:c}=t;if(!l&&!c)if(r.left!==r.right&&r.top!==r.bottom){if(void 0===r.right)continue;for(let t=r.left;t<=r.right;t++){const o={...r,left:t,right:t};s.push(jn(e,a,o,i?{top:o.top,bottom:o.top,left:o.left,right:o.left}:void 0))}}else s.push(jn(e,a,r,i?{top:r.top,bottom:r.top,left:r.left,right:r.left}:void 0))}return s}function jn(e,t,o,i){if(o.left!==o.right&&o.top!==o.bottom)throw new Error(`Zone should be a single column or row: ${ni(o)}`);if(i){const s=ni(o),n=ni(i);return{labelCell:e.getRangeFromSheetXC(t,n),dataRange:e.getRangeFromSheetXC(t,s)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,ni(o))}}function Yn(e,t){const o=t.labelCell?.zone;let i=t.dataRange.zone;if(o){const{numberOfRows:e,numberOfCols:t}=vi(i);1===e?i={...i,left:i.left+1}:1===t&&(i={...i,top:i.top+1})}const s=t.dataRange.clone({zone:i});return{label:t.labelCell?e.getRangeString(t.labelCell,"forceSheetReference",!0):void 0,range:e.getRangeString(s,"forceSheetReference",!0)}}function Xn(e,t,o){if(!t)return;let i={...t.zone};o&&t.zone.bottom>t.zone.top&&(i.top=i.top+1);const s=t.clone({zone:i});return e.getRangeString(s,"forceSheetReference",!0)}function Kn(e,t){let o;if(e.labelRange){const i=Hn(oi(e.labelRange),t);o=i?ni(i):void 0}const i=e.dataSets.map(oi).map((e=>Hn(e,t))).filter(dt).map(ni);return{...e,labelRange:o,dataSets:i}}const Qn=["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 Jn{graphColorIndex=0;next(){return Qn[this.graphColorIndex++%Qn.length]}}function er(e){return e&&kt(e)<.3?"#FFFFFF":"#000000"}function tr(e){if(e.dataSets){const t=void 0!==e.dataSets.find((e=>!$o.test(e)));if(t)return 33;if(e.dataSets.map(oi).some((e=>e.top!==e.bottom&&Ii(e))))return 33}return 0}function or(e){if(e.labelRange){if(!$o.test(e.labelRange||""))return 34}return 0}function ir(e,t,o){if(!o)return!1;if(!e)return!1;if(!t)return!0;const i=Ri(t.dataRange.zone);return!(Ri(e.zone)<i)}function sr(e,t,o){if(e){if("text"===o||t?.type!==ys.number||e.type!==ys.number)return e.formattedValue;{let i=t.value-e.value;if("percentage"===o&&0!==i&&(i=i/e.value*100),"percentage"!==o&&e.format)return bo(i,e.format);const s=Math.abs(parseFloat(i.toFixed(2))).toLocaleString();return"percentage"===o?s+"%":s}}return""}function nr(e,t,o,i,s){if("text"===t||e?.type!==ys.number||o?.type!==ys.number)return;const n=o.value-e.value;return n>0?i:n<0?s:void 0}function rr(e,t,o){if("text"===o||e?.type!==ys.number||t?.type!==ys.number)return"neutral";const i=t.value-e.value;return i>0?"up":i<0?"down":"neutral"}const ar={Errors:{25:n("The range is invalid"),52:n("The argument is missing. Please provide a value"),53:n("The second argument is missing. Please provide a value"),54:n("The minpoint must be a number"),55:n("The midpoint must be a number"),56:n("The maxpoint must be a number"),57:n("The first value must be a number"),58:n("The second value must be a number"),48:n("Minimum must be smaller then Maximum"),51:n("Minimum must be smaller then Midpoint"),50:n("Midpoint must be smaller then Maximum"),49:n("Lower inflection point must be smaller than upper inflection point"),59:n("Invalid Minpoint formula"),61:n("Invalid Maxpoint formula"),60:n("Invalid Midpoint formula"),62:n("Invalid upper inflection point formula"),63:n("Invalid lower inflection point formula"),24:n("A range needs to be defined"),Unexpected:n("The rule is invalid for an unknown reason")},ColorScale:n("Color scale"),IconSet:n("Icon set")},lr={IsEmpty:n("Is empty"),IsNotEmpty:n("Is not empty"),ContainsText:n("Contains"),NotContains:n("Does not contain"),BeginsWith:n("Starts with"),EndsWith:n("Ends with"),Equal:n("Is equal to"),NotEqual:n("Is not equal to"),GreaterThan:n("Is greater than"),GreaterThanOrEqual:n("Is greater than or equal to"),LessThan:n("Is less than"),LessThanOrEqual:n("Is less than or equal to"),Between:n("Is between"),NotBetween:n("Is not between")},cr={Series:n("Series"),Errors:{Unexpected:n("The chart definition is invalid for an unknown reason"),33:n("The dataset is invalid"),34:n("Labels are invalid"),35:n("The key value is invalid"),36:n("The baseline value is invalid"),37:n("The data range is invalid"),38:n("A minimum range limit value is needed"),39:n("The minimum range limit value must be a number"),40:n("A maximum range limit value is needed"),41:n("The maximum range limit value must be a number"),42:n("Minimum range limit must be smaller than maximum range limit"),43:n("The lower inflection point value must be a number"),44:n("The upper inflection point value must be a number")}},hr={Custom:n("Custom")},dr=n("Merged cells are preventing this operation. Unmerge those cells and try again."),ur={Errors:{Unexpected:n("Cannot split the selection for an unknown reason"),92:n("There is no match for the selected separator in the selection"),89:n("Only a selection from a single column can be split"),91:n("Splitting will overwrite existing content")}};function gr(e,t){if(t.dataRange){const o=t.labelCell?[ni(t.labelCell.zone)]:[],i=fi([ni(t.dataRange.zone)],o)[0];if(void 0===i)return[];const s=e.getRangeFromSheetXC(t.dataRange.sheetId,i);return e.getRangeValues(s).map((e=>""===e?void 0:e))}return[]}function pr(e,t){const o=Ke(0,Math.max(e.length,...t.map((e=>e.data?.length||0)))).filter((o=>{const i=e[o],s=t.map((e=>e.data?.[o]));return i||s.some((e=>0===e||Boolean(e)))}));return{labels:o.map((t=>e[t]||"")),dataSetsValues:t.map((e=>({...e,data:o.map((t=>e.data[t]))})))}}function mr(e,t){const o=new Set(e),i={};o.forEach((e=>{i[e]=new Array(t.length).fill(0)}));for(const o of Ke(0,e.length)){const n=e[o];for(const e of Ke(0,t.length))i[n][e]+="number"==typeof(s=t[e].data[o])?s:0}var s;return{labels:Array.from(o),dataSetsValues:t.map(((e,t)=>({...e,data:Array.from(o).map((e=>i[e][t]))})))}}function fr(e){return e?e.length>oe?e.substring(0,oe)+"…":e:""}function br(e,t,o,i,n=!0){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:s(e.title),fontColor:o},legend:{onClick:void 0},tooltips:{callbacks:{label:function(e,t){let o=t.datasets?.[e.datasetIndex||0]?.label;const s=""!==e.yLabel?e.yLabel:t.datasets?.[e.datasetIndex||0]?.data?.[e.index||0],n=i&&"number"==typeof s?bo(s,i):s?.toLocaleString()||"";return o?`${o}: ${n}`:n}}}},data:{labels:n?t.map(fr):t,datasets:[]}}}function vr(e,t,o){let i={values:[],formattedValues:[]};if(o)o.invalidXc||o.invalidSheetName||(i={formattedValues:e.getRangeFormattedValues(o),values:e.getRangeValues(o).map((e=>String(e)))});else if(1===t.length)for(let o=0;o<gr(e,t[0]).length;o++)i.formattedValues.push(""),i.values.push("");else if(t[0]){i={formattedValues:Ke(0,gr(e,t[0]).length).map((e=>e.toString())),values:i.formattedValues}}return i}function Sr(e,t){for(const o of t){const t=e.getRangeFormats(o.dataRange).find((e=>void 0!==e&&!xo(e)));if(t)return t}}function Cr(e,t){const o=[];for(const[i,s]of Object.entries(t)){let t;if(s.labelCell){const o=s.labelCell,n=o?e.getEvaluatedCell({sheetId:o.sheetId,col:o.zone.left,row:o.zone.top}):void 0;t=n&&o?fr(n.formattedValue):t=`${cr.Series} ${parseInt(i)+1}`}else t=t=`${cr.Series} ${parseInt(i)+1}`;let n=s.dataRange?gr(e,s):[];o.push({data:n,label:t})}return o}function Er(e){return 0===e?"origin":e-1}class wr extends Bn{dataSets;labelRange;background;verticalAxisPosition;legendPosition;stacked;aggregated;type="bar";dataSetsHaveTitle;constructor(e,t,o){super(e,t,o),this.dataSets=Zn(o,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Qo(o,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle}static transformDefinition(e,t){return Kn(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,tr,or)}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=Wn(this.sheetId,e,this.dataSets),o=Gn(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new wr(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new wr(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,o){return{type:"bar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,o||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,o||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated}}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>Yn(this.getters,e))).filter((e=>""!==e.range&&e.range!==J)),t=Xn(this.getters,this.labelRange,ir(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:zn(this.background||w),fontColor:zn(er(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:o,isStale:i}=$n(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const s=this.getDefinitionWithSpecificDataSets(t,o);return new wr(s,this.sheetId,this.getters)}}function xr(e){return e.dataRange&&!$o.test(e.dataRange)?37:0}function yr(e,t){return t((t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):0),(t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):0))}function Ir(e){return e.sectionRule&&Number(e.sectionRule.rangeMin)>=Number(e.sectionRule.rangeMax)?42:0}function Rr(e,t){if(""===e)switch(t){case"rangeMin":return 38;case"rangeMax":return 40}return 0}function Tr(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 Ar extends Bn{dataRange;sectionRule;background;type="gauge";constructor(e,t,o){super(e,t,o),this.dataRange=Qo(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,xr,e.chainValidations(yr(Rr,e.batchValidations),yr(Tr,e.batchValidations),Ir),e.chainValidations((o=Tr,(0,e.batchValidations)((e=>e.sectionRule?o(e.sectionRule.lowerInflectionPoint.value,"lowerInflectionPointValue"):0),(e=>e.sectionRule?o(e.sectionRule.upperInflectionPoint.value,"upperInflectionPointValue"):0)))));var o}static transformDefinition(e,t){let o;return e.dataRange&&(o=Hn(oi(e.dataRange),t)),{...e,dataRange:o?ni(o):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=Gn(this.sheetId,e,this.dataRange),o=this.getDefinitionWithSpecificRanges(t,e);return new Ar(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.dataRange,e);return new Ar(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=qn(this.dataRange,e);if(this.dataRange===t)return this;const o=this.getDefinitionWithSpecificRanges(t);return new Ar(o,this.sheetId,this.getters)}}const Or={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},Mr={inSeconds:function(e){return Math.floor(e/Or.second)},inMinutes:function(e){return Math.floor(e/Or.minute)},inHours:function(e){return Math.floor(e/Or.hour)},inDays:function(e){return Math.floor(e/Or.day)},inMonths:function(e){return Math.floor(e/Or.month)},inYears:function(e){return Math.floor(e/Or.year)}},Nr=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function _r(e,t){const o=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),i=function(e,t){const o=e.map((e=>Te(e)?.jsDate));if(o.some((e=>void 0===e))||e.length<2)return;const i=o.map((e=>e.getTime())),s=Rt(i)-Tt(i),n=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(Or.second>=Or[n]&&Mr.inSeconds(s)<180)return"second";if(Or.minute>=Or[n]&&Mr.inMinutes(s)<180)return"minute";if(Or.hour>=Or[n]&&Mr.inHours(s)<96)return"hour";if(Or.day>=Or[n]&&Mr.inDays(s)<90)return"day";if(Or.month>=Or[n]&&Mr.inMonths(s)<36)return"month";return"year"}(e,o),s={};return i&&(s[i]=o),{parser:o,displayFormats:s,unit:i}}class Fr extends Bn{dataSets;labelRange;background;verticalAxisPosition;legendPosition;labelsAsText;stacked;aggregated;type="line";dataSetsHaveTitle;cumulative;constructor(e,t,o){super(e,t,o),this.dataSets=Zn(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Qo(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.dataSetsHaveTitle=e.dataSetsHaveTitle,this.cumulative=e.cumulative}static validateChartDefinition(e,t){return e.checkValidations(t,tr,or)}static transformDefinition(e,t){return Kn(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,o){return{type:"line",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,o||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,o||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:o,isStale:i}=$n(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const s=this.getDefinitionWithSpecificDataSets(t,o);return new Fr(s,this.sheetId,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>Yn(this.getters,e))).filter((e=>""!==e.range&&e.range!==J)),t=Xn(this.getters,this.labelRange,ir(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:zn(this.background||w),fontColor:zn(er(this.background)),dataSets:e,labelRange:t}}copyForSheetId(e){const t=Wn(this.sheetId,e,this.dataSets),o=Gn(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new Fr(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Fr(t,e,this.getters)}}function Dr(e,t){return kr(e,t)||Pr(e,t)}function Lr(e,t){return function(e,t){return!e.labelsAsText&&kr(e.labelRange,t)}(e,t)?"time":function(e,t){return!e.labelsAsText&&Pr(e.labelRange,t)}(e,t)?"linear":"category"}function kr(e,t){if(!e||!Pr(e,t))return!1;const o=t.getEvaluatedCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}).format;return Boolean(o&&Nr.test(o))}function Pr(e,t){if(!e)return!1;const o=t.getRangeValues(e);return!o.some((e=>isNaN(Number(e))&&e))&&!o.every((e=>!e))}class Ur extends Bn{dataSets;labelRange;background;legendPosition;type="pie";aggregated;dataSetsHaveTitle;constructor(e,t,o){super(e,t,o),this.dataSets=Zn(o,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Qo(o,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle}static transformDefinition(e,t){return Kn(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,tr,or)}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,o){return{type:"pie",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,o||this.sheetId))),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,o||this.sheetId):void 0,title:this.title,aggregated:this.aggregated}}copyForSheetId(e){const t=Wn(this.sheetId,e,this.dataSets),o=Gn(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new Ur(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Ur(t,e,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>Yn(this.getters,e))).filter((e=>""!==e.range&&e.range!==J)),t=Xn(this.getters,this.labelRange,ir(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:zn(this.background||w),fontColor:zn(er(this.background)),verticalAxisPosition:"left",dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:o,isStale:i}=$n(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const s=this.getDefinitionWithSpecificDataSets(t,o);return new Ur(s,this.sheetId,this.getters)}}function Vr(e,t){const o=[],i=Rt(t.map((e=>e.data.length)));for(let t=0;t<=i;t++)o.push(e.next());return o}function zr(e){return e.keyValue&&!$o.test(e.keyValue)?35:0}function Br(e){return e.baseline&&!$o.test(e.baseline)?36:0}class Hr extends Bn{keyValue;baseline;baselineMode;baselineDescr;background;baselineColorUp;baselineColorDown;fontColor;type="scorecard";constructor(e,t,o){super(e,t,o),this.keyValue=Qo(o,t,e.keyValue),this.baseline=Qo(o,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,zr,Br)}static getDefinitionFromContextCreation(e){return{background:e.background,type:"scorecard",keyValue:e.range?e.range[0]:void 0,title:e.title||"",baselineMode:se,baselineColorUp:ne,baselineColorDown:re,baseline:e.auxiliaryRange||""}}static transformDefinition(e,t){let o,i;return e.baseline&&(o=Hn(oi(e.baseline),t)),e.keyValue&&(i=Hn(oi(e.keyValue),t)),{...e,baseline:o?ni(o):void 0,keyValue:i?ni(i):void 0}}copyForSheetId(e){const t=Gn(this.sheetId,e,this.baseline),o=Gn(this.sheetId,e,this.keyValue),i=this.getDefinitionWithSpecificRanges(t,o,e);return new Hr(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,e);return new Hr(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,o){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:"scorecard",background:this.background,baseline:e?this.getters.getRangeString(e,o||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,o||this.sheetId):void 0}}getDefinitionForExcel(){}updateRanges(e){const t=qn(this.baseline,e),o=qn(this.keyValue,e);if(this.baseline===t&&this.keyValue===o)return this;const i=this.getDefinitionWithSpecificRanges(t,o);return new Hr(i,this.sheetId,this.getters)}}const $r=new zi;$r.add("bar",{match:e=>"bar"===e,createChart:(e,t,o)=>new wr(e,t,o),getChartRuntime:function(e,t){let o=vr(t,e.dataSets,e.labelRange).formattedValues,i=Cr(t,e.dataSets);e.dataSetsHaveTitle&&i[0]&&o.length>i[0].data.length&&o.shift(),({labels:o,dataSetsValues:i}=pr(o,i)),e.aggregated&&({labels:o,dataSetsValues:i}=mr(o,i));const s=function(e,t,o){const i=er(e.background),s=br(e,t,i,o),n={labels:{fontColor:i}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?n.display=!1:n.position=e.legendPosition,s.options.legend={...s.options?.legend,...n},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:i}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:i,beginAtZero:!0,callback:e=>o?bo(e,o):e?.toLocaleString()||e}}]},e.stacked&&(s.options.scales.xAxes[0].stacked=!0,s.options.scales.yAxes[0].stacked=!0),s}(e,o,Sr(t,e.dataSets)),n=new Jn;for(let{label:e,data:t}of i){const o=n.next(),i={label:e,data:t,borderColor:o,backgroundColor:o};s.data.datasets.push(i)}return{chartJsConfig:s,background:e.background||w}},validateChartDefinition:(e,t)=>wr.validateChartDefinition(e,t),transformDefinition:(e,t)=>wr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>wr.getDefinitionFromContextCreation(e),name:n("Bar"),sequence:10}),$r.add("line",{match:e=>"line"===e,createChart:(e,t,o)=>new Fr(e,t,o),getChartRuntime:function(e,t){const o=Lr(e,t),i=vr(t,e.dataSets,e.labelRange);let s="linear"===o?i.values:i.formattedValues,n=Cr(t,e.dataSets);e.dataSetsHaveTitle&&n[0]&&s.length>n[0].data.length&&s.shift(),({labels:s,dataSetsValues:n}=pr(s,n)),"time"===o&&({labels:s,dataSetsValues:n}=function(e,t){if(0===e.length||e.every((e=>!e)))return{labels:e,dataSetsValues:t};const o=[...e],i=Be(t);for(let e=0;e<o.length;e++)if(!o[e]){o[e]=ft(o,e);for(let t of i)t.data[e]=void 0}return{labels:o,dataSetsValues:i}}(s,n)),e.aggregated&&({labels:s,dataSetsValues:n}=mr(s,n));const r="category"===o,a=Sr(t,e.dataSets),l=function(e,t,o,i){const s=er(e.background),n=br(e,t,s,o,i),r={labels:{fontColor:s,generateLabels(e){const{data:t}=e,o=window.Chart.defaults.global.legend.labels.generateLabels(e);for(const[e,i]of o.entries())i.fillStyle=t.datasets[e].borderColor;return o}}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,n.options.legend={...n.options?.legend,...r},n.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},n.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:s}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:s,beginAtZero:!0,callback:e=>o?bo(e,o):e?.toLocaleString()||e}}]},e.stacked&&(n.options.scales.yAxes[0].stacked=!0),n}(e,s,a,r),c=function(e,t){if(t)return e.getEvaluatedCell({sheetId:t.sheetId,col:t.zone.left,row:t.zone.top}).format}(t,e.labelRange);"time"===o?(l.options.scales.xAxes[0].type="time",l.options.scales.xAxes[0].time=_r(s,c),l.options.scales.xAxes[0].ticks.maxTicksLimit=15):"linear"===o&&(l.options.scales.xAxes[0].type="linear",l.options.scales.xAxes[0].ticks.callback=e=>bo(e,c),l.options.tooltips.callbacks.title=e=>bo(e[0]?.xLabel||"",c));const h=new Jn;for(let[t,{label:i,data:r}]of n.entries()){["linear","time"].includes(o)&&(r=r.map(((e,t)=>({x:s[t]||void 0,y:e}))));const n=h.next();let a=Ut(n);if(e.stacked&&(a.a=ae),e.cumulative){let e=0;r=r.map((t=>isNaN(t)?t:(e+=parseFloat(t),e)))}const c={label:i,data:r,lineTension:0,borderColor:n,backgroundColor:Pt(a),pointBackgroundColor:n,fill:!!e.stacked&&Er(t)};l.data.datasets.push(c)}return{chartJsConfig:l,background:e.background||w}},validateChartDefinition:(e,t)=>Fr.validateChartDefinition(e,t),transformDefinition:(e,t)=>Fr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Fr.getDefinitionFromContextCreation(e),name:n("Line"),sequence:20}),$r.add("pie",{match:e=>"pie"===e,createChart:(e,t,o)=>new Ur(e,t,o),getChartRuntime:function(e,t){let o=vr(t,e.dataSets,e.labelRange).formattedValues,i=Cr(t,e.dataSets);e.dataSetsHaveTitle&&i[0]&&o.length>i[0].data.length&&o.shift(),({labels:o,dataSetsValues:i}=pr(o,i)),e.aggregated&&({labels:o,dataSetsValues:i}=mr(o,i));const s=function(e,t,o){const i=er(e.background),s=br(e,t,i,o),n={labels:{fontColor:i}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?n.display=!1:n.position=e.legendPosition,s.options.legend={...s.options?.legend,...n},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,o,Sr(t,e.dataSets)),n=new Jn;for(let{label:e,data:t}of i){const o={label:e,data:t,borderColor:"#FFFFFF",backgroundColor:Vr(n,i)};s.data.datasets.push(o)}return{chartJsConfig:s,background:e.background||w}},validateChartDefinition:(e,t)=>Ur.validateChartDefinition(e,t),transformDefinition:(e,t)=>Ur.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Ur.getDefinitionFromContextCreation(e),name:n("Pie"),sequence:30}),$r.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,o)=>new Hr(e,t,o),getChartRuntime:function(e,t){let o,i,n="",r="";if(e.keyValue){const i={sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top};o=t.getEvaluatedCell(i),n=String(o.value),r=o.formattedValue}const a=e.baseline;if(a){const o={sheetId:e.baseline.sheetId,col:e.baseline.zone.left,row:e.baseline.zone.top};i=t.getEvaluatedCell(o)}const{background:l,fontColor:c}=t.getStyleOfSingleCellChart(e.background,e.keyValue);return{title:s(e.title),keyValue:r||n,baselineDisplay:sr(i,o,e.baselineMode),baselineArrow:rr(i,o,e.baselineMode),baselineColor:nr(i,e.baselineMode,o,e.baselineColorUp,e.baselineColorDown),baselineDescr:e.baselineDescr?s(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)=>Hr.validateChartDefinition(e,t),transformDefinition:(e,t)=>Hr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Hr.getDefinitionFromContextCreation(e),name:n("Scorecard"),sequence:40}),$r.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,o)=>new Ar(e,t,o),getChartRuntime:function(e,t){const o=function(e){const t=br(e,[],er(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),i=e.sectionRule.colors,s=e.sectionRule.lowerInflectionPoint,n=e.sectionRule.upperInflectionPoint,r=Number(s.value),a=Number(n.value),l=Number(e.sectionRule.rangeMin),c=Number(e.sectionRule.rangeMax),h=c-l,d=[];if(""!==s.value){const e="number"===s.type?r:l+h*r/100;d.push({value:We(e,l,c),color:i.lowerColor})}if(""!==n.value){const e="number"===n.type?a:l+h*a/100;d.push({value:We(e,l,c),color:i.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(i.upperColor);const p=e.dataRange,m=h/30;let f=l-m,b=null,v=!1;if(void 0!==p){const e=t.getEvaluatedCell({sheetId:p.sheetId,col:p.zone.left,row:p.zone.top});e.type===ys.number&&(f=We(e.value,l-m,c+m),b=()=>t.getRangeFormattedValues(p)[0],v=!0)}return o.options.valueLabel.display=v,o.options.valueLabel.formatter=b,o.data.datasets.push({data:u,minValue:Number(e.sectionRule.rangeMin),value:f,backgroundColor:g}),{chartJsConfig:o,background:t.getStyleOfSingleCellChart(e.background,p).background}},validateChartDefinition:(e,t)=>Ar.validateChartDefinition(e,t),transformDefinition:(e,t)=>Ar.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Ar.getDefinitionFromContextCreation(e),name:n("Gauge"),sequence:50});const Wr=new zi;Wr.add("line",Ai),Wr.add("bar",Ai),Wr.add("pie",Ai),Wr.add("gauge",Ai),Wr.add("scorecard",Pi);const Gr=new zi;Ni`
|
|
347
|
+
`;class kn extends t.Component{static template="o-spreadsheet-LinkEditor";static components={Menu:wn};menuItems=Pn.getMenuItems();link=t.useState(this.defaultState);menu=t.useState({isOpen:!1});linkEditorRef=t.useRef("linkEditor");position=pn(this.linkEditorRef);urlInput=t.useRef("urlInput");setup(){t.onMounted((()=>this.urlInput.el?.focus()))}get defaultState(){const{col:e,row:t}=this.props.cellPosition,o=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t});return i.link?{url:i.link.url,label:i.formattedValue,isUrlEditable:i.link.isUrlEditable}:{label:i.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,o=ji(t);o&&(this.link.url=o.url,this.link.label=o.label,this.link.isUrlEditable=o.isUrlEditable)}getUrlRepresentation(e){return qi(e,this.env.model.getters)}openMenu(){this.menu.isOpen=!0}removeLink(){this.link.url="",this.link.isUrlEditable=!0}save(){const{col:e,row:t}=this.props.cellPosition,o=this.link.label||this.link.url;this.env.model.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:this.env.model.getters.getActiveSheetId(),content:nt(o,this.link.url)}),this.props.onClosed?.()}cancel(){this.props.onClosed?.()}onKeyDown(e){switch(e.key){case"Enter":this.link.url&&this.save(),e.stopPropagation(),e.preventDefault();break;case"Escape":this.cancel(),e.stopPropagation()}}}const Un={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:kn,cellCorner:"BottomLeft"})};kn.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const Vn=new zi;function zn(e){return 8===(e=_t(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}Vn.add("ErrorToolTip",Qs).add("LinkCell",yn).add("LinkEditor",Un).add("FilterMenu",on);class Bn{sheetId;title;getters;constructor(e,t,o){this.title=e.title,this.sheetId=t,this.getters=o}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 Hn(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?ci(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?ri(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}function $n(e,t,o,i){let s=!1;const n=[];for(let i in o){let r=o[i];if(r.labelCell){const e=qn(r.labelCell,t);r.labelCell!==e&&(s=!0,r={...r,labelCell:e})}const a=qn(r.dataRange,t);void 0===a||e.getRangeString(a,a.sheetId)===J?(s=!0,r=void 0):a!==r.dataRange&&(s=!0,r={...r,dataRange:a}),n[i]=r}let r=i;const a=qn(r,t);a!==r&&(s=!0,r=a);return{isStale:s,dataSets:n.filter(dt),labelRange:r}}function Wn(e,t,o){return o.map((o=>({dataRange:Ko(e,t,o.dataRange),labelCell:o.labelCell?Ko(e,t,o.labelCell):void 0})))}function Gn(e,t,o){return o?Ko(e,t,o):void 0}function qn(e,t){if(!e)return;const o=t(e);switch(o.changeType){case"NONE":return e;case"REMOVE":return;default:return o.range}}function Zn(e,t,o,i){const s=[];for(const n of t){const t=e.getRangeFromSheetXC(o,n),{unboundedZone:r,sheetId:a,invalidSheetName:l,invalidXc:c}=t;if(!l&&!c)if(r.left!==r.right&&r.top!==r.bottom){if(void 0===r.right)continue;for(let t=r.left;t<=r.right;t++){const o={...r,left:t,right:t};s.push(jn(e,a,o,i?{top:o.top,bottom:o.top,left:o.left,right:o.left}:void 0))}}else s.push(jn(e,a,r,i?{top:r.top,bottom:r.top,left:r.left,right:r.left}:void 0))}return s}function jn(e,t,o,i){if(o.left!==o.right&&o.top!==o.bottom)throw new Error(`Zone should be a single column or row: ${ni(o)}`);if(i){const s=ni(o),n=ni(i);return{labelCell:e.getRangeFromSheetXC(t,n),dataRange:e.getRangeFromSheetXC(t,s)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,ni(o))}}function Yn(e,t){const o=t.labelCell?.zone;let i=t.dataRange.zone;if(o){const{numberOfRows:e,numberOfCols:t}=vi(i);1===e?i={...i,left:i.left+1}:1===t&&(i={...i,top:i.top+1})}const s=t.dataRange.clone({zone:i});return{label:t.labelCell?e.getRangeString(t.labelCell,"forceSheetReference",!0):void 0,range:e.getRangeString(s,"forceSheetReference",!0)}}function Xn(e,t,o){if(!t)return;let i={...t.zone};o&&t.zone.bottom>t.zone.top&&(i.top=i.top+1);const s=t.clone({zone:i});return e.getRangeString(s,"forceSheetReference",!0)}function Kn(e,t){let o;if(e.labelRange){const i=Hn(oi(e.labelRange),t);o=i?ni(i):void 0}const i=e.dataSets.map(oi).map((e=>Hn(e,t))).filter(dt).map(ni);return{...e,labelRange:o,dataSets:i}}const Qn=["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 Jn{graphColorIndex=0;next(){return Qn[this.graphColorIndex++%Qn.length]}}function er(e){return e&&Pt(e)<.3?"#FFFFFF":"#000000"}function tr(e){if(e.dataSets){const t=void 0!==e.dataSets.find((e=>!$o.test(e)));if(t)return 33;if(e.dataSets.map(oi).some((e=>e.top!==e.bottom&&Ii(e))))return 33}return 0}function or(e){if(e.labelRange){if(!$o.test(e.labelRange||""))return 34}return 0}function ir(e,t,o){if(!o)return!1;if(!e)return!1;if(!t)return!0;const i=Ri(t.dataRange.zone);return!(Ri(e.zone)<i)}function sr(e,t,o){if(e){if("text"===o||t?.type!==ys.number||e.type!==ys.number)return e.formattedValue;{let i=t.value-e.value;if("percentage"===o&&0!==i&&(i=i/e.value*100),"percentage"!==o&&e.format)return bo(i,e.format);const s=Math.abs(parseFloat(i.toFixed(2))).toLocaleString();return"percentage"===o?s+"%":s}}return""}function nr(e,t,o,i,s){if("text"===t||e?.type!==ys.number||o?.type!==ys.number)return;const n=o.value-e.value;return n>0?i:n<0?s:void 0}function rr(e,t,o){if("text"===o||e?.type!==ys.number||t?.type!==ys.number)return"neutral";const i=t.value-e.value;return i>0?"up":i<0?"down":"neutral"}const ar={Errors:{25:n("The range is invalid"),52:n("The argument is missing. Please provide a value"),53:n("The second argument is missing. Please provide a value"),54:n("The minpoint must be a number"),55:n("The midpoint must be a number"),56:n("The maxpoint must be a number"),57:n("The first value must be a number"),58:n("The second value must be a number"),48:n("Minimum must be smaller then Maximum"),51:n("Minimum must be smaller then Midpoint"),50:n("Midpoint must be smaller then Maximum"),49:n("Lower inflection point must be smaller than upper inflection point"),59:n("Invalid Minpoint formula"),61:n("Invalid Maxpoint formula"),60:n("Invalid Midpoint formula"),62:n("Invalid upper inflection point formula"),63:n("Invalid lower inflection point formula"),24:n("A range needs to be defined"),Unexpected:n("The rule is invalid for an unknown reason")},ColorScale:n("Color scale"),IconSet:n("Icon set")},lr={IsEmpty:n("Is empty"),IsNotEmpty:n("Is not empty"),ContainsText:n("Contains"),NotContains:n("Does not contain"),BeginsWith:n("Starts with"),EndsWith:n("Ends with"),Equal:n("Is equal to"),NotEqual:n("Is not equal to"),GreaterThan:n("Is greater than"),GreaterThanOrEqual:n("Is greater than or equal to"),LessThan:n("Is less than"),LessThanOrEqual:n("Is less than or equal to"),Between:n("Is between"),NotBetween:n("Is not between")},cr={Series:n("Series"),Errors:{Unexpected:n("The chart definition is invalid for an unknown reason"),33:n("The dataset is invalid"),34:n("Labels are invalid"),35:n("The key value is invalid"),36:n("The baseline value is invalid"),37:n("The data range is invalid"),38:n("A minimum range limit value is needed"),39:n("The minimum range limit value must be a number"),40:n("A maximum range limit value is needed"),41:n("The maximum range limit value must be a number"),42:n("Minimum range limit must be smaller than maximum range limit"),43:n("The lower inflection point value must be a number"),44:n("The upper inflection point value must be a number")}},hr={Custom:n("Custom")},dr=n("Merged cells are preventing this operation. Unmerge those cells and try again."),ur={Errors:{Unexpected:n("Cannot split the selection for an unknown reason"),92:n("There is no match for the selected separator in the selection"),89:n("Only a selection from a single column can be split"),91:n("Splitting will overwrite existing content")}};function gr(e,t){if(t.dataRange){const o=t.labelCell?[ni(t.labelCell.zone)]:[],i=fi([ni(t.dataRange.zone)],o)[0];if(void 0===i)return[];const s=e.getRangeFromSheetXC(t.dataRange.sheetId,i);return e.getRangeValues(s).map((e=>""===e?void 0:e))}return[]}function pr(e,t){const o=Ke(0,Math.max(e.length,...t.map((e=>e.data?.length||0)))).filter((o=>{const i=e[o],s=t.map((e=>e.data?.[o]));return i||s.some((e=>0===e||Boolean(e)))}));return{labels:o.map((t=>e[t]||"")),dataSetsValues:t.map((e=>({...e,data:o.map((t=>e.data[t]))})))}}function mr(e,t){const o=new Set(e),i={};o.forEach((e=>{i[e]=new Array(t.length).fill(0)}));for(const o of Ke(0,e.length)){const n=e[o];for(const e of Ke(0,t.length))i[n][e]+="number"==typeof(s=t[e].data[o])?s:0}var s;return{labels:Array.from(o),dataSetsValues:t.map(((e,t)=>({...e,data:Array.from(o).map((e=>i[e][t]))})))}}function fr(e){return e?e.length>oe?e.substring(0,oe)+"…":e:""}function br(e,t,o,i,n=!0){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:s(e.title),fontColor:o},legend:{onClick:void 0},tooltips:{callbacks:{label:function(e,t){let o=t.datasets?.[e.datasetIndex||0]?.label;const s=""!==e.yLabel?e.yLabel:t.datasets?.[e.datasetIndex||0]?.data?.[e.index||0],n=i&&"number"==typeof s?bo(s,i):s?.toLocaleString()||"";return o?`${o}: ${n}`:n}}}},data:{labels:n?t.map(fr):t,datasets:[]}}}function vr(e,t,o){let i={values:[],formattedValues:[]};if(o)o.invalidXc||o.invalidSheetName||(i={formattedValues:e.getRangeFormattedValues(o),values:e.getRangeValues(o).map((e=>String(e)))});else if(1===t.length)for(let o=0;o<gr(e,t[0]).length;o++)i.formattedValues.push(""),i.values.push("");else if(t[0]){i={formattedValues:Ke(0,gr(e,t[0]).length).map((e=>e.toString())),values:i.formattedValues}}return i}function Sr(e,t){for(const o of t){const t=e.getRangeFormats(o.dataRange).find((e=>void 0!==e&&!xo(e)));if(t)return t}}function Cr(e,t){const o=[];for(const[i,s]of Object.entries(t)){let t;if(s.labelCell){const o=s.labelCell,n=o?e.getEvaluatedCell({sheetId:o.sheetId,col:o.zone.left,row:o.zone.top}):void 0;t=n&&o?fr(n.formattedValue):t=`${cr.Series} ${parseInt(i)+1}`}else t=t=`${cr.Series} ${parseInt(i)+1}`;let n=s.dataRange?gr(e,s):[];o.push({data:n,label:t})}return o}function Er(e){return 0===e?"origin":e-1}class wr extends Bn{dataSets;labelRange;background;verticalAxisPosition;legendPosition;stacked;aggregated;type="bar";dataSetsHaveTitle;constructor(e,t,o){super(e,t,o),this.dataSets=Zn(o,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Qo(o,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle}static transformDefinition(e,t){return Kn(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,tr,or)}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=Wn(this.sheetId,e,this.dataSets),o=Gn(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new wr(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new wr(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,o){return{type:"bar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,o||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,o||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated}}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>Yn(this.getters,e))).filter((e=>""!==e.range&&e.range!==J)),t=Xn(this.getters,this.labelRange,ir(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:zn(this.background||w),fontColor:zn(er(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:o,isStale:i}=$n(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const s=this.getDefinitionWithSpecificDataSets(t,o);return new wr(s,this.sheetId,this.getters)}}function xr(e){return e.dataRange&&!$o.test(e.dataRange)?37:0}function yr(e,t){return t((t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):0),(t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):0))}function Ir(e){return e.sectionRule&&Number(e.sectionRule.rangeMin)>=Number(e.sectionRule.rangeMax)?42:0}function Rr(e,t){if(""===e)switch(t){case"rangeMin":return 38;case"rangeMax":return 40}return 0}function Tr(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 Ar extends Bn{dataRange;sectionRule;background;type="gauge";constructor(e,t,o){super(e,t,o),this.dataRange=Qo(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,xr,e.chainValidations(yr(Rr,e.batchValidations),yr(Tr,e.batchValidations),Ir),e.chainValidations((o=Tr,(0,e.batchValidations)((e=>e.sectionRule?o(e.sectionRule.lowerInflectionPoint.value,"lowerInflectionPointValue"):0),(e=>e.sectionRule?o(e.sectionRule.upperInflectionPoint.value,"upperInflectionPointValue"):0)))));var o}static transformDefinition(e,t){let o;return e.dataRange&&(o=Hn(oi(e.dataRange),t)),{...e,dataRange:o?ni(o):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=Gn(this.sheetId,e,this.dataRange),o=this.getDefinitionWithSpecificRanges(t,e);return new Ar(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.dataRange,e);return new Ar(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=qn(this.dataRange,e);if(this.dataRange===t)return this;const o=this.getDefinitionWithSpecificRanges(t);return new Ar(o,this.sheetId,this.getters)}}const Or={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},Mr={inSeconds:function(e){return Math.floor(e/Or.second)},inMinutes:function(e){return Math.floor(e/Or.minute)},inHours:function(e){return Math.floor(e/Or.hour)},inDays:function(e){return Math.floor(e/Or.day)},inMonths:function(e){return Math.floor(e/Or.month)},inYears:function(e){return Math.floor(e/Or.year)}},Nr=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function _r(e,t){const o=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),i=function(e,t){const o=e.map((e=>Te(e)?.jsDate));if(o.some((e=>void 0===e))||e.length<2)return;const i=o.map((e=>e.getTime())),s=Rt(i)-Tt(i),n=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(Or.second>=Or[n]&&Mr.inSeconds(s)<180)return"second";if(Or.minute>=Or[n]&&Mr.inMinutes(s)<180)return"minute";if(Or.hour>=Or[n]&&Mr.inHours(s)<96)return"hour";if(Or.day>=Or[n]&&Mr.inDays(s)<90)return"day";if(Or.month>=Or[n]&&Mr.inMonths(s)<36)return"month";return"year"}(e,o),s={};return i&&(s[i]=o),{parser:o,displayFormats:s,unit:i}}class Fr extends Bn{dataSets;labelRange;background;verticalAxisPosition;legendPosition;labelsAsText;stacked;aggregated;type="line";dataSetsHaveTitle;cumulative;constructor(e,t,o){super(e,t,o),this.dataSets=Zn(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Qo(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.dataSetsHaveTitle=e.dataSetsHaveTitle,this.cumulative=e.cumulative}static validateChartDefinition(e,t){return e.checkValidations(t,tr,or)}static transformDefinition(e,t){return Kn(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,o){return{type:"line",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,o||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,o||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:o,isStale:i}=$n(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const s=this.getDefinitionWithSpecificDataSets(t,o);return new Fr(s,this.sheetId,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>Yn(this.getters,e))).filter((e=>""!==e.range&&e.range!==J)),t=Xn(this.getters,this.labelRange,ir(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:zn(this.background||w),fontColor:zn(er(this.background)),dataSets:e,labelRange:t}}copyForSheetId(e){const t=Wn(this.sheetId,e,this.dataSets),o=Gn(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new Fr(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Fr(t,e,this.getters)}}function Dr(e,t){return Pr(e,t)||kr(e,t)}function Lr(e,t){return function(e,t){return!e.labelsAsText&&Pr(e.labelRange,t)}(e,t)?"time":function(e,t){return!e.labelsAsText&&kr(e.labelRange,t)}(e,t)?"linear":"category"}function Pr(e,t){if(!e||!kr(e,t))return!1;const o=t.getEvaluatedCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}).format;return Boolean(o&&Nr.test(o))}function kr(e,t){if(!e)return!1;const o=t.getRangeValues(e);return!o.some((e=>isNaN(Number(e))&&e))&&!o.every((e=>!e))}class Ur extends Bn{dataSets;labelRange;background;legendPosition;type="pie";aggregated;dataSetsHaveTitle;constructor(e,t,o){super(e,t,o),this.dataSets=Zn(o,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Qo(o,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle}static transformDefinition(e,t){return Kn(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,tr,or)}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,o){return{type:"pie",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,o||this.sheetId))),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,o||this.sheetId):void 0,title:this.title,aggregated:this.aggregated}}copyForSheetId(e){const t=Wn(this.sheetId,e,this.dataSets),o=Gn(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new Ur(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Ur(t,e,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>Yn(this.getters,e))).filter((e=>""!==e.range&&e.range!==J)),t=Xn(this.getters,this.labelRange,ir(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:zn(this.background||w),fontColor:zn(er(this.background)),verticalAxisPosition:"left",dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:o,isStale:i}=$n(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const s=this.getDefinitionWithSpecificDataSets(t,o);return new Ur(s,this.sheetId,this.getters)}}function Vr(e,t){const o=[],i=Rt(t.map((e=>e.data.length)));for(let t=0;t<=i;t++)o.push(e.next());return o}function zr(e){return e.keyValue&&!$o.test(e.keyValue)?35:0}function Br(e){return e.baseline&&!$o.test(e.baseline)?36:0}class Hr extends Bn{keyValue;baseline;baselineMode;baselineDescr;background;baselineColorUp;baselineColorDown;fontColor;type="scorecard";constructor(e,t,o){super(e,t,o),this.keyValue=Qo(o,t,e.keyValue),this.baseline=Qo(o,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,zr,Br)}static getDefinitionFromContextCreation(e){return{background:e.background,type:"scorecard",keyValue:e.range?e.range[0]:void 0,title:e.title||"",baselineMode:se,baselineColorUp:ne,baselineColorDown:re,baseline:e.auxiliaryRange||""}}static transformDefinition(e,t){let o,i;return e.baseline&&(o=Hn(oi(e.baseline),t)),e.keyValue&&(i=Hn(oi(e.keyValue),t)),{...e,baseline:o?ni(o):void 0,keyValue:i?ni(i):void 0}}copyForSheetId(e){const t=Gn(this.sheetId,e,this.baseline),o=Gn(this.sheetId,e,this.keyValue),i=this.getDefinitionWithSpecificRanges(t,o,e);return new Hr(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,e);return new Hr(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,o){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:"scorecard",background:this.background,baseline:e?this.getters.getRangeString(e,o||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,o||this.sheetId):void 0}}getDefinitionForExcel(){}updateRanges(e){const t=qn(this.baseline,e),o=qn(this.keyValue,e);if(this.baseline===t&&this.keyValue===o)return this;const i=this.getDefinitionWithSpecificRanges(t,o);return new Hr(i,this.sheetId,this.getters)}}const $r=new zi;$r.add("bar",{match:e=>"bar"===e,createChart:(e,t,o)=>new wr(e,t,o),getChartRuntime:function(e,t){let o=vr(t,e.dataSets,e.labelRange).formattedValues,i=Cr(t,e.dataSets);e.dataSetsHaveTitle&&i[0]&&o.length>i[0].data.length&&o.shift(),({labels:o,dataSetsValues:i}=pr(o,i)),e.aggregated&&({labels:o,dataSetsValues:i}=mr(o,i));const s=function(e,t,o){const i=er(e.background),s=br(e,t,i,o),n={labels:{fontColor:i}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?n.display=!1:n.position=e.legendPosition,s.options.legend={...s.options?.legend,...n},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:i}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:i,beginAtZero:!0,callback:e=>o?bo(e,o):e?.toLocaleString()||e}}]},e.stacked&&(s.options.scales.xAxes[0].stacked=!0,s.options.scales.yAxes[0].stacked=!0),s}(e,o,Sr(t,e.dataSets)),n=new Jn;for(let{label:e,data:t}of i){const o=n.next(),i={label:e,data:t,borderColor:o,backgroundColor:o};s.data.datasets.push(i)}return{chartJsConfig:s,background:e.background||w}},validateChartDefinition:(e,t)=>wr.validateChartDefinition(e,t),transformDefinition:(e,t)=>wr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>wr.getDefinitionFromContextCreation(e),name:n("Bar"),sequence:10}),$r.add("line",{match:e=>"line"===e,createChart:(e,t,o)=>new Fr(e,t,o),getChartRuntime:function(e,t){const o=Lr(e,t),i=vr(t,e.dataSets,e.labelRange);let s="linear"===o?i.values:i.formattedValues,n=Cr(t,e.dataSets);e.dataSetsHaveTitle&&n[0]&&s.length>n[0].data.length&&s.shift(),({labels:s,dataSetsValues:n}=pr(s,n)),"time"===o&&({labels:s,dataSetsValues:n}=function(e,t){if(0===e.length||e.every((e=>!e)))return{labels:e,dataSetsValues:t};const o=[...e],i=Be(t);for(let e=0;e<o.length;e++)if(!o[e]){o[e]=ft(o,e);for(let t of i)t.data[e]=void 0}return{labels:o,dataSetsValues:i}}(s,n)),e.aggregated&&({labels:s,dataSetsValues:n}=mr(s,n));const r="category"===o,a=Sr(t,e.dataSets),l=function(e,t,o,i){const s=er(e.background),n=br(e,t,s,o,i),r={labels:{fontColor:s,generateLabels(e){const{data:t}=e,o=window.Chart.defaults.global.legend.labels.generateLabels(e);for(const[e,i]of o.entries())i.fillStyle=t.datasets[e].borderColor;return o}}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,n.options.legend={...n.options?.legend,...r},n.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},n.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:s}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:s,beginAtZero:!0,callback:e=>o?bo(e,o):e?.toLocaleString()||e}}]},e.stacked&&(n.options.scales.yAxes[0].stacked=!0),n}(e,s,a,r),c=function(e,t){if(t)return e.getEvaluatedCell({sheetId:t.sheetId,col:t.zone.left,row:t.zone.top}).format}(t,e.labelRange);"time"===o?(l.options.scales.xAxes[0].type="time",l.options.scales.xAxes[0].time=_r(s,c),l.options.scales.xAxes[0].ticks.maxTicksLimit=15):"linear"===o&&(l.options.scales.xAxes[0].type="linear",l.options.scales.xAxes[0].ticks.callback=e=>bo(e,c),l.options.tooltips.callbacks.title=e=>bo(e[0]?.xLabel||"",c));const h=new Jn;for(let[t,{label:i,data:r}]of n.entries()){["linear","time"].includes(o)&&(r=r.map(((e,t)=>({x:s[t]||void 0,y:e}))));const n=h.next();let a=Ut(n);if(e.stacked&&(a.a=ae),e.cumulative){let e=0;r=r.map((t=>isNaN(t)?t:(e+=parseFloat(t),e)))}const c={label:i,data:r,lineTension:0,borderColor:n,backgroundColor:kt(a),pointBackgroundColor:n,fill:!!e.stacked&&Er(t)};l.data.datasets.push(c)}return{chartJsConfig:l,background:e.background||w}},validateChartDefinition:(e,t)=>Fr.validateChartDefinition(e,t),transformDefinition:(e,t)=>Fr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Fr.getDefinitionFromContextCreation(e),name:n("Line"),sequence:20}),$r.add("pie",{match:e=>"pie"===e,createChart:(e,t,o)=>new Ur(e,t,o),getChartRuntime:function(e,t){let o=vr(t,e.dataSets,e.labelRange).formattedValues,i=Cr(t,e.dataSets);e.dataSetsHaveTitle&&i[0]&&o.length>i[0].data.length&&o.shift(),({labels:o,dataSetsValues:i}=pr(o,i)),e.aggregated&&({labels:o,dataSetsValues:i}=mr(o,i));const s=function(e,t,o){const i=er(e.background),s=br(e,t,i,o),n={labels:{fontColor:i}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?n.display=!1:n.position=e.legendPosition,s.options.legend={...s.options?.legend,...n},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,o,Sr(t,e.dataSets)),n=new Jn;for(let{label:e,data:t}of i){const o={label:e,data:t,borderColor:"#FFFFFF",backgroundColor:Vr(n,i)};s.data.datasets.push(o)}return{chartJsConfig:s,background:e.background||w}},validateChartDefinition:(e,t)=>Ur.validateChartDefinition(e,t),transformDefinition:(e,t)=>Ur.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Ur.getDefinitionFromContextCreation(e),name:n("Pie"),sequence:30}),$r.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,o)=>new Hr(e,t,o),getChartRuntime:function(e,t){let o,i,n="",r="";if(e.keyValue){const i={sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top};o=t.getEvaluatedCell(i),n=String(o.value),r=o.formattedValue}const a=e.baseline;if(a){const o={sheetId:e.baseline.sheetId,col:e.baseline.zone.left,row:e.baseline.zone.top};i=t.getEvaluatedCell(o)}const{background:l,fontColor:c}=t.getStyleOfSingleCellChart(e.background,e.keyValue);return{title:s(e.title),keyValue:r||n,baselineDisplay:sr(i,o,e.baselineMode),baselineArrow:rr(i,o,e.baselineMode),baselineColor:nr(i,e.baselineMode,o,e.baselineColorUp,e.baselineColorDown),baselineDescr:e.baselineDescr?s(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)=>Hr.validateChartDefinition(e,t),transformDefinition:(e,t)=>Hr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Hr.getDefinitionFromContextCreation(e),name:n("Scorecard"),sequence:40}),$r.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,o)=>new Ar(e,t,o),getChartRuntime:function(e,t){const o=function(e){const t=br(e,[],er(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),i=e.sectionRule.colors,s=e.sectionRule.lowerInflectionPoint,n=e.sectionRule.upperInflectionPoint,r=Number(s.value),a=Number(n.value),l=Number(e.sectionRule.rangeMin),c=Number(e.sectionRule.rangeMax),h=c-l,d=[];if(""!==s.value){const e="number"===s.type?r:l+h*r/100;d.push({value:We(e,l,c),color:i.lowerColor})}if(""!==n.value){const e="number"===n.type?a:l+h*a/100;d.push({value:We(e,l,c),color:i.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(i.upperColor);const p=e.dataRange,m=h/30;let f=l-m,b=null,v=!1;if(void 0!==p){const e=t.getEvaluatedCell({sheetId:p.sheetId,col:p.zone.left,row:p.zone.top});e.type===ys.number&&(f=We(e.value,l-m,c+m),b=()=>t.getRangeFormattedValues(p)[0],v=!0)}return o.options.valueLabel.display=v,o.options.valueLabel.formatter=b,o.data.datasets.push({data:u,minValue:Number(e.sectionRule.rangeMin),value:f,backgroundColor:g}),{chartJsConfig:o,background:t.getStyleOfSingleCellChart(e.background,p).background}},validateChartDefinition:(e,t)=>Ar.validateChartDefinition(e,t),transformDefinition:(e,t)=>Ar.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Ar.getDefinitionFromContextCreation(e),name:n("Gauge"),sequence:50});const Wr=new zi;Wr.add("line",Ai),Wr.add("bar",Ai),Wr.add("pie",Ai),Wr.add("gauge",Ai),Wr.add("scorecard",ki);const Gr=new zi;Ni`
|
|
348
348
|
.o-chart-container {
|
|
349
349
|
width: 100%;
|
|
350
350
|
height: 100%;
|
|
351
351
|
position: relative;
|
|
352
352
|
}
|
|
353
|
-
`;class qr extends t.Component{static template="o-spreadsheet-ChartFigure";static components={};onDoubleClick(){this.env.model.dispatch("SELECT_FIGURE",{id:this.props.figure.id}),this.env.openSidePanel("ChartPanel")}get chartType(){return this.env.model.getters.getChartType(this.props.figure.id)}get chartComponent(){const e=this.chartType,t=Wr.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}qr.props={figure:Object,onFigureDeleted:Function};class Zr extends t.Component{static template="o-spreadsheet-ImageFigure";static components={};get figureId(){return this.props.figure.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}}function jr(e,t){const o=Be(t),i=e.getSheetViewDimension(),s=i.width,n=i.height;if(o.width>s){const e=s/o.width;o.width=s,o.height=o.height*e}if(o.height>n){const e=n/o.height;o.height=n,o.width=o.width*e}return o}Zr.props={figure:Object,onFigureDeleted:Function};const Yr=new zi;function Xr(e,t){return{id:"copy",name:n("Copy"),sequence:2,description:"Ctrl+C",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("COPY"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function Kr(e,t){return{id:"cut",name:n("Cut"),sequence:3,description:"Ctrl+X",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("CUT"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function Qr(e,t,o){return{id:"delete",name:n("Delete"),sequence:10,execute:()=>{o.model.dispatch("DELETE_FIGURE",{sheetId:o.model.getters.getActiveSheetId(),id:e}),t()}}}Yr.add("chart",{Component:qr,SidePanelComponent:"ChartPanel",menuBuilder:function(e,t,o){return _n([{id:"edit",name:n("Edit"),sequence:1,execute:()=>{o.model.dispatch("SELECT_FIGURE",{id:e}),o.openSidePanel("ChartPanel")}},Xr(e,o),Kr(e,o),Qr(e,t,o)])}}),Yr.add("image",{Component:Zr,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t,o){return _n([Xr(e,o),Kr(e,o),{id:"reset_size",name:n("Reset size"),sequence:4,execute:()=>{const t=o.model.getters.getImageSize(e),{height:i,width:s}=jr(o.model.getters,t);o.model.dispatch("UPDATE_FIGURE",{sheetId:o.model.getters.getActiveSheetId(),id:e,height:i,width:s})}},Qr(e,t,o)])}});const Jr=(new zi).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let o=e.base;"after"===e.position&&o++;for(let i=0;i<e.quantity;i++)t.push(i+o);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],o=[...e.elements].sort(((e,t)=>e-t));for(let i of Qe(o)){const o=0===i[0]?0:i[0]-1,s=0===i[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:i.length,base:o,sheetId:e.sheetId,position:s})}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 Os.values())Jr.contains(e)||Jr.add(e,ea);function ea(e){return[e]}const ta={MergeIsDestructive:n("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:n("You can't merge cells inside of an existing filter.")};function oa(e,t){const o=$r.getAll().find((t=>t.match(e.type)));if(!o)throw new Error("Unknown chart type.");return o.transformDefinition(e,t)}function ia(e,t){let o=e;e.left!==e.right&&(o={...e,left:e.left+1});const i=[ni(o)],n=t.getActiveSheetId(),r=t.getCell({sheetId:n,col:e.left,row:e.top});if(1===Ri(e)&&r?.content)return{type:"scorecard",title:"",background:r.style?.fillColor||void 0,keyValue:ni(e),baselineMode:se,baselineColorUp:ne,baselineColorDown:re};let a="";const l=t.getEvaluatedCellsInZone(n,{...o,bottom:o.top}),c=!!l.find((e=>e.type!==ys.empty&&e.type!==ys.number));if(c){const e=l.filter((e=>e.type!==ys.error&&e.type!==ys.empty)).map((e=>e.formattedValue)),t=e.splice(-1)[0];a=e.join(", "),t&&(a+=(a?" "+s("and")+" ":"")+t)}let h;e.left!==e.right&&(h=ni({...e,right:e.left}));const d=o.right===o.left?"none":"top";return Dr(h?t.getRangeFromSheetXC(n,h):void 0,t)?{title:a,dataSets:i,labelsAsText:!1,stacked:!1,aggregated:!1,cumulative:!1,labelRange:h,type:"line",dataSetsHaveTitle:c,verticalAxisPosition:"left",legendPosition:d}:{title:a,dataSets:i,labelRange:h,type:"bar",stacked:!1,aggregated:!1,dataSetsHaveTitle:c,verticalAxisPosition:"left",legendPosition:d}}const sa=[ys.number,ys.error,ys.text,ys.boolean];function na(e,t,o,i,s){let r=Ns.Success,a=i.right>i.left;if(e.model.getters.doesIntersectMerge(t,i)){let o;a=!1;for(let s=i.top;s<=i.bottom;s++){o=[];for(let n=i.left;n<=i.right;n++){let i=e.model.getters.getMerge({sheetId:t,col:n,row:s});i&&!o.includes(i.id.toString())&&o.push(i.id.toString())}if(o.length>=2){a=!0;break}}}const{col:l,row:c}=o;if(a)r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s});else{const o=e.model.getters.getContiguousZone(t,i);ui(o,i)?r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s}):e.askConfirmation(n("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?"),(()=>{i=o,r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s})}),(()=>{r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s})}))}if(r.isCancelledBecause(64)){const{col:t,row:s}=o;e.model.selection.selectZone({cell:{col:t,row:s},zone:i}),e.raiseError(n("Cannot sort. To sort, select only cells or only merges that have the same size."))}}function ra(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause(19)&&e.raiseError(n("This operation is not allowed with multiple selections."))}const aa={filterOverlap:n("You cannot create overlapping filters."),nonContinuousTargets:n("A filter can only be created on a continuous selection."),mergeInFilter:n("You can't create a filter over a range that contains a merge.")};function la(e,t,o){const i=e.model.dispatch("CREATE_FILTER_TABLE",{target:o,sheetId:t});i.isCancelledBecause(79)?e.raiseError(aa.filterOverlap):i.isCancelledBecause(81)?e.raiseError(aa.mergeInFilter):i.isCancelledBecause(82)&&e.raiseError(aa.nonContinuousTargets)}const ca={wrongPasteSelection:n("This operation is not allowed with multiple selections."),willRemoveExistingMerge:n("This operation is not possible due to a merge. Please remove the merges first than try again."),wrongFigurePasteOption:n("Cannot do a special paste of a figure."),frozenPaneOverlap:n("Cannot paste merged cells over a frozen pane.")};function ha(e,t){t.isSuccessful||(t.reasons.includes(20)?e.raiseError(ca.wrongPasteSelection):t.reasons.includes(2)?e.raiseError(ca.willRemoveExistingMerge):t.reasons.includes(22)?e.raiseError(ca.wrongFigurePasteOption):t.reasons.includes(76)&&e.raiseError(ca.frozenPaneOverlap))}function da(e,t,o){const i=e.model.dispatch("PASTE",{target:t,pasteOption:o});ha(e,i)}function ua(e,t,o){const i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,text:o});ha(e,i)}function ga(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 pa(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 ma(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function fa(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const ba=async e=>va(e,"onlyValue");async function va(e,t){const o=e.model.getters.getClipboardTextContent(),i=await e.clipboard.readText();switch(i.status){case"ok":const s=e.model.getters.getSelectedZones();i&&i.content!==o?ua(e,s,i.content):da(e,s,t);break;case"notImplemented":e.raiseError(n("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(n("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const Sa=(e,t)=>{const o=t.model.getters.getActiveSheetId(),i=t.model.getters.getElementsFromSelection(e),s=t.model.getters.checkElementsIncludeAllVisibleHeaders(o,e,i),n=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(o,e,i);return!s&&!n},Ca=e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Tt([...t]),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.top,i=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",base:o,quantity:i,dimension:"ROW"})},Ea=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Tt([...t]),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.left,i=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",dimension:"COL",base:o,quantity:i})},wa=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Rt([...t]),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.right,i=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",dimension:"COL",base:o,quantity:i})};const xa=async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),o=e.model.uuidGenerator.uuidv4(),i=await async function(e){try{return await e.imageProvider.requestImage()}catch{return void e.raiseError(n("An unexpected error occurred during the image transfer"))}}(e);if(!i)throw new Error("No image provider was given to the environment");const s=jr(e.model.getters,i.size),r=function(e,t){const{x:o,y:i}=e.getMainViewportCoordinates(),{scrollX:s,scrollY:n}=e.getActiveSheetScrollInfo(),r=e.getSheetViewDimension(),a=e.getVisibleRect(e.getActiveMainViewport()),l=Math.min(a.width,r.width-o),c=Math.min(a.height,r.height-i);return{x:o+s+Math.max(0,(l-t.width)/2),y:i+n+Math.max(0,(c-t.height)/2)}}(e.model.getters,s);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:o,position:r,size:s,definition:i})}},ya=e=>ma(e,"0.00%"),Ia=e=>{let{col:t,row:o}=e.model.getters.getActivePosition();e.model.dispatch("OPEN_CELL_POPOVER",{col:t,row:o,popoverType:"LinkEditor"})},Ra=e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,o)},Ta=e=>1===e.model.getters.getSelectedZones().length,Aa=(e,t)=>{if(!Ta(e))return!1;const o="COL"===t?e.model.getters.getActiveCols():e.model.getters.getActiveRows(),i="COL"===t?e.model.getters.getActiveRows():e.model.getters.getActiveCols(),s=e.model.getters.getActiveSheetId(),n=ui(e.model.getters.getSelectedZone(),e.model.getters.getSheetZone(s));return function(e){const t=Array.from(e).sort(((e,t)=>e-t));for(let e=1;e<t.length;e++)if(t[e]-t[e-1]!=1)return!1;return!0}(o)&&(0===i.size||n)},Oa={name:n("Undo"),description:"Ctrl+Z",execute:e=>e.model.dispatch("REQUEST_UNDO"),isEnabled:e=>e.model.getters.canUndo(),icon:"o-spreadsheet-Icon.UNDO"},Ma={name:n("Redo"),description:"Ctrl+Y",execute:e=>e.model.dispatch("REQUEST_REDO"),isEnabled:e=>e.model.getters.canRedo(),icon:"o-spreadsheet-Icon.REDO"},Na={name:n("Copy"),description:"Ctrl+C",isReadonlyAllowed:!0,execute:async e=>{e.model.dispatch("COPY"),await e.clipboard.write(e.model.getters.getClipboardContent())},icon:"o-spreadsheet-Icon.COPY"},_a={name:n("Cut"),description:"Ctrl+X",execute:async e=>{ra(e),await e.clipboard.write(e.model.getters.getClipboardContent())},icon:"o-spreadsheet-Icon.CUT"},Fa={name:n("Paste"),description:"Ctrl+V",execute:async e=>va(e),icon:"o-spreadsheet-Icon.PASTE"},Da={name:n("Paste special"),isVisible:e=>!e.model.getters.isCutOperation(),icon:"o-spreadsheet-Icon.PASTE"},La={name:n("Paste value only"),description:"Ctrl+Shift+V",execute:ba},ka={name:n("Paste format only"),execute:e=>da(e,e.model.getters.getSelectedZones(),"onlyFormat")},Pa={name:n("Find and replace"),description:"Ctrl+H",isReadonlyAllowed:!0,execute:e=>{e.openSidePanel("FindAndReplace",{})},icon:"o-spreadsheet-Icon.FIND_AND_REPLACE"},Ua={name:n("Delete values"),execute:e=>e.model.dispatch("DELETE_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},Va={name:e=>{if(e.model.getters.getSelectedZones().length>1)return n("Delete rows");let t,o;const i=e.model.getters.getActiveRows();if(0!==i.size)t=Tt([...i]),o=Rt([...i]);else{const i=e.model.getters.getSelectedZones()[0];t=i.top,o=i.bottom}return t===o?n("Delete row %s",(t+1).toString()):n("Delete rows %s - %s",(t+1).toString(),(o+1).toString())},execute:e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){const o=e.model.getters.getSelectedZones()[0];for(let e=o.top;e<=o.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>Sa("ROW",e)},za={...Va,isVisible:Ta},Ba={name:e=>{if(e.model.getters.getSelectedZones().length>1)return n("Clear rows");let t,o;const i=e.model.getters.getActiveRows();if(0!==i.size)t=Tt([...i]),o=Rt([...i]);else{const i=e.model.getters.getSelectedZones()[0];t=i.top,o=i.bottom}return t===o?n("Clear row %s",(t+1).toString()):n("Clear rows %s - %s",(t+1).toString(),(o+1).toString())},execute:e=>{const t=e.model.getters.getActiveSheetId(),o=[...e.model.getters.getActiveRows()].map((o=>e.model.getters.getRowsZone(t,o,o)));e.model.dispatch("DELETE_CONTENT",{target:o,sheetId:e.model.getters.getActiveSheetId()})}},Ha={name:e=>{if(e.model.getters.getSelectedZones().length>1)return n("Delete columns");let t,o;const i=e.model.getters.getActiveCols();if(0!==i.size)t=Tt([...i]),o=Rt([...i]);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?n("Delete column %s",Bt(t)):n("Delete columns %s - %s",Bt(t),Bt(o))},execute:e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){const o=e.model.getters.getSelectedZones()[0];for(let e=o.left;e<=o.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>Sa("COL",e)},$a={...Ha,isVisible:Ta},Wa={name:e=>{if(e.model.getters.getSelectedZones().length>1)return n("Clear columns");let t,o;const i=e.model.getters.getActiveCols();if(0!==i.size)t=Tt([...i]),o=Rt([...i]);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?n("Clear column %s",Bt(t)):n("Clear columns %s - %s",Bt(t),Bt(o))},execute:e=>{const t=e.model.getters.getActiveSheetId(),o=[...e.model.getters.getActiveCols()].map((o=>e.model.getters.getColsZone(t,o,o)));e.model.dispatch("DELETE_CONTENT",{target:o,sheetId:e.model.getters.getActiveSheetId()})}},Ga={name:n("Delete cells"),isVisible:Ta},qa={name:n("Delete cell and shift up"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});ha(e,o)}},Za={name:n("Delete cell and shift left"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});ha(e,o)}},ja={name:n("Merge cells"),isEnabled:e=>!Ya(e),isActive:e=>Xa(e),execute:e=>function(e){if(Ya(e))return;const t=e.model.getters.getSelectedZones(),o=[t[t.length-1]],i=e.model.getters.getActiveSheetId();Xa(e)?e.model.dispatch("REMOVE_MERGE",{sheetId:i,target:o}):function(e,t,o){const i=e.model.dispatch("ADD_MERGE",{sheetId:t,target:o});i.isCancelledBecause(81)?e.raiseError(ta.MergeInFilter):i.isCancelledBecause(3)&&e.askConfirmation(ta.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:o,force:!0})}))}(e,i,o)}(e),icon:"o-spreadsheet-Icon.MERGE_CELL"};function Ya(e){const t=e.model.getters.getSelectedZones(),{top:o,left:i,right:s,bottom:n}=e.model.getters.getSelectedZone(),{sheetId:r}=e.model.getters.getActivePosition(),{xSplit:a,ySplit:l}=e.model.getters.getPaneDivisions(r);return t.length>1||o===n&&i===s||i<a&&a<=s||o<l&&l<=n}function Xa(e){if(!Ya(e)){const t=e.model.getters.getSelectedZones(),{col:o,row:i,sheetId:s}=e.model.getters.getActivePosition(),n=e.model.getters.expandZone(s,yi({col:o,row:i}));return ui(t[0],n)}return!1}var Ka=Object.freeze({__proto__:null,undo:Oa,redo:Ma,copy:Na,cut:_a,paste:Fa,pasteSpecial:Da,pasteSpecialValue:La,pasteSpecialFormat:ka,findAndReplace:Pa,deleteValues:Ua,deleteRows:Va,deleteRow:za,clearRows:Ba,deleteCols:Ha,deleteCol:$a,clearCols:Wa,deleteCells:Ga,deleteCellShiftUp:qa,deleteCellShiftLeft:Za,mergeCells:ja});const Qa=/(.*?)\((.*?)\)(.*)/,Ja=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function el(e,t=""){return function(e,t){let o=e.match(Qa),i=o[1].trim();if(!i)throw new Error(`Function argument definition is missing a name: '${e}'.`);let s,n=[],r=!1,a=!1,l=!1;for(let e of o[2].split(",")){const t=e.trim().toUpperCase();let o=Ja.find((e=>t===e));o?n.push(o):"RANGE<ANY>"===t?n.push("RANGE"):"OPTIONAL"===t?r=!0:"REPEATING"===t?a=!0:"LAZY"===t?l=!0:t.startsWith("DEFAULT=")&&(s=e.trim().slice(8))}const c={name:i,description:t,type:n};r&&(c.optional=!0);a&&(c.repeating=!0);l&&(c.lazy=!0);void 0!==s&&(c.default=!0,c.defaultValue=s);return c}(e,t)}function tl(e){let t=0,o=0,i=0;for(let s of e.args)t++,s.optional||s.repeating||s.default||o++,s.repeating&&i++;const s=e;return s.minArgRequired=o,s.maxArgPossible=i?1/0:t,s.nbrArgRepeating=i,s.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const o=e-t;return e=>{if(e<=o)return e;return o+((e-o)%t||t)}}(t,i),s.hidden=e.hidden||!1,s}const ol={description:n("Apply a large number format"),args:[el("value (number)",n("The number.")),el("unit (string, optional)",n("The formatting unit. Use 'k', 'm', or 'b' to force the unit"))],returns:["NUMBER"],computeFormat:(e,t)=>{const o=Math.abs(Qi(e.value)),i=e.format;if(void 0!==t){const e=t?.value;switch(e){case"k":return Mo(i,1e3,"k");case"m":return Mo(i,1e6,"m");case"b":return Mo(i,1e9,"b");default:throw new Error(n("The formatting unit should be 'k', 'm' or 'b'."))}}return o<1e5?Mo(i,0,""):o<1e8?Mo(i,1e3,"k"):o<1e11?Mo(i,1e6,"m"):Mo(i,1e9,"b")},compute:function(e){return Qi(e)}};var il=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:ol});const sl=/^-?[a-z0-9]+$/i,nl={description:n("Absolute value of a number."),args:[el("value (number)",n("The number of which to return the absolute value."))],returns:["NUMBER"],compute:function(e){return Math.abs(Qi(e))},isExported:!0},rl={description:n("Inverse cosine of a value, in radians."),args:[el("value (number)",n("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>Math.abs(t)<=1),n("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},al={description:n("Inverse hyperbolic cosine of a number."),args:[el("value (number)",n("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=Qi(e);return Xi((()=>t>=1),n("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},ll={description:n("Inverse cotangent of a value."),args:[el("value (number)",n("The value for which to calculate the inverse cotangent."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},cl={description:n("Inverse hyperbolic cotangent of a value."),args:[el("value (number)",n("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=Qi(e);return Xi((()=>Math.abs(t)>1),n("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},hl={description:n("Inverse sine of a value, in radians."),args:[el("value (number)",n("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>Math.abs(t)<=1),n("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},dl={description:n("Inverse hyperbolic sine of a number."),args:[el("value (number)",n("The value for which to calculate the inverse hyperbolic sine."))],returns:["NUMBER"],compute:function(e){return Math.asinh(Qi(e))},isExported:!0},ul={description:n("Inverse tangent of a value, in radians."),args:[el("value (number)",n("The value for which to calculate the inverse tangent."))],returns:["NUMBER"],compute:function(e){return Math.atan(Qi(e))},isExported:!0},gl={description:n("Angle from the X axis to a point (x,y), in radians."),args:[el("x (number)",n("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),el("y (number)",n("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 o=Qi(e),i=Qi(t);return Xi((()=>0!==o||0!==i),n("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(i,o)},isExported:!0},pl={description:n("Inverse hyperbolic tangent of a number."),args:[el("value (number)",n("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>Math.abs(t)<1),n("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},ml={description:n("Rounds number up to nearest multiple of factor."),args:[el("value (number)",n("The value to round up to the nearest integer multiple of factor.")),el("factor (number, default=1)",n("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){const o=Qi(e),i=Qi(t);return Xi((()=>i>=0||o<=0),n("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),o.toString())),i?Math.ceil(o/i)*i:0},isExported:!0},fl={description:n("Rounds number up to nearest multiple of factor."),args:[el("number (number)",n("The value to round up to the nearest integer multiple of significance.")),el("significance (number, default=1)",n("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),el("mode (number, default=0)",n("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=>e?.format,compute:function(e,t=1,o=0){let i=Qi(t);if(0===i)return 0;const s=Qi(e);if(i=Math.abs(i),s>=0)return Math.ceil(s/i)*i;return 0===Qi(o)?-Math.floor(Math.abs(s)/i)*i:-Math.ceil(Math.abs(s)/i)*i},isExported:!0},bl={description:n("Rounds number up to nearest multiple of factor."),args:[el("number (number)",n("The value to round up to the nearest integer multiple of significance.")),el("significance (number, default=1)",n("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){return fl.compute(e,t,0)},isExported:!0},vl={description:n("Cosine of an angle provided in radians."),args:[el("angle (number)",n("The angle to find the cosine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.cos(Qi(e))},isExported:!0},Sl={description:n("Hyperbolic cosine of any real number."),args:[el("value (number)",n("Any real value to calculate the hyperbolic cosine of."))],returns:["NUMBER"],compute:function(e){return Math.cosh(Qi(e))},isExported:!0},Cl={description:n("Cotangent of an angle provided in radians."),args:[el("angle (number)",n("The angle to find the cotangent of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},El={description:n("Hyperbolic cotangent of any real number."),args:[el("value (number)",n("Any real value to calculate the hyperbolic cotangent of."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},wl={description:n("Number of empty values."),args:[el("value1 (any, range)",n("The first value or range in which to count the number of blanks.")),el("value2 (any, range, repeating)",n("Additional values or ranges in which to count the number of blanks."))],returns:["NUMBER"],compute:function(...e){return us(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},xl={description:n("A conditional count across a range."),args:[el("range (range)",n("The range that is tested against criterion.")),el("criterion (string)",n("The pattern or test to apply to range."))],returns:["NUMBER"],compute:function(...e){let t=0;return vs(e,((e,o)=>{t+=1})),t},isExported:!0},yl={description:n("Count values depending on multiple criteria."),args:[el("criteria_range1 (range)",n("The range to check against criterion1.")),el("criterion1 (string)",n("The pattern or test to apply to criteria_range1.")),el("criteria_range2 (any, range, repeating)",n("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.")),el("criterion2 (string, repeating)",n("Additional criteria to check."))],returns:["NUMBER"],compute:function(...e){let t=0;return vs(e,((e,o)=>{t+=1})),t},isExported:!0};function Il(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const Rl={description:n("Counts number of unique values in a range."),args:[el("value1 (any, range)",n("The first value or range to consider for uniqueness.")),el("value2 (any, range, repeating)",n("Additional values or ranges to consider for uniqueness."))],returns:["NUMBER"],compute:function(...e){return us(e,((e,t)=>Il(t)?e.add(t):e),new Set).size}},Tl={description:n("Counts number of unique values in a range, filtered by a set of criteria."),args:[el("range (range)",n("The range of cells from which the number of unique values will be counted.")),el("criteria_range1 (range)",n("The range of cells over which to evaluate criterion1.")),el("criterion1 (string)",n("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),el("criteria_range2 (any, range, repeating)",n("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.")),el("criterion2 (string, repeating)",n("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=new Set;return vs(t,((t,i)=>{const s=e[t][i];Il(s)&&o.add(s)})),o.size}},Al={description:n("Cosecant of an angle provided in radians."),args:[el("angle (number)",n("The angle to find the cosecant of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},Ol={description:n("Hyperbolic cosecant of any real number."),args:[el("value (number)",n("Any real value to calculate the hyperbolic cosecant of."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},Ml={description:n("Converts from another base to decimal."),args:[el("value (string)",n("The number to convert.")),el(",base (number)",n("The base to convert the value from."))],returns:["NUMBER"],compute:function(e,t){let o=Qi(t);o=Math.floor(o),Xi((()=>2<=o&&o<=36),n("The base (%s) must be between 2 and 36 inclusive.",o.toString()));const i=os(e);if(""===i)return 0;Xi((()=>!!sl.test(i)),n("The value (%s) must be a valid base %s representation.",i,o.toString()));const s=parseInt(i,o);return Xi((()=>!isNaN(s)),n("The value (%s) must be a valid base %s representation.",i,o.toString())),s},isExported:!0},Nl={description:n("Converts an angle value in radians to degrees."),args:[el("angle (number)",n("The angle to convert from radians to degrees."))],returns:["NUMBER"],compute:function(e){return 180*Qi(e)/Math.PI},isExported:!0},_l={description:n("Euler's number, e (~2.718) raised to a power."),args:[el("value (number)",n("The exponent to raise e."))],returns:["NUMBER"],compute:function(e){return Math.exp(Qi(e))},isExported:!0},Fl={description:n("Rounds number down to nearest multiple of factor."),args:[el("value (number)",n("The value to round down to the nearest integer multiple of factor.")),el("factor (number, default=1)",n("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){const o=Qi(e),i=Qi(t);return Xi((()=>i>=0||o<=0),n("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),o.toString())),i?Math.floor(o/i)*i:0},isExported:!0},Dl={description:n("Rounds number down to nearest multiple of factor."),args:[el("number (number)",n("The value to round down to the nearest integer multiple of significance.")),el("significance (number, default=1)",n("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),el("mode (number, default=0)",n("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=>e?.format,compute:function(e,t=1,o=0){let i=Qi(t);if(0===i)return 0;const s=Qi(e);if(i=Math.abs(i),s>=0)return Math.floor(s/i)*i;return 0===Qi(o)?-Math.ceil(Math.abs(s)/i)*i:-Math.floor(Math.abs(s)/i)*i},isExported:!0},Ll={description:n("Rounds number down to nearest multiple of factor."),args:[el("number (number)",n("The value to round down to the nearest integer multiple of significance.")),el("significance (number, default=1)",n("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){return Dl.compute(e,t,0)},isExported:!0},kl={description:n("Whether the provided value is even."),args:[el("value (number)",n("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Ji(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},Pl={description:n("Rounds number up to nearest multiple of factor."),args:[el("number (number)",n("The value to round up to the nearest integer multiple of significance.")),el("significance (number, default=1)",n("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){return fl.compute(e,t,0)},isExported:!0},Ul={description:n("Whether the provided value is even."),args:[el("value (number)",n("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Ji(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},Vl={description:n("The logarithm of a number, base e (euler's number)."),args:[el("value (number)",n("The value for which to calculate the logarithm, base e."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>t>0),n("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},zl={description:n("Modulo (remainder) operator."),args:[el("dividend (number)",n("The number to be divided to find the remainder.")),el("divisor (number)",n("The number to divide by."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){const o=Qi(t);Xi((()=>0!==o),n("The divisor must be different from 0."));const i=Qi(e)%o;return i>0&&o<0||i<0&&o>0?i+o:i},isExported:!0},Bl={description:n("Rounds a number up to the nearest odd integer."),args:[el("value (number)",n("The value to round to the next greatest odd number."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e){const t=Qi(e);let o=Math.ceil(Math.abs(t));return o=1&o?o:o+1,t<0?-o:o},isExported:!0},Hl={description:n("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},$l={description:n("A number raised to a power."),args:[el("base (number)",n("The number to raise to the exponent power.")),el("exponent (number)",n("The exponent to raise base to."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){const o=Qi(e),i=Qi(t);return Xi((()=>o>=0||Number.isInteger(i)),n("The exponent (%s) must be an integer when the base is negative.",i.toString())),Math.pow(o,i)},isExported:!0},Wl={description:n("Result of multiplying a series of numbers together."),args:[el("factor1 (number, range<number>)",n("The first number or range to calculate for the product.")),el("factor2 (number, range<number>, repeating)",n("More numbers or ranges to calculate for the product."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=0,o=1;for(let i of e)if(Array.isArray(i))for(let e of i)for(let i of e)"number"==typeof i&&(o*=i,t+=1);else null!=i&&(o*=Ji(i),t+=1);return 0===t?0:o},isExported:!0},Gl={description:n("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},ql={description:n("Random integer between two values, inclusive."),args:[el("low (number)",n("The low end of the random range.")),el("high (number)",n("The high end of the random range."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){let o=Qi(e);Number.isInteger(o)||(o=Math.ceil(o));let i=Qi(t);return Number.isInteger(i)||(i=Math.floor(i)),Xi((()=>o<=i),n("The high (%s) must be greater than or equal to the low (%s).",i.toString(),o.toString())),o+Math.ceil((i-o+1)*Math.random())-1},isExported:!0},Zl={description:n("Rounds a number according to standard rules."),args:[el("value (number)",n("The value to round to places number of places.")),el("places (number, default=0)",n("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Qi(e);let i=Qi(t);const s=Math.abs(o);let n;return 0===i?n=Math.round(s):(Number.isInteger(i)||(i=Math.trunc(i)),n=Math.round(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?n:-n},isExported:!0},jl={description:n("Rounds down a number."),args:[el("value (number)",n("The value to round to places number of places, always rounding down.")),el("places (number, default=0)",n("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Qi(e);let i=Qi(t);const s=Math.abs(o);let n;return 0===i?n=Math.floor(s):(Number.isInteger(i)||(i=Math.trunc(i)),n=Math.floor(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?n:-n},isExported:!0},Yl={description:n("Rounds up a number."),args:[el("value (number)",n("The value to round to places number of places, always rounding up.")),el("places (number, default=0)",n("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Qi(e);let i=Qi(t);const s=Math.abs(o);let n;return 0===i?n=Math.ceil(s):(Number.isInteger(i)||(i=Math.trunc(i)),n=Math.ceil(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?n:-n},isExported:!0},Xl={description:n("Secant of an angle provided in radians."),args:[el("angle (number)",n("The angle to find the secant of, in radians."))],returns:["NUMBER"],compute:function(e){return 1/Math.cos(Qi(e))},isExported:!0},Kl={description:n("Hyperbolic secant of any real number."),args:[el("value (number)",n("Any real value to calculate the hyperbolic secant of."))],returns:["NUMBER"],compute:function(e){return 1/Math.cosh(Qi(e))},isExported:!0},Ql={description:n("Sine of an angle provided in radians."),args:[el("angle (number)",n("The angle to find the sine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.sin(Qi(e))},isExported:!0},Jl={description:n("Hyperbolic sine of any real number."),args:[el("value (number)",n("Any real value to calculate the hyperbolic sine of."))],returns:["NUMBER"],compute:function(e){return Math.sinh(Qi(e))},isExported:!0},ec={description:n("Positive square root of a positive number."),args:[el("value (number)",n("The number for which to calculate the positive square root."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e){const t=Qi(e);return Xi((()=>t>=0),n("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},tc={description:n("Sum of a series of numbers and/or cells."),args:[el("value1 (number, range<number>)",n("The first number or range to add together.")),el("value2 (number, range<number>, repeating)",n("Additional numbers or ranges to add to value1."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){return gs(e,((e,t)=>e+t),0)},isExported:!0},oc={description:n("A conditional sum across a range."),args:[el("criteria_range (range)",n("The range which is tested against criterion.")),el("criterion (string)",n("The pattern or test to apply to range.")),el("sum_range (range, default=criteria_range)",n("The range to be summed, if different from range."))],returns:["NUMBER"],compute:function(e,t,o){void 0===o&&(o=e);let i=0;return vs([e,t],((e,t)=>{const s=o[e][t];"number"==typeof s&&(i+=s)})),i},isExported:!0},ic={description:n("Sums a range depending on multiple criteria."),args:[el("sum_range (range)",n("The range to sum.")),el("criteria_range1 (range)",n("The range to check against criterion1.")),el("criterion1 (string)",n("The pattern or test to apply to criteria_range1.")),el("criteria_range2 (any, range, repeating)",n("Additional ranges to check.")),el("criterion2 (string, repeating)",n("Additional criteria to check."))],returns:["NUMBER"],compute:function(e,...t){let o=0;return vs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o+=s)})),o},isExported:!0},sc={description:n("Tangent of an angle provided in radians."),args:[el("angle (number)",n("The angle to find the tangent of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.tan(Qi(e))},isExported:!0},nc={description:n("Hyperbolic tangent of any real number."),args:[el("value (number)",n("Any real value to calculate the hyperbolic tangent of."))],returns:["NUMBER"],compute:function(e){return Math.tanh(Qi(e))},isExported:!0},rc={description:n("Truncates a number."),args:[el("value (number)",n("The value to be truncated.")),el("places (number, default=0)",n("The number of significant digits to the right of the decimal point to retain."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Qi(e);let i=Qi(t);return 0===i?Math.trunc(o):(Number.isInteger(i)||(i=Math.trunc(i)),Math.trunc(o*Math.pow(10,i))/Math.pow(10,i))},isExported:!0};var ac=Object.freeze({__proto__:null,ABS:nl,ACOS:rl,ACOSH:al,ACOT:ll,ACOTH:cl,ASIN:hl,ASINH:dl,ATAN:ul,ATAN2:gl,ATANH:pl,CEILING:ml,CEILING_MATH:fl,CEILING_PRECISE:bl,COS:vl,COSH:Sl,COT:Cl,COTH:El,COUNTBLANK:wl,COUNTIF:xl,COUNTIFS:yl,COUNTUNIQUE:Rl,COUNTUNIQUEIFS:Tl,CSC:Al,CSCH:Ol,DECIMAL:Ml,DEGREES:Nl,EXP:_l,FLOOR:Fl,FLOOR_MATH:Dl,FLOOR_PRECISE:Ll,ISEVEN:kl,ISO_CEILING:Pl,ISODD:Ul,LN:Vl,MOD:zl,ODD:Bl,PI:Hl,POWER:$l,PRODUCT:Wl,RAND:Gl,RANDBETWEEN:ql,ROUND:Zl,ROUNDDOWN:jl,ROUNDUP:Yl,SEC:Xl,SECH:Kl,SIN:Ql,SINH:Jl,SQRT:ec,SUM:tc,SUMIF:oc,SUMIFS:ic,TAN:sc,TANH:nc,TRUNC:rc});function lc(e,t,o){let i=[],s=[],r=0,a=0;cs([e],(e=>{i.push(e),r+=1})),cs([t],(e=>{s.push(e),a+=1})),Xi((()=>r===a),n("[[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=i[e],o=s[e];"number"==typeof t&&"number"==typeof o&&(l+=1,c+=t,h+=o)}Xi((()=>0!==l&&(!o||1!==l)),n("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=i[e],o=s[e];"number"==typeof t&&"number"==typeof o&&(g+=(t-d)*(o-u))}return g/(l-(o?1:0))}function cc(e,t,o){let i=0,s=0;const r=o?ps:gs;s=r(e,((e,t)=>(i+=1,e+t)),0),Xi((()=>0!==i&&(!t||1!==i)),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const a=s/i;return r(e,((e,t)=>e+Math.pow(t-a,2)),0)/(i-(t?1:0))}function hc(e,t,o){const i=Qi(t);Xi((()=>o?0<=i&&i<=1:0<i&&i<1),n("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let s,r=[],a=0;return cs(e,(e=>{"number"==typeof e&&(s=Es(r,e,"nextSmaller","asc",r.length,((e,t)=>e[t])),r.splice(s+1,0,e),a++)})),Xi((()=>0!==a),n("[[FUNCTION_NAME]] has no valid input data.")),o||Xi((()=>1/(a+1)<=i&&i<=a/(a+1)),n("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),ao(r,i,o)}const dc={description:n("Average magnitude of deviations from mean."),args:[el("value1 (number, range<number>)",n("The first value or range of the sample.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){let t=0;const o=gs(e,((e,o)=>(t+=1,e+o)),0);Xi((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const i=o/t;return gs(e,((e,t)=>e+Math.abs(i-t)),0)/t},isExported:!0},uc={description:n("Numerical average value in a dataset, ignoring text."),args:[el("value1 (number, range<number>)",n("The first value or range to consider when calculating the average value.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=0;const o=gs(e,((e,o)=>(t+=1,e+o)),0);return Xi((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},gc=n("[[FUNCTION_NAME]] has mismatched range sizes."),pc=n("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),mc={description:n("Weighted average."),args:[el("values (number, range<number>)",n("Values to average.")),el("weights (number, range<number>)",n("Weights for each corresponding value.")),el("additional_values (number, range<number>, repeating)",n("Additional values to average.")),el("additional_weights (number, range<number>, repeating)",n("Additional weights."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t,o,i=0,s=0;Xi((()=>e.length%2==0),n("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let r=0;r<e.length-1;r+=2)if(t=e[r],o=e[r+1],Array.isArray(t)){Xi((()=>Array.isArray(o)),gc);let e=t.length,r=t[0].length;Xi((()=>e===o.length&&r===o[0].length),gc);for(let a=0;a<e;a++)for(let e=0;e<r;e++){let r=t[a][e],l=o[a][e],c="number"==typeof r,h="number"==typeof l;Xi((()=>c===h),n("[[FUNCTION_NAME]] expects number values.")),h&&(Xi((()=>l>=0),pc),i+=r*l,s+=l)}}else o=Qi(o),t=Qi(t),Xi((()=>o>=0),pc),i+=t*o,s+=o;return Xi((()=>0!==s),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/s}},fc={description:n("Numerical average value in a dataset."),args:[el("value1 (number, range<number>)",n("The first value or range to consider when calculating the average value.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=0;const o=ps(e,((e,o)=>(t+=1,e+o)),0);return Xi((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},bc={description:n("Average of values depending on criteria."),args:[el("criteria_range (range)",n("The range to check against criterion.")),el("criterion (string)",n("The pattern or test to apply to criteria_range.")),el("average_range (range, default=criteria_range)",n("The range to average. If not included, criteria_range is used for the average instead."))],returns:["NUMBER"],compute:function(e,t,o){null==o&&(o=e);let i=0,s=0;return vs([e,t],((t,n)=>{const r=(o||e)[t][n];"number"==typeof r&&(i+=1,s+=r)})),Xi((()=>0!==i),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/i},isExported:!0},vc={description:n("Average of values depending on multiple criteria."),args:[el("average_range (range)",n("The range to average.")),el("criteria_range1 (range)",n("The range to check against criterion1.")),el("criterion1 (string)",n("The pattern or test to apply to criteria_range1.")),el("criteria_range2 (any, range, repeating)",n("Additional criteria_range and criterion to check.")),el("criterion2 (string, repeating)",n("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=0,i=0;return vs(t,((t,s)=>{const n=e[t][s];"number"==typeof n&&(o+=1,i+=n)})),Xi((()=>0!==o),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/o},isExported:!0},Sc={description:n("The number of numeric values in dataset."),args:[el("value1 (number, range<number>)",n("The first value or range to consider when counting.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){let t=0;for(let o of e)if(Array.isArray(o))for(let e of o)for(let o of e)"number"==typeof o&&(t+=1);else("string"!=typeof o||so(o)||Te(o))&&(t+=1);return t},isExported:!0},Cc={description:n("The number of values in a dataset."),args:[el("value1 (any, range)",n("The first value or range to consider when counting.")),el("value2 (any, range, repeating)",n("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){return us(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},Ec={description:n("The covariance of a dataset."),args:[el("data_y (any, range)",n("The range representing the array or matrix of dependent data.")),el("data_x (any, range)",n("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return lc(e,t,!1)},isExported:!0},wc={description:n("The covariance of a dataset."),args:[el("data_y (any, range)",n("The range representing the array or matrix of dependent data.")),el("data_x (any, range)",n("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return lc(e,t,!1)},isExported:!0},xc={description:n("The sample covariance of a dataset."),args:[el("data_y (any, range)",n("The range representing the array or matrix of dependent data.")),el("data_x (any, range)",n("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return lc(e,t,!0)},isExported:!0},yc={description:n("Nth largest element from a data set."),args:[el("data (any, range)",n("Array or range containing the dataset to consider.")),el("n (number)",n("The rank from largest to smallest of the element to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){const o=Math.trunc(Qi(t));let i,s=[],r=0;cs([e],(e=>{"number"==typeof e&&(i=Es(s,e,"nextSmaller","asc",s.length,((e,t)=>e[t])),s.splice(i+1,0,e),r++,r>o&&(s.shift(),r--))}));const a=s.shift();return Xi((()=>void 0!==a),n("[[FUNCTION_NAME]] has no valid input data.")),Xi((()=>r>=o),n("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},Ic={description:n("Maximum value in a numeric dataset."),args:[el("value1 (number, range<number>)",n("The first value or range to consider when calculating the maximum value.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=gs(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},Rc={description:n("Maximum numeric value in a dataset."),args:[el("value1 (any, range)",n("The first value or range to consider when calculating the maximum value.")),el("value2 (any, range, repeating)",n("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=ps(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},Tc={description:n("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:[el("range (range)",n("The range of cells from which the maximum will be determined.")),el("criteria_range1 (range)",n("The range of cells over which to evaluate criterion1.")),el("criterion1 (string)",n("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),el("criteria_range2 (any, range, repeating)",n("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.")),el("criterion2 (string, repeating)",n("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=-1/0;return vs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o=o<s?s:o)})),o===-1/0?0:o},isExported:!0},Ac={description:n("Median value in a numeric dataset."),args:[el("value1 (any, range)",n("The first value or range to consider when calculating the median value.")),el("value2 (any, range, repeating)",n("Additional values or ranges to consider when calculating the median value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=[];return hs(e,(e=>{t.push(e)})),hc(t,.5,!0)},isExported:!0},Oc={description:n("Minimum value in a numeric dataset."),args:[el("value1 (number, range<number>)",n("The first value or range to consider when calculating the minimum value.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=gs(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Mc={description:n("Minimum numeric value in a dataset."),args:[el("value1 (number, range<number>)",n("The first value or range to consider when calculating the minimum value.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=ps(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},Nc={description:n("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:[el("range (range)",n("The range of cells from which the minimum will be determined.")),el("criteria_range1 (range)",n("The range of cells over which to evaluate criterion1.")),el("criterion1 (string)",n("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),el("criteria_range2 (any, range, repeating)",n("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.")),el("criterion2 (string, repeating)",n("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=1/0;return vs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o=o>s?s:o)})),o===1/0?0:o},isExported:!0},_c={description:n("Value at a given percentile of a dataset."),args:[el("data (any, range)",n("The array or range containing the dataset to consider.")),el("percentile (number)",n("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return Dc.compute(e,t)},isExported:!0},Fc={description:n("Value at a given percentile of a dataset exclusive of 0 and 1."),args:[el("data (any, range)",n("The array or range containing the dataset to consider.")),el("percentile (number)",n("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return hc([e],t,!1)},isExported:!0},Dc={description:n("Value at a given percentile of a dataset."),args:[el("data (any, range)",n("The array or range containing the dataset to consider.")),el("percentile (number)",n("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return hc([e],t,!0)},isExported:!0},Lc={description:n("Value nearest to a specific quartile of a dataset."),args:[el("data (any, range)",n("The array or range containing the dataset to consider.")),el("quartile_number (number)",n("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return Pc.compute(e,t)},isExported:!0},kc={description:n("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:[el("data (any, range)",n("The array or range containing the dataset to consider.")),el("quartile_number (number)",n("Which quartile value, exclusive of 0 and 4, to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return hc([e],.25*Math.trunc(Qi(t)),!1)},isExported:!0},Pc={description:n("Value nearest to a specific quartile of a dataset."),args:[el("data (any, range)",n("The array or range containing the dataset to consider.")),el("quartile_number (number)",n("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return hc([e],.25*Math.trunc(Qi(t)),!0)},isExported:!0},Uc={description:n("Nth smallest element in a data set."),args:[el("data (any, range)",n("The array or range containing the dataset to consider.")),el("n (number)",n("The rank from smallest to largest of the element to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){const o=Math.trunc(Qi(t));let i,s=[],r=0;cs([e],(e=>{"number"==typeof e&&(i=Es(s,e,"nextSmaller","asc",s.length,((e,t)=>e[t])),s.splice(i+1,0,e),r++,r>o&&(s.pop(),r--))}));const a=s.pop();return Xi((()=>void 0!==a),n("[[FUNCTION_NAME]] has no valid input data.")),Xi((()=>r>=o),n("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},Vc={description:n("Standard deviation."),args:[el("value1 (number, range<number>)",n("The first value or range of the sample.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Gc.compute(...e))},isExported:!0},zc={description:n("Standard deviation of entire population."),args:[el("value1 (number, range<number>)",n("The first value or range of the population.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(qc.compute(...e))},isExported:!0},Bc={description:n("Standard deviation."),args:[el("value1 (number, range<number>)",n("The first value or range of the sample.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Zc.compute(...e))},isExported:!0},Hc={description:n("Standard deviation of sample (text as 0)."),args:[el("value1 (number, range<number>)",n("The first value or range of the sample.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(jc.compute(...e))},isExported:!0},$c={description:n("Standard deviation of entire population."),args:[el("value1 (number, range<number>)",n("The first value or range of the population.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Yc.compute(...e))},isExported:!0},Wc={description:n("Standard deviation of entire population (text as 0)."),args:[el("value1 (number, range<number>)",n("The first value or range of the population.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Xc.compute(...e))},isExported:!0},Gc={description:n("Variance."),args:[el("value1 (number, range<number>)",n("The first value or range of the sample.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return cc(e,!0,!1)},isExported:!0},qc={description:n("Variance of entire population."),args:[el("value1 (number, range<number>)",n("The first value or range of the population.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return cc(e,!1,!1)},isExported:!0},Zc={description:n("Variance."),args:[el("value1 (number, range<number>)",n("The first value or range of the sample.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return cc(e,!0,!1)},isExported:!0},jc={description:n("Variance of sample (text as 0)."),args:[el("value1 (number, range<number>)",n("The first value or range of the sample.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return cc(e,!0,!0)},isExported:!0},Yc={description:n("Variance of entire population."),args:[el("value1 (number, range<number>)",n("The first value or range of the population.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return cc(e,!1,!1)},isExported:!0},Xc={description:n("Variance of entire population (text as 0)."),args:[el("value1 (number, range<number>)",n("The first value or range of the population.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return cc(e,!1,!0)},isExported:!0};var Kc=Object.freeze({__proto__:null,AVEDEV:dc,AVERAGE:uc,AVERAGE_WEIGHTED:mc,AVERAGEA:fc,AVERAGEIF:bc,AVERAGEIFS:vc,COUNT:Sc,COUNTA:Cc,COVAR:Ec,COVARIANCE_P:wc,COVARIANCE_S:xc,LARGE:yc,MAX:Ic,MAXA:Rc,MAXIFS:Tc,MEDIAN:Ac,MIN:Oc,MINA:Mc,MINIFS:Nc,PERCENTILE:_c,PERCENTILE_EXC:Fc,PERCENTILE_INC:Dc,QUARTILE:Lc,QUARTILE_EXC:kc,QUARTILE_INC:Pc,SMALL:Uc,STDEV:Vc,STDEV_P:zc,STDEV_S:Bc,STDEVA:Hc,STDEVP:$c,STDEVPA:Wc,VAR:Gc,VAR_P:qc,VAR_S:Zc,VARA:jc,VARP:Yc,VARPA:Xc});function Qc(e,t,o){const i=new Map,s=e.length;for(let t=s-1;t>=0;t--)i.set(os(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(n("The field must be a number or a string"));let r;if("number"==typeof t){if(r=Math.trunc(t)-1,r<0||s-1<r)throw new Error(n("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),s.toString()))}else{const e=os(t).toUpperCase();if(r=i.get(e)??-1,-1===r)throw new Error(n("The field (%s) must be one of %s.",os(t),[...i.keys()].toString()))}const a=o[0].length;if(a<2)throw new Error(n("The criteria range contains %s row, it must be at least 2 rows.",a.toString()));let l=new Set;const c=e[0].length;for(let t=1;t<a;t++){let s=[],n=!0;for(let r=0;r<o.length;r++){const a=os(o[r][0]).toUpperCase(),l=i.get(a),h=o[r][t];if(void 0!==h){if(void 0===l){n=!1;break}s.push([e[l].slice(1,c)]),s.push(h)}}if(n){if(!(s.length>0)){l=new Set(Array(c-1).keys());break}vs(s,((e,t)=>{l.add(t)}),!0)}}const h=e[r];return[...l].map((e=>h[e+1]))}const Jc=[el("database (range)",n("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.")),el("field (any)",n("Indicates which column in database contains the values to be extracted and operated on.")),el("criteria (range)",n("An array or range containing zero or more criteria to filter the database values by before operating."))],eh={description:n("Average of a set of values from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return uc.compute([i])},isExported:!0},th={description:n("Counts values from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Sc.compute([i])},isExported:!0},oh={description:n("Counts values and text from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Cc.compute([i])},isExported:!0},ih={description:n("Single value from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Xi((()=>1===i.length),n("More than one match found in DGET evaluation.")),i[0]},isExported:!0},sh={description:n("Maximum of values from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Ic.compute([i])},isExported:!0},nh={description:n("Minimum of values from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Oc.compute([i])},isExported:!0},rh={description:n("Product of values from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Wl.compute([i])},isExported:!0},ah={description:n("Standard deviation of population sample from table."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Vc.compute([i])},isExported:!0},lh={description:n("Standard deviation of entire population from table."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return $c.compute([i])},isExported:!0},ch={description:n("Sum of values from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return tc.compute([i])},isExported:!0},hh={description:n("Variance of population sample from table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Gc.compute([i])},isExported:!0},dh={description:n("Variance of a population from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Yc.compute([i])},isExported:!0};var uh=Object.freeze({__proto__:null,DAVERAGE:eh,DCOUNT:th,DCOUNTA:oh,DGET:ih,DMAX:sh,DMIN:nh,DPRODUCT:rh,DSTDEV:ah,DSTDEVP:lh,DSUM:ch,DVAR:hh,DVARP:dh});var gh;!function(e){e.WHOLE_YEARS="Y",e.WHOLE_MONTHS="M",e.WHOLE_DAYS="D",e.DAYS_WITHOUT_WHOLE_MONTHS="MD",e.MONTH_WITHOUT_WHOLE_YEARS="YM",e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR="YD"}(gh||(gh={}));const ph={description:n("Converts year/month/day into a date."),args:[el("year (number)",n("The year component of the date.")),el("month (number)",n("The month component of the date.")),el("day (number)",n("The day component of the date."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){let i=Math.trunc(Qi(e));const s=Math.trunc(Qi(t)),r=Math.trunc(Qi(o));Xi((()=>0<=i&&i<=9999),n("The year (%s) must be between 0 and 9999 inclusive.",i.toString())),i<1900&&(i+=1900);const a=Me(new be(i,s-1,r));return Xi((()=>a>=0),n("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),a},isExported:!0},mh={description:n("Calculates the number of days, months, or years between two dates."),args:[el("start_date (date)",n("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.")),el("end_date (date)",n("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.")),el("unit (string)",n('A text abbreviation for unit of time. Accepted values are "Y" (the number of whole years between start_date and end_date), "M" (the number of whole months between start_date and end_date), "D" (the number of days between start_date and end_date), "MD" (the number of days between start_date and end_date after subtracting whole months), "YM" (the number of whole months between start_date and end_date after subtracting whole years), "YD" (the number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart).'))],returns:["NUMBER"],compute:function(e,t,o){const i=os(o).toUpperCase();Xi((()=>Object.values(gh).includes(i)),((e,t)=>{const o=e.map((e=>`'${e}'`)).join(", ");return n("The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.",t,o)})(Object.values(gh),os(o)));const s=Math.trunc(Qi(e)),r=Math.trunc(Qi(t)),a=Oe(s),l=Oe(r);switch(Xi((()=>r>=s),n("start_date (%s) should be on or before end_date (%s).",a.toLocaleDateString(),l.toLocaleDateString())),i){case gh.WHOLE_YEARS:return Ue(a,l);case gh.WHOLE_MONTHS:return ke(a,l);case gh.WHOLE_DAYS:return Pe(a,l);case gh.MONTH_WITHOUT_WHOLE_YEARS:return ke(a,l)-12*Ue(a,l);case gh.DAYS_WITHOUT_WHOLE_MONTHS:let e=l.getDate()-a.getDate();if(e<0){e=Ne(new be(l.getFullYear(),l.getMonth()-1,1))-Math.abs(e)}return e;case gh.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR:{if(function(e,t){return Le(e,t,1)<1}(s,r))return Pe(a,l);const e=new be(a.getFullYear(),l.getMonth(),l.getDate());let t=Pe(a,e);return t<0&&(e.setFullYear(a.getFullYear()+1),t=Pe(a,e)),t}}},isExported:!0},fh={description:n("Converts a date string to a date value."),args:[el("date_string (string)",n("The string representing the date."))],returns:["NUMBER"],compute:function(e){const t=os(e),o=Te(t);return Xi((()=>null!==o),n("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(o.value)},isExported:!0},bh={description:n("Day of the month that a specific date falls on."),args:[el("date (string)",n("The date from which to extract the day."))],returns:["NUMBER"],compute:function(e){return as(e).getDate()},isExported:!0},vh={description:n("Number of days between two dates."),args:[el("end_date (date)",n("The end of the date range.")),el("start_date (date)",n("The start of the date range."))],returns:["NUMBER"],compute:function(e,t){const o=as(e),i=as(t),s=o.getTime()-i.getTime();return Math.round(s/Se)},isExported:!0},Sh={description:n("Number of days between two dates on a 360-day year (months of 30 days)."),args:[el("start_date (date)",n("The start date to consider in the calculation.")),el("end_date (date)",n("The end date to consider in the calculation.")),el("method (number, default=0)",n("An indicator of what day count method to use. (0) US NASD method (1) European method"))],returns:["NUMBER"],compute:function(e,t,o=0){const i=Qi(e),s=Qi(t),n=rs(o)?4:0,r=Vh.compute(e,t,n);return Math.sign(s-i)*Math.round(360*r)},isExported:!0},Ch={description:n("Date a number of months before/after another date."),args:[el("start_date (date)",n("The date from which to calculate the result.")),el("months (number)",n("The number of months before (negative) or after (positive) 'start_date' to calculate."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){return Me(Fe(as(e),Math.trunc(Qi(t)),!1))},isExported:!0},Eh={description:n("Last day of a month before or after a date."),args:[el("start_date (date)",n("The date from which to calculate the result.")),el("months (number)",n("The number of months before (negative) or after (positive) 'start_date' to consider."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){const o=as(e),i=Math.trunc(Qi(t)),s=o.getFullYear(),n=o.getMonth();return Me(new be(s,n+i+1,0))},isExported:!0},wh={description:n("Hour component of a specific time."),args:[el("time (date)",n("The time from which to calculate the hour component."))],returns:["NUMBER"],compute:function(e){return as(e).getHours()},isExported:!0},xh={description:n("ISO week number of the year."),args:[el("date (date)",n("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=as(e),o=t.getFullYear();let i=1;for(;4!==new be(o,0,i).getDay();)i+=1;const s=new be(o,0,i-3);let n=31;for(;4!==new be(o,11,n).getDay();)n-=1;const r=new be(o,11,n+3);let a,l;switch(a=s.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=s;break;case 1:l=new be(o,11,n+3+1);break;case-1:let e=1;for(;4!==new be(o-1,0,e).getDay();)e+=1;l=new be(o-1,0,e-3)}const c=(t.getTime()-l.getTime())/Se;return Math.floor(c/7)+1},isExported:!0},yh={description:n("Minute component of a specific time."),args:[el("time (date)",n("The time from which to calculate the minute component."))],returns:["NUMBER"],compute:function(e){return as(e).getMinutes()},isExported:!0},Ih={description:n("Month of the year a specific date falls in"),args:[el("date (date)",n("The date from which to extract the month."))],returns:["NUMBER"],compute:function(e){return as(e).getMonth()+1},isExported:!0},Rh={description:n("Net working days between two provided days."),args:[el("start_date (date)",n("The start date of the period from which to calculate the number of net working days.")),el("end_date (date)",n("The end date of the period from which to calculate the number of net working days.")),el("holidays (date, range<date>, optional)",n("A range or array constant containing the date serial numbers to consider holidays."))],returns:["NUMBER"],compute:function(e,t,o){return Ah.compute(e,t,1,o)},isExported:!0};function Th(e){if("string"==typeof e){Xi((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),n('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let o=0;o<7;o++)"1"===e[o]&&t.push((o+1)%7);return t}if("number"==typeof e)return Xi((()=>1<=e&&e<=7||11<=e&&e<=17),n("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(n("The weekend must be a number or a string."))}const Ah={description:n("Net working days between two dates (specifying weekends)."),args:[el("start_date (date)",n("The start date of the period from which to calculate the number of net working days.")),el("end_date (date)",n("The end date of the period from which to calculate the number of net working days.")),el("weekend (any, default=1)",n("A number or string representing which days of the week are considered weekends.")),el("holidays (date, range<date>, optional)",n("A range or array constant containing the dates to consider as holidays."))],returns:["NUMBER"],compute:function(e,t,o=1,i){const s=as(e),n=as(t),r=Th(o);let a=new Set;void 0!==i&&cs([i],(e=>{const t=as(e);a.add(t.getTime())}));const l=s.getTime()>n.getTime(),c=be.fromTimestamp((l?s:n).getTime());let h=be.fromTimestamp((l?n:s).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},Oh={description:n("Current date and time as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy hh:mm:ss",compute:function(){let e=be.now();const t=e.getTime()-ve.getTime(),o=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/Se)+o},isExported:!0},Mh={description:n("Minute component of a specific time."),args:[el("time (date)",n("The time from which to calculate the second component."))],returns:["NUMBER"],compute:function(e){return as(e).getSeconds()},isExported:!0},Nh={description:n("Converts hour/minute/second into a time."),args:[el("hour (number)",n("The hour component of the time.")),el("minute (number)",n("The minute component of the time.")),el("second (number)",n("The second component of the time."))],returns:["DATE"],computeFormat:()=>"hh:mm:ss a",compute:function(e,t,o){let i=Math.trunc(Qi(e)),s=Math.trunc(Qi(t)),r=Math.trunc(Qi(o));return s+=Math.floor(r/60),r=r%60+(r<0?60:0),i+=Math.floor(s/60),s=s%60+(s<0?60:0),i%=24,Xi((()=>i>=0),n("The function [[FUNCTION_NAME]] result cannot be negative")),i/24+s/1440+r/86400},isExported:!0},_h={description:n("Converts a time string into its serial number representation."),args:[el("time_string (string)",n("The string that holds the time representation."))],returns:["NUMBER"],compute:function(e){const t=os(e),o=Te(t);Xi((()=>null!==o),n("The time_string (%s) cannot be parsed to date/time.",t));const i=o.value-Math.trunc(o.value);return i<0?1+i:i},isExported:!0},Fh={description:n("Current date as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(){const e=be.now();return Me(new be(e.getFullYear(),e.getMonth(),e.getDate()))},isExported:!0},Dh={description:n("Day of the week of the date provided (as number)."),args:[el("date (date)",n("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.")),el("type (number, default=1)",n("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 o=as(e),i=Math.round(Qi(t)),s=o.getDay();return Xi((()=>[1,2,3].includes(i)),n("The type (%s) must be 1, 2 or 3.",i.toString())),1===i?s+1:2===i?0===s?7:s:0===s?6:s-1},isExported:!0},Lh={description:n("Week number of the year."),args:[el("date (date)",n("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.")),el("type (number, default=1)",n("A number representing the day that a week starts on. Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const o=as(e),i=Math.round(Qi(t));if(Xi((()=>1===i||2===i||11<=i&&i<=17||21===i),n("The type (%s) is out of range.",i.toString())),21===i)return xh.compute(e);let s;s=1===i||2===i?i-1:i-10==7?0:i-10;const r=o.getFullYear();let a=1,l=new be(r,0,a);for(;l.getDay()!==s;)a+=1,l=new be(r,0,a);const c=(o.getTime()-l.getTime())/Se;return c<0?1:Math.floor(c/7)+(1===a?1:2)},isExported:!0},kh={description:n("Date after a number of workdays."),args:[el("start_date (date)",n("The date from which to begin counting.")),el("num_days (number)",n("The number of working days to advance from start_date. If negative, counts backwards.")),el("holidays (date, range<date>, optional)",n("A range or array constant containing the dates to consider holidays."))],returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){return Ph.compute(e,t,1,o)},isExported:!0},Ph={description:n("Date after a number of workdays (specifying weekends)."),args:[el("start_date (date)",n("The date from which to begin counting.")),el("num_days (number)",n("The number of working days to advance from start_date. If negative, counts backwards.")),el("weekend (any, default=1)",n("A number or string representing which days of the week are considered weekends.")),el("holidays (date, range<date>, optional)",n("A range or array constant containing the dates to consider holidays."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o=1,i){let s=as(e),r=Math.trunc(Qi(t));"string"==typeof o&&Xi((()=>"1111111"!==o),n("The weekend (%s) must be different from '1111111'.",o));const a=Th(o);let l=new Set;void 0!==i&&cs([i],(e=>{const t=as(e);l.add(t.getTime())}));let c=be.fromTimestamp(s.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-ve.getTime();return Math.round(g/Se)},isExported:!0},Uh={description:n("Year specified by a given date."),args:[el("date (date)",n("The date from which to extract the year."))],returns:["NUMBER"],compute:function(e){return as(e).getFullYear()},isExported:!0},Vh={description:n("Exact number of years between two dates."),args:[el("start_date (date)",n("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.")),el("end_date (date)",n("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.")),el("day_count_convention (number, default=0)",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o=0){let i=Math.trunc(Qi(e)),s=Math.trunc(Qi(t));const r=Math.trunc(Qi(o));return Xi((()=>i>=0),n("The start_date (%s) must be positive or null.",i.toString())),Xi((()=>s>=0),n("The end_date (%s) must be positive or null.",s.toString())),Xi((()=>0<=r&&r<=4),n("The day_count_convention (%s) must be between 0 and 4 inclusive.",r.toString())),Le(i,s,r)}},zh={description:n("First day of the month preceding a date."),args:[el("date (date)",n("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=as(e),o=t.getFullYear(),i=t.getMonth();return Me(new be(o,i,1))}},Bh={description:n("Last day of the month following a date."),args:[el("date (date)",n("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){return Eh.compute(e,0)}},Hh={description:n("Quarter of the year a specific date falls in"),args:[el("date (date)",n("The date from which to extract the quarter."))],returns:["NUMBER"],compute:function(e){return Math.ceil((as(e).getMonth()+1)/3)}},$h={description:n("First day of the quarter of the year a specific date falls in."),args:[el("date (date)",n("The date from which to calculate the start of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Hh.compute(e),o=Uh.compute(e);return Me(new be(o,3*(t-1),1))}},Wh={description:n("Last day of the quarter of the year a specific date falls in."),args:[el("date (date)",n("The date from which to calculate the end of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Hh.compute(e),o=Uh.compute(e);return Me(new be(o,3*t,0))}},Gh={description:n("First day of the year a specific date falls in."),args:[el("date (date)",n("The date from which to calculate the start of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Uh.compute(e);return Me(new be(t,0,1))}},qh={description:n("Last day of the year a specific date falls in."),args:[el("date (date)",n("The date from which to calculate the end of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Uh.compute(e);return Me(new be(t+1,0,0))}};var Zh=Object.freeze({__proto__:null,DATE:ph,DATEDIF:mh,DATEVALUE:fh,DAY:bh,DAYS:vh,DAYS360:Sh,EDATE:Ch,EOMONTH:Eh,HOUR:wh,ISOWEEKNUM:xh,MINUTE:yh,MONTH:Ih,NETWORKDAYS:Rh,NETWORKDAYS_INTL:Ah,NOW:Oh,SECOND:Mh,TIME:Nh,TIMEVALUE:_h,TODAY:Fh,WEEKDAY:Dh,WEEKNUM:Lh,WORKDAY:kh,WORKDAY_INTL:Ph,YEAR:Uh,YEARFRAC:Vh,MONTH_START:zh,MONTH_END:Bh,QUARTER:Hh,QUARTER_START:$h,QUARTER_END:Wh,YEAR_START:Gh,YEAR_END:qh});const jh={description:n("Compare two numeric values, returning 1 if they're equal."),args:[el("number1 (number)",n("The first number to compare.")),el("number2 (number, default=0)",n("The second number to compare."))],returns:["NUMBER"],compute:function(e,t=0){return Qi(e)===Qi(t)?1:0},isExported:!0};var Yh=Object.freeze({__proto__:null,DELTA:jh});function Xh(e,t){Xi((()=>e<t),n("The maturity (%s) must be strictly greater than the settlement (%s).",t.toString(),e.toString()))}function Kh(e,t){Xi((()=>t<e),n("The settlement date (%s) must be strictly greater than the issue date (%s).",e.toString(),t.toString()))}function Qh(e){Xi((()=>[1,2,4].includes(e)),n("The frequency (%s) must be one of %s",e.toString(),[1,2,4].toString()))}function Jh(e){Xi((()=>0<=e&&e<=4),n("The day_count_convention (%s) must be between 0 and 4 inclusive.",e.toString()))}function ed(e){Xi((()=>e>0),n("The redemption (%s) must be strictly positive.",e.toString()))}function td(e){Xi((()=>e>0),n("The price (%s) must be strictly positive.",e.toString()))}function od(e){Xi((()=>e>0),n("The number_of_periods (%s) must be greater than 0.",e.toString()))}function id(e){Xi((()=>e>0),n("The rate (%s) must be strictly positive.",e.toString()))}function sd(e){Xi((()=>e>0),n("The life (%s) must be strictly positive.",e.toString()))}function nd(e){Xi((()=>e>=0),n("The cost (%s) must be positive or null.",e.toString()))}function rd(e){Xi((()=>e>0),n("The period (%s) must be strictly positive.",e.toString()))}function ad(e){Xi((()=>e>=0),n("The salvage (%s) must be positive or null.",e.toString()))}function ld(e){Xi((()=>e>0),n("The present value (%s) must be strictly positive.",e.toString()))}function cd(e,t){Xi((()=>e<=t),n("The period (%s) must be less than or equal life (%s).",e.toString(),t.toString()))}function hd(e){Xi((()=>e>0),n("The investment (%s) must be strictly positive.",e.toString()))}function dd(e){Xi((()=>e>0),n("The discount (%s) must be strictly positive.",e.toString()))}function ud(e){Xi((()=>e<1),n("The discount (%s) must be smaller than 1.",e.toString()))}function gd(e){Xi((()=>e>0),n("The depreciation factor (%s) must be strictly positive.",e.toString()))}function pd(e,t){const o=as(e),i=as(t),s=as(e);s.setFullYear(o.getFullYear()+1),Xi((()=>i.getTime()<=s.getTime()),n("The settlement date (%s) must at most one year after the maturity date (%s).",e.toString(),t.toString()))}function md(e,t,o){od(o),Xi((()=>e>0),n("The first_period (%s) must be strictly positive.",e.toString())),Xi((()=>t>0),n("The last_period (%s) must be strictly positive.",t.toString())),Xi((()=>e<=t),n("The first_period (%s) must be smaller or equal to the last_period (%s).",e.toString(),t.toString())),Xi((()=>t<=o),n("The last_period (%s) must be smaller or equal to the number_of_periods (%s).",e.toString(),o.toString()))}function fd(e){Xi((()=>e>-1),n("The rate_guess (%s) must be strictly greater than -1.",e.toString()))}function bd(e,t){Xi((()=>e.length===t.length&&e[0].length===t[0].length),n("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."))}function vd(e){Xi((()=>e.every((t=>t>=e[0]))),n("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e[0].toString()))}const Sd=[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))];function Cd(e,t,o,i,s=1e-10,r){let a,l,c,h,d=o,u=!1,g=0;do{c=e(d),isNaN(c)?(Xi((()=>g<i&&void 0!==r),n("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<s||Math.abs(c)<s,Xi((()=>g<i),n("Function [[FUNCTION_NAME]] didn't find any result.")),g++)}while(!u);return d}const Ed={description:n("Accrued interest of security paying at maturity."),args:[el("issue (date)",n("The date the security was initially issued.")),el("maturity (date)",n("The maturity date of the security.")),el("rate (number)",n("The annualized rate of interest.")),el("redemption (number)",n("The redemption amount per 100 face value, or par.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const n=Math.trunc(Qi(e)),r=Math.trunc(Qi(t)),a=Qi(i),l=Qi(o),c=Math.trunc(Qi(s));Kh(r,n),Jh(c),ed(a),id(l);return a*l*Vh.compute(n,r,s)},isExported:!0},wd={description:n("Depreciation for an accounting period."),args:[el("cost (number)",n("The initial cost of the asset.")),el("purchase_date (date)",n("The date the asset was purchased.")),el("first_period_end (date)",n("The date the first period ended.")),el("salvage (number)",n("The value of the asset at the end of depreciation.")),el("period (number)",n("The single period within life for which to calculate depreciation.")),el("rate (number)",n("The deprecation rate.")),el("day_count_convention (number, optional)",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r,a=0){a=a||0;const l=Qi(e),c=Math.trunc(Qi(t)),h=Math.trunc(Qi(o)),d=Qi(i),u=Qi(s),g=Qi(r),p=Math.trunc(Qi(a));!function(e){Xi((()=>e>0),n("The cost (%s) must be strictly positive.",e.toString()))}(l),ad(d),function(e,t){Xi((()=>e<=t),n("The salvage (%s) must be smaller or equal than the cost (%s).",e.toString(),t.toString()))}(d,l),function(e){Xi((()=>e>=0),n("The period (%s) must be positive or null.",e.toString()))}(u),id(g),Jh(p),Xi((()=>c<=h),n("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,b=Vh.compute(c,h,p),v=c===h?f:f*b,S=l-v-f*m;return S>=d?0===m?v:f:d-S<f?f-(d-S):0},isExported:!0},xd={description:n("Days in coupon period containing settlement date."),args:Sd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Qi(e)),n=Math.trunc(Qi(t)),r=Math.trunc(Qi(o)),a=Math.trunc(Qi(i));if(Xh(s,n),Qh(r),Jh(a),1===a){const s=Ad.compute(e,t,o,i);return Rd.compute(e,t,o,i)-s}return(3===a?365:360)/r},isExported:!0},yd={description:n("Days from settlement until next coupon."),args:Sd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Qi(e)),n=Math.trunc(Qi(t)),r=Math.trunc(Qi(o)),a=Math.trunc(Qi(i));Xh(s,n),Qh(r),Jh(a);const l=Ad.compute(s,n,o,i);if([1,2,3].includes(a))return s-l;if(4===a){const e=Le(l,s,a);return Math.round(360*e)}const c=as(s),h=as(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&&_e(h)&&_e(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&_e(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},Id={description:n("Days from settlement until next coupon."),args:Sd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Qi(e)),n=Math.trunc(Qi(t)),r=Math.trunc(Qi(o)),a=Math.trunc(Qi(i));Xh(s,n),Qh(r),Jh(a);const l=Rd.compute(s,n,o,i);if([1,2,3].includes(a))return l-s;if(4===a){const e=Le(s,l,a);return Math.round(360*e)}const c=yd.compute(e,t,o,a);return xd.compute(e,t,o,a)-c},isExported:!0},Rd={description:n("Next coupon date after the settlement date."),args:Sd,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Qi(e)),n=Math.trunc(Qi(t)),r=Math.trunc(Qi(o)),a=Math.trunc(Qi(i));Xh(s,n),Qh(r),Jh(a);const l=12/r,c=Td.compute(e,t,o,i);return Me(Fe(as(n),-(c-1)*l,!0))},isExported:!0},Td={description:n("Number of coupons between settlement and maturity."),args:Sd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Qi(e)),n=Math.trunc(Qi(t)),r=Math.trunc(Qi(o)),a=Math.trunc(Qi(i));Xh(s,n),Qh(r),Jh(a);let l=1,c=n;const h=12/r;for(;c>s;)c=Me(Fe(as(c),-h,!1)),l++;return l-1},isExported:!0},Ad={description:n("Last coupon date prior to or on the settlement date."),args:Sd,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Qi(e)),n=Math.trunc(Qi(t)),r=Math.trunc(Qi(o)),a=Math.trunc(Qi(i));Xh(s,n),Qh(r),Jh(a);const l=12/r,c=Td.compute(e,t,o,i);return Me(Fe(as(n),-c*l,!0))},isExported:!0},Od={description:n("Cumulative interest paid over a set of periods."),args:[el("rate (number)",n("The interest rate.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("present_value (number)",n("The current value of the annuity.")),el("first_period (number)",n("The number of the payment period to begin the cumulative calculation.")),el("last_period (number)",n("The number of the payment period to end the cumulative calculation.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){const r=Qi(i),a=Qi(s),l=Qi(e),c=Qi(o),h=Qi(t);md(r,a,h),id(l),ld(c);let d=0;for(let t=r;t<=a;t++){d+=Bd.compute(e,t,h,o,0,n)}return d},isExported:!0},Md={description:n("Cumulative principal paid over a set of periods."),args:[el("rate (number)",n("The interest rate.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("present_value (number)",n("The current value of the annuity.")),el("first_period (number)",n("The number of the payment period to begin the cumulative calculation.")),el("last_period (number)",n("The number of the payment period to end the cumulative calculation.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){const r=Qi(i),a=Qi(s),l=Qi(e),c=Qi(o),h=Qi(t);md(r,a,h),id(l),ld(c);let d=0;for(let t=r;t<=a;t++){d+=Kd.compute(e,t,h,o,0,n)}return d},isExported:!0},Nd={description:n("Depreciation via declining balance method."),args:[el("cost (number)",n("The initial cost of the asset.")),el("salvage (number)",n("The value of the asset at the end of depreciation.")),el("life (number)",n("The number of periods over which the asset is depreciated.")),el("period (number)",n("The single period within life for which to calculate depreciation.")),el("month (number, optional)",n("The number of months in the first year of depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,...s){const r=Qi(e),a=Qi(t),l=Qi(o),c=Math.trunc(Qi(i)),h=s.length?Math.trunc(Qi(s[0])):12,d=l+(12===h?0:1);nd(r),ad(a),rd(c),sd(l),Xi((()=>1<=h&&h<=12),n("The month (%s) must be between 1 and 12 inclusive.",h.toString())),Xi((()=>c<=d),n("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},_d={description:n("Depreciation via double-declining balance method."),args:[el("cost (number)",n("The initial cost of the asset.")),el("salvage (number)",n("The value of the asset at the end of depreciation.")),el("life (number)",n("The number of periods over which the asset is depreciated.")),el("period (number)",n("The single period within life for which to calculate depreciation.")),el("factor (number, default=2)",n("The factor by which depreciation decreases."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,s=2){s=s||0;const n=Qi(e),r=Qi(t),a=Qi(o),l=Qi(i),c=Qi(s);if(nd(n),ad(r),rd(l),sd(a),cd(l,a),gd(c),0===n||r>=n)return 0;const h=c/a;if(h>1)return 1===i?n-r:0;if(l<=1)return n*h;const d=n*Math.pow(1-h,l-1),u=n*Math.pow(1-h,l),g=u<r?d-r:d-u;return Math.max(g,0)},isExported:!0},Fd={description:n("Discount rate of a security based on price."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("price (number)",n("The price at which the security is bought per 100 face value.")),el("redemption (number)",n("The redemption amount per 100 face value, or par.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const n=Math.trunc(Qi(e)),r=Math.trunc(Qi(t)),a=Qi(o),l=Qi(i),c=Math.trunc(Qi(s));Xh(n,r),Jh(c),td(a),ed(l);return(l-a)/l/Vh.compute(n,r,c)},isExported:!0},Dd={description:n("Convert a decimal fraction to decimal value."),args:[el("fractional_price (number)",n("The price quotation given using fractional decimal conventions.")),el("unit (number)",n("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const o=Qi(e),i=Math.trunc(Qi(t));Xi((()=>i>0),n("The unit (%s) must be strictly positive.",i.toString()));const s=Math.trunc(o);return s+(o-s)*(10**Math.ceil(Math.log10(i))/i)},isExported:!0},Ld={description:n("Convert a decimal value to decimal fraction."),args:[el("decimal_price (number)",n("The price quotation given as a decimal value.")),el("unit (number)",n("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const o=Qi(e),i=Math.trunc(Qi(t));Xi((()=>i>0),n("The unit (%s) must be strictly positive.",i.toString()));const s=Math.trunc(o);return s+(o-s)*(i/10**Math.ceil(Math.log10(i)))},isExported:!0},kd={description:n("Number of periods for an investment to reach a value."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("rate (number)",n("The annualized rate of interest.")),el("yield (number)",n("The expected annual yield of the security.")),el("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){r=r||0;const a=Math.trunc(Qi(e)),l=Math.trunc(Qi(t)),c=Qi(o),h=Qi(i),d=Math.trunc(Qi(s)),u=Math.trunc(Qi(r));Xh(a,l),Qh(d),Jh(u),Xi((()=>c>=0),n("The rate (%s) must be positive or null.",c.toString())),Xi((()=>h>=0),n("The yield (%s) must be positive or null.",h.toString()));const g=Vh.compute(a,l,u),p=g-Math.trunc(g)||1/d,m=Math.ceil(g*d),f=c/d,b=h/d;let v=0,S=0;for(let e=1;e<=m;e++){const t=(f+(e===m?1:0))/(1+b)**e;S+=(p+(e-1)/d)*t,v+=t}return 0===v?0:S/v},isExported:!0},Pd={description:n("Annual effective interest rate."),args:[el("nominal_rate (number)",n("The nominal interest rate per year.")),el("periods_per_year (number)",n("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const o=Qi(e),i=Math.trunc(Qi(t));return Xi((()=>o>0),n("The nominal rate (%s) must be strictly greater than 0.",o.toString())),Xi((()=>i>0),n("The number of periods by year (%s) must strictly greater than 0.",i.toString())),Math.pow(1+o/i,i)-1},isExported:!0},Ud={description:n("Future value of an annuity investment."),args:[el("rate (number)",n("The interest rate.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("payment_amount (number)",n("The amount per period to be paid.")),el("present_value (number, default=0)",n("The current value of the annuity.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const n=Qi(e),r=Qi(t),a=Qi(o),l=Qi(i),c=rs(s)?1:0;return n?-l*(1+n)**r-a*(1+n*c)*((1+n)**r-1)/n:-(l+a*r)},isExported:!0},Vd={description:n("Future value of principal from series of rates."),args:[el("principal (number)",n("The amount of initial capital or value to compound against.")),el("rate_schedule (number, range<number>)",n("A series of interest rates to compound against the principal."))],returns:["NUMBER"],compute:function(e,t){return us([t],((e,t)=>e*(1+Qi(t))),Qi(e))},isExported:!0},zd={description:n("Calculates effective interest rate."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("investment (number)",n("The amount invested in the security.")),el("redemption (number)",n("The amount to be received at maturity.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){const n=Math.trunc(Qi(e)),r=Math.trunc(Qi(t)),a=Qi(i),l=Qi(o);Xh(n,r),hd(l),ed(a);return(a-l)/l/Vh.compute(n,r,s)},isExported:!0},Bd={description:n("Payment on the principal of an investment."),args:[el("rate (number)",n("The annualized rate of interest.")),el("period (number)",n("The amortization period, in terms of number of periods.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("present_value (number)",n("The current value of the annuity.")),el("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,s=0,n=0){return Xd.compute(e,o,i,s,n)-Kd.compute(e,t,o,i,s,n)},isExported:!0},Hd={description:n("Internal rate of return given periodic cashflows."),args:[el("cashflow_amounts (number, range<number>)",n("An array or range containing the income or payments associated with the investment.")),el("rate_guess (number, default=0.1)",n("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t=.1){const o=Qi(t);fd(o);let i=!1,s=!1,r=[];hs([e],(e=>{e>0&&(i=!0),e<0&&(s=!0),r.push(e)})),Xi((()=>i&&s),n("The cashflow_amounts must include negative and positive values."));const a=r.shift();return Cd((function(e){return function(e,t,o){const i=o.length;let s=0;return o.reduce(((t,o)=>(s++,t+o*e**(i-s))),t*e**i)}(e,a,r)}),(function(e){return function(e,t,o){const i=o.length;let s=0;return o.reduce(((t,o)=>(s++,t+o*(i-s)*e**(i-s-1))),t*i*e**(i-1))}(e,a,r)}),o+1,20,1e-5)-1},isExported:!0},$d={description:n("Returns the interest paid at a particular period of an investment."),args:[el("rate (number)",n("The interest rate.")),el("period (number)",n("The period for which you want to view the interest payment.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("present_value (number)",n("The current value of the annuity."))],returns:["NUMBER"],compute:function(e,t,o,i){const s=Qi(e),r=Qi(t),a=Qi(o),l=Qi(i);Xi((()=>0!==a),n("The number of periods must be different than 0.",a.toString()));return-1*(l-l*(r/a))*s},isExported:!0},Wd={description:n("Modified Macaulay duration."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("rate (number)",n("The annualized rate of interest.")),el("yield (number)",n("The expected annual yield of the security.")),el("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){return kd.compute(e,t,o,i,s,n)/(1+Qi(i)/Math.trunc(Qi(s)))},isExported:!0},Gd={description:n("Modified internal rate of return."),args:[el("cashflow_amounts (range<number>)",n("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),el("financing_rate (number)",n("The interest rate paid on funds invested.")),el("reinvestment_return_rate (number)",n("The return (as a percentage) earned on reinvestment of income received from the investment."))],returns:["NUMBER"],compute:function(e,t,o){const i=Qi(t),s=Qi(o),r=(a=e,a.length?a[0].map(((e,t)=>a.map((e=>e[t])))):a).flat().filter(dt).map(Qi);var a;const l=r.length;let c=0,h=0;for(const e of Ke(0,l)){const t=r[e];t>=0?c+=t*(s+1)**(l-e-1):h+=t/(i+1)**e}Xi((()=>0!==h&&0!==c),n("There must be both positive and negative values in cashflow_amounts."));return(-c/h)**(1/(l-1))-1},isExported:!0},qd={description:n("Annual nominal interest rate."),args:[el("effective_rate (number)",n("The effective interest rate per year.")),el("periods_per_year (number)",n("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const o=Qi(e),i=Math.trunc(Qi(t));return Xi((()=>o>0),n("The effective rate (%s) must must strictly greater than 0.",o.toString())),Xi((()=>i>0),n("The number of periods by year (%s) must strictly greater than 0.",i.toString())),(Math.pow(o+1,1/i)-1)*i},isExported:!0},Zd={description:n("Number of payment periods for an investment."),args:[el("rate (number)",n("The interest rate.")),el("payment_amount (number)",n("The amount of each payment made.")),el("present_value (number)",n("The current value of the annuity.")),el("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const n=Qi(e),r=Qi(t),a=Qi(o),l=Qi(i),c=rs(s)?1:0;if(0===n)return-(l+a)/r;const h=r*(1+n*c)/n;return Math.log((h-l)/(a+h))/Math.log(1+n)},isExported:!0};const jd={description:n("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:[el("discount (number)",n("The discount rate of the investment over one period.")),el("cashflow1 (number, range<number>)",n("The first future cash flow.")),el("cashflow2 (number, range<number>, repeating)",n("Additional future cash flows."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,...t){const o=Qi(e);return Xi((()=>-1!==o),n("The discount (%s) must be different from -1.",o.toString())),function(e,t,o){let i=0;return gs(o,((t,o)=>(i++,t+o/(1+e)**i)),t)}(o,0,t)},isExported:!0},Yd={description:n("Computes the number of periods needed for an investment to reach a value."),args:[el("rate (number)",n("The rate at which the investment grows each period.")),el("present_value (number)",n("The investment's current value.")),el("future_value (number)",n("The investment's desired future value."))],returns:["NUMBER"],compute:function(e,t,o){const i=Qi(e),s=Qi(t),r=Qi(o);return id(i),Xi((()=>s>0),n("The present_value (%s) must be strictly positive.",s.toString())),Xi((()=>r>0),n("The future_value (%s) must be strictly positive.",r.toString())),(Math.log(r)-Math.log(s))/Math.log(1+i)},isExported:!0},Xd={description:n("Periodic payment for an annuity investment."),args:[el("rate (number)",n("The annualized rate of interest.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("present_value (number)",n("The current value of the annuity.")),el("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const n=Qi(t),r=Qi(e),a=rs(s)?1:0;let l=Qi(i),c=Qi(o);if(od(n),0===r)return-(l+c)/n;let h=-(c*(1+r)**n+l);return h=h*r/((1+r*a)*((1+r)**n-1)),h},isExported:!0},Kd={description:n("Payment on the principal of an investment."),args:[el("rate (number)",n("The annualized rate of interest.")),el("period (number)",n("The amortization period, in terms of number of periods.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("present_value (number)",n("The current value of the annuity.")),el("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,s=0,r=0){s=s||0,r=r||0;const a=Qi(o),l=Qi(e),c=Qi(t),h=rs(r)?1:0,d=Qi(s),u=Qi(i);od(a),Xi((()=>c>0&&c<=a),n("The period must be between 1 and number_of_periods",a.toString()));const g=Xd.compute(l,a,u,d,r);if(1===h&&1===c)return g;return g+-Ud.compute(l,0===h?c-1:c-2,g,u+g*h,0)*l},isExported:!0},Qd={description:n("Present value of an annuity investment."),args:[el("rate (number)",n("The interest rate.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("payment_amount (number)",n("The amount per period to be paid.")),el("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const n=Qi(e),r=Qi(t),a=Qi(o),l=Qi(i),c=rs(s)?1:0;return n?-(a*(1+n*c)*((1+n)**r-1)/n+l)/(1+n)**r:-(l+a*r)},isExported:!0},Jd={description:n("Price of a security paying periodic interest."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("rate (number)",n("The annualized rate of interest.")),el("yield (number)",n("The expected annual yield of the security.")),el("redemption (number)",n("The redemption amount per 100 face value, or par.")),el("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r,a=0){a=a||0;const l=Math.trunc(Qi(e)),c=Math.trunc(Qi(t)),h=Qi(o),d=Qi(i),u=Qi(s),g=Math.trunc(Qi(r)),p=Math.trunc(Qi(a));Xh(l,c),Qh(g),Jh(p),Xi((()=>h>=0),n("The rate (%s) must be positive or null.",h.toString())),Xi((()=>d>=0),n("The yield (%s) must be positive or null.",d.toString())),ed(u);const m=Vh.compute(l,c,p)*g,f=Math.ceil(m),b=m-Math.floor(m)||1,v=1+d/g,S=100*h/g;if(1===f)return(S+u)/(b*d/g+1)-S*(1-b);let C=0;for(let e=1;e<=f;e++)C+=S/v**(e-1+b);return u/v**(f-1+b)+C-S*(1-b)},isExported:!0},eu={description:n("Price of a discount security."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("discount (number)",n("The discount rate of the security at time of purchase.")),el("redemption (number)",n("The redemption amount per 100 face value, or par.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const n=Math.trunc(Qi(e)),r=Math.trunc(Qi(t)),a=Qi(o),l=Qi(i),c=Math.trunc(Qi(s));Xh(n,r),Jh(c),dd(a),ed(l);return l-a*l*Vh.compute(n,r,c)},isExported:!0},tu={description:n("Calculates the price of a security paying interest at maturity, based on expected yield."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("issue (date)",n("The date the security was initially issued.")),el("rate (number)",n("The annualized rate of interest.")),el("yield (number)",n("The expected annual yield of the security.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){r=r||0;const a=Math.trunc(Qi(e)),l=Math.trunc(Qi(t)),c=Math.trunc(Qi(o)),h=Qi(i),d=Qi(s),u=Math.trunc(Qi(r));Kh(a,c),Xh(a,l),Jh(u),Xi((()=>h>=0),n("The rate (%s) must be positive or null.",h.toString())),Xi((()=>d>=0),n("The yield (%s) must be positive or null.",d.toString()));const g=Vh.compute(a,l,u),p=Vh.compute(a,c,u);return(100+Vh.compute(c,l,u)*h*100)/(1+g*d)-p*h*100},isExported:!0},ou=.1,iu={description:n("Interest rate of an annuity investment."),args:[el("number_of_periods (number)",n("The number of payments to be made.")),el("payment_per_period (number)",n("The amount per period to be paid.")),el("present_value (number)",n("The current value of the annuity.")),el("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period.")),el("rate_guess (number, default=0.1)",n("An estimate for what the interest rate will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t,o,i=0,s=0,r=.1){i=i||0,s=s||0,r=r||ou;const a=Qi(e),l=Qi(t),c=rs(s)?1:0,h=Qi(r);let d=Qi(i),u=Qi(o);od(a),Xi((()=>[l,u,d].some((e=>e>0))&&[l,u,d].some((e=>e<0))),n("There must be both positive and negative values in [payment_amount, present_value, future_value].",a.toString())),fd(h),d-=l*c,u+=l*c;return Cd((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),o=Math.pow(1+e,a);return u*a*t+l*(a*t/e-(o-1)/e/e)}),h,40,1e-5)},isExported:!0},su={description:n("Amount received at maturity for a security."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("investment (number)",n("The amount invested (irrespective of face value of each security).")),el("discount (number)",n("The discount rate of the security invested in.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const n=Math.trunc(Qi(e)),r=Math.trunc(Qi(t)),a=Qi(o),l=Qi(i),c=Math.trunc(Qi(s));Xh(n,r),Jh(c),hd(a),dd(l);return a/(1-l*Vh.compute(n,r,c))},isExported:!0},nu={description:n("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[el("number_of_periods (number)",n("The number of periods.")),el("present_value (number)",n("The present value of the investment.")),el("future_value (number)",n("The future value of the investment."))],returns:["NUMBER"],compute:function(e,t,o){const i=Qi(e),s=Qi(t),n=Qi(o);return od(i),(n/s)**(1/i)-1},isExported:!0},ru={description:n("Depreciation of an asset using the straight-line method."),args:[el("cost (number)",n("The initial cost of the asset.")),el("salvage (number)",n("The value of the asset at the end of depreciation.")),el("life (number)",n("The number of periods over which the asset is depreciated."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o){return(Qi(e)-Qi(t))/Qi(o)},isExported:!0},au={description:n("Depreciation via sum of years digit method."),args:[el("cost (number)",n("The initial cost of the asset.")),el("salvage (number)",n("The value of the asset at the end of depreciation.")),el("life (number)",n("The number of periods over which the asset is depreciated.")),el("period (number)",n("The single period within life for which to calculate depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i){const s=Qi(e),n=Qi(t),r=Qi(o),a=Qi(i);rd(a),sd(r),cd(a,r);return(r-a+1)/(r*(r+1)/2)*(s-n)},isExported:!0},lu={description:n("Price of a US Treasury bill."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("discount (number)",n("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Qi(e)),s=Math.trunc(Qi(t)),n=Qi(o);Xh(i,s),pd(i,s),dd(n),ud(n);return 100*(1-n*Vh.compute(i,s,2))},isExported:!0},cu={description:n("Equivalent rate of return for a US Treasury bill."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("discount (number)",n("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Qi(e)),s=Math.trunc(Qi(t)),n=Qi(o);Xh(i,s),pd(i,s),dd(n),ud(n);const r=vh.compute(s,i);if(r<=182)return 365*n/(360-n*r);const a=lu.compute(i,s,n)/100,l=r/(366===r?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},hu={description:n("The yield of a US Treasury bill based on price."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("price (number)",n("The price at which the security is bought per 100 face value."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Qi(e)),s=Math.trunc(Qi(t)),n=Qi(o);Xh(i,s),pd(i,s),td(n);return(100-n)/n*(1/Vh.compute(i,s,2))},isExported:!0},du={description:n("Variable declining balance. WARNING : does not handle decimal periods."),args:[el("cost (number)",n("The initial cost of the asset.")),el("salvage (number)",n("The value of the asset at the end of depreciation.")),el("life (number)",n("The number of periods over which the asset is depreciated.")),el("start (number)",n("Starting period to calculate depreciation.")),el("end (number)",n("Ending period to calculate depreciation.")),el("factor (number, default=2)",n("The number of months in the first year of depreciation.")),el("no_switch (number, default=false)",n("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=2,a=false){r=r||0;const l=Qi(e),c=Qi(t),h=Qi(o),d=Math.trunc(Qi(i)),u=Math.trunc(Qi(s)),g=Qi(r),p=rs(a);if(nd(l),ad(c),function(e,t,o){sd(o),Xi((()=>e>=0),n("The start_period (%s) must be greater or equal than 0.",e.toString())),Xi((()=>t>=0),n("The end_period (%s) must be greater or equal than 0.",t.toString())),Xi((()=>e<=t),n("The start_period (%s) must be smaller or equal to the end_period (%s).",e.toString(),t.toString())),Xi((()=>t<=o),n("The end_period (%s) must be smaller or equal to the life (%s).",e.toString(),o.toString()))}(d,u,h),gd(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,b=0,v=0,S=!1;for(let e=0;e<u;e++){if(!S||p){const t=f*m,o=(f-c)/(h-e);!p&&o>t?(S=!0,b=o):b=t}const t=Math.max(f-b,c);e>=d&&(v+=f-t),f=t}return v},isExported:!0},uu={description:n("Internal rate of return given non-periodic cash flows."),args:[el("cashflow_amounts (range<number>)",n("An range containing the income or payments associated with the investment.")),el("cashflow_dates (range<number>)",n("An range with dates corresponding to the cash flows in cashflow_amounts.")),el("rate_guess (number, default=0.1)",n("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],compute:function(e,t,o=.1){const i=Qi(o=o||0),s=e.flat().map(Qi),r=t.flat().map(Qi);var a;bd(e,t),a=s,Xi((()=>a.some((e=>e>0))&&a.some((e=>e<0))),n("There must be both positive and negative values in cashflow_amounts.")),vd(r),fd(i);const l=new Map;for(const e of Ke(0,r.length)){const t=r[e];l.has(t)?l.set(t,l.get(t)+s[e]):l.set(t,s[e])}const c=Array.from(l.keys()),h=c.map((e=>l.get(e)));return Cd((e=>{let t=h[0];for(const o of Ke(1,h.length)){const i=(c[0]-c[o])/365;t+=h[o]*(1+e)**i}return t}),(e=>{let t=0;for(const o of Ke(1,h.length)){const i=(c[0]-c[o])/365;t+=i*h[o]*(1+e)**(i-1)}return t}),i,40,1e-5,(e=>e?e/10-.9:-.9))},isExported:!0},gu={description:n("Net present value given to non-periodic cash flows.."),args:[el("discount (number)",n("The discount rate of the investment over one period.")),el("cashflow_amounts (number, range<number>)",n("An range containing the income or payments associated with the investment.")),el("cashflow_dates (number, range<number>)",n("An range with dates corresponding to the cash flows in cashflow_amounts."))],returns:["NUMBER"],compute:function(e,t,o){const i=Qi(e),s=Array.isArray(t)?t.flat().map(Ji):[Ji(t)],r=Array.isArray(o)?o.flat().map(Ji):[Ji(o)];if(Array.isArray(o)&&Array.isArray(t)?bd(t,o):Xi((()=>s.length===r.length),n("There must be the same number of values in cashflow_amounts and cashflow_dates.")),vd(r),id(i),1===s.length)return s[0];const a=new Map;for(const e of Ke(0,r.length)){const t=r[e];a.has(t)?a.set(t,a.get(t)+s[e]):a.set(t,s[e])}const l=Array.from(a.keys()),c=l.map((e=>a.get(e)));let h=c[0];for(const e of Ke(1,c.length)){const t=(l[0]-l[e])/365;h+=c[e]*(1+i)**t}return h},isExported:!0},pu={description:n("Annual yield of a security paying periodic interest."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("rate (number)",n("The annualized rate of interest.")),el("price (number)",n("The price at which the security is bought per 100 face value.")),el("redemption (number)",n("The redemption amount per 100 face value, or par.")),el("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r,a=0){a=a||0;const l=Math.trunc(Qi(e)),c=Math.trunc(Qi(t)),h=Qi(o),d=Qi(i),u=Qi(s),g=Math.trunc(Qi(r)),p=Math.trunc(Qi(a));Xh(l,c),Qh(g),Jh(p),Xi((()=>h>=0),n("The rate (%s) must be positive or null.",h.toString())),td(d),ed(u);const m=Vh.compute(l,c,p)*g,f=Math.ceil(m),b=m-Math.floor(m)||1,v=100*h/g;if(1===f){const e=d+v*(1-b);return(u+v-e)*g*(1/b)/e}const S=Cd((function(e){return function(e,t,o,i,s,n){let r=n-(e+s*(1-t))*i**(o-1+t);for(let e=1;e<=o;e++)r+=s*i**(e-1);return r}(d,b,f,e,v,u)}),(function(e){return function(e,t,o,i,s){let n=-(e+s*(1-t))*(o-1+t)*i**(o-2+t);for(let e=1;e<=o;e++)n+=s*(e-1)*i**(e-2);return n}(d,b,f,e,v)}),1+(h+1)/g,100,1e-5);return(S-1)*g},isExported:!0},mu={description:n("Annual yield of a discount security."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("price (number)",n("The price at which the security is bought per 100 face value.")),el("redemption (number)",n("The redemption amount per 100 face value, or par.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const n=Math.trunc(Qi(e)),r=Math.trunc(Qi(t)),a=Qi(o),l=Qi(i),c=Math.trunc(Qi(s));Xh(n,r),Jh(c),td(a),ed(l);return(l/a-1)/Vh.compute(e,t,s)},isExported:!0},fu={description:n("Annual yield of a security paying interest at maturity."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("issue (date)",n("The date the security was initially issued.")),el("rate (number)",n("The annualized rate of interest.")),el("price (number)",n("The price at which the security is bought.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){r=r||0;const a=Math.trunc(Qi(e)),l=Math.trunc(Qi(t)),c=Math.trunc(Qi(o)),h=Qi(i),d=Qi(s),u=Math.trunc(Qi(r));Xh(a,l),Jh(u),Xi((()=>a>=c),n("The settlement (%s) must be greater than or equal to the issue (%s).",a.toString(),c.toString())),Xi((()=>h>=0),n("The rate (%s) must be positive or null.",h.toString())),td(d);const g=Vh.compute(c,l,u),p=Vh.compute(c,a,u),m=Vh.compute(a,l,u);return(100*(1+h*g)/(d+100*h*p)-1)/m},isExported:!0};var bu=Object.freeze({__proto__:null,ACCRINTM:Ed,AMORLINC:wd,COUPDAYS:xd,COUPDAYBS:yd,COUPDAYSNC:Id,COUPNCD:Rd,COUPNUM:Td,COUPPCD:Ad,CUMIPMT:Od,CUMPRINC:Md,DB:Nd,DDB:_d,DISC:Fd,DOLLARDE:Dd,DOLLARFR:Ld,DURATION:kd,EFFECT:Pd,FV:Ud,FVSCHEDULE:Vd,INTRATE:zd,IPMT:Bd,IRR:Hd,ISPMT:$d,MDURATION:Wd,MIRR:Gd,NOMINAL:qd,NPER:Zd,NPV:jd,PDURATION:Yd,PMT:Xd,PPMT:Kd,PV:Qd,PRICE:Jd,PRICEDISC:eu,PRICEMAT:tu,RATE:iu,RECEIVED:su,RRI:nu,SLN:ru,SYD:au,TBILLPRICE:lu,TBILLEQ:cu,TBILLYIELD:hu,VDB:du,XIRR:uu,XNPV:gu,YIELD:pu,YIELDDISC:mu,YIELDMAT:fu});const vu={description:n("Whether a value is an error other than #N/A."),args:[el("value (any, lazy)",n("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return e?.errorType!=a.NotAvailable}},isExported:!0},Su={description:n("Whether a value is an error."),args:[el("value (any, lazy)",n("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},Cu={description:n("Whether a value is `true` or `false`."),args:[el("value (any, lazy)",n("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},Eu={description:n("Whether a value is the error #N/A."),args:[el("value (any, lazy)",n("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return e?.errorType==a.NotAvailable}},isExported:!0},wu={description:n("Whether a value is non-textual."),args:[el("value (any, lazy)",n("The value to be checked."))],returns:["BOOLEAN"],compute:function(e){try{return"string"!=typeof e()}catch(e){return!0}},isExported:!0},xu={description:n("Whether a value is a number."),args:[el("value (any, lazy)",n("The value to be verified as a number."))],returns:["BOOLEAN"],compute:function(e){try{return"number"==typeof e()}catch(e){return!1}},isExported:!0},yu={description:n("Whether a value is text."),args:[el("value (any, lazy)",n("The value to be verified as text."))],returns:["BOOLEAN"],compute:function(e){try{return"string"==typeof e()}catch(e){return!1}},isExported:!0},Iu={description:n("Whether the referenced cell is empty"),args:[el("value (any, lazy)",n("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},Ru={description:n("Returns the error value #N/A."),args:[],returns:["BOOLEAN"],compute:function(e){throw new g},isExported:!0};var Tu=Object.freeze({__proto__:null,ISERR:vu,ISERROR:Su,ISLOGICAL:Cu,ISNA:Eu,ISNONTEXT:wu,ISNUMBER:xu,ISTEXT:yu,ISBLANK:Iu,NA:Ru});const Au={description:n("Logical `and` operator."),args:[el("logical_expression1 (boolean, range<boolean>)",n("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.")),el("logical_expression2 (boolean, range<boolean>, repeating)",n("More expressions that represent logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!0;return ms(e,(e=>(t=!0,o=o&&e,o))),Xi((()=>t),n("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},Ou={description:n("Returns value depending on logical expression."),args:[el("logical_expression (boolean)",n("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")),el("value_if_true (any, lazy)",n("The value the function returns if logical_expression is TRUE.")),el("value_if_false (any, lazy, default=FALSE)",n("The value the function returns if logical_expression is FALSE."))],returns:["ANY"],compute:function(e,t,o=(()=>!1)){const i=rs(e)?t():o();return null==i?"":i},isExported:!0},Mu={description:n("Value if it is not an error, otherwise 2nd argument."),args:[el("value (any, lazy)",n("The value to return if value itself is not an error.")),el('value_if_error (any, lazy, default="empty")',n("The value the function returns if value is an error."))],returns:["ANY"],computeFormat:(e,t=(()=>({value:""})))=>{try{return e().format}catch(e){return t()?.format}},compute:function(e,t=(()=>"")){let o;try{o=e()}catch(e){o=t()}return null==o?"":o},isExported:!0},Nu={description:n("Value if it is not an #N/A error, otherwise 2nd argument."),args:[el("value (any, lazy)",n("The value to return if value itself is not #N/A an error.")),el('value_if_error (any, lazy, default="empty")',n("The value the function returns if value is an #N/A error."))],returns:["ANY"],compute:function(e,t=(()=>"")){let o;try{o=e()}catch(i){o=i.errorType===a.NotAvailable?t():e()}return null==o?"":o},isExported:!0},_u={description:n("Returns a value depending on multiple logical expressions."),args:[el("condition1 (boolean, lazy)",n("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")),el("value1 (any, lazy)",n("The returned value if condition1 is TRUE.")),el("condition2 (boolean, lazy, repeating)",n("Additional conditions to be evaluated if the previous ones are FALSE.")),el("value2 (any, lazy, repeating)",n("Additional values to be returned if their corresponding conditions are TRUE."))],returns:["ANY"],compute:function(...e){Xi((()=>e.length%2==0),n("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(rs(e[t]())){const o=e[t+1]();return null!==o?o:""}throw new Error(n("No match."))},isExported:!0},Fu={description:n("Returns opposite of provided logical value."),args:[el("logical_expression (boolean)",n("An expression or reference to a cell holding an expression that represents some logical value."))],returns:["BOOLEAN"],compute:function(e){return!rs(e)},isExported:!0},Du={description:n("Logical `or` operator."),args:[el("logical_expression1 (boolean, range<boolean>)",n("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.")),el("logical_expression2 (boolean, range<boolean>, repeating)",n("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!1;return ms(e,(e=>(t=!0,o=o||e,!o))),Xi((()=>t),n("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},Lu={description:n("Logical `xor` operator."),args:[el("logical_expression1 (boolean, range<boolean>)",n("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.")),el("logical_expression2 (boolean, range<boolean>, repeating)",n("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!1;return ms(e,(e=>(t=!0,o=o?!e:e,!0))),Xi((()=>t),n("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0};var ku=Object.freeze({__proto__:null,AND:Au,IF:Ou,IFERROR:Mu,IFNA:Nu,IFS:_u,NOT:Fu,OR:Du,XOR:Lu});function Pu(e,t){if(void 0===e)throw new g(n("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",os(t)))}const Uu={description:n("Returns a cell reference as a string. "),args:[el("row (number)",n("The row number of the cell reference. ")),el("column (number)",n("The column number (not name) of the cell reference. A is column number 1. ")),el("absolute_relative_mode (number, default=1)",n("An indicator of whether the reference is row/column absolute. 1 is row and column absolute (e.g. $A$1), 2 is row absolute and column relative (e.g. A$1), 3 is row relative and column absolute (e.g. $A1), and 4 is row and column relative (e.g. A1).")),el("use_a1_notation (boolean, default=TRUE)",n("A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).")),el("sheet (string, optional)",n("A string indicating the name of the sheet into which the address points."))],returns:["STRING"],compute:function(e,t,o=1,i=!0,s){const r=es(e),a=es(t);ts(r),ts(a);const l=es(o);var c,h;Xi((()=>[1,2,3,4].includes(l)),(c=4,h=l,n("The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.",1..toString(),c.toString(),h.toString())));let d;if(rs(i)){d=Zt(a-1,r-1,{rowFixed:!![1,2].includes(l),colFixed:!![1,3].includes(l)})}else{d=([1,2].includes(l)?`R${r}`:`R[${r}]`)+([1,3].includes(l)?`C${a}`:`C[${a}]`)}return void 0!==s?`${$e(os(s))}!${d}`:d},isExported:!0},Vu={description:n("Column number of a specified cell."),args:[el("cell_reference (meta, default='this cell')",n("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){const t=e||this.__originCellXC?.();Xi((()=>!!t),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return ii(t).left+1},isExported:!0},zu={description:n("Number of columns in a specified array or range."),args:[el("range (meta)",n("The range whose column count will be returned."))],returns:["NUMBER"],compute:function(e){const t=ii(e);return t.right-t.left+1},isExported:!0},Bu={description:n("Horizontal lookup"),args:[el("search_key (any)",n("The value to search for. For example, 42, 'Cats', or I24.")),el("range (range)",n("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")),el("index (number)",n("The row index of the value to be returned, where the first row in range is numbered 1.")),el("is_sorted (boolean, default=true)",n("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,o,i=true){const s=Math.trunc(Qi(o)),r=ss(e);Xi((()=>1<=s&&s<=t[0].length),n("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=rs(i)?Es(t,r,"nextSmaller","asc",t.length,Cs):ws(t,r,"strict",t.length,Cs);const l=t[a];return Pu(l,e),l[s-1]},isExported:!0},Hu={description:n("Returns the content of a cell, specified by row and column offset."),args:[el("reference (any, range)",n("The range of cells from which the values are returned.")),el("row (number)",n("The index of the row to be returned from within the reference range of cells.")),el("column (number)",n("The index of the column to be returned from within the reference range of cells."))],returns:["ANY"],computeFormat:(e,t,o)=>{const i=Qi(t.value);return e[Qi(o.value)-1][i-1]?.format},compute:function(e,t,o){const i=(s=e,Array.isArray(s)&&Array.isArray(s[0])?e:[[e]]);var s;const r=Qi(t),a=Qi(o);return Xi((()=>a>=0&&a-1<i.length&&r>=0&&r-1<i[0].length),n("Index out of range.")),Xi((()=>0!==t&&0!==o),n("This function can only return a single cell value, not an array. Provide valid row and column indices.")),i[a-1][r-1]},isExported:!0},$u={description:n("Look up a value."),args:[el("search_key (any)",n("The value to search for. For example, 42, 'Cats', or I24.")),el("search_array (range)",n("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.")),el("result_range (range, optional)",n("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,o){let i=t.length,s=t[0].length;const r=ss(e),a=s>=i,l=Es(t,r,"nextSmaller","asc",a?s:i,a?Ss:Cs);return-1===l&&Pu(void 0,e),Pu(a?t[0][l]:t[l][s-1],e),void 0===o?a?t[i-1][l]:t[l][s-1]:(i=o.length,s=o[0].length,Xi((()=>1===i||1===s),n("The result_range must be a single row or a single column.")),i>1?(Xi((()=>l<=i-1),n("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(l+1).toString())),o[l][0]):(Xi((()=>l<=s-1),n("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(l+1).toString())),o[0][l]))},isExported:!0},Wu={description:n("Position of item in range that matches value."),args:[el("search_key (any)",n("The value to search for. For example, 42, 'Cats', or I24.")),el("range (any, range)",n("The one-dimensional array to be searched.")),el("search_type (number, default=1)",n("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,o=1){let i=Qi(o);const s=ss(e),r=t.length,a=t[0].length;Xi((()=>1===r||1===a),n("The range must be a single row or a single column."));let l=-1;const c=1===r?Ss:Cs,h=1===r?t[0].length:t.length;switch(i=Math.sign(i),i){case 1:l=Es(t,s,"nextSmaller","asc",h,c);break;case 0:l=ws(t,s,"strict",h,c);break;case-1:l=Es(t,s,"nextGreater","desc",h,c)}return Pu(1===r?t[0][l]:t[l],e),l+1},isExported:!0},Gu={description:n("Row number of a specified cell."),args:[el("cell_reference (meta, default='this cell')",n("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){e=e||this.__originCellXC?.(),Xi((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return ii(e).top+1},isExported:!0},qu={description:n("Number of rows in a specified array or range."),args:[el("range (meta)",n("The range whose row count will be returned."))],returns:["NUMBER"],compute:function(e){const t=ii(e);return t.bottom-t.top+1},isExported:!0},Zu={description:n("Vertical lookup."),args:[el("search_key (any)",n("The value to search for. For example, 42, 'Cats', or I24.")),el("range (any, range)",n("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")),el("index (number)",n("The column index of the value to be returned, where the first column in range is numbered 1.")),el("is_sorted (boolean, default=true)",n("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,o,i=true){const s=Math.trunc(Qi(o)),r=ss(e);Xi((()=>1<=s&&s<=t.length),n("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=rs(i)?Es(t,r,"nextSmaller","asc",t[0].length,Ss):ws(t,r,"strict",t[0].length,Ss);const l=t[s-1][a];return Pu(l,e),l},isExported:!0},ju={description:n("Search a range for a match and return the corresponding item from a second range."),args:[el("search_key (any)",n("The value to search for.")),el("lookup_range (any, range)",n("The range to consider for the search. Should be a single column or a single row.")),el("return_range (any, range)",n("The range containing the return value. Should have the same dimensions as lookup_range.")),el("if_not_found (any, lazy, optional)",n("If a valid match is not found, return this value.")),el("match_mode (any, default=0)",n("(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match.")),el("search_mode (any, default=1)",n("(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,o,i,s=0,r=1){const a=Math.trunc(Qi(s)),l=Math.trunc(Qi(r)),c=ss(e);Xi((()=>1===t.length||1===t[0].length),n("lookup_range should be either a single row or single column.")),Xi((()=>1===o.length||1===o[0].length),n("return_range should be either a single row or single column.")),Xi((()=>o.length===t.length&&o[0].length===t[0].length),n("return_range should have the same dimensions as lookup_range.")),Xi((()=>[-1,1,-2,2].includes(l)),n("searchMode should be a value in [-1, 1, -2, 2].")),Xi((()=>[-1,0,1].includes(a)),n("matchMode should be a value in [-1, 0, 1]."));const h=1===t.length?Ss:Cs,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=Es(t,c,u,2===l?"asc":"desc",d,h)}else p=ws(t,c,u,d,h,g);if(-1!==p)return 1===t.length?o[0][p]:o[p][0];const m=i?.();return Pu(m,e),m},isExported:!0};var Yu=Object.freeze({__proto__:null,ADDRESS:Uu,COLUMN:Vu,COLUMNS:zu,HLOOKUP:Bu,INDEX:Hu,LOOKUP:$u,MATCH:Wu,ROW:Gu,ROWS:qu,VLOOKUP:Zu,XLOOKUP:ju});const Xu={description:n("Sum of two numbers."),args:[el("value1 (number)",n("The first addend.")),el("value2 (number)",n("The second addend."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Qi(e)+Qi(t)}},Ku={description:n("Concatenation of two values."),args:[el("value1 (string)",n("The value to which value2 will be appended.")),el("value2 (string)",n("The value to append to value1."))],returns:["STRING"],compute:function(e,t){return os(e)+os(t)},isExported:!0},Qu={description:n("One number divided by another."),args:[el("dividend (number)",n("The number to be divided.")),el("divisor (number)",n("The number to divide by."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){const o=Qi(t);return Xi((()=>0!==o),n("The divisor must be different from zero.")),Qi(e)/o}};function Ju(e){return null==e}const eg={number:0,string:"",boolean:!1},tg={description:n("Equal."),args:[el("value1 (any)",n("The first value.")),el("value2 (any)",n("The value to test against value1 for equality."))],returns:["BOOLEAN"],compute:function(e,t){return e=Ju(e)?eg[typeof t]:e,t=Ju(t)?eg[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function og(e,t,o){e=Ju(e)?eg[typeof t]:e,t=Ju(t)?eg[typeof e]:t,"number"!=typeof e&&(e=os(e).toUpperCase()),"number"!=typeof t&&(t=os(t).toUpperCase());const i=typeof e,s=typeof t;return"string"===i&&"number"===s||("string"!==s||"number"!==i)&&o(e,t)}const ig={description:n("Strictly greater than."),args:[el("value1 (any)",n("The value to test as being greater than value2.")),el("value2 (any)",n("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return og(e,t,((e,t)=>e>t))}},sg={description:n("Greater than or equal to."),args:[el("value1 (any)",n("The value to test as being greater than or equal to value2.")),el("value2 (any)",n("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return og(e,t,((e,t)=>e>=t))}},ng={description:n("Less than."),args:[el("value1 (any)",n("The value to test as being less than value2.")),el("value2 (any)",n("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!sg.compute(e,t)}},rg={description:n("Less than or equal to."),args:[el("value1 (any)",n("The value to test as being less than or equal to value2.")),el("value2 (any)",n("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!ig.compute(e,t)}},ag={description:n("Difference of two numbers."),args:[el("value1 (number)",n("The minuend, or number to be subtracted from.")),el("value2 (number)",n("The subtrahend, or number to subtract from value1."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Qi(e)-Qi(t)}},lg={description:n("Product of two numbers"),args:[el("factor1 (number)",n("The first multiplicand.")),el("factor2 (number)",n("The second multiplicand."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Qi(e)*Qi(t)}},cg={description:n("Not equal."),args:[el("value1 (any)",n("The first value.")),el("value2 (any)",n("The value to test against value1 for inequality."))],returns:["BOOLEAN"],compute:function(e,t){return!tg.compute(e,t)}},hg={description:n("A number raised to a power."),args:[el("base (number)",n("The number to raise to the exponent power.")),el("exponent (number)",n("The exponent to raise base to."))],returns:["NUMBER"],compute:function(e,t){return $l.compute(e,t)}},dg={description:n("A number with the sign reversed."),args:[el("value (number)",n("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],computeFormat:e=>e?.format,returns:["NUMBER"],compute:function(e){return-Qi(e)}},ug={description:n("Value interpreted as a percentage."),args:[el("percentage (number)",n("The value to interpret as a percentage."))],returns:["NUMBER"],compute:function(e){return Qi(e)/100}},gg={description:n("A specified number, unchanged."),args:[el("value (any)",n("The number to return."))],returns:["ANY"],computeFormat:e=>e?.format,compute:function(e){return null===e?"":e}};var pg=Object.freeze({__proto__:null,ADD:Xu,CONCAT:Ku,DIVIDE:Qu,EQ:tg,GT:ig,GTE:sg,LT:ng,LTE:rg,MINUS:ag,MULTIPLY:lg,NE:cg,POW:hg,UMINUS:dg,UNARY_PERCENT:ug,UPLUS:gg});const mg=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,fg={description:n("Gets character associated with number."),args:[el("table_number (number)",n("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(Qi(e));return Xi((()=>t>=1),n("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},bg={description:n("Remove non-printable characters from a piece of text."),args:[el("text (string)",n("The text whose non-printable characters are to be removed."))],returns:["STRING"],compute:function(e){const t=os(e);let o="";for(const e of t)e&&e.charCodeAt(0)>31&&(o+=e);return o},isExported:!0},vg={description:n("Appends strings to one another."),args:[el("string1 (string, range<string>)",n("The initial string.")),el("string2 (string, range<string>, repeating)",n("More strings to append in sequence."))],returns:["STRING"],compute:function(...e){return us(e,((e,t)=>e+os(t)),"")},isExported:!0},Sg={description:n("Tests whether two strings are identical."),args:[el("string1 (string)",n("The first string to compare.")),el("string2 (string)",n("The second string to compare."))],returns:["BOOLEAN"],compute:function(e,t){return os(e)===os(t)},isExported:!0},Cg={description:n("First position of string found in text, case-sensitive."),args:[el("search_for (string)",n("The string to look for within text_to_search.")),el("text_to_search (string)",n("The text to search for the first occurrence of search_for.")),el("starting_at (number, default=1)",n("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,o=1){const i=os(e),s=os(t),r=Qi(o);Xi((()=>""!==s),n("The text_to_search must be non-empty.")),Xi((()=>r>=1),n("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=s.indexOf(i,r-1);return Xi((()=>a>=0),n("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i.toString(),s)),a+1},isExported:!0},Eg={description:n("Concatenates elements of arrays with delimiter."),args:[el("delimiter (string)",n("The character or string to place between each concatenated value.")),el("value_or_array1 (string, range<string>)",n("The value or values to be appended using delimiter.")),el("value_or_array2 (string, range<string>, repeating)",n("More values to be appended using delimiter."))],returns:["STRING"],compute:function(e,...t){const o=os(e);return us(t,((e,t)=>(e?e+o:"")+os(t)),"")}},wg={description:n("Substring from beginning of specified string."),args:[el("text (string)",n("The string from which the left portion will be returned.")),el("number_of_characters (number, optional)",n("The number of characters to return from the left side of string."))],returns:["STRING"],compute:function(e,...t){const o=t.length?Qi(t[0]):1;return Xi((()=>o>=0),n("The number_of_characters (%s) must be positive or null.",o.toString())),os(e).substring(0,o)},isExported:!0},xg={description:n("Length of a string."),args:[el("text (string)",n("The string whose length will be returned."))],returns:["NUMBER"],compute:function(e){return os(e).length},isExported:!0},yg={description:n("Converts a specified string to lowercase."),args:[el("text (string)",n("The string to convert to lowercase."))],returns:["STRING"],compute:function(e){return os(e).toLowerCase()},isExported:!0},Ig={description:n("A segment of a string."),args:[el("text (string)",n("The string to extract a segment from.")),el("starting_at (number)",n("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),el("extract_length (number)",n("The length of the segment to extract."))],returns:["STRING"],compute:function(e,t,o){const i=os(e),s=Qi(t),r=Qi(o);return Xi((()=>s>=1),n("The starting_at argument (%s) must be positive greater than one.",s.toString())),Xi((()=>r>=0),n("The extract_length argument (%s) must be positive or null.",r.toString())),i.slice(s-1,s+r-1)},isExported:!0},Rg={description:n("Capitalizes each word in a specified string."),args:[el("text_to_capitalize (string)",n("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 os(e).replace(mg,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},Tg={description:n("Replaces part of a text string with different text."),args:[el("text (string)",n("The text, a part of which will be replaced.")),el("position (number)",n("The position where the replacement will begin (starting from 1).")),el("length (number)",n("The number of characters in the text to be replaced.")),el("new_text (string)",n("The text which will be inserted into the original text."))],returns:["STRING"],compute:function(e,t,o,i){const s=Qi(t);Xi((()=>s>=1),n("The position (%s) must be greater than or equal to 1.",s.toString()));const r=os(e),a=Qi(o),l=os(i);return r.substring(0,s-1)+l+r.substring(s-1+a)},isExported:!0},Ag={description:n("A substring from the end of a specified string."),args:[el("text (string)",n("The string from which the right portion will be returned.")),el("number_of_characters (number, optional)",n("The number of characters to return from the right side of string."))],returns:["STRING"],compute:function(e,...t){const o=t.length?Qi(t[0]):1;Xi((()=>o>=0),n("The number_of_characters (%s) must be positive or null.",o.toString()));const i=os(e),s=i.length;return i.substring(s-o,s)},isExported:!0},Og={description:n("First position of string found in text, ignoring case."),args:[el("search_for (string)",n("The string to look for within text_to_search.")),el("text_to_search (string)",n("The text to search for the first occurrence of search_for.")),el("starting_at (number, default=1)",n("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,o=1){const i=os(e).toLowerCase(),s=os(t).toLowerCase(),r=Qi(o);Xi((()=>""!==s),n("The text_to_search must be non-empty.")),Xi((()=>r>=1),n("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=s.indexOf(i,r-1);return Xi((()=>a>=0),n("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i,s)),a+1},isExported:!0},Mg={description:n("Replaces existing text with new text in a string."),args:[el("text_to_search (string)",n("The text within which to search and replace.")),el("search_for (string)",n("The string to search for within text_to_search.")),el("replace_with (string)",n("The string that will replace search_for.")),el("occurrence_number (number, optional)",n("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,o,i){const s=Qi(i);Xi((()=>s>=0),n("The occurrenceNumber (%s) must be positive or null.",s.toString()));const r=os(e),a=os(t);if(""===a)return r;const l=os(o),c=new RegExp(ze(a),"g");if(0===s)return r.replace(c,l);let h=0;return r.replace(c,(e=>++h===s?l:e))},isExported:!0},Ng={description:n("Combines text from multiple strings and/or arrays."),args:[el("delimiter (string)",n(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")),el("ignore_empty (boolean)",n("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")),el("text1 (string, range<string>)",n("Any text item. This could be a string, or an array of strings in a range.")),el("text2 (string, range<string>, repeating)",n("Additional text item(s)."))],returns:["STRING"],compute:function(e,t,...o){const i=os(e),s=rs(t);let n=0;return us(o,((e,t)=>s&&""===os(t)?e:(n++?e+i:"")+os(t)),"")},isExported:!0},_g={description:n("Removes space characters."),args:[el("text (string)",n("The text or reference to a cell containing text to be trimmed."))],returns:["STRING"],compute:function(e){return os(e).trim()},isExported:!0},Fg={description:n("Converts a specified string to uppercase."),args:[el("text (string)",n("The string to convert to uppercase."))],returns:["STRING"],compute:function(e){return os(e).toUpperCase()},isExported:!0},Dg={description:n("Converts a number to text according to a specified format."),args:[el("number (number)",n("The number, date or time to format.")),el("format (string)",n("The pattern by which to format the number, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){return bo(Qi(e),os(t))},isExported:!0};var Lg=Object.freeze({__proto__:null,CHAR:fg,CLEAN:bg,CONCATENATE:vg,EXACT:Sg,FIND:Cg,JOIN:Eg,LEFT:wg,LEN:xg,LOWER:yg,MID:Ig,PROPER:Rg,REPLACE:Tg,RIGHT:Ag,SEARCH:Og,SUBSTITUTE:Mg,TEXTJOIN:Ng,TRIM:_g,UPPER:Fg,TEXT:Dg});const kg={description:n("Creates a hyperlink in a cell."),args:[el("url (string)",n("The full URL of the link enclosed in quotation marks.")),el("link_label (string, optional)",n("The text to display in the cell, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){const o=os(e).trim(),i=os(t)||o;return""===o?i:nt(i,o)},isExported:!0};var Pg=Object.freeze({__proto__:null,HYPERLINK:kg});const Ug=[{name:n("Database"),functions:uh},{name:n("Date"),functions:Zh},{name:n("Financial"),functions:bu},{name:n("Info"),functions:Tu},{name:n("Lookup"),functions:Yu},{name:n("Logical"),functions:ku},{name:n("Math"),functions:ac},{name:n("Misc"),functions:il},{name:n("Operator"),functions:pg},{name:n("Statistical"),functions:Kc},{name:n("Text"),functions:Lg},{name:n("Engineering"),functions:Yh},{name:n("Web"),functions:Pg}],Vg=/^[A-Z0-9\_\.]+$/;function zg(e){return e.map((e=>{if(void 0!==e)return"function"==typeof e?()=>Bg(e()):Bg(e)}))}function Bg(e){return Array.isArray(e)?e.map((e=>e.map((e=>e?.value)))):e?.value}const Hg=new class extends zi{mapping={};add(e,t){if(e=e.toUpperCase(),!Vg.test(e))throw new Error(n("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const o=tl(t);return function(e){let t=!1,o=!1,i=!1;for(let s of e){if(s.type.includes("META")&&s.type.length>1)throw new Error(n("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&&!s.repeating)throw new Error(n("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=o||t||i,r=!(s.optional||s.repeating||s.default);if(e&&r)throw new Error(n("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=s.repeating,o=s.optional,i=s.default}}(o.args),this.mapping[e]=function(...e){const t=o.compute.bind(this),i=o.computeFormat?o.computeFormat.bind(this):()=>{};return{value:t(...zg(e)),format:i(...e)}},super.add(e,o),this}};for(let e of Ug){const t=e.functions;for(let o in t){const i=t[o];i.category=i.category||e.name,o=o.replace(/_/g,"."),Hg.add(o,{isExported:!1,...i})}}const $g={name:e=>{const t=pa(e);return 1===t?n("Insert row"):n("Insert %s rows",t.toString())},isVisible:e=>Aa(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW"},Wg={name:e=>{const t=pa(e);return 1===t?n("Insert row above"):n("Insert %s rows above",t.toString())},execute:Ca,isVisible:e=>Aa(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},Gg={...Wg,name:e=>{const t=pa(e);return 1===t?n("Row above"):n("%s Rows above",t.toString())}},qg={...Wg,name:e=>{const t=pa(e);return 1===t?n("Insert row"):n("Insert %s rows",t.toString())},isVisible:Ta,icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},Zg={execute:e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Rt([...t]),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.bottom,i=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",base:o,quantity:i,dimension:"ROW"})},name:e=>{const t=pa(e);return 1===t?n("Insert row below"):n("Insert %s rows below",t.toString())},isVisible:e=>Aa(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_AFTER"},jg={...Zg,name:e=>{const t=pa(e);return 1===t?n("Row below"):n("%s Rows below",t.toString())}},Yg={name:e=>{const t=ga(e);return 1===t?n("Insert column"):n("Insert %s columns",t.toString())},isVisible:e=>Aa(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL"},Xg={name:e=>{const t=ga(e);return 1===t?n("Insert column left"):n("Insert %s columns left",t.toString())},execute:Ea,isVisible:e=>Aa(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},Kg={...Xg,name:e=>{const t=ga(e);return 1===t?n("Column left"):n("%s Columns left",t.toString())}},Qg={...Xg,name:e=>{const t=ga(e);return 1===t?n("Insert column"):n("Insert %s columns",t.toString())},isVisible:Ta,icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},Jg={name:e=>{const t=ga(e);return 1===t?n("Insert column right"):n("Insert %s columns right",t.toString())},execute:wa,isVisible:e=>Aa(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_AFTER"},ep={...Jg,name:e=>{const t=ga(e);return 1===t?n("Column right"):n("%s Columns right",t.toString())},execute:wa},tp={name:n("Insert cells"),isVisible:e=>Ta(e)&&0===e.model.getters.getActiveCols().size&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_CELL"},op={name:n("Insert cells and shift down"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});ha(e,o)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN"},ip={name:n("Insert cells and shift right"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});ha(e,o)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT"},sp={name:n("Chart"),execute:e=>{const t=e.model.getters,o=e.model.uuidGenerator.uuidv4(),i=t.getActiveSheetId();1===Ri(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection();const s={width:536,height:335},n=function(e,t){const{x:o,y:i}=e.getMainViewportCoordinates(),{scrollX:s,scrollY:n}=e.getActiveSheetScrollInfo(),{width:r,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:o+s+Math.max(0,(r-t.width)/2),y:i+n+Math.max(0,(a-t.height)/2)}}(t,s);e.model.dispatch("CREATE_CHART",{sheetId:i,id:o,position:n,size:s,definition:ia(e.model.getters.getSelectedZone(),e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{id:o}),e.openSidePanel("ChartPanel"))},icon:"o-spreadsheet-Icon.INSERT_CHART"},np={name:n("Image"),description:"Ctrl+O",execute:xa,isVisible:e=>void 0!==e.imageProvider,icon:"o-spreadsheet-Icon.INSERT_IMAGE"},rp={name:n("Function"),icon:"o-spreadsheet-Icon.SHOW_HIDE_FORMULA"},ap={name:n("SUM"),execute:e=>e.startCellEdition("=SUM(")},lp={name:n("AVERAGE"),execute:e=>e.startCellEdition("=AVERAGE(")},cp={name:n("COUNT"),execute:e=>e.startCellEdition("=COUNT(")},hp={name:n("MAX"),execute:e=>e.startCellEdition("=MAX(")},dp={name:n("MIN"),execute:e=>e.startCellEdition("=MIN(")},up={name:n("All"),children:[function(){return mp(Hg.getKeys().filter((e=>!Hg.get(e).hidden)))}]};const gp={name:n("Link"),execute:Ia,icon:"o-spreadsheet-Icon.INSERT_LINK"},pp={name:n("Insert sheet"),execute:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSheetIds().indexOf(t)+1,i=e.model.uuidGenerator.uuidv4();e.model.dispatch("CREATE_SHEET",{sheetId:i,position:o}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:i})},icon:"o-spreadsheet-Icon.INSERT_SHEET"};function mp(e){return e.sort().map(((e,t)=>({name:e,sequence:10*t,execute:t=>t.startCellEdition(`=${e}(`)})))}const fp=new Ln;fp.add("cut",{..._a,sequence:10}).add("copy",{...Na,sequence:20}).add("paste",{...Fa,sequence:30}).add("paste_special",{...Da,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...La,sequence:10}).addChild("paste_format_only",["paste_special"],{...ka,sequence:20}).add("add_row_before",{...qg,sequence:70}).add("add_column_before",{...Qg,sequence:90}).add("insert_cell",{...tp,sequence:100,separator:!0}).addChild("insert_cell_down",["insert_cell"],{...op,name:n("Shift down"),sequence:10}).addChild("insert_cell_right",["insert_cell"],{...ip,name:n("Shift right"),sequence:20}).add("delete_row",{...za,sequence:110,icon:"o-spreadsheet-Icon.DELETE"}).add("delete_column",{...$a,sequence:120,icon:"o-spreadsheet-Icon.DELETE"}).add("delete_cell",{...Ga,sequence:130,separator:!0,icon:"o-spreadsheet-Icon.DELETE"}).addChild("delete_cell_up",["delete_cell"],{...qa,name:n("Shift up"),sequence:10,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP"}).addChild("delete_cell_left",["delete_cell"],{...Za,name:n("Shift left"),sequence:20,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT"}).add("insert_link",{...gp,name:e=>{const t=e.model.getters.getActiveSheetId(),{col:o,row:i}=e.model.getters.getActivePosition(),s=e.model.getters.getEvaluatedCell({sheetId:t,col:o,row:i});return s&&s.link?n("Edit link"):n("Insert link")},sequence:150,separator:!0});const bp={name:n("Sort range"),isVisible:Ta,icon:"o-spreadsheet-Icon.SORT_RANGE"},vp={name:n("Ascending (A ⟶ Z)"),execute:e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();na(e,i,t.cell,o[0],"ascending")},icon:"o-spreadsheet-Icon.SORT_ASCENDING"},Sp={name:n("Descending (Z ⟶ A)"),execute:e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();na(e,i,t.cell,o[0],"descending")},icon:"o-spreadsheet-Icon.SORT_DESCENDING"},Cp={name:n("Create filter"),execute:e=>{const t=e.model.getters.getSelectedZones();1===t.length&&1===Ri(t[0])&&e.model.selection.selectTableAroundSelection();const o=e.model.getters.getActiveSheetId();la(e,o,e.model.getters.getSelectedZones())},isVisible:e=>!Ra(e),isEnabled:e=>(e=>Ti(...e.model.getters.getSelectedZones()))(e),icon:"o-spreadsheet-Icon.MENU_FILTER_ICON"},Ep={name:n("Remove filter"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:t,target:e.model.getters.getSelectedZones()})},isVisible:Ra,icon:"o-spreadsheet-Icon.MENU_FILTER_ICON"},wp={name:n("Split text to columns"),sequence:1,execute:e=>e.openSidePanel("SplitToColumns",{}),isEnabled:e=>e.model.getters.isSingleColSelected(),icon:"o-spreadsheet-Icon.SPLIT_TEXT"},xp={name:n("Automatic"),execute:e=>ma(e,""),isActive:e=>function(e){const t=e.model.getters.getCell(e.model.getters.getActivePosition());return!t||!t.format}(e)},yp={name:n("Number"),description:"1,000.12",execute:e=>ma(e,"#,##0.00"),isActive:e=>nm(e,"#,##0.00")},Ip={name:n("Format as percent"),execute:ya,icon:"o-spreadsheet-Icon.PERCENT"},Rp={name:n("Percent"),description:"10.12%",execute:ya,isActive:e=>nm(e,"0.00%")},Tp={name:n("Currency"),description:"$1,000.12",execute:e=>ma(e,"[$$]#,##0.00"),isActive:e=>nm(e,"[$$]#,##0.00")},Ap={name:n("Currency rounded"),description:"$1,000",execute:e=>ma(e,"[$$]#,##0"),isActive:e=>nm(e,"[$$]#,##0")},Op={name:n("Custom currency"),isVisible:e=>void 0!==e.loadCurrencies,execute:e=>{e.openSidePanel("CustomCurrency",{})}},Mp={name:n("Date"),description:"9/26/2008",execute:e=>ma(e,"m/d/yyyy"),isActive:e=>nm(e,"m/d/yyyy")},Np={name:n("Time"),description:"10:43:00 PM",execute:e=>ma(e,"hh:mm:ss a"),isActive:e=>nm(e,"hh:mm:ss a")},_p={name:n("Date time"),description:"9/26/2008 22:43:00",execute:e=>ma(e,"m/d/yyyy hh:mm:ss"),isActive:e=>nm(e,"m/d/yyyy hh:mm:ss")},Fp={name:n("Duration"),description:"27:51:38",execute:e=>ma(e,"hhhh:mm:ss"),isActive:e=>nm(e,"hhhh:mm:ss")},Dp={name:n("Increase decimal places"),icon:"o-spreadsheet-Icon.INCREASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:1})},Lp={name:n("Decrease decimal places"),icon:"o-spreadsheet-Icon.DECRASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:-1})},kp={name:n("Bold"),description:"Ctrl+B",execute:e=>fa(e,{bold:!e.model.getters.getCurrentStyle().bold}),icon:"o-spreadsheet-Icon.BOLD",isActive:e=>!!e.model.getters.getCurrentStyle().bold},Pp={name:n("Italic"),description:"Ctrl+I",execute:e=>fa(e,{italic:!e.model.getters.getCurrentStyle().italic}),icon:"o-spreadsheet-Icon.ITALIC",isActive:e=>!!e.model.getters.getCurrentStyle().italic},Up={name:n("Underline"),description:"Ctrl+U",execute:e=>fa(e,{underline:!e.model.getters.getCurrentStyle().underline}),icon:"o-spreadsheet-Icon.UNDERLINE",isActive:e=>!!e.model.getters.getCurrentStyle().underline},Vp={name:n("Strikethrough"),execute:e=>fa(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),icon:"o-spreadsheet-Icon.STRIKE",isActive:e=>!!e.model.getters.getCurrentStyle().strikethrough},zp={name:n("Font size"),children:fe.map((e=>({name:e.toString(),sequence:e,id:`font_size_${e}`,execute:t=>fa(t,{fontSize:e}),isActive:t=>function(e,t){const o=e.model.getters.getCurrentStyle().fontSize||Z;return o===t}(t,e)}))),icon:"o-spreadsheet-Icon.FONT_SIZE"},Bp={name:n("Alignment"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},Hp={name:n("Horizontal align"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},$p={name:n("Left"),description:"Ctrl+Shift+L",execute:e=>fa(e,{align:"left"}),isActive:e=>"left"===rm(e),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},Wp={name:n("Center"),description:"Ctrl+Shift+E",execute:e=>fa(e,{align:"center"}),isActive:e=>"center"===rm(e),icon:"o-spreadsheet-Icon.ALIGN_CENTER"},Gp={name:n("Right"),description:"Ctrl+Shift+R",execute:e=>fa(e,{align:"right"}),isActive:e=>"right"===rm(e),icon:"o-spreadsheet-Icon.ALIGN_RIGHT"},qp={name:n("Vertical align"),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},Zp={name:n("Top"),execute:e=>fa(e,{verticalAlign:"top"}),isActive:e=>"top"===(e.model.getters.getCurrentStyle().verticalAlign||Y),icon:"o-spreadsheet-Icon.ALIGN_TOP"},jp={name:n("Middle"),execute:e=>fa(e,{verticalAlign:"middle"}),isActive:e=>"middle"===(e.model.getters.getCurrentStyle().verticalAlign||Y),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},Yp={name:n("Bottom"),execute:e=>fa(e,{verticalAlign:"bottom"}),isActive:e=>"bottom"===(e.model.getters.getCurrentStyle().verticalAlign||Y),icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"},Xp={name:n("Wrapping"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},Kp={name:n("Overflow"),execute:e=>fa(e,{wrapping:"overflow"}),isActive:e=>"overflow"===(e.model.getters.getCurrentStyle().wrapping||"overflow"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},Qp={name:n("Wrap"),execute:e=>fa(e,{wrapping:"wrap"}),isActive:e=>"wrap"===e.model.getters.getCurrentStyle().wrapping,icon:"o-spreadsheet-Icon.WRAPPING_WRAP"},Jp={name:n("Clip"),execute:e=>fa(e,{wrapping:"clip"}),isActive:e=>"clip"===e.model.getters.getCurrentStyle().wrapping,icon:"o-spreadsheet-Icon.WRAPPING_CLIP"},em={name:n("Text Color"),icon:"o-spreadsheet-Icon.TEXT_COLOR"},tm={name:n("Fill Color"),icon:"o-spreadsheet-Icon.FILL_COLOR"},om={name:n("Conditional formatting"),execute:e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},icon:"o-spreadsheet-Icon.CONDITIONAL_FORMAT"},im={name:n("Paint Format"),execute:e=>e.model.dispatch("ACTIVATE_PAINT_FORMAT",{target:e.model.getters.getSelectedZones()}),icon:"o-spreadsheet-Icon.PAINT_FORMAT",isActive:e=>e.model.getters.isPaintingFormat()},sm={name:n("Clear formatting"),description:"Ctrl+<",execute:e=>{e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},icon:"o-spreadsheet-Icon.CLEAR_FORMAT"};function nm(e,t){return e.model.getters.getCell(e.model.getters.getActivePosition())?.format===t}function rm(e){const t=e.model.getters.getCurrentStyle();if(t.align)return t.align;return e.model.getters.getActiveCell().defaultAlign}var am=Object.freeze({__proto__:null,formatNumberAutomatic:xp,formatNumberNumber:yp,formatPercent:Ip,formatNumberPercent:Rp,formatNumberCurrency:Tp,formatNumberCurrencyRounded:Ap,formatCustomCurrency:Op,formatNumberDate:Mp,formatNumberTime:Np,formatNumberDateTime:_p,formatNumberDuration:Fp,incraseDecimalPlaces:Dp,decraseDecimalPlaces:Lp,formatBold:kp,formatItalic:Pp,formatUnderline:Up,formatStrikethrough:Vp,formatFontSize:zp,formatAlignment:Bp,formatAlignmentHorizontal:Hp,formatAlignmentLeft:$p,formatAlignmentCenter:Wp,formatAlignmentRight:Gp,formatAlignmentVertical:qp,formatAlignmentTop:Zp,formatAlignmentMiddle:jp,formatAlignmentBottom:Yp,formatWrapping:Xp,formatWrappingOverflow:Kp,formatWrappingWrap:Qp,formatWrappingClip:Jp,textColor:em,fillColor:tm,formatCF:om,paintFormat:im,clearFormat:sm});function lm(e,t,o){const i=e.model.getters.getActiveSheetId(),s="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(s,{sheetId:i,quantity:o}).isCancelledBecause(66)&&e.raiseError(dr)}const cm={name:e=>{const t=e.model.getters.getElementsFromSelection("COL");let o=t[0],i=t[t.length-1];return 1===t.length?n("Hide column %s",Bt(o).toString()):i-o+1===t.length?n("Hide columns %s - %s",Bt(o).toString(),Bt(i).toString()):n("Hide columns")},execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getElementsFromSelection("COL");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"COL",o)},icon:"o-spreadsheet-Icon.HIDE_COL"},hm={name:n("Unhide columns"),execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))}},dm={name:n("Unhide all columns"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"COL",elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0},um={name:e=>{const t=e.model.getters.getElementsFromSelection("ROW");let o=t[0],i=t[t.length-1];return 1===t.length?n("Hide row %s",(o+1).toString()):i-o+1===t.length?n("Hide rows %s - %s",(o+1).toString(),(i+1).toString()):n("Hide rows")},execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getElementsFromSelection("ROW");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"ROW",o)},icon:"o-spreadsheet-Icon.HIDE_ROW"},gm={name:n("Unhide rows"),execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))}},pm={name:n("Unhide all rows"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"ROW",elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0},mm={name:n("Unfreeze"),isVisible:e=>{const{xSplit:t,ySplit:o}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+o>0},execute:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),icon:"o-spreadsheet-Icon.UNFREEZE"},fm={name:n("Freeze"),icon:"o-spreadsheet-Icon.FREEZE"},bm={name:n("No rows"),execute:e=>e.model.dispatch("UNFREEZE_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit},vm={name:n("1 row"),execute:e=>lm(e,"ROW",1),isReadonlyAllowed:!0},Sm={name:n("2 rows"),execute:e=>lm(e,"ROW",2),isReadonlyAllowed:!0},Cm={name:n("Up to current row"),execute:e=>{const{bottom:t}=e.model.getters.getSelectedZone();lm(e,"ROW",t+1)},isReadonlyAllowed:!0},Em={name:n("No columns"),execute:e=>e.model.dispatch("UNFREEZE_COLUMNS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit},wm={name:n("1 column"),execute:e=>lm(e,"COL",1),isReadonlyAllowed:!0},xm={name:n("2 columns"),execute:e=>lm(e,"COL",2),isReadonlyAllowed:!0},ym={name:n("Up to current column"),execute:e=>{const{right:t}=e.model.getters.getSelectedZone();lm(e,"COL",t+1)},isReadonlyAllowed:!0},Im={name:e=>e.model.getters.getGridLinesVisibility(e.model.getters.getActiveSheetId())?n("Hide gridlines"):n("Show gridlines"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},icon:"o-spreadsheet-Icon.SHOW_HIDE_GRID"},Rm={name:e=>e.model.getters.shouldShowFormulas()?n("Hide formulas"):n("Show formulas"),execute:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,icon:"o-spreadsheet-Icon.SHOW_HIDE_FORMULA"},Tm={name:e=>Am(e)?n("Remove selected filters"):n("Create filter"),isActive:e=>Am(e),isEnabled:e=>!Om(e),execute:e=>function(e){if(Am(e))return void e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()});if(Om(e))return;e.model.selection.selectTableAroundSelection();const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();la(e,t,o)}(e),icon:"o-spreadsheet-Icon.FILTER_ICON_INACTIVE"};function Am(e){const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,o)}function Om(e){return!Ti(...e.model.getters.getSelectedZones())}var Mm=Object.freeze({__proto__:null,hideCols:cm,unhideCols:hm,unhideAllCols:dm,hideRows:um,unhideRows:gm,unhideAllRows:pm,unFreezePane:mm,freezePane:fm,unFreezeRows:bm,freezeFirstRow:vm,freezeSecondRow:Sm,freezeCurrentRow:Cm,unFreezeCols:Em,freezeFirstCol:wm,freezeSecondCol:xm,freezeCurrentCol:ym,viewGridlines:Im,viewFormulas:Rm,createRemoveFilter:Tm});const Nm=new Ln;Nm.add("cut",{..._a,sequence:10}).add("copy",{...Na,sequence:20}).add("paste",{...Fa,sequence:30}).add("paste_special",{...Da,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...La,sequence:10}).addChild("paste_format_only",["paste_special"],{...ka,sequence:20}).add("sort_columns",{...bp,name:e=>e.model.getters.getActiveCols().size>1?n("Sort columns"):n("Sort column"),sequence:50,separator:!0}).addChild("sort_ascending",["sort_columns"],{...vp,sequence:10}).addChild("sort_descending",["sort_columns"],{...Sp,sequence:20}).add("add_column_before",{...Xg,sequence:70}).add("add_column_after",{...Jg,sequence:80}).add("delete_column",{...Ha,sequence:90,icon:"o-spreadsheet-Icon.DELETE"}).add("clear_column",{...Wa,sequence:100,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_columns",{...cm,sequence:105,separator:!0}).add("unhide_columns",{...hm,sequence:106,separator:!0}).add("conditional_formatting",{...om,sequence:110});const _m=new Ln;_m.add("format_number_automatic",{...xp,sequence:10,separator:!0}).add("format_number_number",{...yp,sequence:20}).add("format_number_percent",{...Rp,sequence:30,separator:!0}).add("format_number_currency",{...Tp,sequence:40}).add("format_number_currency_rounded",{...Ap,sequence:50}).add("format_custom_currency",{...Op,sequence:60,separator:!0}).add("format_number_date",{...Mp,sequence:70}).add("format_number_time",{...Np,sequence:80}).add("format_number_date_time",{..._p,sequence:90}).add("format_number_duration",{...Fp,sequence:100,separator:!0});const Fm={name:n("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[()=>_m.getAll()]},Dm=new Ln;Dm.add("cut",{..._a,sequence:10}).add("copy",{...Na,sequence:20}).add("paste",{...Fa,sequence:30}).add("paste_special",{...Da,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...La,sequence:10}).addChild("paste_format_only",["paste_special"],{...ka,sequence:20}).add("add_row_before",{...Wg,sequence:50}).add("add_row_after",{...Zg,sequence:60}).add("delete_row",{...Va,sequence:70,icon:"o-spreadsheet-Icon.DELETE"}).add("clear_row",{...Ba,sequence:80,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_rows",{...um,sequence:85,separator:!0}).add("unhide_rows",{...gm,sequence:86,separator:!0}).add("conditional_formatting",{...om,sequence:90});const Lm=new Ln;Lm.add("file",{name:n("File"),sequence:10}).add("edit",{name:n("Edit"),sequence:20}).addChild("undo",["edit"],{...Oa,sequence:10}).addChild("redo",["edit"],{...Ma,sequence:20,separator:!0}).addChild("copy",["edit"],{...Na,sequence:30}).addChild("cut",["edit"],{..._a,sequence:40}).addChild("paste",["edit"],{...Fa,sequence:50}).addChild("paste_special",["edit"],{...Da,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...La,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{...ka,sequence:20}).addChild("find_and_replace",["edit"],{...Pa,sequence:65,separator:!0}).addChild("delete",["edit"],{name:n("Delete"),icon:"o-spreadsheet-Icon.DELETE",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...Ua,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...Va,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...Ha,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{...qa,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...Za,sequence:50}).addChild("edit_unhide_columns",["edit"],{...dm,sequence:80}).addChild("edit_unhide_rows",["edit"],{...pm,sequence:80}).add("view",{name:n("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...mm,sequence:4}).addChild("freeze_panes",["view"],{...fm,sequence:5,separator:!0}).addChild("unfreeze_rows",["view","freeze_panes"],{...bm,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...vm,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...Sm,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...Cm,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...Em,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...wm,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...xm,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...ym,sequence:40}).addChild("view_gridlines",["view"],{...Im,sequence:10}).addChild("view_formulas",["view"],{...Rm,sequence:15}).add("insert",{name:n("Insert"),sequence:40}).addChild("insert_row",["insert"],{...$g,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...Gg,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...jg,sequence:20}).addChild("insert_column",["insert"],{...Yg,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...Kg,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...ep,sequence:20}).addChild("insert_cell",["insert"],{...tp,sequence:43}).addChild("insert_cell_down",["insert","insert_cell"],{...op,name:n("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...ip,name:n("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...pp,sequence:80,separator:!0}).addChild("insert_chart",["insert"],{...sp,sequence:50}).addChild("insert_image",["insert"],{...np,sequence:55}).addChild("insert_function",["insert"],{...rp,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...ap,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...lp,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{...cp,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...hp,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...dp,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...up,sequence:50}).addChild("categories_function_list",["insert","insert_function"],(()=>{const e=Hg.content;return[...new Set(Hg.getAll().filter((e=>!e.hidden)).map((e=>e.category)))].filter(dt).sort().map(((t,o)=>{const i=Object.keys(e).filter((o=>e[o].category===t&&!e[o].hidden));return{name:t,children:mp(i)}}))})).addChild("insert_link",["insert"],{...gp,separator:!0,sequence:70}).add("format",{name:n("Format"),sequence:50}).addChild("format_number",["format"],{...Fm,name:n("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{...kp,sequence:20}).addChild("format_italic",["format"],{...Pp,sequence:30}).addChild("format_underline",["format"],{...Up,sequence:40}).addChild("format_strikethrough",["format"],{...Vp,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...zp,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...Bp,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...$p,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...Wp,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...Gp,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{...Zp,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...jp,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{...Yp,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...Xp,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...Kp,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...Qp,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...Jp,sequence:30}).addChild("format_cf",["format"],{...om,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...sm,sequence:100,separator:!0}).add("data",{name:n("Data"),sequence:60}).addChild("sort_range",["data"],{...bp,sequence:10,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...vp,sequence:10}).addChild("sort_descending",["data","sort_range"],{...Sp,sequence:20}).addChild("split_to_columns",["data"],{...wp,sequence:20,separator:!0}).addChild("add_data_filter",["data"],{...Cp,sequence:30}).addChild("remove_data_filter",["data"],{...Ep,sequence:30});const km=new class extends zi{addTransformation(e,t,o){for(let i of t)this.content[i]||(this.content[i]=new Map),this.content[i].set(e,o);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},Pm={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function Um(e,t){const o=Pm[e.key];e.shiftKey?t.resizeAnchorZone(o,un(e)?"end":1):t.moveAnchorCell(o,un(e)?"end":1)}const Vm=new ti;Ni`
|
|
353
|
+
`;class qr extends t.Component{static template="o-spreadsheet-ChartFigure";static components={};onDoubleClick(){this.env.model.dispatch("SELECT_FIGURE",{id:this.props.figure.id}),this.env.openSidePanel("ChartPanel")}get chartType(){return this.env.model.getters.getChartType(this.props.figure.id)}get chartComponent(){const e=this.chartType,t=Wr.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}qr.props={figure:Object,onFigureDeleted:Function};class Zr extends t.Component{static template="o-spreadsheet-ImageFigure";static components={};get figureId(){return this.props.figure.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}}function jr(e,t){const o=Be(t),i=e.getSheetViewDimension(),s=i.width,n=i.height;if(o.width>s){const e=s/o.width;o.width=s,o.height=o.height*e}if(o.height>n){const e=n/o.height;o.height=n,o.width=o.width*e}return o}Zr.props={figure:Object,onFigureDeleted:Function};const Yr=new zi;function Xr(e,t){return{id:"copy",name:n("Copy"),sequence:2,description:"Ctrl+C",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("COPY"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function Kr(e,t){return{id:"cut",name:n("Cut"),sequence:3,description:"Ctrl+X",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("CUT"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function Qr(e,t,o){return{id:"delete",name:n("Delete"),sequence:10,execute:()=>{o.model.dispatch("DELETE_FIGURE",{sheetId:o.model.getters.getActiveSheetId(),id:e}),t()}}}Yr.add("chart",{Component:qr,SidePanelComponent:"ChartPanel",menuBuilder:function(e,t,o){return _n([{id:"edit",name:n("Edit"),sequence:1,execute:()=>{o.model.dispatch("SELECT_FIGURE",{id:e}),o.openSidePanel("ChartPanel")}},Xr(e,o),Kr(e,o),Qr(e,t,o)])}}),Yr.add("image",{Component:Zr,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t,o){return _n([Xr(e,o),Kr(e,o),{id:"reset_size",name:n("Reset size"),sequence:4,execute:()=>{const t=o.model.getters.getImageSize(e),{height:i,width:s}=jr(o.model.getters,t);o.model.dispatch("UPDATE_FIGURE",{sheetId:o.model.getters.getActiveSheetId(),id:e,height:i,width:s})}},Qr(e,t,o)])}});const Jr=(new zi).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let o=e.base;"after"===e.position&&o++;for(let i=0;i<e.quantity;i++)t.push(i+o);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],o=[...e.elements].sort(((e,t)=>e-t));for(let i of Qe(o)){const o=0===i[0]?0:i[0]-1,s=0===i[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:i.length,base:o,sheetId:e.sheetId,position:s})}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 Os.values())Jr.contains(e)||Jr.add(e,ea);function ea(e){return[e]}const ta={MergeIsDestructive:n("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:n("You can't merge cells inside of an existing filter.")};function oa(e,t){const o=$r.getAll().find((t=>t.match(e.type)));if(!o)throw new Error("Unknown chart type.");return o.transformDefinition(e,t)}function ia(e,t){let o=e;e.left!==e.right&&(o={...e,left:e.left+1});const i=[ni(o)],n=t.getActiveSheetId(),r=t.getCell({sheetId:n,col:e.left,row:e.top});if(1===Ri(e)&&r?.content)return{type:"scorecard",title:"",background:r.style?.fillColor||void 0,keyValue:ni(e),baselineMode:se,baselineColorUp:ne,baselineColorDown:re};let a="";const l=t.getEvaluatedCellsInZone(n,{...o,bottom:o.top}),c=!!l.find((e=>e.type!==ys.empty&&e.type!==ys.number));if(c){const e=l.filter((e=>e.type!==ys.error&&e.type!==ys.empty)).map((e=>e.formattedValue)),t=e.splice(-1)[0];a=e.join(", "),t&&(a+=(a?" "+s("and")+" ":"")+t)}let h;e.left!==e.right&&(h=ni({...e,right:e.left}));const d=o.right===o.left?"none":"top";return Dr(h?t.getRangeFromSheetXC(n,h):void 0,t)?{title:a,dataSets:i,labelsAsText:!1,stacked:!1,aggregated:!1,cumulative:!1,labelRange:h,type:"line",dataSetsHaveTitle:c,verticalAxisPosition:"left",legendPosition:d}:{title:a,dataSets:i,labelRange:h,type:"bar",stacked:!1,aggregated:!1,dataSetsHaveTitle:c,verticalAxisPosition:"left",legendPosition:d}}const sa=[ys.number,ys.error,ys.text,ys.boolean];function na(e,t,o,i,s){let r=Ns.Success,a=i.right>i.left;if(e.model.getters.doesIntersectMerge(t,i)){let o;a=!1;for(let s=i.top;s<=i.bottom;s++){o=[];for(let n=i.left;n<=i.right;n++){let i=e.model.getters.getMerge({sheetId:t,col:n,row:s});i&&!o.includes(i.id.toString())&&o.push(i.id.toString())}if(o.length>=2){a=!0;break}}}const{col:l,row:c}=o;if(a)r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s});else{const o=e.model.getters.getContiguousZone(t,i);ui(o,i)?r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s}):e.askConfirmation(n("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?"),(()=>{i=o,r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s})}),(()=>{r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s})}))}if(r.isCancelledBecause(64)){const{col:t,row:s}=o;e.model.selection.selectZone({cell:{col:t,row:s},zone:i}),e.raiseError(n("Cannot sort. To sort, select only cells or only merges that have the same size."))}}function ra(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause(19)&&e.raiseError(n("This operation is not allowed with multiple selections."))}const aa={filterOverlap:n("You cannot create overlapping filters."),nonContinuousTargets:n("A filter can only be created on a continuous selection."),mergeInFilter:n("You can't create a filter over a range that contains a merge.")};function la(e,t,o){const i=e.model.dispatch("CREATE_FILTER_TABLE",{target:o,sheetId:t});i.isCancelledBecause(79)?e.raiseError(aa.filterOverlap):i.isCancelledBecause(81)?e.raiseError(aa.mergeInFilter):i.isCancelledBecause(82)&&e.raiseError(aa.nonContinuousTargets)}const ca={wrongPasteSelection:n("This operation is not allowed with multiple selections."),willRemoveExistingMerge:n("This operation is not possible due to a merge. Please remove the merges first than try again."),wrongFigurePasteOption:n("Cannot do a special paste of a figure."),frozenPaneOverlap:n("Cannot paste merged cells over a frozen pane.")};function ha(e,t){t.isSuccessful||(t.reasons.includes(20)?e.raiseError(ca.wrongPasteSelection):t.reasons.includes(2)?e.raiseError(ca.willRemoveExistingMerge):t.reasons.includes(22)?e.raiseError(ca.wrongFigurePasteOption):t.reasons.includes(76)&&e.raiseError(ca.frozenPaneOverlap))}function da(e,t,o){const i=e.model.dispatch("PASTE",{target:t,pasteOption:o});ha(e,i)}function ua(e,t,o){const i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,text:o});ha(e,i)}function ga(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 pa(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 ma(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function fa(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const ba=async e=>va(e,"onlyValue");async function va(e,t){const o=e.model.getters.getClipboardTextContent(),i=await e.clipboard.readText();switch(i.status){case"ok":const s=e.model.getters.getSelectedZones();i&&i.content!==o?ua(e,s,i.content):da(e,s,t);break;case"notImplemented":e.raiseError(n("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(n("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const Sa=(e,t)=>{const o=t.model.getters.getActiveSheetId(),i=t.model.getters.getElementsFromSelection(e),s=t.model.getters.checkElementsIncludeAllVisibleHeaders(o,e,i),n=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(o,e,i);return!s&&!n},Ca=e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Tt([...t]),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.top,i=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",base:o,quantity:i,dimension:"ROW"})},Ea=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Tt([...t]),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.left,i=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",dimension:"COL",base:o,quantity:i})},wa=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Rt([...t]),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.right,i=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",dimension:"COL",base:o,quantity:i})};const xa=async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),o=e.model.uuidGenerator.uuidv4(),i=await async function(e){try{return await e.imageProvider.requestImage()}catch{return void e.raiseError(n("An unexpected error occurred during the image transfer"))}}(e);if(!i)throw new Error("No image provider was given to the environment");const s=jr(e.model.getters,i.size),r=function(e,t){const{x:o,y:i}=e.getMainViewportCoordinates(),{scrollX:s,scrollY:n}=e.getActiveSheetScrollInfo(),r=e.getSheetViewDimension(),a=e.getVisibleRect(e.getActiveMainViewport()),l=Math.min(a.width,r.width-o),c=Math.min(a.height,r.height-i);return{x:o+s+Math.max(0,(l-t.width)/2),y:i+n+Math.max(0,(c-t.height)/2)}}(e.model.getters,s);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:o,position:r,size:s,definition:i})}},ya=e=>ma(e,"0.00%"),Ia=e=>{let{col:t,row:o}=e.model.getters.getActivePosition();e.model.dispatch("OPEN_CELL_POPOVER",{col:t,row:o,popoverType:"LinkEditor"})},Ra=e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,o)},Ta=e=>1===e.model.getters.getSelectedZones().length,Aa=(e,t)=>{if(!Ta(e))return!1;const o="COL"===t?e.model.getters.getActiveCols():e.model.getters.getActiveRows(),i="COL"===t?e.model.getters.getActiveRows():e.model.getters.getActiveCols(),s=e.model.getters.getActiveSheetId(),n=ui(e.model.getters.getSelectedZone(),e.model.getters.getSheetZone(s));return function(e){const t=Array.from(e).sort(((e,t)=>e-t));for(let e=1;e<t.length;e++)if(t[e]-t[e-1]!=1)return!1;return!0}(o)&&(0===i.size||n)},Oa={name:n("Undo"),description:"Ctrl+Z",execute:e=>e.model.dispatch("REQUEST_UNDO"),isEnabled:e=>e.model.getters.canUndo(),icon:"o-spreadsheet-Icon.UNDO"},Ma={name:n("Redo"),description:"Ctrl+Y",execute:e=>e.model.dispatch("REQUEST_REDO"),isEnabled:e=>e.model.getters.canRedo(),icon:"o-spreadsheet-Icon.REDO"},Na={name:n("Copy"),description:"Ctrl+C",isReadonlyAllowed:!0,execute:async e=>{e.model.dispatch("COPY"),await e.clipboard.write(e.model.getters.getClipboardContent())},icon:"o-spreadsheet-Icon.COPY"},_a={name:n("Cut"),description:"Ctrl+X",execute:async e=>{ra(e),await e.clipboard.write(e.model.getters.getClipboardContent())},icon:"o-spreadsheet-Icon.CUT"},Fa={name:n("Paste"),description:"Ctrl+V",execute:async e=>va(e),icon:"o-spreadsheet-Icon.PASTE"},Da={name:n("Paste special"),isVisible:e=>!e.model.getters.isCutOperation(),icon:"o-spreadsheet-Icon.PASTE"},La={name:n("Paste value only"),description:"Ctrl+Shift+V",execute:ba},Pa={name:n("Paste format only"),execute:e=>da(e,e.model.getters.getSelectedZones(),"onlyFormat")},ka={name:n("Find and replace"),description:"Ctrl+H",isReadonlyAllowed:!0,execute:e=>{e.openSidePanel("FindAndReplace",{})},icon:"o-spreadsheet-Icon.FIND_AND_REPLACE"},Ua={name:n("Delete values"),execute:e=>e.model.dispatch("DELETE_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},Va={name:e=>{if(e.model.getters.getSelectedZones().length>1)return n("Delete rows");let t,o;const i=e.model.getters.getActiveRows();if(0!==i.size)t=Tt([...i]),o=Rt([...i]);else{const i=e.model.getters.getSelectedZones()[0];t=i.top,o=i.bottom}return t===o?n("Delete row %s",(t+1).toString()):n("Delete rows %s - %s",(t+1).toString(),(o+1).toString())},execute:e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){const o=e.model.getters.getSelectedZones()[0];for(let e=o.top;e<=o.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>Sa("ROW",e)},za={...Va,isVisible:Ta},Ba={name:e=>{if(e.model.getters.getSelectedZones().length>1)return n("Clear rows");let t,o;const i=e.model.getters.getActiveRows();if(0!==i.size)t=Tt([...i]),o=Rt([...i]);else{const i=e.model.getters.getSelectedZones()[0];t=i.top,o=i.bottom}return t===o?n("Clear row %s",(t+1).toString()):n("Clear rows %s - %s",(t+1).toString(),(o+1).toString())},execute:e=>{const t=e.model.getters.getActiveSheetId(),o=[...e.model.getters.getActiveRows()].map((o=>e.model.getters.getRowsZone(t,o,o)));e.model.dispatch("DELETE_CONTENT",{target:o,sheetId:e.model.getters.getActiveSheetId()})}},Ha={name:e=>{if(e.model.getters.getSelectedZones().length>1)return n("Delete columns");let t,o;const i=e.model.getters.getActiveCols();if(0!==i.size)t=Tt([...i]),o=Rt([...i]);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?n("Delete column %s",Bt(t)):n("Delete columns %s - %s",Bt(t),Bt(o))},execute:e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){const o=e.model.getters.getSelectedZones()[0];for(let e=o.left;e<=o.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>Sa("COL",e)},$a={...Ha,isVisible:Ta},Wa={name:e=>{if(e.model.getters.getSelectedZones().length>1)return n("Clear columns");let t,o;const i=e.model.getters.getActiveCols();if(0!==i.size)t=Tt([...i]),o=Rt([...i]);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?n("Clear column %s",Bt(t)):n("Clear columns %s - %s",Bt(t),Bt(o))},execute:e=>{const t=e.model.getters.getActiveSheetId(),o=[...e.model.getters.getActiveCols()].map((o=>e.model.getters.getColsZone(t,o,o)));e.model.dispatch("DELETE_CONTENT",{target:o,sheetId:e.model.getters.getActiveSheetId()})}},Ga={name:n("Delete cells"),isVisible:Ta},qa={name:n("Delete cell and shift up"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});ha(e,o)}},Za={name:n("Delete cell and shift left"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});ha(e,o)}},ja={name:n("Merge cells"),isEnabled:e=>!Ya(e),isActive:e=>Xa(e),execute:e=>function(e){if(Ya(e))return;const t=e.model.getters.getSelectedZones(),o=[t[t.length-1]],i=e.model.getters.getActiveSheetId();Xa(e)?e.model.dispatch("REMOVE_MERGE",{sheetId:i,target:o}):function(e,t,o){const i=e.model.dispatch("ADD_MERGE",{sheetId:t,target:o});i.isCancelledBecause(81)?e.raiseError(ta.MergeInFilter):i.isCancelledBecause(3)&&e.askConfirmation(ta.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:o,force:!0})}))}(e,i,o)}(e),icon:"o-spreadsheet-Icon.MERGE_CELL"};function Ya(e){const t=e.model.getters.getSelectedZones(),{top:o,left:i,right:s,bottom:n}=e.model.getters.getSelectedZone(),{sheetId:r}=e.model.getters.getActivePosition(),{xSplit:a,ySplit:l}=e.model.getters.getPaneDivisions(r);return t.length>1||o===n&&i===s||i<a&&a<=s||o<l&&l<=n}function Xa(e){if(!Ya(e)){const t=e.model.getters.getSelectedZones(),{col:o,row:i,sheetId:s}=e.model.getters.getActivePosition(),n=e.model.getters.expandZone(s,yi({col:o,row:i}));return ui(t[0],n)}return!1}var Ka=Object.freeze({__proto__:null,undo:Oa,redo:Ma,copy:Na,cut:_a,paste:Fa,pasteSpecial:Da,pasteSpecialValue:La,pasteSpecialFormat:Pa,findAndReplace:ka,deleteValues:Ua,deleteRows:Va,deleteRow:za,clearRows:Ba,deleteCols:Ha,deleteCol:$a,clearCols:Wa,deleteCells:Ga,deleteCellShiftUp:qa,deleteCellShiftLeft:Za,mergeCells:ja});const Qa=/(.*?)\((.*?)\)(.*)/,Ja=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function el(e,t=""){return function(e,t){let o=e.match(Qa),i=o[1].trim();if(!i)throw new Error(`Function argument definition is missing a name: '${e}'.`);let s,n=[],r=!1,a=!1,l=!1;for(let e of o[2].split(",")){const t=e.trim().toUpperCase();let o=Ja.find((e=>t===e));o?n.push(o):"RANGE<ANY>"===t?n.push("RANGE"):"OPTIONAL"===t?r=!0:"REPEATING"===t?a=!0:"LAZY"===t?l=!0:t.startsWith("DEFAULT=")&&(s=e.trim().slice(8))}const c={name:i,description:t,type:n};r&&(c.optional=!0);a&&(c.repeating=!0);l&&(c.lazy=!0);void 0!==s&&(c.default=!0,c.defaultValue=s);return c}(e,t)}function tl(e){let t=0,o=0,i=0;for(let s of e.args)t++,s.optional||s.repeating||s.default||o++,s.repeating&&i++;const s=e;return s.minArgRequired=o,s.maxArgPossible=i?1/0:t,s.nbrArgRepeating=i,s.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const o=e-t;return e=>{if(e<=o)return e;return o+((e-o)%t||t)}}(t,i),s.hidden=e.hidden||!1,s}const ol={description:n("Apply a large number format"),args:[el("value (number)",n("The number.")),el("unit (string, optional)",n("The formatting unit. Use 'k', 'm', or 'b' to force the unit"))],returns:["NUMBER"],computeFormat:(e,t)=>{const o=Math.abs(Qi(e.value)),i=e.format;if(void 0!==t){const e=t?.value;switch(e){case"k":return Mo(i,1e3,"k");case"m":return Mo(i,1e6,"m");case"b":return Mo(i,1e9,"b");default:throw new Error(n("The formatting unit should be 'k', 'm' or 'b'."))}}return o<1e5?Mo(i,0,""):o<1e8?Mo(i,1e3,"k"):o<1e11?Mo(i,1e6,"m"):Mo(i,1e9,"b")},compute:function(e){return Qi(e)}};var il=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:ol});const sl=/^-?[a-z0-9]+$/i,nl={description:n("Absolute value of a number."),args:[el("value (number)",n("The number of which to return the absolute value."))],returns:["NUMBER"],compute:function(e){return Math.abs(Qi(e))},isExported:!0},rl={description:n("Inverse cosine of a value, in radians."),args:[el("value (number)",n("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>Math.abs(t)<=1),n("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},al={description:n("Inverse hyperbolic cosine of a number."),args:[el("value (number)",n("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=Qi(e);return Xi((()=>t>=1),n("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},ll={description:n("Inverse cotangent of a value."),args:[el("value (number)",n("The value for which to calculate the inverse cotangent."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},cl={description:n("Inverse hyperbolic cotangent of a value."),args:[el("value (number)",n("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=Qi(e);return Xi((()=>Math.abs(t)>1),n("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},hl={description:n("Inverse sine of a value, in radians."),args:[el("value (number)",n("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>Math.abs(t)<=1),n("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},dl={description:n("Inverse hyperbolic sine of a number."),args:[el("value (number)",n("The value for which to calculate the inverse hyperbolic sine."))],returns:["NUMBER"],compute:function(e){return Math.asinh(Qi(e))},isExported:!0},ul={description:n("Inverse tangent of a value, in radians."),args:[el("value (number)",n("The value for which to calculate the inverse tangent."))],returns:["NUMBER"],compute:function(e){return Math.atan(Qi(e))},isExported:!0},gl={description:n("Angle from the X axis to a point (x,y), in radians."),args:[el("x (number)",n("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),el("y (number)",n("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 o=Qi(e),i=Qi(t);return Xi((()=>0!==o||0!==i),n("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(i,o)},isExported:!0},pl={description:n("Inverse hyperbolic tangent of a number."),args:[el("value (number)",n("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>Math.abs(t)<1),n("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},ml={description:n("Rounds number up to nearest multiple of factor."),args:[el("value (number)",n("The value to round up to the nearest integer multiple of factor.")),el("factor (number, default=1)",n("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){const o=Qi(e),i=Qi(t);return Xi((()=>i>=0||o<=0),n("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),o.toString())),i?Math.ceil(o/i)*i:0},isExported:!0},fl={description:n("Rounds number up to nearest multiple of factor."),args:[el("number (number)",n("The value to round up to the nearest integer multiple of significance.")),el("significance (number, default=1)",n("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),el("mode (number, default=0)",n("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=>e?.format,compute:function(e,t=1,o=0){let i=Qi(t);if(0===i)return 0;const s=Qi(e);if(i=Math.abs(i),s>=0)return Math.ceil(s/i)*i;return 0===Qi(o)?-Math.floor(Math.abs(s)/i)*i:-Math.ceil(Math.abs(s)/i)*i},isExported:!0},bl={description:n("Rounds number up to nearest multiple of factor."),args:[el("number (number)",n("The value to round up to the nearest integer multiple of significance.")),el("significance (number, default=1)",n("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){return fl.compute(e,t,0)},isExported:!0},vl={description:n("Cosine of an angle provided in radians."),args:[el("angle (number)",n("The angle to find the cosine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.cos(Qi(e))},isExported:!0},Sl={description:n("Hyperbolic cosine of any real number."),args:[el("value (number)",n("Any real value to calculate the hyperbolic cosine of."))],returns:["NUMBER"],compute:function(e){return Math.cosh(Qi(e))},isExported:!0},Cl={description:n("Cotangent of an angle provided in radians."),args:[el("angle (number)",n("The angle to find the cotangent of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},El={description:n("Hyperbolic cotangent of any real number."),args:[el("value (number)",n("Any real value to calculate the hyperbolic cotangent of."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},wl={description:n("Number of empty values."),args:[el("value1 (any, range)",n("The first value or range in which to count the number of blanks.")),el("value2 (any, range, repeating)",n("Additional values or ranges in which to count the number of blanks."))],returns:["NUMBER"],compute:function(...e){return us(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},xl={description:n("A conditional count across a range."),args:[el("range (range)",n("The range that is tested against criterion.")),el("criterion (string)",n("The pattern or test to apply to range."))],returns:["NUMBER"],compute:function(...e){let t=0;return vs(e,((e,o)=>{t+=1})),t},isExported:!0},yl={description:n("Count values depending on multiple criteria."),args:[el("criteria_range1 (range)",n("The range to check against criterion1.")),el("criterion1 (string)",n("The pattern or test to apply to criteria_range1.")),el("criteria_range2 (any, range, repeating)",n("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.")),el("criterion2 (string, repeating)",n("Additional criteria to check."))],returns:["NUMBER"],compute:function(...e){let t=0;return vs(e,((e,o)=>{t+=1})),t},isExported:!0};function Il(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const Rl={description:n("Counts number of unique values in a range."),args:[el("value1 (any, range)",n("The first value or range to consider for uniqueness.")),el("value2 (any, range, repeating)",n("Additional values or ranges to consider for uniqueness."))],returns:["NUMBER"],compute:function(...e){return us(e,((e,t)=>Il(t)?e.add(t):e),new Set).size}},Tl={description:n("Counts number of unique values in a range, filtered by a set of criteria."),args:[el("range (range)",n("The range of cells from which the number of unique values will be counted.")),el("criteria_range1 (range)",n("The range of cells over which to evaluate criterion1.")),el("criterion1 (string)",n("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),el("criteria_range2 (any, range, repeating)",n("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.")),el("criterion2 (string, repeating)",n("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=new Set;return vs(t,((t,i)=>{const s=e[t][i];Il(s)&&o.add(s)})),o.size}},Al={description:n("Cosecant of an angle provided in radians."),args:[el("angle (number)",n("The angle to find the cosecant of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},Ol={description:n("Hyperbolic cosecant of any real number."),args:[el("value (number)",n("Any real value to calculate the hyperbolic cosecant of."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},Ml={description:n("Converts from another base to decimal."),args:[el("value (string)",n("The number to convert.")),el(",base (number)",n("The base to convert the value from."))],returns:["NUMBER"],compute:function(e,t){let o=Qi(t);o=Math.floor(o),Xi((()=>2<=o&&o<=36),n("The base (%s) must be between 2 and 36 inclusive.",o.toString()));const i=os(e);if(""===i)return 0;Xi((()=>!!sl.test(i)),n("The value (%s) must be a valid base %s representation.",i,o.toString()));const s=parseInt(i,o);return Xi((()=>!isNaN(s)),n("The value (%s) must be a valid base %s representation.",i,o.toString())),s},isExported:!0},Nl={description:n("Converts an angle value in radians to degrees."),args:[el("angle (number)",n("The angle to convert from radians to degrees."))],returns:["NUMBER"],compute:function(e){return 180*Qi(e)/Math.PI},isExported:!0},_l={description:n("Euler's number, e (~2.718) raised to a power."),args:[el("value (number)",n("The exponent to raise e."))],returns:["NUMBER"],compute:function(e){return Math.exp(Qi(e))},isExported:!0},Fl={description:n("Rounds number down to nearest multiple of factor."),args:[el("value (number)",n("The value to round down to the nearest integer multiple of factor.")),el("factor (number, default=1)",n("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){const o=Qi(e),i=Qi(t);return Xi((()=>i>=0||o<=0),n("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),o.toString())),i?Math.floor(o/i)*i:0},isExported:!0},Dl={description:n("Rounds number down to nearest multiple of factor."),args:[el("number (number)",n("The value to round down to the nearest integer multiple of significance.")),el("significance (number, default=1)",n("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),el("mode (number, default=0)",n("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=>e?.format,compute:function(e,t=1,o=0){let i=Qi(t);if(0===i)return 0;const s=Qi(e);if(i=Math.abs(i),s>=0)return Math.floor(s/i)*i;return 0===Qi(o)?-Math.ceil(Math.abs(s)/i)*i:-Math.floor(Math.abs(s)/i)*i},isExported:!0},Ll={description:n("Rounds number down to nearest multiple of factor."),args:[el("number (number)",n("The value to round down to the nearest integer multiple of significance.")),el("significance (number, default=1)",n("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){return Dl.compute(e,t,0)},isExported:!0},Pl={description:n("Whether the provided value is even."),args:[el("value (number)",n("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Ji(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},kl={description:n("Rounds number up to nearest multiple of factor."),args:[el("number (number)",n("The value to round up to the nearest integer multiple of significance.")),el("significance (number, default=1)",n("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){return fl.compute(e,t,0)},isExported:!0},Ul={description:n("Whether the provided value is even."),args:[el("value (number)",n("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Ji(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},Vl={description:n("The logarithm of a number, base e (euler's number)."),args:[el("value (number)",n("The value for which to calculate the logarithm, base e."))],returns:["NUMBER"],compute:function(e){const t=Qi(e);return Xi((()=>t>0),n("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},zl={description:n("Modulo (remainder) operator."),args:[el("dividend (number)",n("The number to be divided to find the remainder.")),el("divisor (number)",n("The number to divide by."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){const o=Qi(t);Xi((()=>0!==o),n("The divisor must be different from 0."));const i=Qi(e)%o;return i>0&&o<0||i<0&&o>0?i+o:i},isExported:!0},Bl={description:n("Rounds a number up to the nearest odd integer."),args:[el("value (number)",n("The value to round to the next greatest odd number."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e){const t=Qi(e);let o=Math.ceil(Math.abs(t));return o=1&o?o:o+1,t<0?-o:o},isExported:!0},Hl={description:n("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},$l={description:n("A number raised to a power."),args:[el("base (number)",n("The number to raise to the exponent power.")),el("exponent (number)",n("The exponent to raise base to."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){const o=Qi(e),i=Qi(t);return Xi((()=>o>=0||Number.isInteger(i)),n("The exponent (%s) must be an integer when the base is negative.",i.toString())),Math.pow(o,i)},isExported:!0},Wl={description:n("Result of multiplying a series of numbers together."),args:[el("factor1 (number, range<number>)",n("The first number or range to calculate for the product.")),el("factor2 (number, range<number>, repeating)",n("More numbers or ranges to calculate for the product."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=0,o=1;for(let i of e)if(Array.isArray(i))for(let e of i)for(let i of e)"number"==typeof i&&(o*=i,t+=1);else null!=i&&(o*=Ji(i),t+=1);return 0===t?0:o},isExported:!0},Gl={description:n("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},ql={description:n("Random integer between two values, inclusive."),args:[el("low (number)",n("The low end of the random range.")),el("high (number)",n("The high end of the random range."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){let o=Qi(e);Number.isInteger(o)||(o=Math.ceil(o));let i=Qi(t);return Number.isInteger(i)||(i=Math.floor(i)),Xi((()=>o<=i),n("The high (%s) must be greater than or equal to the low (%s).",i.toString(),o.toString())),o+Math.ceil((i-o+1)*Math.random())-1},isExported:!0},Zl={description:n("Rounds a number according to standard rules."),args:[el("value (number)",n("The value to round to places number of places.")),el("places (number, default=0)",n("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Qi(e);let i=Qi(t);const s=Math.abs(o);let n;return 0===i?n=Math.round(s):(Number.isInteger(i)||(i=Math.trunc(i)),n=Math.round(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?n:-n},isExported:!0},jl={description:n("Rounds down a number."),args:[el("value (number)",n("The value to round to places number of places, always rounding down.")),el("places (number, default=0)",n("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Qi(e);let i=Qi(t);const s=Math.abs(o);let n;return 0===i?n=Math.floor(s):(Number.isInteger(i)||(i=Math.trunc(i)),n=Math.floor(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?n:-n},isExported:!0},Yl={description:n("Rounds up a number."),args:[el("value (number)",n("The value to round to places number of places, always rounding up.")),el("places (number, default=0)",n("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Qi(e);let i=Qi(t);const s=Math.abs(o);let n;return 0===i?n=Math.ceil(s):(Number.isInteger(i)||(i=Math.trunc(i)),n=Math.ceil(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?n:-n},isExported:!0},Xl={description:n("Secant of an angle provided in radians."),args:[el("angle (number)",n("The angle to find the secant of, in radians."))],returns:["NUMBER"],compute:function(e){return 1/Math.cos(Qi(e))},isExported:!0},Kl={description:n("Hyperbolic secant of any real number."),args:[el("value (number)",n("Any real value to calculate the hyperbolic secant of."))],returns:["NUMBER"],compute:function(e){return 1/Math.cosh(Qi(e))},isExported:!0},Ql={description:n("Sine of an angle provided in radians."),args:[el("angle (number)",n("The angle to find the sine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.sin(Qi(e))},isExported:!0},Jl={description:n("Hyperbolic sine of any real number."),args:[el("value (number)",n("Any real value to calculate the hyperbolic sine of."))],returns:["NUMBER"],compute:function(e){return Math.sinh(Qi(e))},isExported:!0},ec={description:n("Positive square root of a positive number."),args:[el("value (number)",n("The number for which to calculate the positive square root."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e){const t=Qi(e);return Xi((()=>t>=0),n("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},tc={description:n("Sum of a series of numbers and/or cells."),args:[el("value1 (number, range<number>)",n("The first number or range to add together.")),el("value2 (number, range<number>, repeating)",n("Additional numbers or ranges to add to value1."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){return gs(e,((e,t)=>e+t),0)},isExported:!0},oc={description:n("A conditional sum across a range."),args:[el("criteria_range (range)",n("The range which is tested against criterion.")),el("criterion (string)",n("The pattern or test to apply to range.")),el("sum_range (range, default=criteria_range)",n("The range to be summed, if different from range."))],returns:["NUMBER"],compute:function(e,t,o){void 0===o&&(o=e);let i=0;return vs([e,t],((e,t)=>{const s=o[e][t];"number"==typeof s&&(i+=s)})),i},isExported:!0},ic={description:n("Sums a range depending on multiple criteria."),args:[el("sum_range (range)",n("The range to sum.")),el("criteria_range1 (range)",n("The range to check against criterion1.")),el("criterion1 (string)",n("The pattern or test to apply to criteria_range1.")),el("criteria_range2 (any, range, repeating)",n("Additional ranges to check.")),el("criterion2 (string, repeating)",n("Additional criteria to check."))],returns:["NUMBER"],compute:function(e,...t){let o=0;return vs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o+=s)})),o},isExported:!0},sc={description:n("Tangent of an angle provided in radians."),args:[el("angle (number)",n("The angle to find the tangent of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.tan(Qi(e))},isExported:!0},nc={description:n("Hyperbolic tangent of any real number."),args:[el("value (number)",n("Any real value to calculate the hyperbolic tangent of."))],returns:["NUMBER"],compute:function(e){return Math.tanh(Qi(e))},isExported:!0},rc={description:n("Truncates a number."),args:[el("value (number)",n("The value to be truncated.")),el("places (number, default=0)",n("The number of significant digits to the right of the decimal point to retain."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Qi(e);let i=Qi(t);return 0===i?Math.trunc(o):(Number.isInteger(i)||(i=Math.trunc(i)),Math.trunc(o*Math.pow(10,i))/Math.pow(10,i))},isExported:!0};var ac=Object.freeze({__proto__:null,ABS:nl,ACOS:rl,ACOSH:al,ACOT:ll,ACOTH:cl,ASIN:hl,ASINH:dl,ATAN:ul,ATAN2:gl,ATANH:pl,CEILING:ml,CEILING_MATH:fl,CEILING_PRECISE:bl,COS:vl,COSH:Sl,COT:Cl,COTH:El,COUNTBLANK:wl,COUNTIF:xl,COUNTIFS:yl,COUNTUNIQUE:Rl,COUNTUNIQUEIFS:Tl,CSC:Al,CSCH:Ol,DECIMAL:Ml,DEGREES:Nl,EXP:_l,FLOOR:Fl,FLOOR_MATH:Dl,FLOOR_PRECISE:Ll,ISEVEN:Pl,ISO_CEILING:kl,ISODD:Ul,LN:Vl,MOD:zl,ODD:Bl,PI:Hl,POWER:$l,PRODUCT:Wl,RAND:Gl,RANDBETWEEN:ql,ROUND:Zl,ROUNDDOWN:jl,ROUNDUP:Yl,SEC:Xl,SECH:Kl,SIN:Ql,SINH:Jl,SQRT:ec,SUM:tc,SUMIF:oc,SUMIFS:ic,TAN:sc,TANH:nc,TRUNC:rc});function lc(e,t,o){let i=[],s=[],r=0,a=0;cs([e],(e=>{i.push(e),r+=1})),cs([t],(e=>{s.push(e),a+=1})),Xi((()=>r===a),n("[[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=i[e],o=s[e];"number"==typeof t&&"number"==typeof o&&(l+=1,c+=t,h+=o)}Xi((()=>0!==l&&(!o||1!==l)),n("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=i[e],o=s[e];"number"==typeof t&&"number"==typeof o&&(g+=(t-d)*(o-u))}return g/(l-(o?1:0))}function cc(e,t,o){let i=0,s=0;const r=o?ps:gs;s=r(e,((e,t)=>(i+=1,e+t)),0),Xi((()=>0!==i&&(!t||1!==i)),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const a=s/i;return r(e,((e,t)=>e+Math.pow(t-a,2)),0)/(i-(t?1:0))}function hc(e,t,o){const i=Qi(t);Xi((()=>o?0<=i&&i<=1:0<i&&i<1),n("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let s,r=[],a=0;return cs(e,(e=>{"number"==typeof e&&(s=Es(r,e,"nextSmaller","asc",r.length,((e,t)=>e[t])),r.splice(s+1,0,e),a++)})),Xi((()=>0!==a),n("[[FUNCTION_NAME]] has no valid input data.")),o||Xi((()=>1/(a+1)<=i&&i<=a/(a+1)),n("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),ao(r,i,o)}const dc={description:n("Average magnitude of deviations from mean."),args:[el("value1 (number, range<number>)",n("The first value or range of the sample.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){let t=0;const o=gs(e,((e,o)=>(t+=1,e+o)),0);Xi((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const i=o/t;return gs(e,((e,t)=>e+Math.abs(i-t)),0)/t},isExported:!0},uc={description:n("Numerical average value in a dataset, ignoring text."),args:[el("value1 (number, range<number>)",n("The first value or range to consider when calculating the average value.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=0;const o=gs(e,((e,o)=>(t+=1,e+o)),0);return Xi((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},gc=n("[[FUNCTION_NAME]] has mismatched range sizes."),pc=n("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),mc={description:n("Weighted average."),args:[el("values (number, range<number>)",n("Values to average.")),el("weights (number, range<number>)",n("Weights for each corresponding value.")),el("additional_values (number, range<number>, repeating)",n("Additional values to average.")),el("additional_weights (number, range<number>, repeating)",n("Additional weights."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t,o,i=0,s=0;Xi((()=>e.length%2==0),n("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let r=0;r<e.length-1;r+=2)if(t=e[r],o=e[r+1],Array.isArray(t)){Xi((()=>Array.isArray(o)),gc);let e=t.length,r=t[0].length;Xi((()=>e===o.length&&r===o[0].length),gc);for(let a=0;a<e;a++)for(let e=0;e<r;e++){let r=t[a][e],l=o[a][e],c="number"==typeof r,h="number"==typeof l;Xi((()=>c===h),n("[[FUNCTION_NAME]] expects number values.")),h&&(Xi((()=>l>=0),pc),i+=r*l,s+=l)}}else o=Qi(o),t=Qi(t),Xi((()=>o>=0),pc),i+=t*o,s+=o;return Xi((()=>0!==s),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/s}},fc={description:n("Numerical average value in a dataset."),args:[el("value1 (number, range<number>)",n("The first value or range to consider when calculating the average value.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=0;const o=ps(e,((e,o)=>(t+=1,e+o)),0);return Xi((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},bc={description:n("Average of values depending on criteria."),args:[el("criteria_range (range)",n("The range to check against criterion.")),el("criterion (string)",n("The pattern or test to apply to criteria_range.")),el("average_range (range, default=criteria_range)",n("The range to average. If not included, criteria_range is used for the average instead."))],returns:["NUMBER"],compute:function(e,t,o){null==o&&(o=e);let i=0,s=0;return vs([e,t],((t,n)=>{const r=(o||e)[t][n];"number"==typeof r&&(i+=1,s+=r)})),Xi((()=>0!==i),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/i},isExported:!0},vc={description:n("Average of values depending on multiple criteria."),args:[el("average_range (range)",n("The range to average.")),el("criteria_range1 (range)",n("The range to check against criterion1.")),el("criterion1 (string)",n("The pattern or test to apply to criteria_range1.")),el("criteria_range2 (any, range, repeating)",n("Additional criteria_range and criterion to check.")),el("criterion2 (string, repeating)",n("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=0,i=0;return vs(t,((t,s)=>{const n=e[t][s];"number"==typeof n&&(o+=1,i+=n)})),Xi((()=>0!==o),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/o},isExported:!0},Sc={description:n("The number of numeric values in dataset."),args:[el("value1 (number, range<number>)",n("The first value or range to consider when counting.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){let t=0;for(let o of e)if(Array.isArray(o))for(let e of o)for(let o of e)"number"==typeof o&&(t+=1);else("string"!=typeof o||so(o)||Te(o))&&(t+=1);return t},isExported:!0},Cc={description:n("The number of values in a dataset."),args:[el("value1 (any, range)",n("The first value or range to consider when counting.")),el("value2 (any, range, repeating)",n("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){return us(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},Ec={description:n("The covariance of a dataset."),args:[el("data_y (any, range)",n("The range representing the array or matrix of dependent data.")),el("data_x (any, range)",n("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return lc(e,t,!1)},isExported:!0},wc={description:n("The covariance of a dataset."),args:[el("data_y (any, range)",n("The range representing the array or matrix of dependent data.")),el("data_x (any, range)",n("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return lc(e,t,!1)},isExported:!0},xc={description:n("The sample covariance of a dataset."),args:[el("data_y (any, range)",n("The range representing the array or matrix of dependent data.")),el("data_x (any, range)",n("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return lc(e,t,!0)},isExported:!0},yc={description:n("Nth largest element from a data set."),args:[el("data (any, range)",n("Array or range containing the dataset to consider.")),el("n (number)",n("The rank from largest to smallest of the element to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){const o=Math.trunc(Qi(t));let i,s=[],r=0;cs([e],(e=>{"number"==typeof e&&(i=Es(s,e,"nextSmaller","asc",s.length,((e,t)=>e[t])),s.splice(i+1,0,e),r++,r>o&&(s.shift(),r--))}));const a=s.shift();return Xi((()=>void 0!==a),n("[[FUNCTION_NAME]] has no valid input data.")),Xi((()=>r>=o),n("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},Ic={description:n("Maximum value in a numeric dataset."),args:[el("value1 (number, range<number>)",n("The first value or range to consider when calculating the maximum value.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=gs(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},Rc={description:n("Maximum numeric value in a dataset."),args:[el("value1 (any, range)",n("The first value or range to consider when calculating the maximum value.")),el("value2 (any, range, repeating)",n("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=ps(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},Tc={description:n("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:[el("range (range)",n("The range of cells from which the maximum will be determined.")),el("criteria_range1 (range)",n("The range of cells over which to evaluate criterion1.")),el("criterion1 (string)",n("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),el("criteria_range2 (any, range, repeating)",n("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.")),el("criterion2 (string, repeating)",n("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=-1/0;return vs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o=o<s?s:o)})),o===-1/0?0:o},isExported:!0},Ac={description:n("Median value in a numeric dataset."),args:[el("value1 (any, range)",n("The first value or range to consider when calculating the median value.")),el("value2 (any, range, repeating)",n("Additional values or ranges to consider when calculating the median value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){let t=[];return hs(e,(e=>{t.push(e)})),hc(t,.5,!0)},isExported:!0},Oc={description:n("Minimum value in a numeric dataset."),args:[el("value1 (number, range<number>)",n("The first value or range to consider when calculating the minimum value.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=gs(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Mc={description:n("Minimum numeric value in a dataset."),args:[el("value1 (number, range<number>)",n("The first value or range to consider when calculating the minimum value.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(...e){const t=ps(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},Nc={description:n("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:[el("range (range)",n("The range of cells from which the minimum will be determined.")),el("criteria_range1 (range)",n("The range of cells over which to evaluate criterion1.")),el("criterion1 (string)",n("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),el("criteria_range2 (any, range, repeating)",n("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.")),el("criterion2 (string, repeating)",n("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=1/0;return vs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o=o>s?s:o)})),o===1/0?0:o},isExported:!0},_c={description:n("Value at a given percentile of a dataset."),args:[el("data (any, range)",n("The array or range containing the dataset to consider.")),el("percentile (number)",n("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return Dc.compute(e,t)},isExported:!0},Fc={description:n("Value at a given percentile of a dataset exclusive of 0 and 1."),args:[el("data (any, range)",n("The array or range containing the dataset to consider.")),el("percentile (number)",n("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return hc([e],t,!1)},isExported:!0},Dc={description:n("Value at a given percentile of a dataset."),args:[el("data (any, range)",n("The array or range containing the dataset to consider.")),el("percentile (number)",n("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return hc([e],t,!0)},isExported:!0},Lc={description:n("Value nearest to a specific quartile of a dataset."),args:[el("data (any, range)",n("The array or range containing the dataset to consider.")),el("quartile_number (number)",n("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return kc.compute(e,t)},isExported:!0},Pc={description:n("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:[el("data (any, range)",n("The array or range containing the dataset to consider.")),el("quartile_number (number)",n("Which quartile value, exclusive of 0 and 4, to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return hc([e],.25*Math.trunc(Qi(t)),!1)},isExported:!0},kc={description:n("Value nearest to a specific quartile of a dataset."),args:[el("data (any, range)",n("The array or range containing the dataset to consider.")),el("quartile_number (number)",n("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return hc([e],.25*Math.trunc(Qi(t)),!0)},isExported:!0},Uc={description:n("Nth smallest element in a data set."),args:[el("data (any, range)",n("The array or range containing the dataset to consider.")),el("n (number)",n("The rank from smallest to largest of the element to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){const o=Math.trunc(Qi(t));let i,s=[],r=0;cs([e],(e=>{"number"==typeof e&&(i=Es(s,e,"nextSmaller","asc",s.length,((e,t)=>e[t])),s.splice(i+1,0,e),r++,r>o&&(s.pop(),r--))}));const a=s.pop();return Xi((()=>void 0!==a),n("[[FUNCTION_NAME]] has no valid input data.")),Xi((()=>r>=o),n("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},Vc={description:n("Standard deviation."),args:[el("value1 (number, range<number>)",n("The first value or range of the sample.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Gc.compute(...e))},isExported:!0},zc={description:n("Standard deviation of entire population."),args:[el("value1 (number, range<number>)",n("The first value or range of the population.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(qc.compute(...e))},isExported:!0},Bc={description:n("Standard deviation."),args:[el("value1 (number, range<number>)",n("The first value or range of the sample.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Zc.compute(...e))},isExported:!0},Hc={description:n("Standard deviation of sample (text as 0)."),args:[el("value1 (number, range<number>)",n("The first value or range of the sample.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(jc.compute(...e))},isExported:!0},$c={description:n("Standard deviation of entire population."),args:[el("value1 (number, range<number>)",n("The first value or range of the population.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Yc.compute(...e))},isExported:!0},Wc={description:n("Standard deviation of entire population (text as 0)."),args:[el("value1 (number, range<number>)",n("The first value or range of the population.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Xc.compute(...e))},isExported:!0},Gc={description:n("Variance."),args:[el("value1 (number, range<number>)",n("The first value or range of the sample.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return cc(e,!0,!1)},isExported:!0},qc={description:n("Variance of entire population."),args:[el("value1 (number, range<number>)",n("The first value or range of the population.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return cc(e,!1,!1)},isExported:!0},Zc={description:n("Variance."),args:[el("value1 (number, range<number>)",n("The first value or range of the sample.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return cc(e,!0,!1)},isExported:!0},jc={description:n("Variance of sample (text as 0)."),args:[el("value1 (number, range<number>)",n("The first value or range of the sample.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return cc(e,!0,!0)},isExported:!0},Yc={description:n("Variance of entire population."),args:[el("value1 (number, range<number>)",n("The first value or range of the population.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return cc(e,!1,!1)},isExported:!0},Xc={description:n("Variance of entire population (text as 0)."),args:[el("value1 (number, range<number>)",n("The first value or range of the population.")),el("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return cc(e,!1,!0)},isExported:!0};var Kc=Object.freeze({__proto__:null,AVEDEV:dc,AVERAGE:uc,AVERAGE_WEIGHTED:mc,AVERAGEA:fc,AVERAGEIF:bc,AVERAGEIFS:vc,COUNT:Sc,COUNTA:Cc,COVAR:Ec,COVARIANCE_P:wc,COVARIANCE_S:xc,LARGE:yc,MAX:Ic,MAXA:Rc,MAXIFS:Tc,MEDIAN:Ac,MIN:Oc,MINA:Mc,MINIFS:Nc,PERCENTILE:_c,PERCENTILE_EXC:Fc,PERCENTILE_INC:Dc,QUARTILE:Lc,QUARTILE_EXC:Pc,QUARTILE_INC:kc,SMALL:Uc,STDEV:Vc,STDEV_P:zc,STDEV_S:Bc,STDEVA:Hc,STDEVP:$c,STDEVPA:Wc,VAR:Gc,VAR_P:qc,VAR_S:Zc,VARA:jc,VARP:Yc,VARPA:Xc});function Qc(e,t,o){const i=new Map,s=e.length;for(let t=s-1;t>=0;t--)i.set(os(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(n("The field must be a number or a string"));let r;if("number"==typeof t){if(r=Math.trunc(t)-1,r<0||s-1<r)throw new Error(n("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),s.toString()))}else{const e=os(t).toUpperCase();if(r=i.get(e)??-1,-1===r)throw new Error(n("The field (%s) must be one of %s.",os(t),[...i.keys()].toString()))}const a=o[0].length;if(a<2)throw new Error(n("The criteria range contains %s row, it must be at least 2 rows.",a.toString()));let l=new Set;const c=e[0].length;for(let t=1;t<a;t++){let s=[],n=!0;for(let r=0;r<o.length;r++){const a=os(o[r][0]).toUpperCase(),l=i.get(a),h=o[r][t];if(void 0!==h){if(void 0===l){n=!1;break}s.push([e[l].slice(1,c)]),s.push(h)}}if(n){if(!(s.length>0)){l=new Set(Array(c-1).keys());break}vs(s,((e,t)=>{l.add(t)}),!0)}}const h=e[r];return[...l].map((e=>h[e+1]))}const Jc=[el("database (range)",n("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.")),el("field (any)",n("Indicates which column in database contains the values to be extracted and operated on.")),el("criteria (range)",n("An array or range containing zero or more criteria to filter the database values by before operating."))],eh={description:n("Average of a set of values from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return uc.compute([i])},isExported:!0},th={description:n("Counts values from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Sc.compute([i])},isExported:!0},oh={description:n("Counts values and text from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Cc.compute([i])},isExported:!0},ih={description:n("Single value from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Xi((()=>1===i.length),n("More than one match found in DGET evaluation.")),i[0]},isExported:!0},sh={description:n("Maximum of values from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Ic.compute([i])},isExported:!0},nh={description:n("Minimum of values from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Oc.compute([i])},isExported:!0},rh={description:n("Product of values from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Wl.compute([i])},isExported:!0},ah={description:n("Standard deviation of population sample from table."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Vc.compute([i])},isExported:!0},lh={description:n("Standard deviation of entire population from table."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return $c.compute([i])},isExported:!0},ch={description:n("Sum of values from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return tc.compute([i])},isExported:!0},hh={description:n("Variance of population sample from table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Gc.compute([i])},isExported:!0},dh={description:n("Variance of a population from a table-like range."),args:Jc,returns:["NUMBER"],compute:function(e,t,o){const i=Qc(e,t,o);return Yc.compute([i])},isExported:!0};var uh=Object.freeze({__proto__:null,DAVERAGE:eh,DCOUNT:th,DCOUNTA:oh,DGET:ih,DMAX:sh,DMIN:nh,DPRODUCT:rh,DSTDEV:ah,DSTDEVP:lh,DSUM:ch,DVAR:hh,DVARP:dh});var gh;!function(e){e.WHOLE_YEARS="Y",e.WHOLE_MONTHS="M",e.WHOLE_DAYS="D",e.DAYS_WITHOUT_WHOLE_MONTHS="MD",e.MONTH_WITHOUT_WHOLE_YEARS="YM",e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR="YD"}(gh||(gh={}));const ph={description:n("Converts year/month/day into a date."),args:[el("year (number)",n("The year component of the date.")),el("month (number)",n("The month component of the date.")),el("day (number)",n("The day component of the date."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){let i=Math.trunc(Qi(e));const s=Math.trunc(Qi(t)),r=Math.trunc(Qi(o));Xi((()=>0<=i&&i<=9999),n("The year (%s) must be between 0 and 9999 inclusive.",i.toString())),i<1900&&(i+=1900);const a=Me(new be(i,s-1,r));return Xi((()=>a>=0),n("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),a},isExported:!0},mh={description:n("Calculates the number of days, months, or years between two dates."),args:[el("start_date (date)",n("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.")),el("end_date (date)",n("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.")),el("unit (string)",n('A text abbreviation for unit of time. Accepted values are "Y" (the number of whole years between start_date and end_date), "M" (the number of whole months between start_date and end_date), "D" (the number of days between start_date and end_date), "MD" (the number of days between start_date and end_date after subtracting whole months), "YM" (the number of whole months between start_date and end_date after subtracting whole years), "YD" (the number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart).'))],returns:["NUMBER"],compute:function(e,t,o){const i=os(o).toUpperCase();Xi((()=>Object.values(gh).includes(i)),((e,t)=>{const o=e.map((e=>`'${e}'`)).join(", ");return n("The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.",t,o)})(Object.values(gh),os(o)));const s=Math.trunc(Qi(e)),r=Math.trunc(Qi(t)),a=Oe(s),l=Oe(r);switch(Xi((()=>r>=s),n("start_date (%s) should be on or before end_date (%s).",a.toLocaleDateString(),l.toLocaleDateString())),i){case gh.WHOLE_YEARS:return Ue(a,l);case gh.WHOLE_MONTHS:return Pe(a,l);case gh.WHOLE_DAYS:return ke(a,l);case gh.MONTH_WITHOUT_WHOLE_YEARS:return Pe(a,l)-12*Ue(a,l);case gh.DAYS_WITHOUT_WHOLE_MONTHS:let e=l.getDate()-a.getDate();if(e<0){e=Ne(new be(l.getFullYear(),l.getMonth()-1,1))-Math.abs(e)}return e;case gh.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR:{if(function(e,t){return Le(e,t,1)<1}(s,r))return ke(a,l);const e=new be(a.getFullYear(),l.getMonth(),l.getDate());let t=ke(a,e);return t<0&&(e.setFullYear(a.getFullYear()+1),t=ke(a,e)),t}}},isExported:!0},fh={description:n("Converts a date string to a date value."),args:[el("date_string (string)",n("The string representing the date."))],returns:["NUMBER"],compute:function(e){const t=os(e),o=Te(t);return Xi((()=>null!==o),n("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(o.value)},isExported:!0},bh={description:n("Day of the month that a specific date falls on."),args:[el("date (string)",n("The date from which to extract the day."))],returns:["NUMBER"],compute:function(e){return as(e).getDate()},isExported:!0},vh={description:n("Number of days between two dates."),args:[el("end_date (date)",n("The end of the date range.")),el("start_date (date)",n("The start of the date range."))],returns:["NUMBER"],compute:function(e,t){const o=as(e),i=as(t),s=o.getTime()-i.getTime();return Math.round(s/Se)},isExported:!0},Sh={description:n("Number of days between two dates on a 360-day year (months of 30 days)."),args:[el("start_date (date)",n("The start date to consider in the calculation.")),el("end_date (date)",n("The end date to consider in the calculation.")),el("method (number, default=0)",n("An indicator of what day count method to use. (0) US NASD method (1) European method"))],returns:["NUMBER"],compute:function(e,t,o=0){const i=Qi(e),s=Qi(t),n=rs(o)?4:0,r=Vh.compute(e,t,n);return Math.sign(s-i)*Math.round(360*r)},isExported:!0},Ch={description:n("Date a number of months before/after another date."),args:[el("start_date (date)",n("The date from which to calculate the result.")),el("months (number)",n("The number of months before (negative) or after (positive) 'start_date' to calculate."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){return Me(Fe(as(e),Math.trunc(Qi(t)),!1))},isExported:!0},Eh={description:n("Last day of a month before or after a date."),args:[el("start_date (date)",n("The date from which to calculate the result.")),el("months (number)",n("The number of months before (negative) or after (positive) 'start_date' to consider."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){const o=as(e),i=Math.trunc(Qi(t)),s=o.getFullYear(),n=o.getMonth();return Me(new be(s,n+i+1,0))},isExported:!0},wh={description:n("Hour component of a specific time."),args:[el("time (date)",n("The time from which to calculate the hour component."))],returns:["NUMBER"],compute:function(e){return as(e).getHours()},isExported:!0},xh={description:n("ISO week number of the year."),args:[el("date (date)",n("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=as(e),o=t.getFullYear();let i=1;for(;4!==new be(o,0,i).getDay();)i+=1;const s=new be(o,0,i-3);let n=31;for(;4!==new be(o,11,n).getDay();)n-=1;const r=new be(o,11,n+3);let a,l;switch(a=s.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=s;break;case 1:l=new be(o,11,n+3+1);break;case-1:let e=1;for(;4!==new be(o-1,0,e).getDay();)e+=1;l=new be(o-1,0,e-3)}const c=(t.getTime()-l.getTime())/Se;return Math.floor(c/7)+1},isExported:!0},yh={description:n("Minute component of a specific time."),args:[el("time (date)",n("The time from which to calculate the minute component."))],returns:["NUMBER"],compute:function(e){return as(e).getMinutes()},isExported:!0},Ih={description:n("Month of the year a specific date falls in"),args:[el("date (date)",n("The date from which to extract the month."))],returns:["NUMBER"],compute:function(e){return as(e).getMonth()+1},isExported:!0},Rh={description:n("Net working days between two provided days."),args:[el("start_date (date)",n("The start date of the period from which to calculate the number of net working days.")),el("end_date (date)",n("The end date of the period from which to calculate the number of net working days.")),el("holidays (date, range<date>, optional)",n("A range or array constant containing the date serial numbers to consider holidays."))],returns:["NUMBER"],compute:function(e,t,o){return Ah.compute(e,t,1,o)},isExported:!0};function Th(e){if("string"==typeof e){Xi((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),n('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let o=0;o<7;o++)"1"===e[o]&&t.push((o+1)%7);return t}if("number"==typeof e)return Xi((()=>1<=e&&e<=7||11<=e&&e<=17),n("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(n("The weekend must be a number or a string."))}const Ah={description:n("Net working days between two dates (specifying weekends)."),args:[el("start_date (date)",n("The start date of the period from which to calculate the number of net working days.")),el("end_date (date)",n("The end date of the period from which to calculate the number of net working days.")),el("weekend (any, default=1)",n("A number or string representing which days of the week are considered weekends.")),el("holidays (date, range<date>, optional)",n("A range or array constant containing the dates to consider as holidays."))],returns:["NUMBER"],compute:function(e,t,o=1,i){const s=as(e),n=as(t),r=Th(o);let a=new Set;void 0!==i&&cs([i],(e=>{const t=as(e);a.add(t.getTime())}));const l=s.getTime()>n.getTime(),c=be.fromTimestamp((l?s:n).getTime());let h=be.fromTimestamp((l?n:s).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},Oh={description:n("Current date and time as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy hh:mm:ss",compute:function(){let e=be.now();const t=e.getTime()-ve.getTime(),o=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/Se)+o},isExported:!0},Mh={description:n("Minute component of a specific time."),args:[el("time (date)",n("The time from which to calculate the second component."))],returns:["NUMBER"],compute:function(e){return as(e).getSeconds()},isExported:!0},Nh={description:n("Converts hour/minute/second into a time."),args:[el("hour (number)",n("The hour component of the time.")),el("minute (number)",n("The minute component of the time.")),el("second (number)",n("The second component of the time."))],returns:["DATE"],computeFormat:()=>"hh:mm:ss a",compute:function(e,t,o){let i=Math.trunc(Qi(e)),s=Math.trunc(Qi(t)),r=Math.trunc(Qi(o));return s+=Math.floor(r/60),r=r%60+(r<0?60:0),i+=Math.floor(s/60),s=s%60+(s<0?60:0),i%=24,Xi((()=>i>=0),n("The function [[FUNCTION_NAME]] result cannot be negative")),i/24+s/1440+r/86400},isExported:!0},_h={description:n("Converts a time string into its serial number representation."),args:[el("time_string (string)",n("The string that holds the time representation."))],returns:["NUMBER"],compute:function(e){const t=os(e),o=Te(t);Xi((()=>null!==o),n("The time_string (%s) cannot be parsed to date/time.",t));const i=o.value-Math.trunc(o.value);return i<0?1+i:i},isExported:!0},Fh={description:n("Current date as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(){const e=be.now();return Me(new be(e.getFullYear(),e.getMonth(),e.getDate()))},isExported:!0},Dh={description:n("Day of the week of the date provided (as number)."),args:[el("date (date)",n("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.")),el("type (number, default=1)",n("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 o=as(e),i=Math.round(Qi(t)),s=o.getDay();return Xi((()=>[1,2,3].includes(i)),n("The type (%s) must be 1, 2 or 3.",i.toString())),1===i?s+1:2===i?0===s?7:s:0===s?6:s-1},isExported:!0},Lh={description:n("Week number of the year."),args:[el("date (date)",n("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.")),el("type (number, default=1)",n("A number representing the day that a week starts on. Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const o=as(e),i=Math.round(Qi(t));if(Xi((()=>1===i||2===i||11<=i&&i<=17||21===i),n("The type (%s) is out of range.",i.toString())),21===i)return xh.compute(e);let s;s=1===i||2===i?i-1:i-10==7?0:i-10;const r=o.getFullYear();let a=1,l=new be(r,0,a);for(;l.getDay()!==s;)a+=1,l=new be(r,0,a);const c=(o.getTime()-l.getTime())/Se;return c<0?1:Math.floor(c/7)+(1===a?1:2)},isExported:!0},Ph={description:n("Date after a number of workdays."),args:[el("start_date (date)",n("The date from which to begin counting.")),el("num_days (number)",n("The number of working days to advance from start_date. If negative, counts backwards.")),el("holidays (date, range<date>, optional)",n("A range or array constant containing the dates to consider holidays."))],returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){return kh.compute(e,t,1,o)},isExported:!0},kh={description:n("Date after a number of workdays (specifying weekends)."),args:[el("start_date (date)",n("The date from which to begin counting.")),el("num_days (number)",n("The number of working days to advance from start_date. If negative, counts backwards.")),el("weekend (any, default=1)",n("A number or string representing which days of the week are considered weekends.")),el("holidays (date, range<date>, optional)",n("A range or array constant containing the dates to consider holidays."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o=1,i){let s=as(e),r=Math.trunc(Qi(t));"string"==typeof o&&Xi((()=>"1111111"!==o),n("The weekend (%s) must be different from '1111111'.",o));const a=Th(o);let l=new Set;void 0!==i&&cs([i],(e=>{const t=as(e);l.add(t.getTime())}));let c=be.fromTimestamp(s.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-ve.getTime();return Math.round(g/Se)},isExported:!0},Uh={description:n("Year specified by a given date."),args:[el("date (date)",n("The date from which to extract the year."))],returns:["NUMBER"],compute:function(e){return as(e).getFullYear()},isExported:!0},Vh={description:n("Exact number of years between two dates."),args:[el("start_date (date)",n("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.")),el("end_date (date)",n("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.")),el("day_count_convention (number, default=0)",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o=0){let i=Math.trunc(Qi(e)),s=Math.trunc(Qi(t));const r=Math.trunc(Qi(o));return Xi((()=>i>=0),n("The start_date (%s) must be positive or null.",i.toString())),Xi((()=>s>=0),n("The end_date (%s) must be positive or null.",s.toString())),Xi((()=>0<=r&&r<=4),n("The day_count_convention (%s) must be between 0 and 4 inclusive.",r.toString())),Le(i,s,r)}},zh={description:n("First day of the month preceding a date."),args:[el("date (date)",n("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=as(e),o=t.getFullYear(),i=t.getMonth();return Me(new be(o,i,1))}},Bh={description:n("Last day of the month following a date."),args:[el("date (date)",n("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){return Eh.compute(e,0)}},Hh={description:n("Quarter of the year a specific date falls in"),args:[el("date (date)",n("The date from which to extract the quarter."))],returns:["NUMBER"],compute:function(e){return Math.ceil((as(e).getMonth()+1)/3)}},$h={description:n("First day of the quarter of the year a specific date falls in."),args:[el("date (date)",n("The date from which to calculate the start of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Hh.compute(e),o=Uh.compute(e);return Me(new be(o,3*(t-1),1))}},Wh={description:n("Last day of the quarter of the year a specific date falls in."),args:[el("date (date)",n("The date from which to calculate the end of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Hh.compute(e),o=Uh.compute(e);return Me(new be(o,3*t,0))}},Gh={description:n("First day of the year a specific date falls in."),args:[el("date (date)",n("The date from which to calculate the start of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Uh.compute(e);return Me(new be(t,0,1))}},qh={description:n("Last day of the year a specific date falls in."),args:[el("date (date)",n("The date from which to calculate the end of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Uh.compute(e);return Me(new be(t+1,0,0))}};var Zh=Object.freeze({__proto__:null,DATE:ph,DATEDIF:mh,DATEVALUE:fh,DAY:bh,DAYS:vh,DAYS360:Sh,EDATE:Ch,EOMONTH:Eh,HOUR:wh,ISOWEEKNUM:xh,MINUTE:yh,MONTH:Ih,NETWORKDAYS:Rh,NETWORKDAYS_INTL:Ah,NOW:Oh,SECOND:Mh,TIME:Nh,TIMEVALUE:_h,TODAY:Fh,WEEKDAY:Dh,WEEKNUM:Lh,WORKDAY:Ph,WORKDAY_INTL:kh,YEAR:Uh,YEARFRAC:Vh,MONTH_START:zh,MONTH_END:Bh,QUARTER:Hh,QUARTER_START:$h,QUARTER_END:Wh,YEAR_START:Gh,YEAR_END:qh});const jh={description:n("Compare two numeric values, returning 1 if they're equal."),args:[el("number1 (number)",n("The first number to compare.")),el("number2 (number, default=0)",n("The second number to compare."))],returns:["NUMBER"],compute:function(e,t=0){return Qi(e)===Qi(t)?1:0},isExported:!0};var Yh=Object.freeze({__proto__:null,DELTA:jh});function Xh(e,t){Xi((()=>e<t),n("The maturity (%s) must be strictly greater than the settlement (%s).",t.toString(),e.toString()))}function Kh(e,t){Xi((()=>t<e),n("The settlement date (%s) must be strictly greater than the issue date (%s).",e.toString(),t.toString()))}function Qh(e){Xi((()=>[1,2,4].includes(e)),n("The frequency (%s) must be one of %s",e.toString(),[1,2,4].toString()))}function Jh(e){Xi((()=>0<=e&&e<=4),n("The day_count_convention (%s) must be between 0 and 4 inclusive.",e.toString()))}function ed(e){Xi((()=>e>0),n("The redemption (%s) must be strictly positive.",e.toString()))}function td(e){Xi((()=>e>0),n("The price (%s) must be strictly positive.",e.toString()))}function od(e){Xi((()=>e>0),n("The number_of_periods (%s) must be greater than 0.",e.toString()))}function id(e){Xi((()=>e>0),n("The rate (%s) must be strictly positive.",e.toString()))}function sd(e){Xi((()=>e>0),n("The life (%s) must be strictly positive.",e.toString()))}function nd(e){Xi((()=>e>=0),n("The cost (%s) must be positive or null.",e.toString()))}function rd(e){Xi((()=>e>0),n("The period (%s) must be strictly positive.",e.toString()))}function ad(e){Xi((()=>e>=0),n("The salvage (%s) must be positive or null.",e.toString()))}function ld(e){Xi((()=>e>0),n("The present value (%s) must be strictly positive.",e.toString()))}function cd(e,t){Xi((()=>e<=t),n("The period (%s) must be less than or equal life (%s).",e.toString(),t.toString()))}function hd(e){Xi((()=>e>0),n("The investment (%s) must be strictly positive.",e.toString()))}function dd(e){Xi((()=>e>0),n("The discount (%s) must be strictly positive.",e.toString()))}function ud(e){Xi((()=>e<1),n("The discount (%s) must be smaller than 1.",e.toString()))}function gd(e){Xi((()=>e>0),n("The depreciation factor (%s) must be strictly positive.",e.toString()))}function pd(e,t){const o=as(e),i=as(t),s=as(e);s.setFullYear(o.getFullYear()+1),Xi((()=>i.getTime()<=s.getTime()),n("The settlement date (%s) must at most one year after the maturity date (%s).",e.toString(),t.toString()))}function md(e,t,o){od(o),Xi((()=>e>0),n("The first_period (%s) must be strictly positive.",e.toString())),Xi((()=>t>0),n("The last_period (%s) must be strictly positive.",t.toString())),Xi((()=>e<=t),n("The first_period (%s) must be smaller or equal to the last_period (%s).",e.toString(),t.toString())),Xi((()=>t<=o),n("The last_period (%s) must be smaller or equal to the number_of_periods (%s).",e.toString(),o.toString()))}function fd(e){Xi((()=>e>-1),n("The rate_guess (%s) must be strictly greater than -1.",e.toString()))}function bd(e,t){Xi((()=>e.length===t.length&&e[0].length===t[0].length),n("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."))}function vd(e){Xi((()=>e.every((t=>t>=e[0]))),n("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e[0].toString()))}const Sd=[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))];function Cd(e,t,o,i,s=1e-10,r){let a,l,c,h,d=o,u=!1,g=0;do{c=e(d),isNaN(c)?(Xi((()=>g<i&&void 0!==r),n("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<s||Math.abs(c)<s,Xi((()=>g<i),n("Function [[FUNCTION_NAME]] didn't find any result.")),g++)}while(!u);return d}const Ed={description:n("Accrued interest of security paying at maturity."),args:[el("issue (date)",n("The date the security was initially issued.")),el("maturity (date)",n("The maturity date of the security.")),el("rate (number)",n("The annualized rate of interest.")),el("redemption (number)",n("The redemption amount per 100 face value, or par.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const n=Math.trunc(Qi(e)),r=Math.trunc(Qi(t)),a=Qi(i),l=Qi(o),c=Math.trunc(Qi(s));Kh(r,n),Jh(c),ed(a),id(l);return a*l*Vh.compute(n,r,s)},isExported:!0},wd={description:n("Depreciation for an accounting period."),args:[el("cost (number)",n("The initial cost of the asset.")),el("purchase_date (date)",n("The date the asset was purchased.")),el("first_period_end (date)",n("The date the first period ended.")),el("salvage (number)",n("The value of the asset at the end of depreciation.")),el("period (number)",n("The single period within life for which to calculate depreciation.")),el("rate (number)",n("The deprecation rate.")),el("day_count_convention (number, optional)",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r,a=0){a=a||0;const l=Qi(e),c=Math.trunc(Qi(t)),h=Math.trunc(Qi(o)),d=Qi(i),u=Qi(s),g=Qi(r),p=Math.trunc(Qi(a));!function(e){Xi((()=>e>0),n("The cost (%s) must be strictly positive.",e.toString()))}(l),ad(d),function(e,t){Xi((()=>e<=t),n("The salvage (%s) must be smaller or equal than the cost (%s).",e.toString(),t.toString()))}(d,l),function(e){Xi((()=>e>=0),n("The period (%s) must be positive or null.",e.toString()))}(u),id(g),Jh(p),Xi((()=>c<=h),n("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,b=Vh.compute(c,h,p),v=c===h?f:f*b,S=l-v-f*m;return S>=d?0===m?v:f:d-S<f?f-(d-S):0},isExported:!0},xd={description:n("Days in coupon period containing settlement date."),args:Sd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Qi(e)),n=Math.trunc(Qi(t)),r=Math.trunc(Qi(o)),a=Math.trunc(Qi(i));if(Xh(s,n),Qh(r),Jh(a),1===a){const s=Ad.compute(e,t,o,i);return Rd.compute(e,t,o,i)-s}return(3===a?365:360)/r},isExported:!0},yd={description:n("Days from settlement until next coupon."),args:Sd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Qi(e)),n=Math.trunc(Qi(t)),r=Math.trunc(Qi(o)),a=Math.trunc(Qi(i));Xh(s,n),Qh(r),Jh(a);const l=Ad.compute(s,n,o,i);if([1,2,3].includes(a))return s-l;if(4===a){const e=Le(l,s,a);return Math.round(360*e)}const c=as(s),h=as(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&&_e(h)&&_e(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&_e(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},Id={description:n("Days from settlement until next coupon."),args:Sd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Qi(e)),n=Math.trunc(Qi(t)),r=Math.trunc(Qi(o)),a=Math.trunc(Qi(i));Xh(s,n),Qh(r),Jh(a);const l=Rd.compute(s,n,o,i);if([1,2,3].includes(a))return l-s;if(4===a){const e=Le(s,l,a);return Math.round(360*e)}const c=yd.compute(e,t,o,a);return xd.compute(e,t,o,a)-c},isExported:!0},Rd={description:n("Next coupon date after the settlement date."),args:Sd,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Qi(e)),n=Math.trunc(Qi(t)),r=Math.trunc(Qi(o)),a=Math.trunc(Qi(i));Xh(s,n),Qh(r),Jh(a);const l=12/r,c=Td.compute(e,t,o,i);return Me(Fe(as(n),-(c-1)*l,!0))},isExported:!0},Td={description:n("Number of coupons between settlement and maturity."),args:Sd,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Qi(e)),n=Math.trunc(Qi(t)),r=Math.trunc(Qi(o)),a=Math.trunc(Qi(i));Xh(s,n),Qh(r),Jh(a);let l=1,c=n;const h=12/r;for(;c>s;)c=Me(Fe(as(c),-h,!1)),l++;return l-1},isExported:!0},Ad={description:n("Last coupon date prior to or on the settlement date."),args:Sd,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Qi(e)),n=Math.trunc(Qi(t)),r=Math.trunc(Qi(o)),a=Math.trunc(Qi(i));Xh(s,n),Qh(r),Jh(a);const l=12/r,c=Td.compute(e,t,o,i);return Me(Fe(as(n),-c*l,!0))},isExported:!0},Od={description:n("Cumulative interest paid over a set of periods."),args:[el("rate (number)",n("The interest rate.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("present_value (number)",n("The current value of the annuity.")),el("first_period (number)",n("The number of the payment period to begin the cumulative calculation.")),el("last_period (number)",n("The number of the payment period to end the cumulative calculation.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){const r=Qi(i),a=Qi(s),l=Qi(e),c=Qi(o),h=Qi(t);md(r,a,h),id(l),ld(c);let d=0;for(let t=r;t<=a;t++){d+=Bd.compute(e,t,h,o,0,n)}return d},isExported:!0},Md={description:n("Cumulative principal paid over a set of periods."),args:[el("rate (number)",n("The interest rate.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("present_value (number)",n("The current value of the annuity.")),el("first_period (number)",n("The number of the payment period to begin the cumulative calculation.")),el("last_period (number)",n("The number of the payment period to end the cumulative calculation.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){const r=Qi(i),a=Qi(s),l=Qi(e),c=Qi(o),h=Qi(t);md(r,a,h),id(l),ld(c);let d=0;for(let t=r;t<=a;t++){d+=Kd.compute(e,t,h,o,0,n)}return d},isExported:!0},Nd={description:n("Depreciation via declining balance method."),args:[el("cost (number)",n("The initial cost of the asset.")),el("salvage (number)",n("The value of the asset at the end of depreciation.")),el("life (number)",n("The number of periods over which the asset is depreciated.")),el("period (number)",n("The single period within life for which to calculate depreciation.")),el("month (number, optional)",n("The number of months in the first year of depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,...s){const r=Qi(e),a=Qi(t),l=Qi(o),c=Math.trunc(Qi(i)),h=s.length?Math.trunc(Qi(s[0])):12,d=l+(12===h?0:1);nd(r),ad(a),rd(c),sd(l),Xi((()=>1<=h&&h<=12),n("The month (%s) must be between 1 and 12 inclusive.",h.toString())),Xi((()=>c<=d),n("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},_d={description:n("Depreciation via double-declining balance method."),args:[el("cost (number)",n("The initial cost of the asset.")),el("salvage (number)",n("The value of the asset at the end of depreciation.")),el("life (number)",n("The number of periods over which the asset is depreciated.")),el("period (number)",n("The single period within life for which to calculate depreciation.")),el("factor (number, default=2)",n("The factor by which depreciation decreases."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,s=2){s=s||0;const n=Qi(e),r=Qi(t),a=Qi(o),l=Qi(i),c=Qi(s);if(nd(n),ad(r),rd(l),sd(a),cd(l,a),gd(c),0===n||r>=n)return 0;const h=c/a;if(h>1)return 1===i?n-r:0;if(l<=1)return n*h;const d=n*Math.pow(1-h,l-1),u=n*Math.pow(1-h,l),g=u<r?d-r:d-u;return Math.max(g,0)},isExported:!0},Fd={description:n("Discount rate of a security based on price."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("price (number)",n("The price at which the security is bought per 100 face value.")),el("redemption (number)",n("The redemption amount per 100 face value, or par.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const n=Math.trunc(Qi(e)),r=Math.trunc(Qi(t)),a=Qi(o),l=Qi(i),c=Math.trunc(Qi(s));Xh(n,r),Jh(c),td(a),ed(l);return(l-a)/l/Vh.compute(n,r,c)},isExported:!0},Dd={description:n("Convert a decimal fraction to decimal value."),args:[el("fractional_price (number)",n("The price quotation given using fractional decimal conventions.")),el("unit (number)",n("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const o=Qi(e),i=Math.trunc(Qi(t));Xi((()=>i>0),n("The unit (%s) must be strictly positive.",i.toString()));const s=Math.trunc(o);return s+(o-s)*(10**Math.ceil(Math.log10(i))/i)},isExported:!0},Ld={description:n("Convert a decimal value to decimal fraction."),args:[el("decimal_price (number)",n("The price quotation given as a decimal value.")),el("unit (number)",n("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const o=Qi(e),i=Math.trunc(Qi(t));Xi((()=>i>0),n("The unit (%s) must be strictly positive.",i.toString()));const s=Math.trunc(o);return s+(o-s)*(i/10**Math.ceil(Math.log10(i)))},isExported:!0},Pd={description:n("Number of periods for an investment to reach a value."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("rate (number)",n("The annualized rate of interest.")),el("yield (number)",n("The expected annual yield of the security.")),el("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){r=r||0;const a=Math.trunc(Qi(e)),l=Math.trunc(Qi(t)),c=Qi(o),h=Qi(i),d=Math.trunc(Qi(s)),u=Math.trunc(Qi(r));Xh(a,l),Qh(d),Jh(u),Xi((()=>c>=0),n("The rate (%s) must be positive or null.",c.toString())),Xi((()=>h>=0),n("The yield (%s) must be positive or null.",h.toString()));const g=Vh.compute(a,l,u),p=g-Math.trunc(g)||1/d,m=Math.ceil(g*d),f=c/d,b=h/d;let v=0,S=0;for(let e=1;e<=m;e++){const t=(f+(e===m?1:0))/(1+b)**e;S+=(p+(e-1)/d)*t,v+=t}return 0===v?0:S/v},isExported:!0},kd={description:n("Annual effective interest rate."),args:[el("nominal_rate (number)",n("The nominal interest rate per year.")),el("periods_per_year (number)",n("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const o=Qi(e),i=Math.trunc(Qi(t));return Xi((()=>o>0),n("The nominal rate (%s) must be strictly greater than 0.",o.toString())),Xi((()=>i>0),n("The number of periods by year (%s) must strictly greater than 0.",i.toString())),Math.pow(1+o/i,i)-1},isExported:!0},Ud={description:n("Future value of an annuity investment."),args:[el("rate (number)",n("The interest rate.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("payment_amount (number)",n("The amount per period to be paid.")),el("present_value (number, default=0)",n("The current value of the annuity.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const n=Qi(e),r=Qi(t),a=Qi(o),l=Qi(i),c=rs(s)?1:0;return n?-l*(1+n)**r-a*(1+n*c)*((1+n)**r-1)/n:-(l+a*r)},isExported:!0},Vd={description:n("Future value of principal from series of rates."),args:[el("principal (number)",n("The amount of initial capital or value to compound against.")),el("rate_schedule (number, range<number>)",n("A series of interest rates to compound against the principal."))],returns:["NUMBER"],compute:function(e,t){return us([t],((e,t)=>e*(1+Qi(t))),Qi(e))},isExported:!0},zd={description:n("Calculates effective interest rate."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("investment (number)",n("The amount invested in the security.")),el("redemption (number)",n("The amount to be received at maturity.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){const n=Math.trunc(Qi(e)),r=Math.trunc(Qi(t)),a=Qi(i),l=Qi(o);Xh(n,r),hd(l),ed(a);return(a-l)/l/Vh.compute(n,r,s)},isExported:!0},Bd={description:n("Payment on the principal of an investment."),args:[el("rate (number)",n("The annualized rate of interest.")),el("period (number)",n("The amortization period, in terms of number of periods.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("present_value (number)",n("The current value of the annuity.")),el("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,s=0,n=0){return Xd.compute(e,o,i,s,n)-Kd.compute(e,t,o,i,s,n)},isExported:!0},Hd={description:n("Internal rate of return given periodic cashflows."),args:[el("cashflow_amounts (number, range<number>)",n("An array or range containing the income or payments associated with the investment.")),el("rate_guess (number, default=0.1)",n("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t=.1){const o=Qi(t);fd(o);let i=!1,s=!1,r=[];hs([e],(e=>{e>0&&(i=!0),e<0&&(s=!0),r.push(e)})),Xi((()=>i&&s),n("The cashflow_amounts must include negative and positive values."));const a=r.shift();return Cd((function(e){return function(e,t,o){const i=o.length;let s=0;return o.reduce(((t,o)=>(s++,t+o*e**(i-s))),t*e**i)}(e,a,r)}),(function(e){return function(e,t,o){const i=o.length;let s=0;return o.reduce(((t,o)=>(s++,t+o*(i-s)*e**(i-s-1))),t*i*e**(i-1))}(e,a,r)}),o+1,20,1e-5)-1},isExported:!0},$d={description:n("Returns the interest paid at a particular period of an investment."),args:[el("rate (number)",n("The interest rate.")),el("period (number)",n("The period for which you want to view the interest payment.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("present_value (number)",n("The current value of the annuity."))],returns:["NUMBER"],compute:function(e,t,o,i){const s=Qi(e),r=Qi(t),a=Qi(o),l=Qi(i);Xi((()=>0!==a),n("The number of periods must be different than 0.",a.toString()));return-1*(l-l*(r/a))*s},isExported:!0},Wd={description:n("Modified Macaulay duration."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("rate (number)",n("The annualized rate of interest.")),el("yield (number)",n("The expected annual yield of the security.")),el("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){return Pd.compute(e,t,o,i,s,n)/(1+Qi(i)/Math.trunc(Qi(s)))},isExported:!0},Gd={description:n("Modified internal rate of return."),args:[el("cashflow_amounts (range<number>)",n("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),el("financing_rate (number)",n("The interest rate paid on funds invested.")),el("reinvestment_return_rate (number)",n("The return (as a percentage) earned on reinvestment of income received from the investment."))],returns:["NUMBER"],compute:function(e,t,o){const i=Qi(t),s=Qi(o),r=(a=e,a.length?a[0].map(((e,t)=>a.map((e=>e[t])))):a).flat().filter(dt).map(Qi);var a;const l=r.length;let c=0,h=0;for(const e of Ke(0,l)){const t=r[e];t>=0?c+=t*(s+1)**(l-e-1):h+=t/(i+1)**e}Xi((()=>0!==h&&0!==c),n("There must be both positive and negative values in cashflow_amounts."));return(-c/h)**(1/(l-1))-1},isExported:!0},qd={description:n("Annual nominal interest rate."),args:[el("effective_rate (number)",n("The effective interest rate per year.")),el("periods_per_year (number)",n("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const o=Qi(e),i=Math.trunc(Qi(t));return Xi((()=>o>0),n("The effective rate (%s) must must strictly greater than 0.",o.toString())),Xi((()=>i>0),n("The number of periods by year (%s) must strictly greater than 0.",i.toString())),(Math.pow(o+1,1/i)-1)*i},isExported:!0},Zd={description:n("Number of payment periods for an investment."),args:[el("rate (number)",n("The interest rate.")),el("payment_amount (number)",n("The amount of each payment made.")),el("present_value (number)",n("The current value of the annuity.")),el("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const n=Qi(e),r=Qi(t),a=Qi(o),l=Qi(i),c=rs(s)?1:0;if(0===n)return-(l+a)/r;const h=r*(1+n*c)/n;return Math.log((h-l)/(a+h))/Math.log(1+n)},isExported:!0};const jd={description:n("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:[el("discount (number)",n("The discount rate of the investment over one period.")),el("cashflow1 (number, range<number>)",n("The first future cash flow.")),el("cashflow2 (number, range<number>, repeating)",n("Additional future cash flows."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,...t){const o=Qi(e);return Xi((()=>-1!==o),n("The discount (%s) must be different from -1.",o.toString())),function(e,t,o){let i=0;return gs(o,((t,o)=>(i++,t+o/(1+e)**i)),t)}(o,0,t)},isExported:!0},Yd={description:n("Computes the number of periods needed for an investment to reach a value."),args:[el("rate (number)",n("The rate at which the investment grows each period.")),el("present_value (number)",n("The investment's current value.")),el("future_value (number)",n("The investment's desired future value."))],returns:["NUMBER"],compute:function(e,t,o){const i=Qi(e),s=Qi(t),r=Qi(o);return id(i),Xi((()=>s>0),n("The present_value (%s) must be strictly positive.",s.toString())),Xi((()=>r>0),n("The future_value (%s) must be strictly positive.",r.toString())),(Math.log(r)-Math.log(s))/Math.log(1+i)},isExported:!0},Xd={description:n("Periodic payment for an annuity investment."),args:[el("rate (number)",n("The annualized rate of interest.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("present_value (number)",n("The current value of the annuity.")),el("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const n=Qi(t),r=Qi(e),a=rs(s)?1:0;let l=Qi(i),c=Qi(o);if(od(n),0===r)return-(l+c)/n;let h=-(c*(1+r)**n+l);return h=h*r/((1+r*a)*((1+r)**n-1)),h},isExported:!0},Kd={description:n("Payment on the principal of an investment."),args:[el("rate (number)",n("The annualized rate of interest.")),el("period (number)",n("The amortization period, in terms of number of periods.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("present_value (number)",n("The current value of the annuity.")),el("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,s=0,r=0){s=s||0,r=r||0;const a=Qi(o),l=Qi(e),c=Qi(t),h=rs(r)?1:0,d=Qi(s),u=Qi(i);od(a),Xi((()=>c>0&&c<=a),n("The period must be between 1 and number_of_periods",a.toString()));const g=Xd.compute(l,a,u,d,r);if(1===h&&1===c)return g;return g+-Ud.compute(l,0===h?c-1:c-2,g,u+g*h,0)*l},isExported:!0},Qd={description:n("Present value of an annuity investment."),args:[el("rate (number)",n("The interest rate.")),el("number_of_periods (number)",n("The number of payments to be made.")),el("payment_amount (number)",n("The amount per period to be paid.")),el("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,s=0){i=i||0,s=s||0;const n=Qi(e),r=Qi(t),a=Qi(o),l=Qi(i),c=rs(s)?1:0;return n?-(a*(1+n*c)*((1+n)**r-1)/n+l)/(1+n)**r:-(l+a*r)},isExported:!0},Jd={description:n("Price of a security paying periodic interest."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("rate (number)",n("The annualized rate of interest.")),el("yield (number)",n("The expected annual yield of the security.")),el("redemption (number)",n("The redemption amount per 100 face value, or par.")),el("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r,a=0){a=a||0;const l=Math.trunc(Qi(e)),c=Math.trunc(Qi(t)),h=Qi(o),d=Qi(i),u=Qi(s),g=Math.trunc(Qi(r)),p=Math.trunc(Qi(a));Xh(l,c),Qh(g),Jh(p),Xi((()=>h>=0),n("The rate (%s) must be positive or null.",h.toString())),Xi((()=>d>=0),n("The yield (%s) must be positive or null.",d.toString())),ed(u);const m=Vh.compute(l,c,p)*g,f=Math.ceil(m),b=m-Math.floor(m)||1,v=1+d/g,S=100*h/g;if(1===f)return(S+u)/(b*d/g+1)-S*(1-b);let C=0;for(let e=1;e<=f;e++)C+=S/v**(e-1+b);return u/v**(f-1+b)+C-S*(1-b)},isExported:!0},eu={description:n("Price of a discount security."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("discount (number)",n("The discount rate of the security at time of purchase.")),el("redemption (number)",n("The redemption amount per 100 face value, or par.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const n=Math.trunc(Qi(e)),r=Math.trunc(Qi(t)),a=Qi(o),l=Qi(i),c=Math.trunc(Qi(s));Xh(n,r),Jh(c),dd(a),ed(l);return l-a*l*Vh.compute(n,r,c)},isExported:!0},tu={description:n("Calculates the price of a security paying interest at maturity, based on expected yield."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("issue (date)",n("The date the security was initially issued.")),el("rate (number)",n("The annualized rate of interest.")),el("yield (number)",n("The expected annual yield of the security.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){r=r||0;const a=Math.trunc(Qi(e)),l=Math.trunc(Qi(t)),c=Math.trunc(Qi(o)),h=Qi(i),d=Qi(s),u=Math.trunc(Qi(r));Kh(a,c),Xh(a,l),Jh(u),Xi((()=>h>=0),n("The rate (%s) must be positive or null.",h.toString())),Xi((()=>d>=0),n("The yield (%s) must be positive or null.",d.toString()));const g=Vh.compute(a,l,u),p=Vh.compute(a,c,u);return(100+Vh.compute(c,l,u)*h*100)/(1+g*d)-p*h*100},isExported:!0},ou=.1,iu={description:n("Interest rate of an annuity investment."),args:[el("number_of_periods (number)",n("The number of payments to be made.")),el("payment_per_period (number)",n("The amount per period to be paid.")),el("present_value (number)",n("The current value of the annuity.")),el("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),el("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period.")),el("rate_guess (number, default=0.1)",n("An estimate for what the interest rate will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t,o,i=0,s=0,r=.1){i=i||0,s=s||0,r=r||ou;const a=Qi(e),l=Qi(t),c=rs(s)?1:0,h=Qi(r);let d=Qi(i),u=Qi(o);od(a),Xi((()=>[l,u,d].some((e=>e>0))&&[l,u,d].some((e=>e<0))),n("There must be both positive and negative values in [payment_amount, present_value, future_value].",a.toString())),fd(h),d-=l*c,u+=l*c;return Cd((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),o=Math.pow(1+e,a);return u*a*t+l*(a*t/e-(o-1)/e/e)}),h,40,1e-5)},isExported:!0},su={description:n("Amount received at maturity for a security."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("investment (number)",n("The amount invested (irrespective of face value of each security).")),el("discount (number)",n("The discount rate of the security invested in.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const n=Math.trunc(Qi(e)),r=Math.trunc(Qi(t)),a=Qi(o),l=Qi(i),c=Math.trunc(Qi(s));Xh(n,r),Jh(c),hd(a),dd(l);return a/(1-l*Vh.compute(n,r,c))},isExported:!0},nu={description:n("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[el("number_of_periods (number)",n("The number of periods.")),el("present_value (number)",n("The present value of the investment.")),el("future_value (number)",n("The future value of the investment."))],returns:["NUMBER"],compute:function(e,t,o){const i=Qi(e),s=Qi(t),n=Qi(o);return od(i),(n/s)**(1/i)-1},isExported:!0},ru={description:n("Depreciation of an asset using the straight-line method."),args:[el("cost (number)",n("The initial cost of the asset.")),el("salvage (number)",n("The value of the asset at the end of depreciation.")),el("life (number)",n("The number of periods over which the asset is depreciated."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o){return(Qi(e)-Qi(t))/Qi(o)},isExported:!0},au={description:n("Depreciation via sum of years digit method."),args:[el("cost (number)",n("The initial cost of the asset.")),el("salvage (number)",n("The value of the asset at the end of depreciation.")),el("life (number)",n("The number of periods over which the asset is depreciated.")),el("period (number)",n("The single period within life for which to calculate depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i){const s=Qi(e),n=Qi(t),r=Qi(o),a=Qi(i);rd(a),sd(r),cd(a,r);return(r-a+1)/(r*(r+1)/2)*(s-n)},isExported:!0},lu={description:n("Price of a US Treasury bill."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("discount (number)",n("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Qi(e)),s=Math.trunc(Qi(t)),n=Qi(o);Xh(i,s),pd(i,s),dd(n),ud(n);return 100*(1-n*Vh.compute(i,s,2))},isExported:!0},cu={description:n("Equivalent rate of return for a US Treasury bill."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("discount (number)",n("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Qi(e)),s=Math.trunc(Qi(t)),n=Qi(o);Xh(i,s),pd(i,s),dd(n),ud(n);const r=vh.compute(s,i);if(r<=182)return 365*n/(360-n*r);const a=lu.compute(i,s,n)/100,l=r/(366===r?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},hu={description:n("The yield of a US Treasury bill based on price."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("price (number)",n("The price at which the security is bought per 100 face value."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Qi(e)),s=Math.trunc(Qi(t)),n=Qi(o);Xh(i,s),pd(i,s),td(n);return(100-n)/n*(1/Vh.compute(i,s,2))},isExported:!0},du={description:n("Variable declining balance. WARNING : does not handle decimal periods."),args:[el("cost (number)",n("The initial cost of the asset.")),el("salvage (number)",n("The value of the asset at the end of depreciation.")),el("life (number)",n("The number of periods over which the asset is depreciated.")),el("start (number)",n("Starting period to calculate depreciation.")),el("end (number)",n("Ending period to calculate depreciation.")),el("factor (number, default=2)",n("The number of months in the first year of depreciation.")),el("no_switch (number, default=false)",n("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=2,a=false){r=r||0;const l=Qi(e),c=Qi(t),h=Qi(o),d=Math.trunc(Qi(i)),u=Math.trunc(Qi(s)),g=Qi(r),p=rs(a);if(nd(l),ad(c),function(e,t,o){sd(o),Xi((()=>e>=0),n("The start_period (%s) must be greater or equal than 0.",e.toString())),Xi((()=>t>=0),n("The end_period (%s) must be greater or equal than 0.",t.toString())),Xi((()=>e<=t),n("The start_period (%s) must be smaller or equal to the end_period (%s).",e.toString(),t.toString())),Xi((()=>t<=o),n("The end_period (%s) must be smaller or equal to the life (%s).",e.toString(),o.toString()))}(d,u,h),gd(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,b=0,v=0,S=!1;for(let e=0;e<u;e++){if(!S||p){const t=f*m,o=(f-c)/(h-e);!p&&o>t?(S=!0,b=o):b=t}const t=Math.max(f-b,c);e>=d&&(v+=f-t),f=t}return v},isExported:!0},uu={description:n("Internal rate of return given non-periodic cash flows."),args:[el("cashflow_amounts (range<number>)",n("An range containing the income or payments associated with the investment.")),el("cashflow_dates (range<number>)",n("An range with dates corresponding to the cash flows in cashflow_amounts.")),el("rate_guess (number, default=0.1)",n("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],compute:function(e,t,o=.1){const i=Qi(o=o||0),s=e.flat().map(Qi),r=t.flat().map(Qi);var a;bd(e,t),a=s,Xi((()=>a.some((e=>e>0))&&a.some((e=>e<0))),n("There must be both positive and negative values in cashflow_amounts.")),vd(r),fd(i);const l=new Map;for(const e of Ke(0,r.length)){const t=r[e];l.has(t)?l.set(t,l.get(t)+s[e]):l.set(t,s[e])}const c=Array.from(l.keys()),h=c.map((e=>l.get(e)));return Cd((e=>{let t=h[0];for(const o of Ke(1,h.length)){const i=(c[0]-c[o])/365;t+=h[o]*(1+e)**i}return t}),(e=>{let t=0;for(const o of Ke(1,h.length)){const i=(c[0]-c[o])/365;t+=i*h[o]*(1+e)**(i-1)}return t}),i,40,1e-5,(e=>e?e/10-.9:-.9))},isExported:!0},gu={description:n("Net present value given to non-periodic cash flows.."),args:[el("discount (number)",n("The discount rate of the investment over one period.")),el("cashflow_amounts (number, range<number>)",n("An range containing the income or payments associated with the investment.")),el("cashflow_dates (number, range<number>)",n("An range with dates corresponding to the cash flows in cashflow_amounts."))],returns:["NUMBER"],compute:function(e,t,o){const i=Qi(e),s=Array.isArray(t)?t.flat().map(Ji):[Ji(t)],r=Array.isArray(o)?o.flat().map(Ji):[Ji(o)];if(Array.isArray(o)&&Array.isArray(t)?bd(t,o):Xi((()=>s.length===r.length),n("There must be the same number of values in cashflow_amounts and cashflow_dates.")),vd(r),id(i),1===s.length)return s[0];const a=new Map;for(const e of Ke(0,r.length)){const t=r[e];a.has(t)?a.set(t,a.get(t)+s[e]):a.set(t,s[e])}const l=Array.from(a.keys()),c=l.map((e=>a.get(e)));let h=c[0];for(const e of Ke(1,c.length)){const t=(l[0]-l[e])/365;h+=c[e]*(1+i)**t}return h},isExported:!0},pu={description:n("Annual yield of a security paying periodic interest."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("rate (number)",n("The annualized rate of interest.")),el("price (number)",n("The price at which the security is bought per 100 face value.")),el("redemption (number)",n("The redemption amount per 100 face value, or par.")),el("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r,a=0){a=a||0;const l=Math.trunc(Qi(e)),c=Math.trunc(Qi(t)),h=Qi(o),d=Qi(i),u=Qi(s),g=Math.trunc(Qi(r)),p=Math.trunc(Qi(a));Xh(l,c),Qh(g),Jh(p),Xi((()=>h>=0),n("The rate (%s) must be positive or null.",h.toString())),td(d),ed(u);const m=Vh.compute(l,c,p)*g,f=Math.ceil(m),b=m-Math.floor(m)||1,v=100*h/g;if(1===f){const e=d+v*(1-b);return(u+v-e)*g*(1/b)/e}const S=Cd((function(e){return function(e,t,o,i,s,n){let r=n-(e+s*(1-t))*i**(o-1+t);for(let e=1;e<=o;e++)r+=s*i**(e-1);return r}(d,b,f,e,v,u)}),(function(e){return function(e,t,o,i,s){let n=-(e+s*(1-t))*(o-1+t)*i**(o-2+t);for(let e=1;e<=o;e++)n+=s*(e-1)*i**(e-2);return n}(d,b,f,e,v)}),1+(h+1)/g,100,1e-5);return(S-1)*g},isExported:!0},mu={description:n("Annual yield of a discount security."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("price (number)",n("The price at which the security is bought per 100 face value.")),el("redemption (number)",n("The redemption amount per 100 face value, or par.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const n=Math.trunc(Qi(e)),r=Math.trunc(Qi(t)),a=Qi(o),l=Qi(i),c=Math.trunc(Qi(s));Xh(n,r),Jh(c),td(a),ed(l);return(l/a-1)/Vh.compute(e,t,s)},isExported:!0},fu={description:n("Annual yield of a security paying interest at maturity."),args:[el("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),el("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),el("issue (date)",n("The date the security was initially issued.")),el("rate (number)",n("The annualized rate of interest.")),el("price (number)",n("The price at which the security is bought.")),el("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){r=r||0;const a=Math.trunc(Qi(e)),l=Math.trunc(Qi(t)),c=Math.trunc(Qi(o)),h=Qi(i),d=Qi(s),u=Math.trunc(Qi(r));Xh(a,l),Jh(u),Xi((()=>a>=c),n("The settlement (%s) must be greater than or equal to the issue (%s).",a.toString(),c.toString())),Xi((()=>h>=0),n("The rate (%s) must be positive or null.",h.toString())),td(d);const g=Vh.compute(c,l,u),p=Vh.compute(c,a,u),m=Vh.compute(a,l,u);return(100*(1+h*g)/(d+100*h*p)-1)/m},isExported:!0};var bu=Object.freeze({__proto__:null,ACCRINTM:Ed,AMORLINC:wd,COUPDAYS:xd,COUPDAYBS:yd,COUPDAYSNC:Id,COUPNCD:Rd,COUPNUM:Td,COUPPCD:Ad,CUMIPMT:Od,CUMPRINC:Md,DB:Nd,DDB:_d,DISC:Fd,DOLLARDE:Dd,DOLLARFR:Ld,DURATION:Pd,EFFECT:kd,FV:Ud,FVSCHEDULE:Vd,INTRATE:zd,IPMT:Bd,IRR:Hd,ISPMT:$d,MDURATION:Wd,MIRR:Gd,NOMINAL:qd,NPER:Zd,NPV:jd,PDURATION:Yd,PMT:Xd,PPMT:Kd,PV:Qd,PRICE:Jd,PRICEDISC:eu,PRICEMAT:tu,RATE:iu,RECEIVED:su,RRI:nu,SLN:ru,SYD:au,TBILLPRICE:lu,TBILLEQ:cu,TBILLYIELD:hu,VDB:du,XIRR:uu,XNPV:gu,YIELD:pu,YIELDDISC:mu,YIELDMAT:fu});const vu={description:n("Whether a value is an error other than #N/A."),args:[el("value (any, lazy)",n("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return e?.errorType!=a.NotAvailable}},isExported:!0},Su={description:n("Whether a value is an error."),args:[el("value (any, lazy)",n("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},Cu={description:n("Whether a value is `true` or `false`."),args:[el("value (any, lazy)",n("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},Eu={description:n("Whether a value is the error #N/A."),args:[el("value (any, lazy)",n("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return e?.errorType==a.NotAvailable}},isExported:!0},wu={description:n("Whether a value is non-textual."),args:[el("value (any, lazy)",n("The value to be checked."))],returns:["BOOLEAN"],compute:function(e){try{return"string"!=typeof e()}catch(e){return!0}},isExported:!0},xu={description:n("Whether a value is a number."),args:[el("value (any, lazy)",n("The value to be verified as a number."))],returns:["BOOLEAN"],compute:function(e){try{return"number"==typeof e()}catch(e){return!1}},isExported:!0},yu={description:n("Whether a value is text."),args:[el("value (any, lazy)",n("The value to be verified as text."))],returns:["BOOLEAN"],compute:function(e){try{return"string"==typeof e()}catch(e){return!1}},isExported:!0},Iu={description:n("Whether the referenced cell is empty"),args:[el("value (any, lazy)",n("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},Ru={description:n("Returns the error value #N/A."),args:[],returns:["BOOLEAN"],compute:function(e){throw new g},isExported:!0};var Tu=Object.freeze({__proto__:null,ISERR:vu,ISERROR:Su,ISLOGICAL:Cu,ISNA:Eu,ISNONTEXT:wu,ISNUMBER:xu,ISTEXT:yu,ISBLANK:Iu,NA:Ru});const Au={description:n("Logical `and` operator."),args:[el("logical_expression1 (boolean, range<boolean>)",n("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.")),el("logical_expression2 (boolean, range<boolean>, repeating)",n("More expressions that represent logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!0;return ms(e,(e=>(t=!0,o=o&&e,o))),Xi((()=>t),n("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},Ou={description:n("Returns value depending on logical expression."),args:[el("logical_expression (boolean)",n("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")),el("value_if_true (any, lazy)",n("The value the function returns if logical_expression is TRUE.")),el("value_if_false (any, lazy, default=FALSE)",n("The value the function returns if logical_expression is FALSE."))],returns:["ANY"],compute:function(e,t,o=(()=>!1)){const i=rs(e)?t():o();return null==i?"":i},isExported:!0},Mu={description:n("Value if it is not an error, otherwise 2nd argument."),args:[el("value (any, lazy)",n("The value to return if value itself is not an error.")),el('value_if_error (any, lazy, default="empty")',n("The value the function returns if value is an error."))],returns:["ANY"],computeFormat:(e,t=(()=>({value:""})))=>{try{return e().format}catch(e){return t()?.format}},compute:function(e,t=(()=>"")){let o;try{o=e()}catch(e){o=t()}return null==o?"":o},isExported:!0},Nu={description:n("Value if it is not an #N/A error, otherwise 2nd argument."),args:[el("value (any, lazy)",n("The value to return if value itself is not #N/A an error.")),el('value_if_error (any, lazy, default="empty")',n("The value the function returns if value is an #N/A error."))],returns:["ANY"],compute:function(e,t=(()=>"")){let o;try{o=e()}catch(i){o=i.errorType===a.NotAvailable?t():e()}return null==o?"":o},isExported:!0},_u={description:n("Returns a value depending on multiple logical expressions."),args:[el("condition1 (boolean, lazy)",n("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")),el("value1 (any, lazy)",n("The returned value if condition1 is TRUE.")),el("condition2 (boolean, lazy, repeating)",n("Additional conditions to be evaluated if the previous ones are FALSE.")),el("value2 (any, lazy, repeating)",n("Additional values to be returned if their corresponding conditions are TRUE."))],returns:["ANY"],compute:function(...e){Xi((()=>e.length%2==0),n("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(rs(e[t]())){const o=e[t+1]();return null!==o?o:""}throw new Error(n("No match."))},isExported:!0},Fu={description:n("Returns opposite of provided logical value."),args:[el("logical_expression (boolean)",n("An expression or reference to a cell holding an expression that represents some logical value."))],returns:["BOOLEAN"],compute:function(e){return!rs(e)},isExported:!0},Du={description:n("Logical `or` operator."),args:[el("logical_expression1 (boolean, range<boolean>)",n("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.")),el("logical_expression2 (boolean, range<boolean>, repeating)",n("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!1;return ms(e,(e=>(t=!0,o=o||e,!o))),Xi((()=>t),n("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},Lu={description:n("Logical `xor` operator."),args:[el("logical_expression1 (boolean, range<boolean>)",n("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.")),el("logical_expression2 (boolean, range<boolean>, repeating)",n("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!1;return ms(e,(e=>(t=!0,o=o?!e:e,!0))),Xi((()=>t),n("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0};var Pu=Object.freeze({__proto__:null,AND:Au,IF:Ou,IFERROR:Mu,IFNA:Nu,IFS:_u,NOT:Fu,OR:Du,XOR:Lu});function ku(e,t){if(void 0===e)throw new g(n("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",os(t)))}const Uu={description:n("Returns a cell reference as a string. "),args:[el("row (number)",n("The row number of the cell reference. ")),el("column (number)",n("The column number (not name) of the cell reference. A is column number 1. ")),el("absolute_relative_mode (number, default=1)",n("An indicator of whether the reference is row/column absolute. 1 is row and column absolute (e.g. $A$1), 2 is row absolute and column relative (e.g. A$1), 3 is row relative and column absolute (e.g. $A1), and 4 is row and column relative (e.g. A1).")),el("use_a1_notation (boolean, default=TRUE)",n("A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).")),el("sheet (string, optional)",n("A string indicating the name of the sheet into which the address points."))],returns:["STRING"],compute:function(e,t,o=1,i=!0,s){const r=es(e),a=es(t);ts(r),ts(a);const l=es(o);var c,h;Xi((()=>[1,2,3,4].includes(l)),(c=4,h=l,n("The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.",1..toString(),c.toString(),h.toString())));let d;if(rs(i)){d=Zt(a-1,r-1,{rowFixed:!![1,2].includes(l),colFixed:!![1,3].includes(l)})}else{d=([1,2].includes(l)?`R${r}`:`R[${r}]`)+([1,3].includes(l)?`C${a}`:`C[${a}]`)}return void 0!==s?`${$e(os(s))}!${d}`:d},isExported:!0},Vu={description:n("Column number of a specified cell."),args:[el("cell_reference (meta, default='this cell')",n("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){const t=e||this.__originCellXC?.();Xi((()=>!!t),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return ii(t).left+1},isExported:!0},zu={description:n("Number of columns in a specified array or range."),args:[el("range (meta)",n("The range whose column count will be returned."))],returns:["NUMBER"],compute:function(e){const t=ii(e);return t.right-t.left+1},isExported:!0},Bu={description:n("Horizontal lookup"),args:[el("search_key (any)",n("The value to search for. For example, 42, 'Cats', or I24.")),el("range (range)",n("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")),el("index (number)",n("The row index of the value to be returned, where the first row in range is numbered 1.")),el("is_sorted (boolean, default=true)",n("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,o,i=true){const s=Math.trunc(Qi(o)),r=ss(e);Xi((()=>1<=s&&s<=t[0].length),n("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=rs(i)?Es(t,r,"nextSmaller","asc",t.length,Cs):ws(t,r,"strict",t.length,Cs);const l=t[a];return ku(l,e),l[s-1]},isExported:!0},Hu={description:n("Returns the content of a cell, specified by row and column offset."),args:[el("reference (any, range)",n("The range of cells from which the values are returned.")),el("row (number)",n("The index of the row to be returned from within the reference range of cells.")),el("column (number)",n("The index of the column to be returned from within the reference range of cells."))],returns:["ANY"],computeFormat:(e,t,o)=>{const i=Qi(t.value);return e[Qi(o.value)-1][i-1]?.format},compute:function(e,t,o){const i=(s=e,Array.isArray(s)&&Array.isArray(s[0])?e:[[e]]);var s;const r=Qi(t),a=Qi(o);return Xi((()=>a>=0&&a-1<i.length&&r>=0&&r-1<i[0].length),n("Index out of range.")),Xi((()=>0!==t&&0!==o),n("This function can only return a single cell value, not an array. Provide valid row and column indices.")),i[a-1][r-1]},isExported:!0},$u={description:n("Look up a value."),args:[el("search_key (any)",n("The value to search for. For example, 42, 'Cats', or I24.")),el("search_array (range)",n("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.")),el("result_range (range, optional)",n("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,o){let i=t.length,s=t[0].length;const r=ss(e),a=s>=i,l=Es(t,r,"nextSmaller","asc",a?s:i,a?Ss:Cs);return-1===l&&ku(void 0,e),ku(a?t[0][l]:t[l][s-1],e),void 0===o?a?t[i-1][l]:t[l][s-1]:(i=o.length,s=o[0].length,Xi((()=>1===i||1===s),n("The result_range must be a single row or a single column.")),i>1?(Xi((()=>l<=i-1),n("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(l+1).toString())),o[l][0]):(Xi((()=>l<=s-1),n("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(l+1).toString())),o[0][l]))},isExported:!0},Wu={description:n("Position of item in range that matches value."),args:[el("search_key (any)",n("The value to search for. For example, 42, 'Cats', or I24.")),el("range (any, range)",n("The one-dimensional array to be searched.")),el("search_type (number, default=1)",n("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,o=1){let i=Qi(o);const s=ss(e),r=t.length,a=t[0].length;Xi((()=>1===r||1===a),n("The range must be a single row or a single column."));let l=-1;const c=1===r?Ss:Cs,h=1===r?t[0].length:t.length;switch(i=Math.sign(i),i){case 1:l=Es(t,s,"nextSmaller","asc",h,c);break;case 0:l=ws(t,s,"strict",h,c);break;case-1:l=Es(t,s,"nextGreater","desc",h,c)}return ku(1===r?t[0][l]:t[l],e),l+1},isExported:!0},Gu={description:n("Row number of a specified cell."),args:[el("cell_reference (meta, default='this cell')",n("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){e=e||this.__originCellXC?.(),Xi((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return ii(e).top+1},isExported:!0},qu={description:n("Number of rows in a specified array or range."),args:[el("range (meta)",n("The range whose row count will be returned."))],returns:["NUMBER"],compute:function(e){const t=ii(e);return t.bottom-t.top+1},isExported:!0},Zu={description:n("Vertical lookup."),args:[el("search_key (any)",n("The value to search for. For example, 42, 'Cats', or I24.")),el("range (any, range)",n("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")),el("index (number)",n("The column index of the value to be returned, where the first column in range is numbered 1.")),el("is_sorted (boolean, default=true)",n("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,o,i=true){const s=Math.trunc(Qi(o)),r=ss(e);Xi((()=>1<=s&&s<=t.length),n("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=rs(i)?Es(t,r,"nextSmaller","asc",t[0].length,Ss):ws(t,r,"strict",t[0].length,Ss);const l=t[s-1][a];return ku(l,e),l},isExported:!0},ju={description:n("Search a range for a match and return the corresponding item from a second range."),args:[el("search_key (any)",n("The value to search for.")),el("lookup_range (any, range)",n("The range to consider for the search. Should be a single column or a single row.")),el("return_range (any, range)",n("The range containing the return value. Should have the same dimensions as lookup_range.")),el("if_not_found (any, lazy, optional)",n("If a valid match is not found, return this value.")),el("match_mode (any, default=0)",n("(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match.")),el("search_mode (any, default=1)",n("(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,o,i,s=0,r=1){const a=Math.trunc(Qi(s)),l=Math.trunc(Qi(r)),c=ss(e);Xi((()=>1===t.length||1===t[0].length),n("lookup_range should be either a single row or single column.")),Xi((()=>1===o.length||1===o[0].length),n("return_range should be either a single row or single column.")),Xi((()=>o.length===t.length&&o[0].length===t[0].length),n("return_range should have the same dimensions as lookup_range.")),Xi((()=>[-1,1,-2,2].includes(l)),n("searchMode should be a value in [-1, 1, -2, 2].")),Xi((()=>[-1,0,1].includes(a)),n("matchMode should be a value in [-1, 0, 1]."));const h=1===t.length?Ss:Cs,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=Es(t,c,u,2===l?"asc":"desc",d,h)}else p=ws(t,c,u,d,h,g);if(-1!==p)return 1===t.length?o[0][p]:o[p][0];const m=i?.();return ku(m,e),m},isExported:!0};var Yu=Object.freeze({__proto__:null,ADDRESS:Uu,COLUMN:Vu,COLUMNS:zu,HLOOKUP:Bu,INDEX:Hu,LOOKUP:$u,MATCH:Wu,ROW:Gu,ROWS:qu,VLOOKUP:Zu,XLOOKUP:ju});const Xu={description:n("Sum of two numbers."),args:[el("value1 (number)",n("The first addend.")),el("value2 (number)",n("The second addend."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Qi(e)+Qi(t)}},Ku={description:n("Concatenation of two values."),args:[el("value1 (string)",n("The value to which value2 will be appended.")),el("value2 (string)",n("The value to append to value1."))],returns:["STRING"],compute:function(e,t){return os(e)+os(t)},isExported:!0},Qu={description:n("One number divided by another."),args:[el("dividend (number)",n("The number to be divided.")),el("divisor (number)",n("The number to divide by."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){const o=Qi(t);return Xi((()=>0!==o),n("The divisor must be different from zero.")),Qi(e)/o}};function Ju(e){return null==e}const eg={number:0,string:"",boolean:!1},tg={description:n("Equal."),args:[el("value1 (any)",n("The first value.")),el("value2 (any)",n("The value to test against value1 for equality."))],returns:["BOOLEAN"],compute:function(e,t){return e=Ju(e)?eg[typeof t]:e,t=Ju(t)?eg[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function og(e,t,o){e=Ju(e)?eg[typeof t]:e,t=Ju(t)?eg[typeof e]:t,"number"!=typeof e&&(e=os(e).toUpperCase()),"number"!=typeof t&&(t=os(t).toUpperCase());const i=typeof e,s=typeof t;return"string"===i&&"number"===s||("string"!==s||"number"!==i)&&o(e,t)}const ig={description:n("Strictly greater than."),args:[el("value1 (any)",n("The value to test as being greater than value2.")),el("value2 (any)",n("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return og(e,t,((e,t)=>e>t))}},sg={description:n("Greater than or equal to."),args:[el("value1 (any)",n("The value to test as being greater than or equal to value2.")),el("value2 (any)",n("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return og(e,t,((e,t)=>e>=t))}},ng={description:n("Less than."),args:[el("value1 (any)",n("The value to test as being less than value2.")),el("value2 (any)",n("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!sg.compute(e,t)}},rg={description:n("Less than or equal to."),args:[el("value1 (any)",n("The value to test as being less than or equal to value2.")),el("value2 (any)",n("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!ig.compute(e,t)}},ag={description:n("Difference of two numbers."),args:[el("value1 (number)",n("The minuend, or number to be subtracted from.")),el("value2 (number)",n("The subtrahend, or number to subtract from value1."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Qi(e)-Qi(t)}},lg={description:n("Product of two numbers"),args:[el("factor1 (number)",n("The first multiplicand.")),el("factor2 (number)",n("The second multiplicand."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Qi(e)*Qi(t)}},cg={description:n("Not equal."),args:[el("value1 (any)",n("The first value.")),el("value2 (any)",n("The value to test against value1 for inequality."))],returns:["BOOLEAN"],compute:function(e,t){return!tg.compute(e,t)}},hg={description:n("A number raised to a power."),args:[el("base (number)",n("The number to raise to the exponent power.")),el("exponent (number)",n("The exponent to raise base to."))],returns:["NUMBER"],compute:function(e,t){return $l.compute(e,t)}},dg={description:n("A number with the sign reversed."),args:[el("value (number)",n("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],computeFormat:e=>e?.format,returns:["NUMBER"],compute:function(e){return-Qi(e)}},ug={description:n("Value interpreted as a percentage."),args:[el("percentage (number)",n("The value to interpret as a percentage."))],returns:["NUMBER"],compute:function(e){return Qi(e)/100}},gg={description:n("A specified number, unchanged."),args:[el("value (any)",n("The number to return."))],returns:["ANY"],computeFormat:e=>e?.format,compute:function(e){return null===e?"":e}};var pg=Object.freeze({__proto__:null,ADD:Xu,CONCAT:Ku,DIVIDE:Qu,EQ:tg,GT:ig,GTE:sg,LT:ng,LTE:rg,MINUS:ag,MULTIPLY:lg,NE:cg,POW:hg,UMINUS:dg,UNARY_PERCENT:ug,UPLUS:gg});const mg=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,fg={description:n("Gets character associated with number."),args:[el("table_number (number)",n("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(Qi(e));return Xi((()=>t>=1),n("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},bg={description:n("Remove non-printable characters from a piece of text."),args:[el("text (string)",n("The text whose non-printable characters are to be removed."))],returns:["STRING"],compute:function(e){const t=os(e);let o="";for(const e of t)e&&e.charCodeAt(0)>31&&(o+=e);return o},isExported:!0},vg={description:n("Appends strings to one another."),args:[el("string1 (string, range<string>)",n("The initial string.")),el("string2 (string, range<string>, repeating)",n("More strings to append in sequence."))],returns:["STRING"],compute:function(...e){return us(e,((e,t)=>e+os(t)),"")},isExported:!0},Sg={description:n("Tests whether two strings are identical."),args:[el("string1 (string)",n("The first string to compare.")),el("string2 (string)",n("The second string to compare."))],returns:["BOOLEAN"],compute:function(e,t){return os(e)===os(t)},isExported:!0},Cg={description:n("First position of string found in text, case-sensitive."),args:[el("search_for (string)",n("The string to look for within text_to_search.")),el("text_to_search (string)",n("The text to search for the first occurrence of search_for.")),el("starting_at (number, default=1)",n("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,o=1){const i=os(e),s=os(t),r=Qi(o);Xi((()=>""!==s),n("The text_to_search must be non-empty.")),Xi((()=>r>=1),n("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=s.indexOf(i,r-1);return Xi((()=>a>=0),n("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i.toString(),s)),a+1},isExported:!0},Eg={description:n("Concatenates elements of arrays with delimiter."),args:[el("delimiter (string)",n("The character or string to place between each concatenated value.")),el("value_or_array1 (string, range<string>)",n("The value or values to be appended using delimiter.")),el("value_or_array2 (string, range<string>, repeating)",n("More values to be appended using delimiter."))],returns:["STRING"],compute:function(e,...t){const o=os(e);return us(t,((e,t)=>(e?e+o:"")+os(t)),"")}},wg={description:n("Substring from beginning of specified string."),args:[el("text (string)",n("The string from which the left portion will be returned.")),el("number_of_characters (number, optional)",n("The number of characters to return from the left side of string."))],returns:["STRING"],compute:function(e,...t){const o=t.length?Qi(t[0]):1;return Xi((()=>o>=0),n("The number_of_characters (%s) must be positive or null.",o.toString())),os(e).substring(0,o)},isExported:!0},xg={description:n("Length of a string."),args:[el("text (string)",n("The string whose length will be returned."))],returns:["NUMBER"],compute:function(e){return os(e).length},isExported:!0},yg={description:n("Converts a specified string to lowercase."),args:[el("text (string)",n("The string to convert to lowercase."))],returns:["STRING"],compute:function(e){return os(e).toLowerCase()},isExported:!0},Ig={description:n("A segment of a string."),args:[el("text (string)",n("The string to extract a segment from.")),el("starting_at (number)",n("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),el("extract_length (number)",n("The length of the segment to extract."))],returns:["STRING"],compute:function(e,t,o){const i=os(e),s=Qi(t),r=Qi(o);return Xi((()=>s>=1),n("The starting_at argument (%s) must be positive greater than one.",s.toString())),Xi((()=>r>=0),n("The extract_length argument (%s) must be positive or null.",r.toString())),i.slice(s-1,s+r-1)},isExported:!0},Rg={description:n("Capitalizes each word in a specified string."),args:[el("text_to_capitalize (string)",n("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 os(e).replace(mg,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},Tg={description:n("Replaces part of a text string with different text."),args:[el("text (string)",n("The text, a part of which will be replaced.")),el("position (number)",n("The position where the replacement will begin (starting from 1).")),el("length (number)",n("The number of characters in the text to be replaced.")),el("new_text (string)",n("The text which will be inserted into the original text."))],returns:["STRING"],compute:function(e,t,o,i){const s=Qi(t);Xi((()=>s>=1),n("The position (%s) must be greater than or equal to 1.",s.toString()));const r=os(e),a=Qi(o),l=os(i);return r.substring(0,s-1)+l+r.substring(s-1+a)},isExported:!0},Ag={description:n("A substring from the end of a specified string."),args:[el("text (string)",n("The string from which the right portion will be returned.")),el("number_of_characters (number, optional)",n("The number of characters to return from the right side of string."))],returns:["STRING"],compute:function(e,...t){const o=t.length?Qi(t[0]):1;Xi((()=>o>=0),n("The number_of_characters (%s) must be positive or null.",o.toString()));const i=os(e),s=i.length;return i.substring(s-o,s)},isExported:!0},Og={description:n("First position of string found in text, ignoring case."),args:[el("search_for (string)",n("The string to look for within text_to_search.")),el("text_to_search (string)",n("The text to search for the first occurrence of search_for.")),el("starting_at (number, default=1)",n("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,o=1){const i=os(e).toLowerCase(),s=os(t).toLowerCase(),r=Qi(o);Xi((()=>""!==s),n("The text_to_search must be non-empty.")),Xi((()=>r>=1),n("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=s.indexOf(i,r-1);return Xi((()=>a>=0),n("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i,s)),a+1},isExported:!0},Mg={description:n("Replaces existing text with new text in a string."),args:[el("text_to_search (string)",n("The text within which to search and replace.")),el("search_for (string)",n("The string to search for within text_to_search.")),el("replace_with (string)",n("The string that will replace search_for.")),el("occurrence_number (number, optional)",n("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,o,i){const s=Qi(i);Xi((()=>s>=0),n("The occurrenceNumber (%s) must be positive or null.",s.toString()));const r=os(e),a=os(t);if(""===a)return r;const l=os(o),c=new RegExp(ze(a),"g");if(0===s)return r.replace(c,l);let h=0;return r.replace(c,(e=>++h===s?l:e))},isExported:!0},Ng={description:n("Combines text from multiple strings and/or arrays."),args:[el("delimiter (string)",n(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")),el("ignore_empty (boolean)",n("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")),el("text1 (string, range<string>)",n("Any text item. This could be a string, or an array of strings in a range.")),el("text2 (string, range<string>, repeating)",n("Additional text item(s)."))],returns:["STRING"],compute:function(e,t,...o){const i=os(e),s=rs(t);let n=0;return us(o,((e,t)=>s&&""===os(t)?e:(n++?e+i:"")+os(t)),"")},isExported:!0},_g={description:n("Removes space characters."),args:[el("text (string)",n("The text or reference to a cell containing text to be trimmed."))],returns:["STRING"],compute:function(e){return os(e).trim()},isExported:!0},Fg={description:n("Converts a specified string to uppercase."),args:[el("text (string)",n("The string to convert to uppercase."))],returns:["STRING"],compute:function(e){return os(e).toUpperCase()},isExported:!0},Dg={description:n("Converts a number to text according to a specified format."),args:[el("number (number)",n("The number, date or time to format.")),el("format (string)",n("The pattern by which to format the number, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){return bo(Qi(e),os(t))},isExported:!0};var Lg=Object.freeze({__proto__:null,CHAR:fg,CLEAN:bg,CONCATENATE:vg,EXACT:Sg,FIND:Cg,JOIN:Eg,LEFT:wg,LEN:xg,LOWER:yg,MID:Ig,PROPER:Rg,REPLACE:Tg,RIGHT:Ag,SEARCH:Og,SUBSTITUTE:Mg,TEXTJOIN:Ng,TRIM:_g,UPPER:Fg,TEXT:Dg});const Pg={description:n("Creates a hyperlink in a cell."),args:[el("url (string)",n("The full URL of the link enclosed in quotation marks.")),el("link_label (string, optional)",n("The text to display in the cell, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){const o=os(e).trim(),i=os(t)||o;return""===o?i:nt(i,o)},isExported:!0};var kg=Object.freeze({__proto__:null,HYPERLINK:Pg});const Ug=[{name:n("Database"),functions:uh},{name:n("Date"),functions:Zh},{name:n("Financial"),functions:bu},{name:n("Info"),functions:Tu},{name:n("Lookup"),functions:Yu},{name:n("Logical"),functions:Pu},{name:n("Math"),functions:ac},{name:n("Misc"),functions:il},{name:n("Operator"),functions:pg},{name:n("Statistical"),functions:Kc},{name:n("Text"),functions:Lg},{name:n("Engineering"),functions:Yh},{name:n("Web"),functions:kg}],Vg=/^[A-Z0-9\_\.]+$/;function zg(e){return e.map((e=>{if(void 0!==e)return"function"==typeof e?()=>Bg(e()):Bg(e)}))}function Bg(e){return Array.isArray(e)?e.map((e=>e.map((e=>e?.value)))):e?.value}const Hg=new class extends zi{mapping={};add(e,t){if(e=e.toUpperCase(),!Vg.test(e))throw new Error(n("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const o=tl(t);return function(e){let t=!1,o=!1,i=!1;for(let s of e){if(s.type.includes("META")&&s.type.length>1)throw new Error(n("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&&!s.repeating)throw new Error(n("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=o||t||i,r=!(s.optional||s.repeating||s.default);if(e&&r)throw new Error(n("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=s.repeating,o=s.optional,i=s.default}}(o.args),this.mapping[e]=function(...e){const t=o.compute.bind(this),i=o.computeFormat?o.computeFormat.bind(this):()=>{};return{value:t(...zg(e)),format:i(...e)}},super.add(e,o),this}};for(let e of Ug){const t=e.functions;for(let o in t){const i=t[o];i.category=i.category||e.name,o=o.replace(/_/g,"."),Hg.add(o,{isExported:!1,...i})}}const $g={name:e=>{const t=pa(e);return 1===t?n("Insert row"):n("Insert %s rows",t.toString())},isVisible:e=>Aa(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW"},Wg={name:e=>{const t=pa(e);return 1===t?n("Insert row above"):n("Insert %s rows above",t.toString())},execute:Ca,isVisible:e=>Aa(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},Gg={...Wg,name:e=>{const t=pa(e);return 1===t?n("Row above"):n("%s Rows above",t.toString())}},qg={...Wg,name:e=>{const t=pa(e);return 1===t?n("Insert row"):n("Insert %s rows",t.toString())},isVisible:Ta,icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},Zg={execute:e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Rt([...t]),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.bottom,i=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",base:o,quantity:i,dimension:"ROW"})},name:e=>{const t=pa(e);return 1===t?n("Insert row below"):n("Insert %s rows below",t.toString())},isVisible:e=>Aa(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_AFTER"},jg={...Zg,name:e=>{const t=pa(e);return 1===t?n("Row below"):n("%s Rows below",t.toString())}},Yg={name:e=>{const t=ga(e);return 1===t?n("Insert column"):n("Insert %s columns",t.toString())},isVisible:e=>Aa(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL"},Xg={name:e=>{const t=ga(e);return 1===t?n("Insert column left"):n("Insert %s columns left",t.toString())},execute:Ea,isVisible:e=>Aa(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},Kg={...Xg,name:e=>{const t=ga(e);return 1===t?n("Column left"):n("%s Columns left",t.toString())}},Qg={...Xg,name:e=>{const t=ga(e);return 1===t?n("Insert column"):n("Insert %s columns",t.toString())},isVisible:Ta,icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},Jg={name:e=>{const t=ga(e);return 1===t?n("Insert column right"):n("Insert %s columns right",t.toString())},execute:wa,isVisible:e=>Aa(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_AFTER"},ep={...Jg,name:e=>{const t=ga(e);return 1===t?n("Column right"):n("%s Columns right",t.toString())},execute:wa},tp={name:n("Insert cells"),isVisible:e=>Ta(e)&&0===e.model.getters.getActiveCols().size&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_CELL"},op={name:n("Insert cells and shift down"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});ha(e,o)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN"},ip={name:n("Insert cells and shift right"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});ha(e,o)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT"},sp={name:n("Chart"),execute:e=>{const t=e.model.getters,o=e.model.uuidGenerator.uuidv4(),i=t.getActiveSheetId();1===Ri(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection();const s={width:536,height:335},n=function(e,t){const{x:o,y:i}=e.getMainViewportCoordinates(),{scrollX:s,scrollY:n}=e.getActiveSheetScrollInfo(),{width:r,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:o+s+Math.max(0,(r-t.width)/2),y:i+n+Math.max(0,(a-t.height)/2)}}(t,s);e.model.dispatch("CREATE_CHART",{sheetId:i,id:o,position:n,size:s,definition:ia(e.model.getters.getSelectedZone(),e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{id:o}),e.openSidePanel("ChartPanel"))},icon:"o-spreadsheet-Icon.INSERT_CHART"},np={name:n("Image"),description:"Ctrl+O",execute:xa,isVisible:e=>void 0!==e.imageProvider,icon:"o-spreadsheet-Icon.INSERT_IMAGE"},rp={name:n("Function"),icon:"o-spreadsheet-Icon.SHOW_HIDE_FORMULA"},ap={name:n("SUM"),execute:e=>e.startCellEdition("=SUM(")},lp={name:n("AVERAGE"),execute:e=>e.startCellEdition("=AVERAGE(")},cp={name:n("COUNT"),execute:e=>e.startCellEdition("=COUNT(")},hp={name:n("MAX"),execute:e=>e.startCellEdition("=MAX(")},dp={name:n("MIN"),execute:e=>e.startCellEdition("=MIN(")},up={name:n("All"),children:[function(){return mp(Hg.getKeys().filter((e=>!Hg.get(e).hidden)))}]};const gp={name:n("Link"),execute:Ia,icon:"o-spreadsheet-Icon.INSERT_LINK"},pp={name:n("Insert sheet"),execute:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSheetIds().indexOf(t)+1,i=e.model.uuidGenerator.uuidv4();e.model.dispatch("CREATE_SHEET",{sheetId:i,position:o}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:i})},icon:"o-spreadsheet-Icon.INSERT_SHEET"};function mp(e){return e.sort().map(((e,t)=>({name:e,sequence:10*t,execute:t=>t.startCellEdition(`=${e}(`)})))}const fp=new Ln;fp.add("cut",{..._a,sequence:10}).add("copy",{...Na,sequence:20}).add("paste",{...Fa,sequence:30}).add("paste_special",{...Da,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...La,sequence:10}).addChild("paste_format_only",["paste_special"],{...Pa,sequence:20}).add("add_row_before",{...qg,sequence:70}).add("add_column_before",{...Qg,sequence:90}).add("insert_cell",{...tp,sequence:100,separator:!0}).addChild("insert_cell_down",["insert_cell"],{...op,name:n("Shift down"),sequence:10}).addChild("insert_cell_right",["insert_cell"],{...ip,name:n("Shift right"),sequence:20}).add("delete_row",{...za,sequence:110,icon:"o-spreadsheet-Icon.DELETE"}).add("delete_column",{...$a,sequence:120,icon:"o-spreadsheet-Icon.DELETE"}).add("delete_cell",{...Ga,sequence:130,separator:!0,icon:"o-spreadsheet-Icon.DELETE"}).addChild("delete_cell_up",["delete_cell"],{...qa,name:n("Shift up"),sequence:10,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP"}).addChild("delete_cell_left",["delete_cell"],{...Za,name:n("Shift left"),sequence:20,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT"}).add("insert_link",{...gp,name:e=>{const t=e.model.getters.getActiveSheetId(),{col:o,row:i}=e.model.getters.getActivePosition(),s=e.model.getters.getEvaluatedCell({sheetId:t,col:o,row:i});return s&&s.link?n("Edit link"):n("Insert link")},sequence:150,separator:!0});const bp={name:n("Sort range"),isVisible:Ta,icon:"o-spreadsheet-Icon.SORT_RANGE"},vp={name:n("Ascending (A ⟶ Z)"),execute:e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();na(e,i,t.cell,o[0],"ascending")},icon:"o-spreadsheet-Icon.SORT_ASCENDING"},Sp={name:n("Descending (Z ⟶ A)"),execute:e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();na(e,i,t.cell,o[0],"descending")},icon:"o-spreadsheet-Icon.SORT_DESCENDING"},Cp={name:n("Create filter"),execute:e=>{const t=e.model.getters.getSelectedZones();1===t.length&&1===Ri(t[0])&&e.model.selection.selectTableAroundSelection();const o=e.model.getters.getActiveSheetId();la(e,o,e.model.getters.getSelectedZones())},isVisible:e=>!Ra(e),isEnabled:e=>(e=>Ti(...e.model.getters.getSelectedZones()))(e),icon:"o-spreadsheet-Icon.MENU_FILTER_ICON"},Ep={name:n("Remove filter"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:t,target:e.model.getters.getSelectedZones()})},isVisible:Ra,icon:"o-spreadsheet-Icon.MENU_FILTER_ICON"},wp={name:n("Split text to columns"),sequence:1,execute:e=>e.openSidePanel("SplitToColumns",{}),isEnabled:e=>e.model.getters.isSingleColSelected(),icon:"o-spreadsheet-Icon.SPLIT_TEXT"},xp={name:n("Automatic"),execute:e=>ma(e,""),isActive:e=>function(e){const t=e.model.getters.getCell(e.model.getters.getActivePosition());return!t||!t.format}(e)},yp={name:n("Number"),description:"1,000.12",execute:e=>ma(e,"#,##0.00"),isActive:e=>nm(e,"#,##0.00")},Ip={name:n("Format as percent"),execute:ya,icon:"o-spreadsheet-Icon.PERCENT"},Rp={name:n("Percent"),description:"10.12%",execute:ya,isActive:e=>nm(e,"0.00%")},Tp={name:n("Currency"),description:"$1,000.12",execute:e=>ma(e,"[$$]#,##0.00"),isActive:e=>nm(e,"[$$]#,##0.00")},Ap={name:n("Currency rounded"),description:"$1,000",execute:e=>ma(e,"[$$]#,##0"),isActive:e=>nm(e,"[$$]#,##0")},Op={name:n("Custom currency"),isVisible:e=>void 0!==e.loadCurrencies,execute:e=>{e.openSidePanel("CustomCurrency",{})}},Mp={name:n("Date"),description:"9/26/2008",execute:e=>ma(e,"m/d/yyyy"),isActive:e=>nm(e,"m/d/yyyy")},Np={name:n("Time"),description:"10:43:00 PM",execute:e=>ma(e,"hh:mm:ss a"),isActive:e=>nm(e,"hh:mm:ss a")},_p={name:n("Date time"),description:"9/26/2008 22:43:00",execute:e=>ma(e,"m/d/yyyy hh:mm:ss"),isActive:e=>nm(e,"m/d/yyyy hh:mm:ss")},Fp={name:n("Duration"),description:"27:51:38",execute:e=>ma(e,"hhhh:mm:ss"),isActive:e=>nm(e,"hhhh:mm:ss")},Dp={name:n("Increase decimal places"),icon:"o-spreadsheet-Icon.INCREASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:1})},Lp={name:n("Decrease decimal places"),icon:"o-spreadsheet-Icon.DECRASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:-1})},Pp={name:n("Bold"),description:"Ctrl+B",execute:e=>fa(e,{bold:!e.model.getters.getCurrentStyle().bold}),icon:"o-spreadsheet-Icon.BOLD",isActive:e=>!!e.model.getters.getCurrentStyle().bold},kp={name:n("Italic"),description:"Ctrl+I",execute:e=>fa(e,{italic:!e.model.getters.getCurrentStyle().italic}),icon:"o-spreadsheet-Icon.ITALIC",isActive:e=>!!e.model.getters.getCurrentStyle().italic},Up={name:n("Underline"),description:"Ctrl+U",execute:e=>fa(e,{underline:!e.model.getters.getCurrentStyle().underline}),icon:"o-spreadsheet-Icon.UNDERLINE",isActive:e=>!!e.model.getters.getCurrentStyle().underline},Vp={name:n("Strikethrough"),execute:e=>fa(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),icon:"o-spreadsheet-Icon.STRIKE",isActive:e=>!!e.model.getters.getCurrentStyle().strikethrough},zp={name:n("Font size"),children:fe.map((e=>({name:e.toString(),sequence:e,id:`font_size_${e}`,execute:t=>fa(t,{fontSize:e}),isActive:t=>function(e,t){const o=e.model.getters.getCurrentStyle().fontSize||Z;return o===t}(t,e)}))),icon:"o-spreadsheet-Icon.FONT_SIZE"},Bp={name:n("Alignment"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},Hp={name:n("Horizontal align"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},$p={name:n("Left"),description:"Ctrl+Shift+L",execute:e=>fa(e,{align:"left"}),isActive:e=>"left"===rm(e),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},Wp={name:n("Center"),description:"Ctrl+Shift+E",execute:e=>fa(e,{align:"center"}),isActive:e=>"center"===rm(e),icon:"o-spreadsheet-Icon.ALIGN_CENTER"},Gp={name:n("Right"),description:"Ctrl+Shift+R",execute:e=>fa(e,{align:"right"}),isActive:e=>"right"===rm(e),icon:"o-spreadsheet-Icon.ALIGN_RIGHT"},qp={name:n("Vertical align"),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},Zp={name:n("Top"),execute:e=>fa(e,{verticalAlign:"top"}),isActive:e=>"top"===(e.model.getters.getCurrentStyle().verticalAlign||Y),icon:"o-spreadsheet-Icon.ALIGN_TOP"},jp={name:n("Middle"),execute:e=>fa(e,{verticalAlign:"middle"}),isActive:e=>"middle"===(e.model.getters.getCurrentStyle().verticalAlign||Y),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},Yp={name:n("Bottom"),execute:e=>fa(e,{verticalAlign:"bottom"}),isActive:e=>"bottom"===(e.model.getters.getCurrentStyle().verticalAlign||Y),icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"},Xp={name:n("Wrapping"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},Kp={name:n("Overflow"),execute:e=>fa(e,{wrapping:"overflow"}),isActive:e=>"overflow"===(e.model.getters.getCurrentStyle().wrapping||"overflow"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},Qp={name:n("Wrap"),execute:e=>fa(e,{wrapping:"wrap"}),isActive:e=>"wrap"===e.model.getters.getCurrentStyle().wrapping,icon:"o-spreadsheet-Icon.WRAPPING_WRAP"},Jp={name:n("Clip"),execute:e=>fa(e,{wrapping:"clip"}),isActive:e=>"clip"===e.model.getters.getCurrentStyle().wrapping,icon:"o-spreadsheet-Icon.WRAPPING_CLIP"},em={name:n("Text Color"),icon:"o-spreadsheet-Icon.TEXT_COLOR"},tm={name:n("Fill Color"),icon:"o-spreadsheet-Icon.FILL_COLOR"},om={name:n("Conditional formatting"),execute:e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},icon:"o-spreadsheet-Icon.CONDITIONAL_FORMAT"},im={name:n("Paint Format"),execute:e=>e.model.dispatch("ACTIVATE_PAINT_FORMAT",{target:e.model.getters.getSelectedZones()}),icon:"o-spreadsheet-Icon.PAINT_FORMAT",isActive:e=>e.model.getters.isPaintingFormat()},sm={name:n("Clear formatting"),description:"Ctrl+<",execute:e=>{e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},icon:"o-spreadsheet-Icon.CLEAR_FORMAT"};function nm(e,t){return e.model.getters.getCell(e.model.getters.getActivePosition())?.format===t}function rm(e){const t=e.model.getters.getCurrentStyle();if(t.align)return t.align;return e.model.getters.getActiveCell().defaultAlign}var am=Object.freeze({__proto__:null,formatNumberAutomatic:xp,formatNumberNumber:yp,formatPercent:Ip,formatNumberPercent:Rp,formatNumberCurrency:Tp,formatNumberCurrencyRounded:Ap,formatCustomCurrency:Op,formatNumberDate:Mp,formatNumberTime:Np,formatNumberDateTime:_p,formatNumberDuration:Fp,incraseDecimalPlaces:Dp,decraseDecimalPlaces:Lp,formatBold:Pp,formatItalic:kp,formatUnderline:Up,formatStrikethrough:Vp,formatFontSize:zp,formatAlignment:Bp,formatAlignmentHorizontal:Hp,formatAlignmentLeft:$p,formatAlignmentCenter:Wp,formatAlignmentRight:Gp,formatAlignmentVertical:qp,formatAlignmentTop:Zp,formatAlignmentMiddle:jp,formatAlignmentBottom:Yp,formatWrapping:Xp,formatWrappingOverflow:Kp,formatWrappingWrap:Qp,formatWrappingClip:Jp,textColor:em,fillColor:tm,formatCF:om,paintFormat:im,clearFormat:sm});function lm(e,t,o){const i=e.model.getters.getActiveSheetId(),s="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(s,{sheetId:i,quantity:o}).isCancelledBecause(66)&&e.raiseError(dr)}const cm={name:e=>{const t=e.model.getters.getElementsFromSelection("COL");let o=t[0],i=t[t.length-1];return 1===t.length?n("Hide column %s",Bt(o).toString()):i-o+1===t.length?n("Hide columns %s - %s",Bt(o).toString(),Bt(i).toString()):n("Hide columns")},execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getElementsFromSelection("COL");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"COL",o)},icon:"o-spreadsheet-Icon.HIDE_COL"},hm={name:n("Unhide columns"),execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))}},dm={name:n("Unhide all columns"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"COL",elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0},um={name:e=>{const t=e.model.getters.getElementsFromSelection("ROW");let o=t[0],i=t[t.length-1];return 1===t.length?n("Hide row %s",(o+1).toString()):i-o+1===t.length?n("Hide rows %s - %s",(o+1).toString(),(i+1).toString()):n("Hide rows")},execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getElementsFromSelection("ROW");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"ROW",o)},icon:"o-spreadsheet-Icon.HIDE_ROW"},gm={name:n("Unhide rows"),execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))}},pm={name:n("Unhide all rows"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"ROW",elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0},mm={name:n("Unfreeze"),isVisible:e=>{const{xSplit:t,ySplit:o}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+o>0},execute:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),icon:"o-spreadsheet-Icon.UNFREEZE"},fm={name:n("Freeze"),icon:"o-spreadsheet-Icon.FREEZE"},bm={name:n("No rows"),execute:e=>e.model.dispatch("UNFREEZE_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit},vm={name:n("1 row"),execute:e=>lm(e,"ROW",1),isReadonlyAllowed:!0},Sm={name:n("2 rows"),execute:e=>lm(e,"ROW",2),isReadonlyAllowed:!0},Cm={name:n("Up to current row"),execute:e=>{const{bottom:t}=e.model.getters.getSelectedZone();lm(e,"ROW",t+1)},isReadonlyAllowed:!0},Em={name:n("No columns"),execute:e=>e.model.dispatch("UNFREEZE_COLUMNS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit},wm={name:n("1 column"),execute:e=>lm(e,"COL",1),isReadonlyAllowed:!0},xm={name:n("2 columns"),execute:e=>lm(e,"COL",2),isReadonlyAllowed:!0},ym={name:n("Up to current column"),execute:e=>{const{right:t}=e.model.getters.getSelectedZone();lm(e,"COL",t+1)},isReadonlyAllowed:!0},Im={name:e=>e.model.getters.getGridLinesVisibility(e.model.getters.getActiveSheetId())?n("Hide gridlines"):n("Show gridlines"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},icon:"o-spreadsheet-Icon.SHOW_HIDE_GRID"},Rm={name:e=>e.model.getters.shouldShowFormulas()?n("Hide formulas"):n("Show formulas"),execute:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,icon:"o-spreadsheet-Icon.SHOW_HIDE_FORMULA"},Tm={name:e=>Am(e)?n("Remove selected filters"):n("Create filter"),isActive:e=>Am(e),isEnabled:e=>!Om(e),execute:e=>function(e){if(Am(e))return void e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()});if(Om(e))return;e.model.selection.selectTableAroundSelection();const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();la(e,t,o)}(e),icon:"o-spreadsheet-Icon.FILTER_ICON_INACTIVE"};function Am(e){const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,o)}function Om(e){return!Ti(...e.model.getters.getSelectedZones())}var Mm=Object.freeze({__proto__:null,hideCols:cm,unhideCols:hm,unhideAllCols:dm,hideRows:um,unhideRows:gm,unhideAllRows:pm,unFreezePane:mm,freezePane:fm,unFreezeRows:bm,freezeFirstRow:vm,freezeSecondRow:Sm,freezeCurrentRow:Cm,unFreezeCols:Em,freezeFirstCol:wm,freezeSecondCol:xm,freezeCurrentCol:ym,viewGridlines:Im,viewFormulas:Rm,createRemoveFilter:Tm});const Nm=new Ln;Nm.add("cut",{..._a,sequence:10}).add("copy",{...Na,sequence:20}).add("paste",{...Fa,sequence:30}).add("paste_special",{...Da,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...La,sequence:10}).addChild("paste_format_only",["paste_special"],{...Pa,sequence:20}).add("sort_columns",{...bp,name:e=>e.model.getters.getActiveCols().size>1?n("Sort columns"):n("Sort column"),sequence:50,separator:!0}).addChild("sort_ascending",["sort_columns"],{...vp,sequence:10}).addChild("sort_descending",["sort_columns"],{...Sp,sequence:20}).add("add_column_before",{...Xg,sequence:70}).add("add_column_after",{...Jg,sequence:80}).add("delete_column",{...Ha,sequence:90,icon:"o-spreadsheet-Icon.DELETE"}).add("clear_column",{...Wa,sequence:100,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_columns",{...cm,sequence:105,separator:!0}).add("unhide_columns",{...hm,sequence:106,separator:!0}).add("conditional_formatting",{...om,sequence:110});const _m=new Ln;_m.add("format_number_automatic",{...xp,sequence:10,separator:!0}).add("format_number_number",{...yp,sequence:20}).add("format_number_percent",{...Rp,sequence:30,separator:!0}).add("format_number_currency",{...Tp,sequence:40}).add("format_number_currency_rounded",{...Ap,sequence:50}).add("format_custom_currency",{...Op,sequence:60,separator:!0}).add("format_number_date",{...Mp,sequence:70}).add("format_number_time",{...Np,sequence:80}).add("format_number_date_time",{..._p,sequence:90}).add("format_number_duration",{...Fp,sequence:100,separator:!0});const Fm={name:n("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[()=>_m.getAll()]},Dm=new Ln;Dm.add("cut",{..._a,sequence:10}).add("copy",{...Na,sequence:20}).add("paste",{...Fa,sequence:30}).add("paste_special",{...Da,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...La,sequence:10}).addChild("paste_format_only",["paste_special"],{...Pa,sequence:20}).add("add_row_before",{...Wg,sequence:50}).add("add_row_after",{...Zg,sequence:60}).add("delete_row",{...Va,sequence:70,icon:"o-spreadsheet-Icon.DELETE"}).add("clear_row",{...Ba,sequence:80,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_rows",{...um,sequence:85,separator:!0}).add("unhide_rows",{...gm,sequence:86,separator:!0}).add("conditional_formatting",{...om,sequence:90});const Lm=new Ln;Lm.add("file",{name:n("File"),sequence:10}).add("edit",{name:n("Edit"),sequence:20}).addChild("undo",["edit"],{...Oa,sequence:10}).addChild("redo",["edit"],{...Ma,sequence:20,separator:!0}).addChild("copy",["edit"],{...Na,sequence:30}).addChild("cut",["edit"],{..._a,sequence:40}).addChild("paste",["edit"],{...Fa,sequence:50}).addChild("paste_special",["edit"],{...Da,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...La,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{...Pa,sequence:20}).addChild("find_and_replace",["edit"],{...ka,sequence:65,separator:!0}).addChild("delete",["edit"],{name:n("Delete"),icon:"o-spreadsheet-Icon.DELETE",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...Ua,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...Va,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...Ha,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{...qa,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...Za,sequence:50}).addChild("edit_unhide_columns",["edit"],{...dm,sequence:80}).addChild("edit_unhide_rows",["edit"],{...pm,sequence:80}).add("view",{name:n("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...mm,sequence:4}).addChild("freeze_panes",["view"],{...fm,sequence:5,separator:!0}).addChild("unfreeze_rows",["view","freeze_panes"],{...bm,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...vm,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...Sm,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...Cm,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...Em,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...wm,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...xm,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...ym,sequence:40}).addChild("view_gridlines",["view"],{...Im,sequence:10}).addChild("view_formulas",["view"],{...Rm,sequence:15}).add("insert",{name:n("Insert"),sequence:40}).addChild("insert_row",["insert"],{...$g,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...Gg,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...jg,sequence:20}).addChild("insert_column",["insert"],{...Yg,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...Kg,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...ep,sequence:20}).addChild("insert_cell",["insert"],{...tp,sequence:43}).addChild("insert_cell_down",["insert","insert_cell"],{...op,name:n("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...ip,name:n("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...pp,sequence:80,separator:!0}).addChild("insert_chart",["insert"],{...sp,sequence:50}).addChild("insert_image",["insert"],{...np,sequence:55}).addChild("insert_function",["insert"],{...rp,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...ap,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...lp,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{...cp,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...hp,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...dp,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...up,sequence:50}).addChild("categories_function_list",["insert","insert_function"],(()=>{const e=Hg.content;return[...new Set(Hg.getAll().filter((e=>!e.hidden)).map((e=>e.category)))].filter(dt).sort().map(((t,o)=>{const i=Object.keys(e).filter((o=>e[o].category===t&&!e[o].hidden));return{name:t,children:mp(i)}}))})).addChild("insert_link",["insert"],{...gp,separator:!0,sequence:70}).add("format",{name:n("Format"),sequence:50}).addChild("format_number",["format"],{...Fm,name:n("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{...Pp,sequence:20}).addChild("format_italic",["format"],{...kp,sequence:30}).addChild("format_underline",["format"],{...Up,sequence:40}).addChild("format_strikethrough",["format"],{...Vp,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...zp,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...Bp,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...$p,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...Wp,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...Gp,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{...Zp,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...jp,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{...Yp,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...Xp,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...Kp,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...Qp,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...Jp,sequence:30}).addChild("format_cf",["format"],{...om,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...sm,sequence:100,separator:!0}).add("data",{name:n("Data"),sequence:60}).addChild("sort_range",["data"],{...bp,sequence:10,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...vp,sequence:10}).addChild("sort_descending",["data","sort_range"],{...Sp,sequence:20}).addChild("split_to_columns",["data"],{...wp,sequence:20,separator:!0}).addChild("add_data_filter",["data"],{...Cp,sequence:30}).addChild("remove_data_filter",["data"],{...Ep,sequence:30});const Pm=new class extends zi{addTransformation(e,t,o){for(let i of t)this.content[i]||(this.content[i]=new Map),this.content[i].set(e,o);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},km={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function Um(e,t){const o=km[e.key];e.shiftKey?t.resizeAnchorZone(o,un(e)?"end":1):t.moveAnchorCell(o,un(e)?"end":1)}const Vm=new ti;Ni`
|
|
354
354
|
.o-selection {
|
|
355
355
|
.o-selection-input {
|
|
356
356
|
display: flex;
|
|
@@ -400,7 +400,7 @@
|
|
|
400
400
|
font-size: calc(100% + 4px);
|
|
401
401
|
}
|
|
402
402
|
}
|
|
403
|
-
`;class zm extends t.Component{static template="o-spreadsheet-SelectionInput";id=Vm.uuidv4();previousRanges=this.props.ranges||[];originSheet=this.env.model.getters.getActiveSheetId();state=t.useState({isMissing:!1,mode:"select-range"});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+1,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((()=>this.focusedInput.el?.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(){const e=this.env.model.getters.getSelectionInputValue(this.id);this.props.onSelectionChanged?.(e),this.previousRanges=e}onKeydown(e){if("F2"===e.key)e.preventDefault(),e.stopPropagation(),this.state.mode="select-range"===this.state.mode?"text-edit":"select-range";else if(e.key.startsWith("Arrow"))e.stopPropagation(),"select-range"===this.state.mode&&(e.preventDefault(),Um(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){this.env.model.dispatch("REMOVE_RANGE",{id:this.id,rangeId:e}),this.triggerChange(),this.props.onSelectionConfirmed?.()}onInputChanged(e,t){const o=t.target,i=this.extractRanges(o.value);this.env.model.dispatch("CHANGE_RANGE",{id:this.id,rangeId:e,value:i}),this.triggerChange()}confirm(){this.env.model.dispatch("UNFOCUS_SELECTION_INPUT");const e=this.env.model.getters.getSelectionInputValue(this.id);this.props.required&&0===e.length&&(this.state.isMissing=!0);const t=this.env.model.getters.getActiveSheetId();this.originSheet!==t&&this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:this.originSheet}),this.props.onSelectionConfirmed?.()}}zm.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 Bm extends t.Component{static template="o-spreadsheet-LineBarPieConfigPanel";static components={SelectionInput:zm};state=t.useState({datasetDispatchResult:void 0,labelsDispatchResult:void 0});dataSeriesRanges=[];labelRange;setup(){this.dataSeriesRanges=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[]].map((e=>cr.Errors[e]||cr.Errors.Unexpected))}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause(33)}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.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})}calculateHeaderPosition(){if(this.isDatasetInvalid||this.isLabelInvalid)return;const e=this.env.model.getters,t=e.getActiveSheetId(),o=Qo(e,t,this.labelRange),i=Zn(e,this.dataSeriesRanges,t,this.props.definition.dataSetsHaveTitle);return i.length?i[0].dataRange.zone.top+1:o?o.zone.top+1:void 0}}Bm.props={figureId:String,definition:Object,updateChart:Function};class Hm extends Bm{static template="o-spreadsheet-BarConfigPanel";onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}}const $m=218,Wm=182;function Gm(e){return
|
|
403
|
+
`;class zm extends t.Component{static template="o-spreadsheet-SelectionInput";id=Vm.uuidv4();previousRanges=this.props.ranges||[];originSheet=this.env.model.getters.getActiveSheetId();state=t.useState({isMissing:!1,mode:"select-range"});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+1,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((()=>this.focusedInput.el?.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(){const e=this.env.model.getters.getSelectionInputValue(this.id);this.props.onSelectionChanged?.(e),this.previousRanges=e}onKeydown(e){if("F2"===e.key)e.preventDefault(),e.stopPropagation(),this.state.mode="select-range"===this.state.mode?"text-edit":"select-range";else if(e.key.startsWith("Arrow"))e.stopPropagation(),"select-range"===this.state.mode&&(e.preventDefault(),Um(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){this.env.model.dispatch("REMOVE_RANGE",{id:this.id,rangeId:e}),this.triggerChange(),this.props.onSelectionConfirmed?.()}onInputChanged(e,t){const o=t.target,i=this.extractRanges(o.value);this.env.model.dispatch("CHANGE_RANGE",{id:this.id,rangeId:e,value:i}),this.triggerChange()}confirm(){this.env.model.dispatch("UNFOCUS_SELECTION_INPUT");const e=this.env.model.getters.getSelectionInputValue(this.id);this.props.required&&0===e.length&&(this.state.isMissing=!0);const t=this.env.model.getters.getActiveSheetId();this.originSheet!==t&&this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:this.originSheet}),this.props.onSelectionConfirmed?.()}}zm.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 Bm extends t.Component{static template="o-spreadsheet-LineBarPieConfigPanel";static components={SelectionInput:zm};state=t.useState({datasetDispatchResult:void 0,labelsDispatchResult:void 0});dataSeriesRanges=[];labelRange;setup(){this.dataSeriesRanges=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[]].map((e=>cr.Errors[e]||cr.Errors.Unexpected))}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause(33)}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.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})}calculateHeaderPosition(){if(this.isDatasetInvalid||this.isLabelInvalid)return;const e=this.env.model.getters,t=e.getActiveSheetId(),o=Qo(e,t,this.labelRange),i=Zn(e,this.dataSeriesRanges,t,this.props.definition.dataSetsHaveTitle);return i.length?i[0].dataRange.zone.top+1:o?o.zone.top+1:void 0}}Bm.props={figureId:String,definition:Object,updateChart:Function};class Hm extends Bm{static template="o-spreadsheet-BarConfigPanel";onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}}const $m=218,Wm=182;function Gm(e){return kt(Vt({h:360*e.offsetX/$m,s:100,l:100*e.offsetY/Wm,a:1}))}Ni`
|
|
404
404
|
.o-color-picker {
|
|
405
405
|
padding: ${6}px 0px;
|
|
406
406
|
box-shadow: 1px 2px 5px 2px rgba(51, 51, 51, 0.15);
|
|
@@ -1194,7 +1194,7 @@
|
|
|
1194
1194
|
background: ${T};
|
|
1195
1195
|
color: #fff;
|
|
1196
1196
|
}
|
|
1197
|
-
`;class Ff extends t.Component{static style=_f;static template="o-spreadsheet-FilterIcon";get style(){const{x:e,y:t}=this.props.position;return`top:${t}px;left:${e}px`}}Ff.props={position:Object,isActive:Boolean,onClick:Function};const Df=Ni``;class Lf extends t.Component{static style=Df;static template="o-spreadsheet-FilterIconsOverlay";static components={FilterIcon:Ff};static defaultProps={gridPosition:{x:0,y:0}};getVisibleFilterHeaders(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getFilterHeaders(e).filter((e=>this.isPositionVisible(e.col,e.row)))}getFilterHeaderPosition(e){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getRowDimensionsInViewport(t,e.row),i=this.env.model.getters.getColDimensionsInViewport(t,e.col),s=this.env.model.getters.getCell({sheetId:t,...e}),n=this.getIconVerticalPosition(o,s);return{x:i.end-W+this.props.gridPosition.x-2-1,y:n+this.props.gridPosition.y}}getIconVerticalPosition(e,t){const o=Math.floor((e.size-W)/2);switch(t?.style?.verticalAlign){case"bottom":return e.end-2-W;case"top":return e.start+2;default:return e.end-W-o}}isFilterActive(e){const t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.isFilterActive({sheetId:t,...e})}toggleFilterMenu(e){const t=this.env.model.getters.getPersistentPopoverTypeAtPosition(e);if(t&&"FilterMenu"===t)return void this.env.model.dispatch("CLOSE_CELL_POPOVER");const{col:o,row:i}=e;this.env.model.dispatch("OPEN_CELL_POPOVER",{col:o,row:i,popoverType:"FilterMenu"})}isPositionVisible(e,t){const o=this.env.model.getters.getVisibleRect({left:e,right:e,top:t,bottom:t});return!(0===o.width||0===o.height)}}function
|
|
1197
|
+
`;class Ff extends t.Component{static style=_f;static template="o-spreadsheet-FilterIcon";get style(){const{x:e,y:t}=this.props.position;return`top:${t}px;left:${e}px`}}Ff.props={position:Object,isActive:Boolean,onClick:Function};const Df=Ni``;class Lf extends t.Component{static style=Df;static template="o-spreadsheet-FilterIconsOverlay";static components={FilterIcon:Ff};static defaultProps={gridPosition:{x:0,y:0}};getVisibleFilterHeaders(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getFilterHeaders(e).filter((e=>this.isPositionVisible(e.col,e.row)))}getFilterHeaderPosition(e){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getRowDimensionsInViewport(t,e.row),i=this.env.model.getters.getColDimensionsInViewport(t,e.col),s=this.env.model.getters.getCell({sheetId:t,...e}),n=this.getIconVerticalPosition(o,s);return{x:i.end-W+this.props.gridPosition.x-2-1,y:n+this.props.gridPosition.y}}getIconVerticalPosition(e,t){const o=Math.floor((e.size-W)/2);switch(t?.style?.verticalAlign){case"bottom":return e.end-2-W;case"top":return e.start+2;default:return e.end-W-o}}isFilterActive(e){const t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.isFilterActive({sheetId:t,...e})}toggleFilterMenu(e){const t=this.env.model.getters.getPersistentPopoverTypeAtPosition(e);if(t&&"FilterMenu"===t)return void this.env.model.dispatch("CLOSE_CELL_POPOVER");const{col:o,row:i}=e;this.env.model.dispatch("OPEN_CELL_POPOVER",{col:o,row:i,popoverType:"FilterMenu"})}isPositionVisible(e,t){const o=this.env.model.getters.getVisibleRect({left:e,right:e,top:t,bottom:t});return!(0===o.width||0===o.height)}}function Pf(e,t){return{...t,...Uf(e,{x:t.x,y:t.y})}}function kf(e,t){return{...t,...Vf(e,{x:t.x,y:t.y})}}function Uf(e,{x:t,y:o}){const{x:i,y:s}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo();return{x:t=t<i?t:t-n,y:o=o<s?o:o-r}}function Vf(e,{x:t,y:o}){const{x:i,y:s}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo();return{x:t=i&&t<i?t:t+n,y:o=s&&o<s?o:o+r}}function zf(e,t,o){return Math.min(Math.max(e,t),o)}Lf.props={gridPosition:{type:Object,optional:!0}};const Bf=5;function Hf(e,t,o){return o.map((e=>Wf(t,e))).filter((o=>function(e,t,o){const{x:i,y:s}=e.getMainViewportCoordinates(),n=[];switch(o.axisType){case"top":case"bottom":case"vCenter":if(t.y<s)return!0;n.push({x:t.x,y:o.position}),n.push({x:t.x+t.width,y:o.position});break;case"left":case"right":case"hCenter":if(t.x<i)return!0;n.push({x:o.position,y:t.y}),n.push({x:o.position,y:t.y+t.height})}return n.some(e.isPositionVisible)}(e,t,o))).map((o=>function(e,t,o){const i=Pf(e,t);return Wf(i,o.axisType)}(e,t,o)))}function $f(e,t,o,i,s){const n=Hf(e,t,o);let r;for(const t of i){const o=Hf(e,t,s);for(const e of n)for(const i of o){if(a=e.position,l=i.position,!(Math.abs(a-l)<=Bf))continue;const o=e.position-i.position;r&&o===r.snapOffset?r.matchedFigIds.push(t.id):(!r||Math.abs(o)<=Math.abs(r.snapOffset))&&(r={matchedFigIds:[t.id],snapOffset:o,snappedAxisType:e.axisType,position:i.position})}}var a,l;return r}function Wf(e,t){let o=0;switch(t){case"top":o=e.y;break;case"bottom":o=e.y+e.height-te;break;case"vCenter":o=e.y+Math.floor(e.height/2)-te;break;case"left":o=e.x;break;case"right":o=e.x+e.width-te;break;case"hCenter":o=e.x+Math.floor(e.width/2)-te}return{position:o,axisType:t}}Ni`
|
|
1198
1198
|
.o-figure-snap-line {
|
|
1199
1199
|
position: relative;
|
|
1200
1200
|
z-index: ${ue.FigureSnapLine};
|
|
@@ -1207,7 +1207,7 @@
|
|
|
1207
1207
|
height: 0px;
|
|
1208
1208
|
}
|
|
1209
1209
|
}
|
|
1210
|
-
`;class Gf extends t.Component{static template="o-spreadsheet-FiguresContainer";static components={FigureComponent:mf};dnd=t.useState({draggedFigure:void 0,horizontalSnap:void 0,verticalSnap:void 0});setup(){t.onMounted((()=>{this.render()}))}getVisibleFigures(){const e=this.env.model.getters.getVisibleFigures();return this.dnd.draggedFigure&&!e.some((e=>e.id===this.dnd.draggedFigure?.id))&&e.push(this.env.model.getters.getFigure(this.env.model.getters.getActiveSheetId(),this.dnd.draggedFigure?.id)),e}get containers(){const e=this.getVisibleFigures(),t=[];for(const o of["topLeft","topRight","bottomLeft","bottomRight"]){const i=e.filter((e=>this.getFigureContainer(e)===o));i.length>0&&t.push({type:o,figures:i,style:this.getContainerStyle(o),inverseViewportStyle:this.getInverseViewportPositionStyle(o)})}return this.dnd.draggedFigure&&t.push({type:"dnd",figures:[this.getDndFigure()],style:this.getContainerStyle("dnd"),inverseViewportStyle:this.getInverseViewportPositionStyle("dnd")}),t}getContainerStyle(e){return this.rectToCss(this.getContainerRect(e))}rectToCss(e){return Li({left:`${e.x}px`,top:`${e.y}px`,width:`${e.width}px`,height:`${e.height}px`})}getContainerRect(e){const{width:t,height:o}=this.env.model.getters.getMainViewportRect(),{x:i,y:s}=this.env.model.getters.getMainViewportCoordinates(),n=["bottomRight","topRight"].includes(e)?i:0,r=t-n,a=["bottomRight","bottomLeft"].includes(e)?s:0;return{x:n,y:a,width:r,height:o-a}}getInverseViewportPositionStyle(e){const{scrollX:t,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo(),{x:i,y:s}=this.env.model.getters.getMainViewportCoordinates();return Li({left:`${["bottomRight","topRight"].includes(e)?-(i+t):0}px`,top:`${["bottomRight","bottomLeft"].includes(e)?-(s+o):0}px`})}getFigureContainer(e){const{x:t,y:o}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.draggedFigure?.id?"dnd":e.x<t&&e.y<o?"topLeft":e.x<t?"bottomLeft":e.y<o?"topRight":"bottomRight"}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly())return;if(!this.env.model.dispatch("SELECT_FIGURE",{id:e.id}).isSuccessful)return;const o=this.env.model.getters.getActiveSheetId(),i={x:t.clientX,y:t.clientY},s={maxX:this.env.model.getters.getColDimensions(o,this.env.model.getters.getNumberCols(o)-1).end,maxY:this.env.model.getters.getRowDimensions(o,this.env.model.getters.getNumberRows(o)-1).end},{x:n,y:r}=kf(this.env.model.getters,e),a={...e,x:n,y:r};ff((t=>{const o=this.env.model.getters,n=function({x:e,y:t},{x:o,y:i},s,{x:n,y:r},{maxX:a,maxY:l},{scrollX:c,scrollY:h}){const d=n?0:-c,u=r?0:-h,g=e-o,p=zf(s.x+g,d,a-s.width-c),m=t-i,f=zf(s.y+m,u,l-s.height-h);return{...s,x:p,y:f}}({x:t.clientX,y:t.clientY},i,a,this.env.model.getters.getMainViewportCoordinates(),s,o.getActiveSheetScrollInfo()),r=this.getOtherFigures(e.id),l=function(e,t,o){const i={...t},s=$f(e,i,["hCenter","right","left"],o,["hCenter","right","left"]),n=$f(e,i,["vCenter","bottom","top"],o,["vCenter","bottom","top"]),{y:r,x:a}=e.getMainViewportCoordinates(),{scrollY:l,scrollX:c}=e.getActiveSheetScrollInfo();if(n){i.y-=n.snapOffset;const e=t.y<r,o=i.y<r;e&&!o?i.y+=l:!e&&o&&(i.y-=l)}if(s){i.x-=s.snapOffset;const e=t.x<a,o=i.x<a;e&&!o?i.x+=c:!e&&o&&(i.x-=c)}return{snappedFigure:i,verticalSnapLine:s,horizontalSnapLine:n}}(o,Pf(o,n),r);this.dnd.draggedFigure=kf(o,l.snappedFigure),this.dnd.horizontalSnap=this.getSnap(l.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(l.verticalSnapLine)}),(t=>{if(!this.dnd.draggedFigure)return;let{x:i,y:s}=Pf(this.env.model.getters,this.dnd.draggedFigure);this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.env.model.dispatch("UPDATE_FIGURE",{sheetId:o,id:e.id,x:i,y:s})}))}startResize(e,t,o,i){i.stopPropagation();const s={x:i.clientX,y:i.clientY},{x:n,y:r}=kf(this.env.model.getters,e),a={...e,x:n,y:r},l=Yr.get(e.tag).keepRatio||!1,c=Yr.get(e.tag).minFigSize||80;ff((i=>{const n={x:i.clientX,y:i.clientY},r=function(e,t,o,{x:i,y:s},{x:n,y:r},a,l,{scrollX:c,scrollY:h}){let{x:d,y:u,width:g,height:p}=e;if(a&&0!=t&&0!=o){const a=Math.min(t*(n-i),e.width-l),c=Math.min(o*(r-s),e.height-l),h=Math.min(a/e.width,c/e.height);g=e.width*(1-h),p=e.height*(1-h),t<0&&(d=e.x+e.width*h),o<0&&(u=e.y+e.height*h)}else{const a=Math.max(t*(i-n),l-e.width),c=Math.max(o*(s-r),l-e.height);g=e.width+a,p=e.height+c,t<0&&(d=e.x-a),o<0&&(u=e.y-c)}return d+c<=0&&(g=g+d+c,d=-c),u+h<=0&&(p=p+u+h,u=-h),{...e,x:d,y:u,width:g,height:p}}(a,t,o,n,s,l,c,this.env.model.getters.getActiveSheetScrollInfo()),h=this.getOtherFigures(e.id),d=function(e,t,o,i,s){const n={...i},r=$f(e,n,[-1===t?"left":"right"],s,["right","left"]);r&&(1===t?n.width-=r.snapOffset:-1===t&&(n.x-=r.snapOffset,n.width+=r.snapOffset));const a=$f(e,n,[-1===o?"top":"bottom"],s,["bottom","top"]);return a&&(1===o?n.height-=a.snapOffset:-1===o&&(n.y-=a.snapOffset,n.height+=a.snapOffset)),n.x=Math.round(n.x),n.y=Math.round(n.y),n.height=Math.round(n.height),n.width=Math.round(n.width),{snappedFigure:n,verticalSnapLine:r,horizontalSnapLine:a}}(this.env.model.getters,t,o,r,h);this.dnd.draggedFigure=d.snappedFigure,this.dnd.horizontalSnap=this.getSnap(d.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(d.verticalSnapLine)}),(i=>{if(!this.dnd.draggedFigure)return;let{x:s,y:n}=Pf(this.env.model.getters,this.dnd.draggedFigure);const r={x:s,y:n};t&&(r.width=this.dnd.draggedFigure.width),o&&(r.height=this.dnd.draggedFigure.height),this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:e.id,...r}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0}))}getOtherFigures(e){return this.getVisibleFigures().filter((t=>t.id!==e))}getDndFigure(){const e=this.getVisibleFigures().find((e=>e.id===this.dnd.draggedFigure?.id));if(!e)throw new Error("Dnd figure not found");return{...e,...this.dnd.draggedFigure}}getFigureStyle(e){return e.id!==this.dnd.draggedFigure?.id?"":Li({opacity:"0.9",cursor:"grabbing"})}getSnap(e){if(!e||!this.dnd.draggedFigure)return;const t=e.matchedFigIds.map((e=>this.getVisibleFigures().find((t=>t.id===e)))).filter(dt).map((e=>{const t=kf(this.env.model.getters,e),o=this.getFigureContainer(e);return mn(t,this.getContainerRect(o))})).filter(dt),o=function(...e){return bn(hi(...e.map(fn)))}(this.dnd.draggedFigure,...t);return{line:e,containerStyle:this.rectToCss(o),lineStyle:this.getSnapLineStyle(e,o)}}getSnapLineStyle(e,t){return e?["top","vCenter","bottom"].includes(e.snappedAxisType)?Li({top:e.position-t.y+"px",left:"0px",width:"100%"}):Li({top:"0px",left:e.position-t.x+"px",height:"100%"}):""}}function qf(e,o,i){let s={col:void 0,row:void 0};const{Date:n}=window;let r=0,a=0,l=0;function c(){return{col:e.model.getters.getColIndex(r),row:e.model.getters.getRowIndex(a)}}const{pause:h,resume:d}=function(e,o){let i;const{setInterval:s,clearInterval:n}=window;return t.useEffect((()=>(i=s(e,o),()=>n(i))),(()=>[o])),{pause:()=>{n(i),i=void 0},resume:()=>{void 0===i&&(i=s(e,o))}}}((function(){const{col:e,row:t}=c(),o=n.now()-l;o>300&&(e!==s.col||t!==s.row)&&p(void 0,void 0);if(o>300){if(e<0||t<0)return;p(e,t)}}),200);function u(e){o.el===e.target&&(r=e.offsetX,a=e.offsetY,l=n.now())}function g(){const{col:e,row:t}=c();e===s.col&&t===s.row||p(void 0,void 0)}function p(e,t){e===s.col&&t===s.row||(s.col=e,s.row=t,i({col:e,row:t}))}return t.onMounted((()=>{const e=o.el;e.addEventListener("mousemove",u),e.addEventListener("mouseleave",h),e.addEventListener("mouseenter",d),e.addEventListener("mousedown",g)})),t.onWillUnmount((()=>{const e=o.el;e.removeEventListener("mousemove",u),e.removeEventListener("mouseleave",h),e.removeEventListener("mouseenter",d),e.removeEventListener("mousedown",g)})),s}Gf.props={onFigureDeleted:Function};class Zf extends t.Component{static template="o-spreadsheet-GridOverlay";static components={FiguresContainer:Gf};static defaultProps={onCellHovered:()=>{},onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{},onFigureDeleted:()=>{}};gridOverlay;setup(){this.gridOverlay=t.useRef("gridOverlay"),qf(this.env,this.gridOverlay,this.props.onCellHovered);const e=new ResizeObserver((()=>{this.props.onGridResized({height:this.gridOverlayEl.clientHeight,width:this.gridOverlayEl.clientWidth})}));t.onMounted((()=>{e.observe(this.gridOverlayEl)})),t.onWillUnmount((()=>{e.disconnect()})),function(e,o,i){let s=null,n=null;function r(e){1===e.touches.length&&(s=e.touches[0].clientX,n=e.touches[0].clientY)}function a(){s=null,n=null}function l(e){if(1!==e.touches.length)return;i()&&(e.preventDefault(),e.stopPropagation());const t=e.touches[0].clientX,r=e.touches[0].clientY;o(s-t,n-r),s=t,n=r}t.onMounted((()=>{e.el.addEventListener("touchstart",r),e.el.addEventListener("touchend",a),e.el.addEventListener("touchmove",l)})),t.onWillUnmount((()=>{e.el.removeEventListener("touchstart",r),e.el.removeEventListener("touchend",a),e.el.removeEventListener("touchmove",l)}))}(this.gridOverlay,this.props.onGridMoved,(()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetDOMScrollInfo();return e>0}))}get gridOverlayEl(){if(!this.gridOverlay.el)throw new Error("GridOverlay el is not defined.");return this.gridOverlay.el}onMouseDown(e){if(e.button>0)return;const[t,o]=this.getCartesianCoordinates(e);this.props.onCellClicked(t,o,{expandZone:e.shiftKey,addZone:un(e)})}onDoubleClick(e){const[t,o]=this.getCartesianCoordinates(e);this.props.onCellDoubleClicked(t,o)}onContextMenu(e){const[t,o]=this.getCartesianCoordinates(e);this.props.onCellRightClicked(t,o,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){return[this.env.model.getters.getColIndex(e.offsetX),this.env.model.getters.getRowIndex(e.offsetY)]}}Zf.props={onCellHovered:{type:Function,optional:!0},onCellDoubleClicked:{type:Function,optional:!0},onCellClicked:{type:Function,optional:!0},onCellRightClicked:{type:Function,optional:!0},onGridResized:{type:Function,optional:!0},onFigureDeleted:{type:Function,optional:!0},onGridMoved:Function,gridOverlayDimensions:String};class jf extends t.Component{static template="o-spreadsheet-GridPopover";static components={Popover:vn};zIndex=ue.GridPopover;get cellPopover(){const e=this.env.model.getters.getCellPopover(this.props.hoveredCell);if(!e.isOpen)return{isOpen:!1};const t=e.anchorRect;return{...e,anchorRect:{...t,x:t.x+this.props.gridRect.x,y:t.y+this.props.gridRect.y}}}}jf.props={hoveredCell:Object,onClosePopover:Function,onMouseWheel:Function,gridRect:Object};class Yf extends t.Component{PADDING=0;MAX_SIZE_MARGIN=0;MIN_ELEMENT_SIZE=0;lastSelectedElementIndex=null;state=t.useState({resizerIsActive:!1,isResizing:!1,isMoving:!1,isSelecting:!1,waitingForMove:!1,activeElement:0,draggerLinePosition:0,draggerShadowPosition:0,draggerShadowThickness:0,delta:0,base:0,position:"before"});_computeHandleDisplay(e){const t=this._getEvOffset(e),o=this._getElementIndex(t);if(o<0)return;const i=this._getDimensionsInViewport(o);t-i.start<this.PADDING&&o!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=i.start,this.state.activeElement=this._getPreviousVisibleElement(o)):i.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=i.end,this.state.activeElement=o):this.state.resizerIsActive=!1}_computeGrabDisplay(e){const t=this._getElementIndex(this._getEvOffset(e)),o=this._getActiveElements(),i=this._getSelectedZoneStart(),s=this._getSelectedZoneEnd();o.has(i)&&i<=t&&t<=s?this.state.waitingForMove=!0:this.state.waitingForMove=!1}onMouseMove(e){this.state.isResizing||this.state.isMoving||this.state.isSelecting||(this._computeHandleDisplay(e),this._computeGrabDisplay(e))}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(e){this._fitElementSize(this.state.activeElement),this.state.isResizing=!1,this._computeHandleDisplay(e),this._computeGrabDisplay(e)}onMouseDown(e){this.state.isResizing=!0,this.state.delta=0;const t=this._getClientPosition(e),o=this.state.draggerLinePosition,i=this._getElementSize(this.state.activeElement),s=o-i+this.MIN_ELEMENT_SIZE,n=this._getMaxSize();ff((e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=o+this.state.delta,this.state.draggerLinePosition<s&&(this.state.draggerLinePosition=s,this.state.delta=this.MIN_ELEMENT_SIZE-i),this.state.draggerLinePosition>n&&(this.state.draggerLinePosition=n,this.state.delta=n-o)}),(e=>{this.state.isResizing=!1,0!==this.state.delta&&this._updateSize()}))}select(e){if(e.button>0)return;const t=this._getElementIndex(this._getEvOffset(e));t<0||(!0!==this.state.waitingForMove?("editing"===this.env.model.getters.getEditionMode()&&this.env.model.selection.getBackToDefault(),this.startSelection(e,t)):this.env.model.getters.isGridSelectionActive()?this.startMovement(e):this._selectElement(t,!1))}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;const t=this._getDimensionsInViewport(this._getSelectedZoneStart()),o=this._getDimensionsInViewport(this._getSelectedZoneEnd()),i=t.start;this.state.draggerLinePosition=i,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=i,this.state.draggerShadowThickness=o.end-t.start;bf(this.env,((e,o)=>{let i="COL"===this._getType()?e:o;if(i>=0){const e=this._getDimensionsInViewport(i);i<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=i,this.state.position="before"):this._getSelectedZoneEnd()<i?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=i,this.state.position="after"):(this.state.draggerLinePosition=t.start,this.state.draggerShadowPosition=t.start,this.state.base=this._getSelectedZoneStart())}}),(()=>{this.state.isMoving=!1,this.state.base!==this._getSelectedZoneStart()&&this._moveElements(),this._computeGrabDisplay(e)}))}startSelection(e,t){this.state.isSelecting=!0,e.shiftKey?this._increaseSelection(t):this._selectElement(t,un(e)),this.lastSelectedElementIndex=t;bf(this.env,((e,t)=>{let o="COL"===this._getType()?e:t;o!==this.lastSelectedElementIndex&&-1!==o&&(this._increaseSelection(o),this.lastSelectedElementIndex=o)}),(()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this.env.model.dispatch(un(e)?"PREPARE_SELECTION_INPUT_EXPANSION":"STOP_SELECTION_INPUT"),this._computeGrabDisplay(e)}))}onMouseUp(e){this.lastSelectedElementIndex=null}onContextMenu(e){e.preventDefault();const t=this._getElementIndex(this._getEvOffset(e));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);const o=this._getType();this.props.onOpenContextMenu(o,e.clientX,e.clientY)}}Ni`
|
|
1210
|
+
`;class Gf extends t.Component{static template="o-spreadsheet-FiguresContainer";static components={FigureComponent:mf};dnd=t.useState({draggedFigure:void 0,horizontalSnap:void 0,verticalSnap:void 0});setup(){t.onMounted((()=>{this.render()}))}getVisibleFigures(){const e=this.env.model.getters.getVisibleFigures();return this.dnd.draggedFigure&&!e.some((e=>e.id===this.dnd.draggedFigure?.id))&&e.push(this.env.model.getters.getFigure(this.env.model.getters.getActiveSheetId(),this.dnd.draggedFigure?.id)),e}get containers(){const e=this.getVisibleFigures(),t=[];for(const o of["topLeft","topRight","bottomLeft","bottomRight"]){const i=e.filter((e=>this.getFigureContainer(e)===o));i.length>0&&t.push({type:o,figures:i,style:this.getContainerStyle(o),inverseViewportStyle:this.getInverseViewportPositionStyle(o)})}return this.dnd.draggedFigure&&t.push({type:"dnd",figures:[this.getDndFigure()],style:this.getContainerStyle("dnd"),inverseViewportStyle:this.getInverseViewportPositionStyle("dnd")}),t}getContainerStyle(e){return this.rectToCss(this.getContainerRect(e))}rectToCss(e){return Li({left:`${e.x}px`,top:`${e.y}px`,width:`${e.width}px`,height:`${e.height}px`})}getContainerRect(e){const{width:t,height:o}=this.env.model.getters.getSheetViewDimension(),{x:i,y:s}=this.env.model.getters.getMainViewportCoordinates(),n=["bottomRight","topRight"].includes(e)?i:0,r=t-n,a=["bottomRight","bottomLeft"].includes(e)?s:0;return{x:n,y:a,width:r,height:o-a}}getInverseViewportPositionStyle(e){const{scrollX:t,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo(),{x:i,y:s}=this.env.model.getters.getMainViewportCoordinates();return Li({left:`${["bottomRight","topRight"].includes(e)?-(i+t):0}px`,top:`${["bottomRight","bottomLeft"].includes(e)?-(s+o):0}px`})}getFigureContainer(e){const{x:t,y:o}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.draggedFigure?.id?"dnd":e.x<t&&e.y<o?"topLeft":e.x<t?"bottomLeft":e.y<o?"topRight":"bottomRight"}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly())return;if(!this.env.model.dispatch("SELECT_FIGURE",{id:e.id}).isSuccessful)return;const o=this.env.model.getters.getActiveSheetId(),i={x:t.clientX,y:t.clientY},s={maxX:this.env.model.getters.getColDimensions(o,this.env.model.getters.getNumberCols(o)-1).end,maxY:this.env.model.getters.getRowDimensions(o,this.env.model.getters.getNumberRows(o)-1).end},{x:n,y:r}=Pf(this.env.model.getters,e),a={...e,x:n,y:r};ff((t=>{const o=this.env.model.getters,n=function({x:e,y:t},{x:o,y:i},s,{x:n,y:r},{maxX:a,maxY:l},{scrollX:c,scrollY:h}){const d=n?0:-c,u=r?0:-h,g=e-o,p=zf(s.x+g,d,a-s.width-c),m=t-i,f=zf(s.y+m,u,l-s.height-h);return{...s,x:p,y:f}}({x:t.clientX,y:t.clientY},i,a,this.env.model.getters.getMainViewportCoordinates(),s,o.getActiveSheetScrollInfo()),r=this.getOtherFigures(e.id),l=function(e,t,o){const i={...t},s=$f(e,i,["hCenter","right","left"],o,["hCenter","right","left"]),n=$f(e,i,["vCenter","bottom","top"],o,["vCenter","bottom","top"]),{y:r,x:a}=e.getMainViewportCoordinates(),{scrollY:l,scrollX:c}=e.getActiveSheetScrollInfo();if(n){i.y-=n.snapOffset;const e=t.y<r,o=i.y<r;e&&!o?i.y+=l:!e&&o&&(i.y-=l)}if(s){i.x-=s.snapOffset;const e=t.x<a,o=i.x<a;e&&!o?i.x+=c:!e&&o&&(i.x-=c)}return{snappedFigure:i,verticalSnapLine:s,horizontalSnapLine:n}}(o,kf(o,n),r);this.dnd.draggedFigure=Pf(o,l.snappedFigure),this.dnd.horizontalSnap=this.getSnap(l.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(l.verticalSnapLine)}),(t=>{if(!this.dnd.draggedFigure)return;let{x:i,y:s}=kf(this.env.model.getters,this.dnd.draggedFigure);this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.env.model.dispatch("UPDATE_FIGURE",{sheetId:o,id:e.id,x:i,y:s})}))}startResize(e,t,o,i){i.stopPropagation();const s={x:i.clientX,y:i.clientY},{x:n,y:r}=Pf(this.env.model.getters,e),a={...e,x:n,y:r},l=Yr.get(e.tag).keepRatio||!1,c=Yr.get(e.tag).minFigSize||80;ff((i=>{const n={x:i.clientX,y:i.clientY},r=function(e,t,o,{x:i,y:s},{x:n,y:r},a,l,{scrollX:c,scrollY:h}){let{x:d,y:u,width:g,height:p}=e;if(a&&0!=t&&0!=o){const a=Math.min(t*(n-i),e.width-l),c=Math.min(o*(r-s),e.height-l),h=Math.min(a/e.width,c/e.height);g=e.width*(1-h),p=e.height*(1-h),t<0&&(d=e.x+e.width*h),o<0&&(u=e.y+e.height*h)}else{const a=Math.max(t*(i-n),l-e.width),c=Math.max(o*(s-r),l-e.height);g=e.width+a,p=e.height+c,t<0&&(d=e.x-a),o<0&&(u=e.y-c)}return d+c<=0&&(g=g+d+c,d=-c),u+h<=0&&(p=p+u+h,u=-h),{...e,x:d,y:u,width:g,height:p}}(a,t,o,n,s,l,c,this.env.model.getters.getActiveSheetScrollInfo()),h=this.getOtherFigures(e.id),d=function(e,t,o,i,s){const n={...i},r=$f(e,n,[-1===t?"left":"right"],s,["right","left"]);r&&(1===t?n.width-=r.snapOffset:-1===t&&(n.x-=r.snapOffset,n.width+=r.snapOffset));const a=$f(e,n,[-1===o?"top":"bottom"],s,["bottom","top"]);return a&&(1===o?n.height-=a.snapOffset:-1===o&&(n.y-=a.snapOffset,n.height+=a.snapOffset)),n.x=Math.round(n.x),n.y=Math.round(n.y),n.height=Math.round(n.height),n.width=Math.round(n.width),{snappedFigure:n,verticalSnapLine:r,horizontalSnapLine:a}}(this.env.model.getters,t,o,r,h);this.dnd.draggedFigure=d.snappedFigure,this.dnd.horizontalSnap=this.getSnap(d.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(d.verticalSnapLine)}),(i=>{if(!this.dnd.draggedFigure)return;let{x:s,y:n}=kf(this.env.model.getters,this.dnd.draggedFigure);const r={x:s,y:n};t&&(r.width=this.dnd.draggedFigure.width),o&&(r.height=this.dnd.draggedFigure.height),this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:e.id,...r}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0}))}getOtherFigures(e){return this.getVisibleFigures().filter((t=>t.id!==e))}getDndFigure(){const e=this.getVisibleFigures().find((e=>e.id===this.dnd.draggedFigure?.id));if(!e)throw new Error("Dnd figure not found");return{...e,...this.dnd.draggedFigure}}getFigureStyle(e){return e.id!==this.dnd.draggedFigure?.id?"":Li({opacity:"0.9",cursor:"grabbing"})}getSnap(e){if(!e||!this.dnd.draggedFigure)return;const t=e.matchedFigIds.map((e=>this.getVisibleFigures().find((t=>t.id===e)))).filter(dt).map((e=>{const t=Pf(this.env.model.getters,e),o=this.getFigureContainer(e);return mn(t,this.getContainerRect(o))})).filter(dt),o=function(...e){return bn(hi(...e.map(fn)))}(this.dnd.draggedFigure,...t);return{line:e,containerStyle:this.rectToCss(o),lineStyle:this.getSnapLineStyle(e,o)}}getSnapLineStyle(e,t){return e?["top","vCenter","bottom"].includes(e.snappedAxisType)?Li({top:e.position-t.y+"px",left:"0px",width:"100%"}):Li({top:"0px",left:e.position-t.x+"px",height:"100%"}):""}}function qf(e,o,i){let s={col:void 0,row:void 0};const{Date:n}=window;let r=0,a=0,l=0;function c(){return{col:e.model.getters.getColIndex(r),row:e.model.getters.getRowIndex(a)}}const{pause:h,resume:d}=function(e,o){let i;const{setInterval:s,clearInterval:n}=window;return t.useEffect((()=>(i=s(e,o),()=>n(i))),(()=>[o])),{pause:()=>{n(i),i=void 0},resume:()=>{void 0===i&&(i=s(e,o))}}}((function(){const{col:e,row:t}=c(),o=n.now()-l;o>300&&(e!==s.col||t!==s.row)&&p(void 0,void 0);if(o>300){if(e<0||t<0)return;p(e,t)}}),200);function u(e){o.el===e.target&&(r=e.offsetX,a=e.offsetY,l=n.now())}function g(){const{col:e,row:t}=c();e===s.col&&t===s.row||p(void 0,void 0)}function p(e,t){e===s.col&&t===s.row||(s.col=e,s.row=t,i({col:e,row:t}))}return t.onMounted((()=>{const e=o.el;e.addEventListener("mousemove",u),e.addEventListener("mouseleave",h),e.addEventListener("mouseenter",d),e.addEventListener("mousedown",g)})),t.onWillUnmount((()=>{const e=o.el;e.removeEventListener("mousemove",u),e.removeEventListener("mouseleave",h),e.removeEventListener("mouseenter",d),e.removeEventListener("mousedown",g)})),s}Gf.props={onFigureDeleted:Function};class Zf extends t.Component{static template="o-spreadsheet-GridOverlay";static components={FiguresContainer:Gf};static defaultProps={onCellHovered:()=>{},onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{},onFigureDeleted:()=>{}};gridOverlay;setup(){this.gridOverlay=t.useRef("gridOverlay"),qf(this.env,this.gridOverlay,this.props.onCellHovered);const e=new ResizeObserver((()=>{this.props.onGridResized({height:this.gridOverlayEl.clientHeight,width:this.gridOverlayEl.clientWidth})}));t.onMounted((()=>{e.observe(this.gridOverlayEl)})),t.onWillUnmount((()=>{e.disconnect()})),function(e,o,i){let s=null,n=null;function r(e){1===e.touches.length&&(s=e.touches[0].clientX,n=e.touches[0].clientY)}function a(){s=null,n=null}function l(e){if(1!==e.touches.length)return;i()&&(e.preventDefault(),e.stopPropagation());const t=e.touches[0].clientX,r=e.touches[0].clientY;o(s-t,n-r),s=t,n=r}t.onMounted((()=>{e.el.addEventListener("touchstart",r),e.el.addEventListener("touchend",a),e.el.addEventListener("touchmove",l)})),t.onWillUnmount((()=>{e.el.removeEventListener("touchstart",r),e.el.removeEventListener("touchend",a),e.el.removeEventListener("touchmove",l)}))}(this.gridOverlay,this.props.onGridMoved,(()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetDOMScrollInfo();return e>0}))}get gridOverlayEl(){if(!this.gridOverlay.el)throw new Error("GridOverlay el is not defined.");return this.gridOverlay.el}onMouseDown(e){if(e.button>0)return;const[t,o]=this.getCartesianCoordinates(e);this.props.onCellClicked(t,o,{expandZone:e.shiftKey,addZone:un(e)})}onDoubleClick(e){const[t,o]=this.getCartesianCoordinates(e);this.props.onCellDoubleClicked(t,o)}onContextMenu(e){const[t,o]=this.getCartesianCoordinates(e);this.props.onCellRightClicked(t,o,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){return[this.env.model.getters.getColIndex(e.offsetX),this.env.model.getters.getRowIndex(e.offsetY)]}}Zf.props={onCellHovered:{type:Function,optional:!0},onCellDoubleClicked:{type:Function,optional:!0},onCellClicked:{type:Function,optional:!0},onCellRightClicked:{type:Function,optional:!0},onGridResized:{type:Function,optional:!0},onFigureDeleted:{type:Function,optional:!0},onGridMoved:Function,gridOverlayDimensions:String};class jf extends t.Component{static template="o-spreadsheet-GridPopover";static components={Popover:vn};zIndex=ue.GridPopover;get cellPopover(){const e=this.env.model.getters.getCellPopover(this.props.hoveredCell);if(!e.isOpen)return{isOpen:!1};const t=e.anchorRect;return{...e,anchorRect:{...t,x:t.x+this.props.gridRect.x,y:t.y+this.props.gridRect.y}}}}jf.props={hoveredCell:Object,onClosePopover:Function,onMouseWheel:Function,gridRect:Object};class Yf extends t.Component{PADDING=0;MAX_SIZE_MARGIN=0;MIN_ELEMENT_SIZE=0;lastSelectedElementIndex=null;state=t.useState({resizerIsActive:!1,isResizing:!1,isMoving:!1,isSelecting:!1,waitingForMove:!1,activeElement:0,draggerLinePosition:0,draggerShadowPosition:0,draggerShadowThickness:0,delta:0,base:0,position:"before"});_computeHandleDisplay(e){const t=this._getEvOffset(e),o=this._getElementIndex(t);if(o<0)return;const i=this._getDimensionsInViewport(o);t-i.start<this.PADDING&&o!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=i.start,this.state.activeElement=this._getPreviousVisibleElement(o)):i.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=i.end,this.state.activeElement=o):this.state.resizerIsActive=!1}_computeGrabDisplay(e){const t=this._getElementIndex(this._getEvOffset(e)),o=this._getActiveElements(),i=this._getSelectedZoneStart(),s=this._getSelectedZoneEnd();o.has(i)&&i<=t&&t<=s?this.state.waitingForMove=!0:this.state.waitingForMove=!1}onMouseMove(e){this.state.isResizing||this.state.isMoving||this.state.isSelecting||(this._computeHandleDisplay(e),this._computeGrabDisplay(e))}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(e){this._fitElementSize(this.state.activeElement),this.state.isResizing=!1,this._computeHandleDisplay(e),this._computeGrabDisplay(e)}onMouseDown(e){this.state.isResizing=!0,this.state.delta=0;const t=this._getClientPosition(e),o=this.state.draggerLinePosition,i=this._getElementSize(this.state.activeElement),s=o-i+this.MIN_ELEMENT_SIZE,n=this._getMaxSize();ff((e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=o+this.state.delta,this.state.draggerLinePosition<s&&(this.state.draggerLinePosition=s,this.state.delta=this.MIN_ELEMENT_SIZE-i),this.state.draggerLinePosition>n&&(this.state.draggerLinePosition=n,this.state.delta=n-o)}),(e=>{this.state.isResizing=!1,0!==this.state.delta&&this._updateSize()}))}select(e){if(e.button>0)return;const t=this._getElementIndex(this._getEvOffset(e));t<0||(!0!==this.state.waitingForMove?("editing"===this.env.model.getters.getEditionMode()&&this.env.model.selection.getBackToDefault(),this.startSelection(e,t)):this.env.model.getters.isGridSelectionActive()?this.startMovement(e):this._selectElement(t,!1))}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;const t=this._getDimensionsInViewport(this._getSelectedZoneStart()),o=this._getDimensionsInViewport(this._getSelectedZoneEnd()),i=t.start;this.state.draggerLinePosition=i,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=i,this.state.draggerShadowThickness=o.end-t.start;bf(this.env,((e,o)=>{let i="COL"===this._getType()?e:o;if(i>=0){const e=this._getDimensionsInViewport(i);i<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=i,this.state.position="before"):this._getSelectedZoneEnd()<i?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=i,this.state.position="after"):(this.state.draggerLinePosition=t.start,this.state.draggerShadowPosition=t.start,this.state.base=this._getSelectedZoneStart())}}),(()=>{this.state.isMoving=!1,this.state.base!==this._getSelectedZoneStart()&&this._moveElements(),this._computeGrabDisplay(e)}))}startSelection(e,t){this.state.isSelecting=!0,e.shiftKey?this._increaseSelection(t):this._selectElement(t,un(e)),this.lastSelectedElementIndex=t;bf(this.env,((e,t)=>{let o="COL"===this._getType()?e:t;o!==this.lastSelectedElementIndex&&-1!==o&&(this._increaseSelection(o),this.lastSelectedElementIndex=o)}),(()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this.env.model.dispatch(un(e)?"PREPARE_SELECTION_INPUT_EXPANSION":"STOP_SELECTION_INPUT"),this._computeGrabDisplay(e)}))}onMouseUp(e){this.lastSelectedElementIndex=null}onContextMenu(e){e.preventDefault();const t=this._getElementIndex(this._getEvOffset(e));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);const o=this._getType();this.props.onOpenContextMenu(o,e.clientX,e.clientY)}}Ni`
|
|
1211
1211
|
.o-col-resizer {
|
|
1212
1212
|
position: absolute;
|
|
1213
1213
|
top: 0;
|
|
@@ -1338,7 +1338,7 @@
|
|
|
1338
1338
|
height: ${F}px;
|
|
1339
1339
|
}
|
|
1340
1340
|
}
|
|
1341
|
-
`,Kf.props={onOpenContextMenu:Function};class Qf extends t.Component{static template="o-spreadsheet-HeadersOverlay";static components={ColResizer:Xf,RowResizer:Kf};selectAll(){this.env.model.selection.selectAll()}}function Jf(e,o,i){const s=t.useRef(e);t.useEffect((function(){const e=s.el,t=window.devicePixelRatio||1,n=e.getContext("2d",{alpha:!1}),r={ctx:n,dpr:t,thinLineWidth:.4*t},{width:a,height:l}=i();e.style.width=`${a}px`,e.style.height=`${l}px`,e.width=a*t,e.height=l*t,e.setAttribute("style",`width:${a}px;height:${l}px;`),n.translate(-m,-m),n.scale(t,t),o.drawGrid(r)}))}function eb(e){function t(e,t){return e*(0===t?1:
|
|
1341
|
+
`,Kf.props={onOpenContextMenu:Function};class Qf extends t.Component{static template="o-spreadsheet-HeadersOverlay";static components={ColResizer:Xf,RowResizer:Kf};selectAll(){this.env.model.selection.selectAll()}}function Jf(e,o,i){const s=t.useRef(e);t.useEffect((function(){const e=s.el,t=window.devicePixelRatio||1,n=e.getContext("2d",{alpha:!1}),r={ctx:n,dpr:t,thinLineWidth:.4*t},{width:a,height:l}=i();e.style.width=`${a}px`,e.style.height=`${l}px`,e.width=a*t,e.height=l*t,e.setAttribute("style",`width:${a}px;height:${l}px;`),n.translate(-m,-m),n.scale(t,t),o.drawGrid(r)}))}function eb(e){function t(e,t){return e*(0===t?1:P)}return o=>{const i=t(o.shiftKey&&!dn()?o.deltaY:o.deltaX,o.deltaMode),s=t(o.shiftKey&&!dn()?o.deltaX:o.deltaY,o.deltaMode);e(i,s)}}Qf.props={onOpenContextMenu:Function},Ni`
|
|
1342
1342
|
.o-border {
|
|
1343
1343
|
position: absolute;
|
|
1344
1344
|
&:hover {
|
|
@@ -1384,8 +1384,8 @@
|
|
|
1384
1384
|
&.corner {
|
|
1385
1385
|
right: 0px;
|
|
1386
1386
|
bottom: 0px;
|
|
1387
|
-
height: ${
|
|
1388
|
-
width: ${
|
|
1387
|
+
height: ${k}px;
|
|
1388
|
+
width: ${k}px;
|
|
1389
1389
|
border-top: 1px solid #e2e3e3;
|
|
1390
1390
|
border-left: 1px solid #e2e3e3;
|
|
1391
1391
|
}
|
|
@@ -1414,9 +1414,9 @@
|
|
|
1414
1414
|
offset="offset"
|
|
1415
1415
|
direction="'vertical'"
|
|
1416
1416
|
onScroll.bind="onScroll"
|
|
1417
|
-
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetDOMScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){const{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{y:e}=this.env.model.getters.getMainViewportRect();return{top:`${this.props.topOffset+e}px`,right:"0px",width:"15px",bottom:"0px"}}onScroll(e){const{scrollX:t}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:t,offsetY:e})}}ab.props={topOffset:{type:Number,optional:!0}};const lb={ROW:Dm,COL:Nm,CELL:fp};class cb extends t.Component{static template="o-spreadsheet-Grid";static components={GridComposer:Nf,GridOverlay:Zf,GridPopover:jf,HeadersOverlay:Qf,Menu:wn,Autofill:vf,ClientTag:Cf,Highlight:ib,Popover:vn,VerticalScrollBar:ab,HorizontalScrollBar:rb,FilterIconsOverlay:Lf};HEADER_HEIGHT=F;HEADER_WIDTH=D;menuState;gridRef;onMouseWheel;canvasPosition;hoveredCell;setup(){this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.canvasPosition=pn(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.focusDefaultElement())),this.props.exposeFocus((()=>this.focusDefaultElement())),Jf("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),t.useEffect((()=>this.focusDefaultElement()),(()=>[this.env.model.getters.getActiveSheetId()])),this.onMouseWheel=eb(((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 Li({top:"26px",left:"48px",height:"calc(100% - 41px)",width:"calc(100% - 63px)"})}onClosePopover(){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.focusDefaultElement()}keyDownMapping={ENTER:()=>{this.env.model.getters.getActiveCell().type===ys.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===ys.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"),F4:()=>this.env.model.dispatch("REQUEST_REDO"),"CTRL+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"CTRL+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"CTRL+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"CTRL+O":()=>xa(this.env),"ALT+=":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:o}=this.env.model.getters.getSelection(),i=this.env.model.getters.getAutomaticSums(e,t,o.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&i.length<=1){const t=i[0]?.zone,o=t?this.env.model.getters.zoneToXC(e,i[0].zone):"",s=`=SUM(${o})`;this.props.onGridComposerCellFocused(s,{start:5,end:5+o.length})}else this.env.model.dispatch("SUM_SELECTION")},"ALT+ENTER":()=>{const e=this.env.model.getters.getActiveCell();e.link&&Zi(e.link,this.env)},"CTRL+HOME":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:o}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,o)},"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),o=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,o)},"SHIFT+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},o=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:o,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},o=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:o,zone:t})},"CTRL+SHIFT+E":()=>this.setHorizontalAlign("center"),"CTRL+SHIFT+L":()=>this.setHorizontalAlign("left"),"CTRL+SHIFT+R":()=>this.setHorizontalAlign("right"),"CTRL+SHIFT+V":()=>ba(this.env),"CTRL+SHIFT+<":()=>this.clearFormatting(),"CTRL+<":()=>this.clearFormatting(),"CTRL+SHIFT+ ":()=>{this.env.model.selection.selectAll()},"CTRL+ALT+=":()=>{const e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),o=1===this.env.model.getters.getSelectedZones().length,i=e.size>0&&o,s=t.size>0&&o;i&&!s?Ea(this.env):s&&!i&&Ca(this.env)},"CTRL+ALT+-":()=>{const e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&0===t.length?this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"COL",elements:e}):t.length>0&&0===e.length&&this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},"SHIFT+PAGEDOWN":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"SHIFT+PAGEUP":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PAGEDOWN:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PAGEUP:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"CTRL+K":()=>Ia(this.env)};focusDefaultElement(){this.env.model.getters.getSelectedFigureId()||"inactive"!==this.env.model.getters.getEditionMode()||this.env.focusableElement.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:D,gridOffsetY:F})}moveCanvas(e,t){const{scrollX:o,scrollY:i}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o+e,offsetY:i+t})}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,{addZone:o,expandZone:i}){o&&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"),i?this.env.model.selection.setAnchorCorner(e,t):o?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t);let s=e,n=t;bf(this.env,((e,t,o)=>{o.preventDefault(),(e!==s&&-1!=e||t!==n&&-1!=t)&&(s=-1===e?s:e,n=-1===t?n:t,this.env.model.selection.setAnchorCorner(s,n))}),(()=>{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 o=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:o,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t}).type===ys.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(),Um(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="";un(e)&&(t+="CTRL+"),e.altKey&&(t+="ALT+"),e.shiftKey&&(t+="SHIFT+"),t+=e.key.toUpperCase();let o=this.keyDownMapping[t];return o?(e.preventDefault(),e.stopPropagation(),void o()):void 0}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:o,top:i}=t;let s="CELL";this.env.model.dispatch("STOP_EDITION"),this.env.model.getters.getActiveCols().has(o)?s="COL":this.env.model.getters.getActiveRows().has(i)&&(s="ROW");const{x:n,y:r,width:a}=this.env.model.getters.getVisibleRect(t);this.toggleContextMenu(s,this.canvasPosition.x+n+a,this.canvasPosition.y+r)}onCellRightClicked(e,t,{x:o,y:i}){const s=this.env.model.getters.getSelectedZones();let n="CELL";pi(e,t,s[s.length-1])?this.env.model.getters.getActiveCols().has(e)?n="COL":this.env.model.getters.getActiveRows().has(t)&&(n="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(n,o,i)}toggleContextMenu(e,t,o){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:o},this.menuState.menuItems=lb[e].getMenuItems()}copy(e,t){if(!this.gridEl.contains(document.activeElement))return;const o=t.clipboardData;if(!o)return void this.displayWarningCopyPasteNotSupported();if("inactive"!==this.env.model.getters.getEditionMode())return;e?ra(this.env):this.env.model.dispatch("COPY");const i=this.env.model.getters.getClipboardContent();for(const e in i)o.setData(e,i[e]);t.preventDefault()}paste(e){if(!this.gridEl.contains(document.activeElement))return;const t=e.clipboardData;if(t){if(t.types.indexOf(Is.PlainText)>-1){const e=t.getData(Is.PlainText),o=this.env.model.getters.getSelectedZones();this.env.model.getters.getClipboardTextContent()===e?da(this.env,o):ua(this.env,o,e)}}else this.displayWarningCopyPasteNotSupported()}displayWarningCopyPasteNotSupported(){this.env.raiseError(n("Copy/Paste is not supported in this browser."))}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}}cb.props={sidePanelIsOpen:Boolean,exposeFocus:Function,focusComposer:String,onComposerContentFocused:Function,onGridComposerCellFocused:Function};class hb{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}}const db=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart"],ub="000000",gb={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},pb={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"},mb="http://schemas.openxmlformats.org/drawingml/2006/main",fb="http://schemas.openxmlformats.org/drawingml/2006/chart",bb={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"},vb={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"},Sb="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Cb=.75,Eb=.1317,wb=8.43,xb=12.75,yb=30,Ib=100,Rb=164,Tb={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}]},Ab=["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"],Ob="[Content_Types].xml";var Mb;!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"}(Mb||(Mb={}));class Nb{_parsingWarnings=new Set;_conversionWarnings=new Set;addParsingWarning(e){this._parsingWarnings.add(e)}addConversionWarning(e){this._conversionWarnings.add(e)}get warnings(){return[...this._parsingWarnings,...this._conversionWarnings]}generateNotSupportedWarning(e,t,o){let i=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;o&&(i+=`Only ${o.join(", ")} are currently supported.`),this._conversionWarnings.has(i)||this._conversionWarnings.add(i)}}const _b=["thin"],Fb=["general","left","center","right"],Db=["top","center","bottom"],Lb=["Arial"],kb=["solid"],Pb=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWith","containsBlanks","notContainsBlanks"],Ub={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},Vb={dashDot:"thin",dashDotDot:"thin",dashed:"dashed",dotted:"dotted",double:"thin",hair:"thin",medium:"medium",mediumDashDot:"thin",mediumDashDotDot:"thin",mediumDashed:"thin",none:void 0,slantDashDot:"thin",thick:"thick",thin:"thin"},zb={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"},Bb={top:"top",center:"middle",bottom:"bottom",justify:"middle",distributed:"middle"},Hb={top:"top",middle:"center",bottom:"bottom"};const $b={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},Wb={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},Gb={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"},qb={b:"bottom",t:"top",l:"left",r:"right",tr:"right"},Zb={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},jb={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"},Yb={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},Xb={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},Kb={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"},Qb={"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 Jb(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=ub;else{if(!e.indexed)return;t=Kb[e.indexed]}var o;return t=6===(o=t).length?"#"+o+"FF":"#"+o.slice(2)+o.slice(0,2),e.tint&&(t=function(e,t){const o=Ut(e),i=zt(o);t<0&&(i.l=i.l*(1+t));t>0&&(i.l=i.l*(1-t)+(100-100*(1-t)));return Pt(Vt(i))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function ev(e,t){const o=e.split("/"),i=t.split("/");let s="",n=0;for(let e=0;e<o.length-1;e++)o[e]===i[e]?n++:s+="../";return s+=i.slice(n).join("/"),s}function tv(e,t=0){const o={};for(let i=0;i<e.length;i++)e[i]&&(o[i+t]=e[i]);return o}function ov(e){const t=[];for(let o of Object.keys(e).map(Number))t[o]=e[o];return t}function iv(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,((e,t)=>String.fromCharCode(parseInt(t,16))))}const sv=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function nv(e,t,o){if(0===e)return;let i=Yb[e]||t.find((t=>t.id===e))?.format;if(i)try{let e=i.replace(/(.*?);.*/,"$1");e=e.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]"),e=e.replace(/\[\$\]/g,"");const t=e.match(/"/g)?.length||0;if(t/2+(e.match(/\[/g)?.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 sv.test(e)}(e)&&(e=function(e){return e=e.toLowerCase(),e=e.replace(/mmmmm/g,"mmm"),e=e.replace(/am\/pm|a\/m/g,"a"),e=e.replace(/hhhh/g,"hh"),e=e.replace(/\bh\b/g,"hh"),e}(e)),function(e){try{return bo(0,e),!0}catch(e){return!1}}(e))return e}catch(e){}o.generateNotSupportedWarning(Mb.NumFmtIdNotSupported,i||`nmFmtId ${e}`)}function rv(e,t){const o=e.borders.map((e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(Mb.DiagonalBorderNotSupported)}(e,t);const o={top:av(e.top,t),bottom:av(e.bottom,t),left:av(e.left,t),right:av(e.right,t)};return Object.keys(o).forEach((e=>void 0===o[e]&&delete o[e])),o}));return tv(o,1)}function av(e,t){if(!e)return;!function(e,t){_b.includes(e.style)||t.generateNotSupportedWarning(Mb.BorderStyleNotSupported,e.style,_b)}(e,t);const o=Vb[e.style];return o?{style:o,color:Jb(e.color)}:void 0}function lv(e,t){return tv(e.styles.map((o=>cv({fontStyle:e.fonts[o.fontId],fillStyle:e.fills[o.fillId],alignment:o.alignment},t))),1)}function cv(e,t){return function(e,t,o){e&&e.name&&!Lb.includes(e.name)&&o.generateNotSupportedWarning(Mb.FontNotSupported,e.name,Lb);t&&t.patternType&&!kb.includes(t.patternType)&&o.generateNotSupportedWarning(Mb.FillStyleNotSupported,t.patternType,kb)}(e?.fontStyle,e?.fillStyle,t),function(e,t){e&&!Fb.includes(e)&&t.generateNotSupportedWarning(Mb.HorizontalAlignmentNotSupported,e,Fb)}(e?.alignment?.horizontal,t),function(e,t){e&&!Db.includes(e)&&t.generateNotSupportedWarning(Mb.VerticalAlignmentNotSupported,e,Db)}(e?.alignment?.vertical,t),{bold:e.fontStyle?.bold,italic:e.fontStyle?.italic,strikethrough:e.fontStyle?.strike,underline:e.fontStyle?.underline,verticalAlign:e.alignment?.vertical?Bb[e.alignment.vertical]:void 0,align:e.alignment?.horizontal?zb[e.alignment.horizontal]:void 0,fillColor:"solid"===e.fillStyle?.patternType?Jb(e.fillStyle?.fgColor):Jb(e.fillStyle?.bgColor),textColor:Jb(e.fontStyle?.color),fontSize:e.fontStyle?.size,wrapping:e.alignment?.wrapText?"wrap":"overflow"}}function hv(e,t){const o=[];for(let i of e.styles){const s=nv(i.numFmtId,e.numFmts,t);s&&(o[i.numFmtId]=s)}return tv(o,1)}function dv(e,t,o){const i=[];let s=1;for(let r of e){if(0===r.cfRules.length)continue;mv(r,t,o);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=uv(s++,r);t&&i.push(t);continue;case"iconSet":const c=gv(s++,r,o);c&&i.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;a=$b[e.type],l.push(e.text);break;case"containsBlanks":case"notContainsBlanks":a=$b[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;a=(n=e.operator).slice(0,1).toUpperCase()+n.slice(1),l.push(e.formula[0]),2===e.formula.length&&l.push(e.formula[1])}a&&void 0!==e.dxfId&&i.push({id:(s++).toString(),ranges:r.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:a,values:l,style:cv({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},o)}})}}var n;return i}function uv(e,t){const o=t.cfRules[0].colorScale;if(!o||o.cfvos.length!==o.colors.length||o.cfvos.length<2||o.cfvos.length>3)return;const i=[];for(let e=0;e<o.cfvos.length;e++)i.push({color:(s=Jb(o.colors[e])||"#FFFFFF",9===s.length&&(s=s.slice(0,7)),parseInt(s.replace("#",""),16)),type:Wb[o.cfvos[e].type],value:o.cfvos[e].value});var s;const n=i[0],r=2===i.length?i[1]:i[2],a=3===i.length?i[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:n,midpoint:a,maximum:r}}}function gv(e,t,o){const i=t.cfRules[0].iconSet;if(!i)return;let s=i.cfvos,n=i.cfIcons;if(s.length<3||n&&n.length<3)return;s.length>3&&(s=[s[0],s[Math.floor(s.length/2)],s[s.length-1]]),n&&n.length>3&&(n=[n[0],n[Math.floor(n.length/2)],n[n.length-1]]);const r=[];for(let e=1;e<=2;e++){const t=Wb[s[e].type];if("value"===t)return;r.push({value:s[e].value||"",operator:s[e].gte?"ge":"gt",type:t})}let a={lower:n?pv(n[0].iconSet,n[0].iconId):pv(i.iconSet,0),middle:n?pv(n[1].iconSet,n[1].iconId):pv(i.iconSet,1),upper:n?pv(n[2].iconSet,n[2].iconId):pv(i.iconSet,2)};i.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(let e of Object.keys(a))if(!a[e])switch(o.generateNotSupportedWarning(Mb.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=nf.dots.good;break;case"middle":a[e]=nf.dots.neutral;break;case"lower":a[e]=nf.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 pv(e,t){const o=Gb[e];return o?0===t?nf[o].bad:1===t?nf[o].neutral:nf[o].good:""}function mv(e,t,o){if(e.cfRules.length>1&&o.generateNotSupportedWarning(Mb.MultipleRulesCfNotSupported),Pb.includes(e.cfRules[0].type)||o.generateNotSupportedWarning(Mb.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const i=t[e.cfRules[0].dxfId];i.border&&o.generateNotSupportedWarning(Mb.CfFormatBorderNotSupported),i.alignment&&o.generateNotSupportedWarning(Mb.CfFormatAlignmentNotSupported),i.numFmt&&o.generateNotSupportedWarning(Mb.CfFormatNumFmtNotSupported)}}class fv{scope;code="";constructor(e=new vv){this.scope=e}append(...e){this.code+=e.map((e=>e.toString())).join("\n")+"\n"}return(e){return new bv(this.scope,this.code,e)}toString(){return Sv(this.code)}}class bv{scope;returnExpression;code;constructor(e,t,o){this.scope=e,this.returnExpression=o,this.code=Sv(t)}toString(){return this.code}wrapInClosure(){const e=this.scope.nextVariableName(),t=new fv(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 fv(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}}class vv{nextId=1;declaredVariables=new Set;nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function Sv(e){let t="",o=0;const i=e.split("\n").map((e=>e.trim())).filter((e=>""!==e));for(const e of i)e.startsWith("}")&&o--,t+="\t".repeat(o)+e+"\n",e.endsWith("{")&&o++;return t.trim()}const Cv=Hg.content,Ev=["%"],wv="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(Ev);function xv(e){e=It(e);const t=new Dv(e),o=[];for(;!t.isOver();){let e=_v(t)||Rv(t)||Tv(t)||Ov(t)||yv(t)||Fv(t)||Av(t)||Nv(t);e||(e={type:"UNKNOWN",value:t.shift()}),o.push(e)}return o}function yv(e){return"?"===e.current()?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const Iv={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function Rv(e){if(e.current()in Iv){const t=e.shift();return{type:Iv[t],value:t}}return null}function Tv(e){for(let t of wv)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:"OPERATOR",value:t};return null}function Av(e){const t=e.remaining().match(Qt);return t?(e.advanceBy(t[0].length),{type:"NUMBER",value:t[0]}):null}function Ov(e){if('"'===e.current()){const t=e.shift();let o=t;for(;e.current()&&(e.current()!==t||"\\"===o[o.length-1]);)o+=e.shift();return'"'===e.current()&&(o+=e.shift()),{type:"STRING",value:o}}return null}const Mv=/\w|\.|!|\$/;function Nv(e){let t="";if("'"===e.current()){let o=e.shift();for(t+=o;e.current();)if(o=e.shift(),t+=o,"'"===o){if(!e.current()||"'"!==e.current())break;o=e.shift(),t+=o}if("'"!==o)return{type:"UNKNOWN",value:t}}for(;e.current()&&Mv.test(e.current());)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in Cv)return{type:"FUNCTION",value:e};return $o.test(e)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function _v(e){let t=0;for(;e.current()===me;)t++,e.shift();if(t)return{type:"SPACE",value:me.repeat(t)};for(;" "===e.current();)t++,e.shift();return t?{type:"SPACE",value:" ".repeat(t)}:null}function Fv(e){return e.currentStartsWith(J)?(e.advanceBy(J.length),{type:"INVALID_REFERENCE",value:J}):null}class Dv{text;currentIndex=0;constructor(e){this.text=e}current(){return this.text[this.currentIndex]}shift(){return this.text[this.currentIndex++]}advanceBy(e){this.currentIndex+=e}isOver(){return this.currentIndex>=this.text.length}remaining(){return this.text.substring(this.currentIndex)}currentStartsWith(e){for(let t=0;t<e.length;t++)if(this.text[this.currentIndex+t]!==e[t])return!1;return!0}}const Lv=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,kv=["-","+"],Pv=["%"],Uv=["*","+","&"],Vv={"^":30,"%":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function zv(e){const t=e.shift();if(!t)throw new h(de);switch(t.type){case"DEBUGGER":const o=$v(e,1e3);return o.debug=!0,o;case"NUMBER":return{type:"NUMBER",value:ro(t.value)};case"STRING":return{type:"STRING",value:Ve(t.value)};case"FUNCTION":const i=function(e){Hv(e,"LEFT_PAREN",n("Missing opening parenthesis"));const t=e[0];if("RIGHT_PAREN"===t?.type)return Hv(e,"RIGHT_PAREN"),[];const o=[];o.push(Bv(e));for(;"RIGHT_PAREN"!==e[0]?.type;)Hv(e,"COMMA",n("Wrong function call")),o.push(Bv(e));return Hv(e,"RIGHT_PAREN"),o}(e);return{type:"FUNCALL",value:t.value,args:i};case"INVALID_REFERENCE":throw new u;case"REFERENCE":if(":"===e[0]?.value&&"REFERENCE"===e[1]?.type){e.shift();const o=e.shift();return{type:"REFERENCE",value:`${t.value}:${o?.value}`}}return{type:"REFERENCE",value:t.value};case"SYMBOL":if(["TRUE","FALSE"].includes(t.value.toUpperCase()))return{type:"BOOLEAN",value:"TRUE"===t.value.toUpperCase()};if(t.value&&Lv.test(t.value)&&"LEFT_PAREN"===e[0]?.type)throw new p(t.value);throw new h(n("Invalid formula"));case"LEFT_PAREN":const s=$v(e);return Hv(e,"RIGHT_PAREN",n("Missing closing parenthesis")),s;case"OPERATOR":const r=t.value;if(kv.includes(r))return{type:"UNARY_OPERATION",value:r,operand:$v(e,Vv[r])};throw new h(n("Unexpected token: %s",t.value));default:throw new h(n("Unexpected token: %s",t.value))}}function Bv(e){const t=e[0];return"COMMA"===t?.type||"RIGHT_PAREN"===t?.type?{type:"EMPTY",value:""}:$v(e)}function Hv(e,t,o=de){const i=e.shift();if(!i||i.type!==t)throw new h(o)}function $v(e,t=0){if(0===e.length)throw new h(de);let o=zv(e);for(;"OPERATOR"===e[0]?.type&&Vv[e[0].value]>t;){const t=e.shift().value;if(Pv.includes(t))o={type:"UNARY_OPERATION",value:t,operand:o,postfix:!0};else{o={type:"BIN_OPERATION",value:t,left:o,right:$v(e,Vv[t])}}}return o}function Wv(e){return Gv(xv(e))}function Gv(e){"="===(e=e.filter((e=>"SPACE"!==e.type)))[0].value&&e.splice(0,1);const t=$v(e);if(e.length)throw new h(de);return t}function qv(e,t,o){switch(t===e.type&&(e=o(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>qv(e,t,o)))};case"UNARY_OPERATION":return{...e,operand:qv(e.operand,t,o)};case"BIN_OPERATION":return{...e,right:qv(e.right,t,o),left:qv(e.left,t,o)};default:return e}}function Zv(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>Zv(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?jv(e)+e.value:e.value+Yv(e);case"BIN_OPERATION":return jv(e)+e.value+Yv(e)}}function jv(e){const t=e.value,o="left"in e?e.left:e.operand,i=o.value;return"BIN_OPERATION"===o.type&&Vv[i]<Vv[t]?`(${Zv(o)})`:Zv(o)}function Yv(e){const t=e.value,o="right"in e?e.right:e.operand,i=Vv[o.value],s=Vv[t];let n=!1;return"BIN_OPERATION"!==o.type?n=!1:i<s?n=!0:i!==s||Uv.includes(t)||(n=!0),n?`(${Zv(o)})`:Zv(o)}var Xv;!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"}(Xv||(Xv={}));const Kv=(e,t=(()=>!0))=>[{goTo:e,guard:t}],Qv=(e,t=(()=>!0))=>({goTo:e,guard:t}),Jv={[Xv.LeftRef]:{REFERENCE:Kv(Xv.Separator),NUMBER:Kv(Xv.FullRowSeparator),SYMBOL:[Qv(Xv.FullColumnSeparator,(e=>Wo(e.value))),Qv(Xv.FullRowSeparator,(e=>Go(e.value)))]},[Xv.FullColumnSeparator]:{SPACE:Kv(Xv.FullColumnSeparator),OPERATOR:Kv(Xv.RightColumnRef,(e=>":"===e.value))},[Xv.FullRowSeparator]:{SPACE:Kv(Xv.FullRowSeparator),OPERATOR:Kv(Xv.RightRowRef,(e=>":"===e.value))},[Xv.Separator]:{SPACE:Kv(Xv.Separator),OPERATOR:Kv(Xv.RightRef,(e=>":"===e.value))},[Xv.RightRef]:{SPACE:Kv(Xv.RightRef),NUMBER:Kv(Xv.Found),REFERENCE:Kv(Xv.Found,(e=>jo(e.value))),SYMBOL:Kv(Xv.Found,(e=>qo(e.value)||Zo(e.value)))},[Xv.RightColumnRef]:{SPACE:Kv(Xv.RightColumnRef),SYMBOL:Kv(Xv.Found,(e=>qo(e.value))),REFERENCE:Kv(Xv.Found,(e=>jo(e.value)))},[Xv.RightRowRef]:{SPACE:Kv(Xv.RightRowRef),NUMBER:Kv(Xv.Found),REFERENCE:Kv(Xv.Found,(e=>jo(e.value))),SYMBOL:Kv(Xv.Found,(e=>Zo(e.value)))},[Xv.Found]:{}};function eS(e){let t=0,o=Jv[Xv.LeftRef],i="";for(;void 0!==o;){const s=e[t++];if(!s)return null;const n=o[s.type]?.find((e=>e.guard(s))),r=n?n.goTo:void 0;switch(r){case void 0:return null;case Xv.Found:return i+=s.value,e.splice(0,t),{type:"REFERENCE",value:i};default:o=Jv[r],i+=s.value}}return null}function tS(e){const t=xv(e),o=[];for(;t.length;)o.push(eS(t)||t.shift());return o}const oS=Hg.content,iS={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},sS={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"},nS={};function rS(e){const t=tS(e),{dependencies:o,constantValues:i}=function(e){const t={numbers:[],strings:[]},o=[];for(const i of e)switch(i.type){case"INVALID_REFERENCE":case"REFERENCE":o.push(i.value);break;case"STRING":const e=Ve(i.value);t.strings.includes(e)||t.strings.push(e);break;case"NUMBER":{const e=ro(i.value);t.numbers.includes(e)||t.numbers.push(e);break}}return{dependencies:o,constantValues:t}}(t),s=function(e,t,o){return pt(e.map((e=>{switch(e.type){case"STRING":const i=Ve(e.value);return`|S${o.strings.indexOf(i)}|`;case"NUMBER":return`|N${o.numbers.indexOf(ro(e.value))}|`;case"REFERENCE":case"INVALID_REFERENCE":return`|${t.indexOf(e.value)}|`;case"SPACE":return"";default:return e.value}})))}(t,o,i);if(!nS[s]){const r=Gv([...t]),a=new vv;if("BIN_OPERATION"===r.type&&":"===r.value)throw new h(n("Invalid formula"));if("EMPTY"===r.type)throw new h(n("Invalid formula"));const l=g(r),c=new fv;c.append(`// ${s}`),c.append(l),c.append(`return ${l.returnExpression};`);let d=new Function("deps","ref","range","ctx",c.toString());function u(e){const t=oS[e.value.toUpperCase()],o=e.args,i=o.length;if(i<t.minArgRequired)throw new h(n("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",e.value.toUpperCase(),t.minArgRequired.toString(),i.toString()));if(i>t.maxArgPossible)throw new h(n("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",e.value.toUpperCase(),t.maxArgPossible.toString(),i.toString()));const s=t.nbrArgRepeating;if(s>1){const o=t.args.length-s;if((i-o)%s!=0)throw new h(n("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(),o.toString(),s.toString()))}let r=[];for(let s=0;s<i;s++){const i=t.getArgToFocus(s+1)-1;if(0<=i&&i<t.args.length){const a=o[s],l=t.args[i],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(n("Function %s expects the parameter %s to be reference to a cell or range, not a %s.",e.value.toUpperCase(),(s+1).toString(),a.type.toLowerCase()));const f=g(a,d,p,{functionName:e.value.toUpperCase(),paramIndex:s+1});r.push(u?f.wrapInClosure():f)}}return r}function g(e,t=!1,s=!1,r={}){const l=new fv(a);if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&t)throw new h(n("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[${i.numbers.indexOf(e.value)}] }`);case"STRING":return l.return(`{ value: this.constantValues.strings[${i.strings.indexOf(e.value)}] }`);case"REFERENCE":const n=o.indexOf(e.value);return s?l.return(`range(deps[${n}])`):l.return(`ref(deps[${n}], ${t?"true":"false"}, "${r.functionName||iS["="]}", ${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=sS[e.value],o=g(e.operand,!1,!1,{functionName:t}).assignResultToVariable();return l.append(o),l.append(`ctx.__lastFnCalled = '${t}';`),l.return(`ctx['${t}'](${o.returnExpression})`)}case"BIN_OPERATION":{const t=iS[e.value],o=g(e.left,!1,!1,{functionName:t}).assignResultToVariable(),i=g(e.right,!1,!1,{functionName:t}).assignResultToVariable();return l.append(o),l.append(i),l.append(`ctx.__lastFnCalled = '${t}';`),l.return(`ctx['${t}'](${o.returnExpression}, ${i.returnExpression})`)}case"EMPTY":return l.return("undefined")}}nS[s]={execute:d}}return{execute:nS[s].execute,dependencies:o,constantValues:i,tokens:t}}function aS(e){return function(e){let t=[],o="";return e.map(((e,i)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(o=""),e.type){case"FUNCTION":o=e.value;break;case"LEFT_PAREN":t.push({parent:o,argPosition:0}),o="";break;case"RIGHT_PAREN":t.pop();break;case"COMMA":t.length&&t[t.length-1].argPosition++}if(t.length){const o=t[t.length-1];o.parent&&(e.functionContext=Object.assign({},o))}return e}))}(function(e){let t=1;const o=[];return e.map((e=>("LEFT_PAREN"===e.type?(o.push(t),e.parenIndex=t,t++):"RIGHT_PAREN"===e.type&&(e.parenIndex=o.pop()),e)))}(function(e){let t=0;return e.map((e=>{const o=e.value.toString().length,i=Object.assign({},e,{start:t,end:t+o,length:o});return t=i.end,i}))}(tS(e))))}function lS(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function cS(e){return Math.round(Cb*e*100)/100}function hS(e){return Math.round(Eb*e*100)/100}function dS(e,t){let o={};e.style&&(o=t.styles[e.style]);const i=function(e,t){if(e.format)return t.formats[e.format];if(e.isFormula){const t=xv(e.content||""),o=Hg.content;if(!t.filter((e=>"FUNCTION"===e.type)).every((e=>o[e.value.toUpperCase()].isExported)))return e.computedFormat}return}(e,t),s={font:{size:o?.fontSize||Z,color:{rgb:o?.textColor?o.textColor:"000000"},family:2,name:"Arial"},fill:o?.fillColor?{fgColor:{rgb:o.fillColor}}:{reservedAttribute:"none"},numFmt:i?{format:i,id:0}:void 0,border:e.border||0,alignment:{horizontal:o.align,vertical:o.verticalAlign?Hb[o.verticalAlign]:void 0,wrapText:"wrap"===o.wrapping}};return s.font.strike=!!o?.strikethrough||void 0,s.font.underline=!!o?.underline||void 0,s.font.bold=!!o?.bold||void 0,s.font.italic=!!o?.italic||void 0,s}function uS(e,t){const o=function(e,t){if(!e)return 0;let o=Xb[e.format];o||(o=pS(e,t)+Rb);return o}(t.numFmt,e.numFmts),i={fontId:pS(t.font,e.fonts),fillId:pS(t.fill,e.fills),borderId:t.border,numFmtId:o,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal,wrapText:t.alignment.wrapText}};return pS(i,e.styles)}function gS(e,t,o){let i,s=e.find((e=>e.path===t));return s?(i=`rId${(s.rels.length+1).toString()}`,s.rels.push({...o,id:i})):(i="rId1",e.push({path:t,rels:[{...o,id:i}]})),i}function pS(e,t){let o=t.length;const i="object"==typeof e?vt:(e,t)=>e===t;for(let s=0;s<o;s++)if(i(e,t[s]))return s;return t[t.length]=e,t.length-1}const mS=[];function fS(e){const t=mS.findIndex((t=>t===e));return-1===t?(mS.push(e),mS.length):t+1}const bS=[];function vS(e){const t=bS.findIndex((t=>t===e));return-1===t?(bS.push(e),bS.length):t+1}function SS(e){return Math.round(914400*e/96)}function CS(e,t,o){let i,s,n=e;if(({xc:n,sheetName:i}=Yo(e)),i){const e=o.sheets.findIndex((e=>e.name===i));if(e<0)throw new Error("Unable to find a sheet with the name "+i);s=e}else s=Number(t);const r=oi(n);return void 0===r.right&&(r.right=o.sheets[s].colNumber),void 0===r.bottom&&(r.bottom=o.sheets[s].rowNumber),(r.right-r.left+1)*(r.bottom-r.top+1)}function ES(e){return Math.round(96*e/914400)}function wS(e,t){let o=0;for(let i=0;i<e;i++){const e=t.cols.find((e=>i>=e.min&&i<=e.max));e?.width?o+=e.width:t.sheetFormat?.defaultColWidth?o+=t.sheetFormat.defaultColWidth:o+=wb}return o/Eb}function xS(e,t){let o=0;for(let i=0;i<e;i++){const e=t.rows[i];e?.height?o+=e.height:t.sheetFormat?.defaultRowHeight?o+=t.sheetFormat.defaultRowHeight:o+=xb}return o/Cb}function yS(e){let t=1;return e.figures.map((o=>function(e,t,o){const i=wS(e.anchors[0].col,o)+ES(e.anchors[0].colOffset),s=wS(e.anchors[1].col,o)+ES(e.anchors[1].colOffset),n=xS(e.anchors[0].row,o)+ES(e.anchors[0].rowOffset),r=xS(e.anchors[1].row,o)+ES(e.anchors[1].rowOffset),a=s-i,l=r-n,c=IS(e.data);return c?{id:t,x:i,y:n,width:a,height:l,tag:"chart",data:IS(e.data)}:void 0}(o,(t++).toString(),e))).filter(dt)}function IS(e){const t=void 0!==e.dataSets[0].label,o=e.labelRange?RS(e.labelRange,t):void 0;let i=e.dataSets.map((e=>RS(e.range,t)));return"pie"===e.type&&i.reverse(),{dataSets:i,dataSetsHaveTitle:t,labelRange:o,title:e.title||"",type:e.type,background:Jb({rgb:e.backgroundColor})||"#FFFFFF",verticalAxisPosition:e.verticalAxisPosition,legendPosition:e.legendPosition,stacked:e.stacked||!1,aggregated:!1,cumulative:e.cumulative||!1,labelsAsText:!1}}function RS(e,t){let{sheetName:o,xc:i}=Yo(e);o=o?$e(o)+"!":"";let s=oi(i);if(t&&void 0!==s.bottom&&void 0!==s.right){const e=s.bottom-s.top+1,t=s.right-s.left+1;1===e?s={...s,left:s.left-1}:1===t&&(s={...s,top:s.top-1})}return o+ni(s)}const TS=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),AS=new RegExp(/SUBTOTAL\(([0-9]*),/g),OS=new RegExp(Po.source,"ig");function MS(e,t){const o=function(e){const t={};for(let o of e.rows)for(let e of o.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 i of e.rows.map((e=>e.cells)).flat())i?.formula&&(i.formula.content=void 0===i.formula.sharedIndex||i.formula.content?"="+i.formula.content:"="+_S(i.xc,o[i.formula.sharedIndex]),i.formula.content=NS(i.formula.content,t))}function NS(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(AS,((e,t)=>{const o=jb[t];return o?o+"(":e}))).replace(TS,((e,o,i,s)=>{o=Number(o)-1,s=s.replace(/\$/g,"");const n=t.externalBooks[o].sheetNames.findIndex((e=>e===i));if(-1===n)return e;const r=t.externalBooks[o].datasets.find((e=>e.sheetId===n))?.data;if(!r)return e;const a=r&&r[s];return(Number(a)?a:`"${a}"`)||e}))}function _S(e,t){const o=qt(t.refCellXc);let i,s=t.formula.slice();do{if(i=OS.exec(s),i){const t=qt(i[0].replace("$","")),n=qt(e),r={colFixed:i[0].startsWith("$"),rowFixed:i[0].includes("$",1)},a={col:n.col-o.col,row:n.row-o.row},l={col:r.colFixed?t.col:t.col+a.col,row:r.rowFixed?t.row:t.row+a.row};s=s.slice(0,i.index)+Zt(l.col,l.row,r)+s.slice(i.index+i[0].length)}}while(i);return s}function FS(e,t){return e.sheets.map((o=>{MS(o,e);const i=function(e){const t=[0,0];for(let o of e.rows)t[0]=Math.max(t[0],Rt(o.cells.map((e=>qt(e.xc).col)))),t[1]=Math.max(t[1],o.index);return t[0]=Math.max(t[0],yb),t[1]=Math.max(t[1],Ib),t}(o),s=o.sheetViews[0];return{id:o.sheetName,areGridLinesVisible:!s||s.showGridLines,name:o.sheetName,colNumber:i[0],rowNumber:i[1],cells:kS(o,e,i,t),merges:o.merges,cols:DS(o,i[0]),rows:LS(o,i[1]),conditionalFormats:dv(o.cfs,e.dxfs,t),figures:yS(o),isVisible:o.isVisible,panes:s?{xSplit:s.pane.xSplit,ySplit:s.pane.ySplit}:{xSplit:0,ySplit:0},filterTables:[]}}))}function DS(e,t){const o={};for(let s=1;s<t+1;s++){const t=e.cols.find((e=>e.min<=s&&s<=e.max));let n;n=t&&t.width?t.width:e.sheetFormat?.defaultColWidth?e.sheetFormat.defaultColWidth:wb,o[s-1]={size:(i=n,i?Math.round(i/Eb*100)/100:i),isHidden:t?.hidden}}var i;return o}function LS(e,t){const o={};for(let s=1;s<t+1;s++){const t=e.rows.find((e=>e.index===s));let n;n=t&&t.height?t.height:e.sheetFormat?.defaultRowHeight?e.sheetFormat.defaultRowHeight:xb,o[s-1]={size:(i=n,i?Math.round(i/Cb*100)/100:i),isHidden:t?.hidden}}var i;return o}function kS(e,t,o,i){const s={},n=t.sharedStrings.map((e=>e.replace(/\n/g,"")));const r=e.hyperlinks.reduce(((e,t)=>(e[t.xc]=t,e)),{});for(let o of e.rows)for(let e of o.cells)s[e.xc]={content:PS(e,r,n,i),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 i of e.rows.filter((e=>e.styleIndex)))for(let e=1;e<=o[0];e++){const o=Zt(e-1,i.index-1);let n=s[o];n||(n={},s[o]=n),n.style=n.style?n.style:i.styleIndex+1,n.border=n.border?n.border:t.styles[i.styleIndex].borderId+1,n.format=n.format?n.format:t.styles[i.styleIndex].numFmtId+1}for(let i of e.cols.filter((e=>e.styleIndex)))for(let e=i.min;e<=Math.min(i.max,o[0]);e++)for(let n=1;n<=o[1];n++){const o=Zt(e-1,n-1);let r=s[o];r||(r={},s[o]=r),r.style=r.style?r.style:i.styleIndex+1,r.border=r.border?r.border:t.styles[i.styleIndex].borderId+1,r.format=r.format?r.format:t.styles[i.styleIndex].numFmtId+1}return s}function PS(e,t,o,i){let s;switch(e.type){case"sharedString":s=o[parseInt(e.value,10)];break;case"boolean":s=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":s=e.value}return s&&t[e.xc]&&(s=function(e,t,o){const i=e.display||t;e.relTarget||e.location||o.generateNotSupportedWarning(Mb.BadlyFormattedHyperlink);const s=e.relTarget?e.relTarget:ct(Yo(e.location).sheetName);return nt(i,s)}(t[e.xc],s,i)),e.formula&&(s=e.formula.content),s}const US={fillColor:"#000000",textColor:"#ffffff",bold:!0},VS={bold:!0},zS={style:"thin",color:"#000000FF"};function BS(e,t){for(const o of t.sheets)for(const t of o.tables){const i=e.sheets.find((e=>e.name===o.sheetName));i&&t.autoFilter&&(i.filterTables||(i.filterTables=[]),i.filterTables.push({range:t.ref}))}!function(e,t){const o=ov(e.styles),i=ov(e.borders);for(let s of t.sheets)for(let t of s.tables){const n=e.sheets.find((e=>e.name===s.sheetName));if(!n)continue;const r=ii(t.ref);for(let e=0;e<t.headerRowCount;e++)HS(US,{...r,bottom:r.top+e},n.cells,o);for(let e=0;e<t.totalsRowCount;e++)HS(VS,{...r,top:r.bottom-e},n.cells,o);t.style?.showFirstColumn&&HS(VS,{...r,right:r.left},n.cells,o),t.style?.showLastColumn&&HS(VS,{...r,left:r.right},n.cells,o);for(let e=r.left;e<=r.right;e++)for(let o=r.top;o<=r.bottom;o++){const s=Zt(e,o),a=n.cells[s],l={left:e===r.left||t.style?.showColumnStripes?zS:void 0,right:e===r.right?zS:void 0,top:o===r.top||t.style?.showRowStripes||o>r.bottom-t.totalsRowCount?zS:void 0,bottom:o===r.bottom?zS:void 0},c=a?.border?{...i[a.border],...l}:l;let h=i.findIndex((e=>vt(e,c)));-1===h&&(h=i.length,i.push(c)),a?a.border=h:n.cells[s]={border:h}}}e.styles=tv(o),e.borders=tv(i)}(e,t),function(e,t){for(let o of e){const e=t.find((e=>e.sheetName===o.name)).tables;for(let t of e){const e=t.name+"[";for(let i of Ci(ii(t.ref))){const s=Zt(i.col,i.row),n=o.cells[s];if(n&&n.content&&n.content.startsWith("=")){let o;for(;-1!==(o=n.content.indexOf(e));){let i=n.content.slice(o+e.length),r=i.indexOf("]");i.startsWith("[")&&(r=i.indexOf("]",r+1),r=i.indexOf("]",r+1)),i=i.slice(0,r);const a=$S(i,t,s);n.content=n.content.slice(0,o)+a+n.content.slice(e.length+o+r+1)}}}}}}(e.sheets,t.sheets)}function HS(e,t,o,i){for(let s=t.left;s<=t.right;s++)for(let n=t.top;n<=t.bottom;n++){const t=Zt(s,n),r=o[t],a=r?.style?{...i[r.style],...e}:e;let l=i.findIndex((e=>vt(e,a)));-1===l&&(l=i.length,i.push(a)),r?r.style=l:o[t]={style:l}}}function $S(e,t,o){const i=e.split(","),s=ii(t.ref),n={...s};let r=!0;if(1===i.length){const e=t.cols.findIndex((e=>e.name===i[0]));n.left=n.right=e+s.left,t.headerRowCount&&(n.top+=t.headerRowCount),t.totalsRowCount&&(n.bottom-=1)}else{switch(i[0].slice(1,i[0].length-1)){case"#All":n.top=t.headerRowCount?s.top+t.headerRowCount:s.top,n.bottom=s.bottom;break;case"#Data":n.top=t.headerRowCount?s.top+t.headerRowCount:s.top,n.bottom=t.totalsRowCount?s.bottom+1:s.bottom;break;case"#This Row":n.top=n.bottom=qt(o).row;break;case"#Headers":n.top=n.bottom=s.top,t.headerRowCount||(r=!1);break;case"#Totals":n.top=n.bottom=s.bottom,t.totalsRowCount||(r=!1)}const e=i[1].slice(1,i[1].length-1),a=t.cols.findIndex((t=>t.name===e));n.left=n.right=a+s.left}return r?n.top!==n.bottom?ni(n):Zt(n.left,n.top):J}function WS(e,t,o){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:o}}function GS(e){return String(e).replace(/\&/g,"&").replace(/\</g,"<").replace(/\>/g,">").replace(/\"/g,""").replace(/\'/g,"'").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"")}function qS(e){return new hb(e.map((([e,t])=>`${e}="${GS(t)}"`)).join(" "))}function ZS(e,t="text/xml"){const o=(new DOMParser).parseFromString(e.toString(),t),i=o.querySelector("parsererror");if(i){const t=i.innerHTML,o=parseInt(t.split(":")[0],10),s=e.toString().trim().split("\n"),n=s.slice(Math.max(o-3,0),Math.min(o+2,s.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${n}`)}return o}function jS(e){if(e)return{style:e.style,color:{rgb:e.color}}}function YS(e,t){return KS`
|
|
1417
|
+
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetDOMScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){const{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{y:e}=this.env.model.getters.getMainViewportRect();return{top:`${this.props.topOffset+e}px`,right:"0px",width:"15px",bottom:"0px"}}onScroll(e){const{scrollX:t}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:t,offsetY:e})}}ab.props={topOffset:{type:Number,optional:!0}};const lb={ROW:Dm,COL:Nm,CELL:fp};class cb extends t.Component{static template="o-spreadsheet-Grid";static components={GridComposer:Nf,GridOverlay:Zf,GridPopover:jf,HeadersOverlay:Qf,Menu:wn,Autofill:vf,ClientTag:Cf,Highlight:ib,Popover:vn,VerticalScrollBar:ab,HorizontalScrollBar:rb,FilterIconsOverlay:Lf};HEADER_HEIGHT=F;HEADER_WIDTH=D;menuState;gridRef;onMouseWheel;canvasPosition;hoveredCell;setup(){this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.canvasPosition=pn(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.focusDefaultElement())),this.props.exposeFocus((()=>this.focusDefaultElement())),Jf("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),t.useEffect((()=>this.focusDefaultElement()),(()=>[this.env.model.getters.getActiveSheetId()])),this.onMouseWheel=eb(((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 Li({top:"26px",left:"48px",height:"calc(100% - 41px)",width:"calc(100% - 63px)"})}onClosePopover(){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.focusDefaultElement()}keyDownMapping={ENTER:()=>{this.env.model.getters.getActiveCell().type===ys.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===ys.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"),F4:()=>this.env.model.dispatch("REQUEST_REDO"),"CTRL+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"CTRL+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"CTRL+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"CTRL+O":()=>xa(this.env),"ALT+=":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:o}=this.env.model.getters.getSelection(),i=this.env.model.getters.getAutomaticSums(e,t,o.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&i.length<=1){const t=i[0]?.zone,o=t?this.env.model.getters.zoneToXC(e,i[0].zone):"",s=`=SUM(${o})`;this.props.onGridComposerCellFocused(s,{start:5,end:5+o.length})}else this.env.model.dispatch("SUM_SELECTION")},"ALT+ENTER":()=>{const e=this.env.model.getters.getActiveCell();e.link&&Zi(e.link,this.env)},"CTRL+HOME":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:o}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,o)},"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),o=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,o)},"SHIFT+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},o=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:o,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},o=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:o,zone:t})},"CTRL+SHIFT+E":()=>this.setHorizontalAlign("center"),"CTRL+SHIFT+L":()=>this.setHorizontalAlign("left"),"CTRL+SHIFT+R":()=>this.setHorizontalAlign("right"),"CTRL+SHIFT+V":()=>ba(this.env),"CTRL+SHIFT+<":()=>this.clearFormatting(),"CTRL+<":()=>this.clearFormatting(),"CTRL+SHIFT+ ":()=>{this.env.model.selection.selectAll()},"CTRL+ALT+=":()=>{const e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),o=1===this.env.model.getters.getSelectedZones().length,i=e.size>0&&o,s=t.size>0&&o;i&&!s?Ea(this.env):s&&!i&&Ca(this.env)},"CTRL+ALT+-":()=>{const e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&0===t.length?this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"COL",elements:e}):t.length>0&&0===e.length&&this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},"SHIFT+PAGEDOWN":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"SHIFT+PAGEUP":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PAGEDOWN:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PAGEUP:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"CTRL+K":()=>Ia(this.env)};focusDefaultElement(){this.env.model.getters.getSelectedFigureId()||"inactive"!==this.env.model.getters.getEditionMode()||this.env.focusableElement.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:D,gridOffsetY:F})}moveCanvas(e,t){const{scrollX:o,scrollY:i}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o+e,offsetY:i+t})}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,{addZone:o,expandZone:i}){o&&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"),i?this.env.model.selection.setAnchorCorner(e,t):o?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t);let s=e,n=t;bf(this.env,((e,t,o)=>{o.preventDefault(),(e!==s&&-1!=e||t!==n&&-1!=t)&&(s=-1===e?s:e,n=-1===t?n:t,this.env.model.selection.setAnchorCorner(s,n))}),(()=>{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 o=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:o,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t}).type===ys.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(),Um(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="";un(e)&&(t+="CTRL+"),e.altKey&&(t+="ALT+"),e.shiftKey&&(t+="SHIFT+"),t+=e.key.toUpperCase();let o=this.keyDownMapping[t];return o?(e.preventDefault(),e.stopPropagation(),void o()):void 0}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:o,top:i}=t;let s="CELL";this.env.model.dispatch("STOP_EDITION"),this.env.model.getters.getActiveCols().has(o)?s="COL":this.env.model.getters.getActiveRows().has(i)&&(s="ROW");const{x:n,y:r,width:a}=this.env.model.getters.getVisibleRect(t);this.toggleContextMenu(s,this.canvasPosition.x+n+a,this.canvasPosition.y+r)}onCellRightClicked(e,t,{x:o,y:i}){const s=this.env.model.getters.getSelectedZones();let n="CELL";pi(e,t,s[s.length-1])?this.env.model.getters.getActiveCols().has(e)?n="COL":this.env.model.getters.getActiveRows().has(t)&&(n="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(n,o,i)}toggleContextMenu(e,t,o){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:o},this.menuState.menuItems=lb[e].getMenuItems()}copy(e,t){if(!this.gridEl.contains(document.activeElement))return;const o=t.clipboardData;if(!o)return void this.displayWarningCopyPasteNotSupported();if("inactive"!==this.env.model.getters.getEditionMode())return;e?ra(this.env):this.env.model.dispatch("COPY");const i=this.env.model.getters.getClipboardContent();for(const e in i)o.setData(e,i[e]);t.preventDefault()}paste(e){if(!this.gridEl.contains(document.activeElement))return;const t=e.clipboardData;if(t){if(t.types.indexOf(Is.PlainText)>-1){const e=t.getData(Is.PlainText),o=this.env.model.getters.getSelectedZones();this.env.model.getters.getClipboardTextContent()===e?da(this.env,o):ua(this.env,o,e)}}else this.displayWarningCopyPasteNotSupported()}displayWarningCopyPasteNotSupported(){this.env.raiseError(n("Copy/Paste is not supported in this browser."))}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}}cb.props={sidePanelIsOpen:Boolean,exposeFocus:Function,focusComposer:String,onComposerContentFocused:Function,onGridComposerCellFocused:Function};class hb{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}}const db=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart"],ub="000000",gb={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},pb={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"},mb="http://schemas.openxmlformats.org/drawingml/2006/main",fb="http://schemas.openxmlformats.org/drawingml/2006/chart",bb={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"},vb={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"},Sb="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Cb=.75,Eb=.1317,wb=8.43,xb=12.75,yb=30,Ib=100,Rb=164,Tb={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}]},Ab=["ACOT","ACOTH","AGGREGATE","ARABIC","BASE","BETA.DIST","BETA.INV","BINOM.DIST","BINOM.DIST.RANGE","BINOM.INV","BITAND","BITLSHIFT","BITOR","BITRSHIFT","BITXOR","BYCOL","BYROW","CEILING.MATH","CEILING.PRECISE","CHISQ.DIST","CHISQ.DIST.RT","CHISQ.INV","CHISQ.INV.RT","CHISQ.TEST","CHOOSECOLS","CHOOSEROWS","COMBINA","CONCAT","CONFIDENCE.NORM","CONFIDENCE.T","COT","COTH","COVARIANCE.P","COVARIANCE.S","CSC","CSCH","DAYS","DECIMAL","DROP","ERF.PRECISE","ERFC.PRECISE","EXPAND","EXPON.DIST","F.DIST","F.DIST.RT","F.INV","F.INV.RT","F.TEST","FIELDVALUE","FILTERXML","FLOOR.MATH","FLOOR.PRECISE","FORECAST.ETS","FORECAST.ETS.CONFINT","FORECAST.ETS.SEASONALITY","FORECAST.ETS.STAT","FORECAST.LINEAR","FORMULATEXT","GAMMA","GAMMA.DIST","GAMMA.INV","GAMMALN.PRECISE","GAUSS","HSTACK","HYPGEOM.DIST","IFNA","IFS","IMCOSH","IMCOT","IMCSC","IMCSCH","IMSEC","IMSECH","IMSINH","IMTAN","ISFORMULA","ISOMITTED","ISOWEEKNUM","LAMBDA","LET","LOGNORM.DIST","LOGNORM.INV","MAKEARRAY","MAP","MAXIFS","MINIFS","MODE.MULT","MODE.SNGL","MUNIT","NEGBINOM.DIST","NORM.DIST","NORM.INV","NORM.S.DIST","NORM.S.INV","NUMBERVALUE","PDURATION","PERCENTILE.EXC","PERCENTILE.INC","PERCENTRANK.EXC","PERCENTRANK.INC","PERMUTATIONA","PHI","POISSON.DIST","PQSOURCE","PYTHON_STR","PYTHON_TYPE","PYTHON_TYPENAME","QUARTILE.EXC","QUARTILE.INC","QUERYSTRING","RANDARRAY","RANK.AVG","RANK.EQ","REDUCE","RRI","SCAN","SEC","SECH","SEQUENCE","SHEET","SHEETS","SKEW.P","SORTBY","STDEV.P","STDEV.S","SWITCH","T.DIST","T.DIST.2T","T.DIST.RT","T.INV","T.INV.2T","T.TEST","TAKE","TEXTAFTER","TEXTBEFORE","TEXTJOIN","TEXTSPLIT","TOCOL","TOROW","UNICHAR","UNICODE","UNIQUE","VAR.P","VAR.S","VSTACK","WEBSERVICE","WEIBULL.DIST","WRAPCOLS","WRAPROWS","XLOOKUP","XOR","Z.TEST"],Ob="[Content_Types].xml";var Mb;!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"}(Mb||(Mb={}));class Nb{_parsingWarnings=new Set;_conversionWarnings=new Set;addParsingWarning(e){this._parsingWarnings.add(e)}addConversionWarning(e){this._conversionWarnings.add(e)}get warnings(){return[...this._parsingWarnings,...this._conversionWarnings]}generateNotSupportedWarning(e,t,o){let i=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;o&&(i+=`Only ${o.join(", ")} are currently supported.`),this._conversionWarnings.has(i)||this._conversionWarnings.add(i)}}const _b=["thin"],Fb=["general","left","center","right"],Db=["top","center","bottom"],Lb=["Arial"],Pb=["solid"],kb=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWith","containsBlanks","notContainsBlanks"],Ub={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},Vb={dashDot:"thin",dashDotDot:"thin",dashed:"dashed",dotted:"dotted",double:"thin",hair:"thin",medium:"medium",mediumDashDot:"thin",mediumDashDotDot:"thin",mediumDashed:"thin",none:void 0,slantDashDot:"thin",thick:"thick",thin:"thin"},zb={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"},Bb={top:"top",center:"middle",bottom:"bottom",justify:"middle",distributed:"middle"},Hb={top:"top",middle:"center",bottom:"bottom"};const $b={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},Wb={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},Gb={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"},qb={b:"bottom",t:"top",l:"left",r:"right",tr:"right"},Zb={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},jb={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"},Yb={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},Xb={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},Kb={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"},Qb={"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 Jb(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=ub;else{if(!e.indexed)return;t=Kb[e.indexed]}var o;return t=6===(o=t).length?"#"+o+"FF":"#"+o.slice(2)+o.slice(0,2),e.tint&&(t=function(e,t){const o=Ut(e),i=zt(o);t<0&&(i.l=i.l*(1+t));t>0&&(i.l=i.l*(1-t)+(100-100*(1-t)));return kt(Vt(i))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function ev(e,t){const o=e.split("/"),i=t.split("/");let s="",n=0;for(let e=0;e<o.length-1;e++)o[e]===i[e]?n++:s+="../";return s+=i.slice(n).join("/"),s}function tv(e,t=0){const o={};for(let i=0;i<e.length;i++)e[i]&&(o[i+t]=e[i]);return o}function ov(e){const t=[];for(let o of Object.keys(e).map(Number))t[o]=e[o];return t}function iv(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,((e,t)=>String.fromCharCode(parseInt(t,16))))}const sv=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function nv(e,t,o){if(0===e)return;let i=Yb[e]||t.find((t=>t.id===e))?.format;if(i)try{let e=i.replace(/(.*?);.*/,"$1");e=e.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]"),e=e.replace(/\[\$\]/g,"");const t=e.match(/"/g)?.length||0;if(t/2+(e.match(/\[/g)?.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 sv.test(e)}(e)&&(e=function(e){return e=e.toLowerCase(),e=e.replace(/mmmmm/g,"mmm"),e=e.replace(/am\/pm|a\/m/g,"a"),e=e.replace(/hhhh/g,"hh"),e=e.replace(/\bh\b/g,"hh"),e}(e)),function(e){try{return bo(0,e),!0}catch(e){return!1}}(e))return e}catch(e){}o.generateNotSupportedWarning(Mb.NumFmtIdNotSupported,i||`nmFmtId ${e}`)}function rv(e,t){const o=e.borders.map((e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(Mb.DiagonalBorderNotSupported)}(e,t);const o={top:av(e.top,t),bottom:av(e.bottom,t),left:av(e.left,t),right:av(e.right,t)};return Object.keys(o).forEach((e=>void 0===o[e]&&delete o[e])),o}));return tv(o,1)}function av(e,t){if(!e)return;!function(e,t){_b.includes(e.style)||t.generateNotSupportedWarning(Mb.BorderStyleNotSupported,e.style,_b)}(e,t);const o=Vb[e.style];return o?{style:o,color:Jb(e.color)}:void 0}function lv(e,t){return tv(e.styles.map((o=>cv({fontStyle:e.fonts[o.fontId],fillStyle:e.fills[o.fillId],alignment:o.alignment},t))),1)}function cv(e,t){return function(e,t,o){e&&e.name&&!Lb.includes(e.name)&&o.generateNotSupportedWarning(Mb.FontNotSupported,e.name,Lb);t&&t.patternType&&!Pb.includes(t.patternType)&&o.generateNotSupportedWarning(Mb.FillStyleNotSupported,t.patternType,Pb)}(e?.fontStyle,e?.fillStyle,t),function(e,t){e&&!Fb.includes(e)&&t.generateNotSupportedWarning(Mb.HorizontalAlignmentNotSupported,e,Fb)}(e?.alignment?.horizontal,t),function(e,t){e&&!Db.includes(e)&&t.generateNotSupportedWarning(Mb.VerticalAlignmentNotSupported,e,Db)}(e?.alignment?.vertical,t),{bold:e.fontStyle?.bold,italic:e.fontStyle?.italic,strikethrough:e.fontStyle?.strike,underline:e.fontStyle?.underline,verticalAlign:e.alignment?.vertical?Bb[e.alignment.vertical]:void 0,align:e.alignment?.horizontal?zb[e.alignment.horizontal]:void 0,fillColor:"solid"===e.fillStyle?.patternType?Jb(e.fillStyle?.fgColor):Jb(e.fillStyle?.bgColor),textColor:Jb(e.fontStyle?.color),fontSize:e.fontStyle?.size,wrapping:e.alignment?.wrapText?"wrap":"overflow"}}function hv(e,t){const o=[];for(let i of e.styles){const s=nv(i.numFmtId,e.numFmts,t);s&&(o[i.numFmtId]=s)}return tv(o,1)}function dv(e,t,o){const i=[];let s=1;for(let r of e){if(0===r.cfRules.length)continue;mv(r,t,o);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=uv(s++,r);t&&i.push(t);continue;case"iconSet":const c=gv(s++,r,o);c&&i.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;a=$b[e.type],l.push(e.text);break;case"containsBlanks":case"notContainsBlanks":a=$b[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;a=(n=e.operator).slice(0,1).toUpperCase()+n.slice(1),l.push(e.formula[0]),2===e.formula.length&&l.push(e.formula[1])}a&&void 0!==e.dxfId&&i.push({id:(s++).toString(),ranges:r.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:a,values:l,style:cv({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},o)}})}}var n;return i}function uv(e,t){const o=t.cfRules[0].colorScale;if(!o||o.cfvos.length!==o.colors.length||o.cfvos.length<2||o.cfvos.length>3)return;const i=[];for(let e=0;e<o.cfvos.length;e++)i.push({color:(s=Jb(o.colors[e])||"#FFFFFF",9===s.length&&(s=s.slice(0,7)),parseInt(s.replace("#",""),16)),type:Wb[o.cfvos[e].type],value:o.cfvos[e].value});var s;const n=i[0],r=2===i.length?i[1]:i[2],a=3===i.length?i[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:n,midpoint:a,maximum:r}}}function gv(e,t,o){const i=t.cfRules[0].iconSet;if(!i)return;let s=i.cfvos,n=i.cfIcons;if(s.length<3||n&&n.length<3)return;s.length>3&&(s=[s[0],s[Math.floor(s.length/2)],s[s.length-1]]),n&&n.length>3&&(n=[n[0],n[Math.floor(n.length/2)],n[n.length-1]]);const r=[];for(let e=1;e<=2;e++){const t=Wb[s[e].type];if("value"===t)return;r.push({value:s[e].value||"",operator:s[e].gte?"ge":"gt",type:t})}let a={lower:n?pv(n[0].iconSet,n[0].iconId):pv(i.iconSet,0),middle:n?pv(n[1].iconSet,n[1].iconId):pv(i.iconSet,1),upper:n?pv(n[2].iconSet,n[2].iconId):pv(i.iconSet,2)};i.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(let e of Object.keys(a))if(!a[e])switch(o.generateNotSupportedWarning(Mb.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=nf.dots.good;break;case"middle":a[e]=nf.dots.neutral;break;case"lower":a[e]=nf.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 pv(e,t){const o=Gb[e];return o?0===t?nf[o].bad:1===t?nf[o].neutral:nf[o].good:""}function mv(e,t,o){if(e.cfRules.length>1&&o.generateNotSupportedWarning(Mb.MultipleRulesCfNotSupported),kb.includes(e.cfRules[0].type)||o.generateNotSupportedWarning(Mb.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const i=t[e.cfRules[0].dxfId];i.border&&o.generateNotSupportedWarning(Mb.CfFormatBorderNotSupported),i.alignment&&o.generateNotSupportedWarning(Mb.CfFormatAlignmentNotSupported),i.numFmt&&o.generateNotSupportedWarning(Mb.CfFormatNumFmtNotSupported)}}class fv{scope;code="";constructor(e=new vv){this.scope=e}append(...e){this.code+=e.map((e=>e.toString())).join("\n")+"\n"}return(e){return new bv(this.scope,this.code,e)}toString(){return Sv(this.code)}}class bv{scope;returnExpression;code;constructor(e,t,o){this.scope=e,this.returnExpression=o,this.code=Sv(t)}toString(){return this.code}wrapInClosure(){const e=this.scope.nextVariableName(),t=new fv(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 fv(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}}class vv{nextId=1;declaredVariables=new Set;nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function Sv(e){let t="",o=0;const i=e.split("\n").map((e=>e.trim())).filter((e=>""!==e));for(const e of i)e.startsWith("}")&&o--,t+="\t".repeat(o)+e+"\n",e.endsWith("{")&&o++;return t.trim()}const Cv=Hg.content,Ev=["%"],wv="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(Ev);function xv(e){e=It(e);const t=new Dv(e),o=[];for(;!t.isOver();){let e=_v(t)||Rv(t)||Tv(t)||Ov(t)||yv(t)||Fv(t)||Av(t)||Nv(t);e||(e={type:"UNKNOWN",value:t.shift()}),o.push(e)}return o}function yv(e){return"?"===e.current()?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const Iv={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function Rv(e){if(e.current()in Iv){const t=e.shift();return{type:Iv[t],value:t}}return null}function Tv(e){for(let t of wv)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:"OPERATOR",value:t};return null}function Av(e){const t=e.remaining().match(Qt);return t?(e.advanceBy(t[0].length),{type:"NUMBER",value:t[0]}):null}function Ov(e){if('"'===e.current()){const t=e.shift();let o=t;for(;e.current()&&(e.current()!==t||"\\"===o[o.length-1]);)o+=e.shift();return'"'===e.current()&&(o+=e.shift()),{type:"STRING",value:o}}return null}const Mv=/\w|\.|!|\$/;function Nv(e){let t="";if("'"===e.current()){let o=e.shift();for(t+=o;e.current();)if(o=e.shift(),t+=o,"'"===o){if(!e.current()||"'"!==e.current())break;o=e.shift(),t+=o}if("'"!==o)return{type:"UNKNOWN",value:t}}for(;e.current()&&Mv.test(e.current());)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in Cv)return{type:"FUNCTION",value:e};return $o.test(e)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function _v(e){let t=0;for(;e.current()===me;)t++,e.shift();if(t)return{type:"SPACE",value:me.repeat(t)};for(;" "===e.current();)t++,e.shift();return t?{type:"SPACE",value:" ".repeat(t)}:null}function Fv(e){return e.currentStartsWith(J)?(e.advanceBy(J.length),{type:"INVALID_REFERENCE",value:J}):null}class Dv{text;currentIndex=0;constructor(e){this.text=e}current(){return this.text[this.currentIndex]}shift(){return this.text[this.currentIndex++]}advanceBy(e){this.currentIndex+=e}isOver(){return this.currentIndex>=this.text.length}remaining(){return this.text.substring(this.currentIndex)}currentStartsWith(e){for(let t=0;t<e.length;t++)if(this.text[this.currentIndex+t]!==e[t])return!1;return!0}}const Lv=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,Pv=["-","+"],kv=["%"],Uv=["*","+","&"],Vv={"^":30,"%":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function zv(e){const t=e.shift();if(!t)throw new h(de);switch(t.type){case"DEBUGGER":const o=$v(e,1e3);return o.debug=!0,o;case"NUMBER":return{type:"NUMBER",value:ro(t.value)};case"STRING":return{type:"STRING",value:Ve(t.value)};case"FUNCTION":const i=function(e){Hv(e,"LEFT_PAREN",n("Missing opening parenthesis"));const t=e[0];if("RIGHT_PAREN"===t?.type)return Hv(e,"RIGHT_PAREN"),[];const o=[];o.push(Bv(e));for(;"RIGHT_PAREN"!==e[0]?.type;)Hv(e,"COMMA",n("Wrong function call")),o.push(Bv(e));return Hv(e,"RIGHT_PAREN"),o}(e);return{type:"FUNCALL",value:t.value,args:i};case"INVALID_REFERENCE":throw new u;case"REFERENCE":if(":"===e[0]?.value&&"REFERENCE"===e[1]?.type){e.shift();const o=e.shift();return{type:"REFERENCE",value:`${t.value}:${o?.value}`}}return{type:"REFERENCE",value:t.value};case"SYMBOL":if(["TRUE","FALSE"].includes(t.value.toUpperCase()))return{type:"BOOLEAN",value:"TRUE"===t.value.toUpperCase()};if(t.value&&Lv.test(t.value)&&"LEFT_PAREN"===e[0]?.type)throw new p(t.value);throw new h(n("Invalid formula"));case"LEFT_PAREN":const s=$v(e);return Hv(e,"RIGHT_PAREN",n("Missing closing parenthesis")),s;case"OPERATOR":const r=t.value;if(Pv.includes(r))return{type:"UNARY_OPERATION",value:r,operand:$v(e,Vv[r])};throw new h(n("Unexpected token: %s",t.value));default:throw new h(n("Unexpected token: %s",t.value))}}function Bv(e){const t=e[0];return"COMMA"===t?.type||"RIGHT_PAREN"===t?.type?{type:"EMPTY",value:""}:$v(e)}function Hv(e,t,o=de){const i=e.shift();if(!i||i.type!==t)throw new h(o)}function $v(e,t=0){if(0===e.length)throw new h(de);let o=zv(e);for(;"OPERATOR"===e[0]?.type&&Vv[e[0].value]>t;){const t=e.shift().value;if(kv.includes(t))o={type:"UNARY_OPERATION",value:t,operand:o,postfix:!0};else{o={type:"BIN_OPERATION",value:t,left:o,right:$v(e,Vv[t])}}}return o}function Wv(e){return Gv(xv(e))}function Gv(e){"="===(e=e.filter((e=>"SPACE"!==e.type)))[0].value&&e.splice(0,1);const t=$v(e);if(e.length)throw new h(de);return t}function qv(e,t,o){switch(t===e.type&&(e=o(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>qv(e,t,o)))};case"UNARY_OPERATION":return{...e,operand:qv(e.operand,t,o)};case"BIN_OPERATION":return{...e,right:qv(e.right,t,o),left:qv(e.left,t,o)};default:return e}}function Zv(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>Zv(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?jv(e)+e.value:e.value+Yv(e);case"BIN_OPERATION":return jv(e)+e.value+Yv(e)}}function jv(e){const t=e.value,o="left"in e?e.left:e.operand,i=o.value;return"BIN_OPERATION"===o.type&&Vv[i]<Vv[t]?`(${Zv(o)})`:Zv(o)}function Yv(e){const t=e.value,o="right"in e?e.right:e.operand,i=Vv[o.value],s=Vv[t];let n=!1;return"BIN_OPERATION"!==o.type?n=!1:i<s?n=!0:i!==s||Uv.includes(t)||(n=!0),n?`(${Zv(o)})`:Zv(o)}var Xv;!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"}(Xv||(Xv={}));const Kv=(e,t=(()=>!0))=>[{goTo:e,guard:t}],Qv=(e,t=(()=>!0))=>({goTo:e,guard:t}),Jv={[Xv.LeftRef]:{REFERENCE:Kv(Xv.Separator),NUMBER:Kv(Xv.FullRowSeparator),SYMBOL:[Qv(Xv.FullColumnSeparator,(e=>Wo(e.value))),Qv(Xv.FullRowSeparator,(e=>Go(e.value)))]},[Xv.FullColumnSeparator]:{SPACE:Kv(Xv.FullColumnSeparator),OPERATOR:Kv(Xv.RightColumnRef,(e=>":"===e.value))},[Xv.FullRowSeparator]:{SPACE:Kv(Xv.FullRowSeparator),OPERATOR:Kv(Xv.RightRowRef,(e=>":"===e.value))},[Xv.Separator]:{SPACE:Kv(Xv.Separator),OPERATOR:Kv(Xv.RightRef,(e=>":"===e.value))},[Xv.RightRef]:{SPACE:Kv(Xv.RightRef),NUMBER:Kv(Xv.Found),REFERENCE:Kv(Xv.Found,(e=>jo(e.value))),SYMBOL:Kv(Xv.Found,(e=>qo(e.value)||Zo(e.value)))},[Xv.RightColumnRef]:{SPACE:Kv(Xv.RightColumnRef),SYMBOL:Kv(Xv.Found,(e=>qo(e.value))),REFERENCE:Kv(Xv.Found,(e=>jo(e.value)))},[Xv.RightRowRef]:{SPACE:Kv(Xv.RightRowRef),NUMBER:Kv(Xv.Found),REFERENCE:Kv(Xv.Found,(e=>jo(e.value))),SYMBOL:Kv(Xv.Found,(e=>Zo(e.value)))},[Xv.Found]:{}};function eS(e){let t=0,o=Jv[Xv.LeftRef],i="";for(;void 0!==o;){const s=e[t++];if(!s)return null;const n=o[s.type]?.find((e=>e.guard(s))),r=n?n.goTo:void 0;switch(r){case void 0:return null;case Xv.Found:return i+=s.value,e.splice(0,t),{type:"REFERENCE",value:i};default:o=Jv[r],i+=s.value}}return null}function tS(e){const t=xv(e),o=[];for(;t.length;)o.push(eS(t)||t.shift());return o}const oS=Hg.content,iS={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},sS={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"},nS={};function rS(e){const t=tS(e),{dependencies:o,constantValues:i}=function(e){const t={numbers:[],strings:[]},o=[];for(const i of e)switch(i.type){case"INVALID_REFERENCE":case"REFERENCE":o.push(i.value);break;case"STRING":const e=Ve(i.value);t.strings.includes(e)||t.strings.push(e);break;case"NUMBER":{const e=ro(i.value);t.numbers.includes(e)||t.numbers.push(e);break}}return{dependencies:o,constantValues:t}}(t),s=function(e,t,o){return pt(e.map((e=>{switch(e.type){case"STRING":const i=Ve(e.value);return`|S${o.strings.indexOf(i)}|`;case"NUMBER":return`|N${o.numbers.indexOf(ro(e.value))}|`;case"REFERENCE":case"INVALID_REFERENCE":return`|${t.indexOf(e.value)}|`;case"SPACE":return"";default:return e.value}})))}(t,o,i);if(!nS[s]){const r=Gv([...t]),a=new vv;if("BIN_OPERATION"===r.type&&":"===r.value)throw new h(n("Invalid formula"));if("EMPTY"===r.type)throw new h(n("Invalid formula"));const l=g(r),c=new fv;c.append(`// ${s}`),c.append(l),c.append(`return ${l.returnExpression};`);let d=new Function("deps","ref","range","ctx",c.toString());function u(e){const t=oS[e.value.toUpperCase()],o=e.args,i=o.length;if(i<t.minArgRequired)throw new h(n("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",e.value.toUpperCase(),t.minArgRequired.toString(),i.toString()));if(i>t.maxArgPossible)throw new h(n("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",e.value.toUpperCase(),t.maxArgPossible.toString(),i.toString()));const s=t.nbrArgRepeating;if(s>1){const o=t.args.length-s;if((i-o)%s!=0)throw new h(n("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(),o.toString(),s.toString()))}let r=[];for(let s=0;s<i;s++){const i=t.getArgToFocus(s+1)-1;if(0<=i&&i<t.args.length){const a=o[s],l=t.args[i],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(n("Function %s expects the parameter %s to be reference to a cell or range, not a %s.",e.value.toUpperCase(),(s+1).toString(),a.type.toLowerCase()));const f=g(a,d,p,{functionName:e.value.toUpperCase(),paramIndex:s+1});r.push(u?f.wrapInClosure():f)}}return r}function g(e,t=!1,s=!1,r={}){const l=new fv(a);if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&t)throw new h(n("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[${i.numbers.indexOf(e.value)}] }`);case"STRING":return l.return(`{ value: this.constantValues.strings[${i.strings.indexOf(e.value)}] }`);case"REFERENCE":const n=o.indexOf(e.value);return s?l.return(`range(deps[${n}])`):l.return(`ref(deps[${n}], ${t?"true":"false"}, "${r.functionName||iS["="]}", ${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=sS[e.value],o=g(e.operand,!1,!1,{functionName:t}).assignResultToVariable();return l.append(o),l.append(`ctx.__lastFnCalled = '${t}';`),l.return(`ctx['${t}'](${o.returnExpression})`)}case"BIN_OPERATION":{const t=iS[e.value],o=g(e.left,!1,!1,{functionName:t}).assignResultToVariable(),i=g(e.right,!1,!1,{functionName:t}).assignResultToVariable();return l.append(o),l.append(i),l.append(`ctx.__lastFnCalled = '${t}';`),l.return(`ctx['${t}'](${o.returnExpression}, ${i.returnExpression})`)}case"EMPTY":return l.return("undefined")}}nS[s]={execute:d}}return{execute:nS[s].execute,dependencies:o,constantValues:i,tokens:t}}function aS(e){return function(e){let t=[],o="";return e.map(((e,i)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(o=""),e.type){case"FUNCTION":o=e.value;break;case"LEFT_PAREN":t.push({parent:o,argPosition:0}),o="";break;case"RIGHT_PAREN":t.pop();break;case"COMMA":t.length&&t[t.length-1].argPosition++}if(t.length){const o=t[t.length-1];o.parent&&(e.functionContext=Object.assign({},o))}return e}))}(function(e){let t=1;const o=[];return e.map((e=>("LEFT_PAREN"===e.type?(o.push(t),e.parenIndex=t,t++):"RIGHT_PAREN"===e.type&&(e.parenIndex=o.pop()),e)))}(function(e){let t=0;return e.map((e=>{const o=e.value.toString().length,i=Object.assign({},e,{start:t,end:t+o,length:o});return t=i.end,i}))}(tS(e))))}function lS(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function cS(e){return Math.round(Cb*e*100)/100}function hS(e){return Math.round(Eb*e*100)/100}function dS(e,t){let o={};e.style&&(o=t.styles[e.style]);const i=function(e,t){if(e.format)return t.formats[e.format];if(e.isFormula){const t=xv(e.content||""),o=Hg.content;if(!t.filter((e=>"FUNCTION"===e.type)).every((e=>o[e.value.toUpperCase()].isExported)))return e.computedFormat}return}(e,t),s={font:{size:o?.fontSize||Z,color:{rgb:o?.textColor?o.textColor:"000000"},family:2,name:"Arial"},fill:o?.fillColor?{fgColor:{rgb:o.fillColor}}:{reservedAttribute:"none"},numFmt:i?{format:i,id:0}:void 0,border:e.border||0,alignment:{horizontal:o.align,vertical:o.verticalAlign?Hb[o.verticalAlign]:void 0,wrapText:"wrap"===o.wrapping}};return s.font.strike=!!o?.strikethrough||void 0,s.font.underline=!!o?.underline||void 0,s.font.bold=!!o?.bold||void 0,s.font.italic=!!o?.italic||void 0,s}function uS(e,t){const o=function(e,t){if(!e)return 0;let o=Xb[e.format];o||(o=pS(e,t)+Rb);return o}(t.numFmt,e.numFmts),i={fontId:pS(t.font,e.fonts),fillId:pS(t.fill,e.fills),borderId:t.border,numFmtId:o,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal,wrapText:t.alignment.wrapText}};return pS(i,e.styles)}function gS(e,t,o){let i,s=e.find((e=>e.path===t));return s?(i=`rId${(s.rels.length+1).toString()}`,s.rels.push({...o,id:i})):(i="rId1",e.push({path:t,rels:[{...o,id:i}]})),i}function pS(e,t){let o=t.length;const i="object"==typeof e?vt:(e,t)=>e===t;for(let s=0;s<o;s++)if(i(e,t[s]))return s;return t[t.length]=e,t.length-1}const mS=[];function fS(e){const t=mS.findIndex((t=>t===e));return-1===t?(mS.push(e),mS.length):t+1}const bS=[];function vS(e){const t=bS.findIndex((t=>t===e));return-1===t?(bS.push(e),bS.length):t+1}function SS(e){return Math.round(914400*e/96)}function CS(e,t,o){let i,s,n=e;if(({xc:n,sheetName:i}=Yo(e)),i){const e=o.sheets.findIndex((e=>e.name===i));if(e<0)throw new Error("Unable to find a sheet with the name "+i);s=e}else s=Number(t);const r=oi(n);return void 0===r.right&&(r.right=o.sheets[s].colNumber),void 0===r.bottom&&(r.bottom=o.sheets[s].rowNumber),(r.right-r.left+1)*(r.bottom-r.top+1)}function ES(e){return Math.round(96*e/914400)}function wS(e,t){let o=0;for(let i=0;i<e;i++){const e=t.cols.find((e=>i>=e.min&&i<=e.max));e?.width?o+=e.width:t.sheetFormat?.defaultColWidth?o+=t.sheetFormat.defaultColWidth:o+=wb}return o/Eb}function xS(e,t){let o=0;for(let i=0;i<e;i++){const e=t.rows[i];e?.height?o+=e.height:t.sheetFormat?.defaultRowHeight?o+=t.sheetFormat.defaultRowHeight:o+=xb}return o/Cb}function yS(e){let t=1;return e.figures.map((o=>function(e,t,o){const i=wS(e.anchors[0].col,o)+ES(e.anchors[0].colOffset),s=wS(e.anchors[1].col,o)+ES(e.anchors[1].colOffset),n=xS(e.anchors[0].row,o)+ES(e.anchors[0].rowOffset),r=xS(e.anchors[1].row,o)+ES(e.anchors[1].rowOffset),a=s-i,l=r-n,c=IS(e.data);return c?{id:t,x:i,y:n,width:a,height:l,tag:"chart",data:IS(e.data)}:void 0}(o,(t++).toString(),e))).filter(dt)}function IS(e){const t=void 0!==e.dataSets[0].label,o=e.labelRange?RS(e.labelRange,t):void 0;let i=e.dataSets.map((e=>RS(e.range,t)));return"pie"===e.type&&i.reverse(),{dataSets:i,dataSetsHaveTitle:t,labelRange:o,title:e.title||"",type:e.type,background:Jb({rgb:e.backgroundColor})||"#FFFFFF",verticalAxisPosition:e.verticalAxisPosition,legendPosition:e.legendPosition,stacked:e.stacked||!1,aggregated:!1,cumulative:e.cumulative||!1,labelsAsText:!1}}function RS(e,t){let{sheetName:o,xc:i}=Yo(e);o=o?$e(o)+"!":"";let s=oi(i);if(t&&void 0!==s.bottom&&void 0!==s.right){const e=s.bottom-s.top+1,t=s.right-s.left+1;1===e?s={...s,left:s.left-1}:1===t&&(s={...s,top:s.top-1})}return o+ni(s)}const TS=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),AS=new RegExp(/SUBTOTAL\(([0-9]*),/g),OS=new RegExp(ko.source,"ig");function MS(e,t){const o=function(e){const t={};for(let o of e.rows)for(let e of o.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 i of e.rows.map((e=>e.cells)).flat())i?.formula&&(i.formula.content=void 0===i.formula.sharedIndex||i.formula.content?"="+i.formula.content:"="+_S(i.xc,o[i.formula.sharedIndex]),i.formula.content=NS(i.formula.content,t))}function NS(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(AS,((e,t)=>{const o=jb[t];return o?o+"(":e}))).replace(TS,((e,o,i,s)=>{o=Number(o)-1,s=s.replace(/\$/g,"");const n=t.externalBooks[o].sheetNames.findIndex((e=>e===i));if(-1===n)return e;const r=t.externalBooks[o].datasets.find((e=>e.sheetId===n))?.data;if(!r)return e;const a=r&&r[s];return(Number(a)?a:`"${a}"`)||e}))}function _S(e,t){const o=qt(t.refCellXc);let i,s=t.formula.slice();do{if(i=OS.exec(s),i){const t=qt(i[0].replace("$","")),n=qt(e),r={colFixed:i[0].startsWith("$"),rowFixed:i[0].includes("$",1)},a={col:n.col-o.col,row:n.row-o.row},l={col:r.colFixed?t.col:t.col+a.col,row:r.rowFixed?t.row:t.row+a.row};s=s.slice(0,i.index)+Zt(l.col,l.row,r)+s.slice(i.index+i[0].length)}}while(i);return s}function FS(e,t){return e.sheets.map((o=>{MS(o,e);const i=function(e){const t=[0,0];for(let o of e.rows)t[0]=Math.max(t[0],Rt(o.cells.map((e=>qt(e.xc).col)))),t[1]=Math.max(t[1],o.index);return t[0]=Math.max(t[0],yb),t[1]=Math.max(t[1],Ib),t}(o),s=o.sheetViews[0];return{id:o.sheetName,areGridLinesVisible:!s||s.showGridLines,name:o.sheetName,colNumber:i[0],rowNumber:i[1],cells:PS(o,e,i,t),merges:o.merges,cols:DS(o,i[0]),rows:LS(o,i[1]),conditionalFormats:dv(o.cfs,e.dxfs,t),figures:yS(o),isVisible:o.isVisible,panes:s?{xSplit:s.pane.xSplit,ySplit:s.pane.ySplit}:{xSplit:0,ySplit:0},filterTables:[]}}))}function DS(e,t){const o={};for(let s=1;s<t+1;s++){const t=e.cols.find((e=>e.min<=s&&s<=e.max));let n;n=t&&t.width?t.width:e.sheetFormat?.defaultColWidth?e.sheetFormat.defaultColWidth:wb,o[s-1]={size:(i=n,i?Math.round(i/Eb*100)/100:i),isHidden:t?.hidden}}var i;return o}function LS(e,t){const o={};for(let s=1;s<t+1;s++){const t=e.rows.find((e=>e.index===s));let n;n=t&&t.height?t.height:e.sheetFormat?.defaultRowHeight?e.sheetFormat.defaultRowHeight:xb,o[s-1]={size:(i=n,i?Math.round(i/Cb*100)/100:i),isHidden:t?.hidden}}var i;return o}function PS(e,t,o,i){const s={},n=t.sharedStrings.map((e=>e.replace(/\n/g,"")));const r=e.hyperlinks.reduce(((e,t)=>(e[t.xc]=t,e)),{});for(let o of e.rows)for(let e of o.cells)s[e.xc]={content:kS(e,r,n,i),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 i of e.rows.filter((e=>e.styleIndex)))for(let e=1;e<=o[0];e++){const o=Zt(e-1,i.index-1);let n=s[o];n||(n={},s[o]=n),n.style=n.style?n.style:i.styleIndex+1,n.border=n.border?n.border:t.styles[i.styleIndex].borderId+1,n.format=n.format?n.format:t.styles[i.styleIndex].numFmtId+1}for(let i of e.cols.filter((e=>e.styleIndex)))for(let e=i.min;e<=Math.min(i.max,o[0]);e++)for(let n=1;n<=o[1];n++){const o=Zt(e-1,n-1);let r=s[o];r||(r={},s[o]=r),r.style=r.style?r.style:i.styleIndex+1,r.border=r.border?r.border:t.styles[i.styleIndex].borderId+1,r.format=r.format?r.format:t.styles[i.styleIndex].numFmtId+1}return s}function kS(e,t,o,i){let s;switch(e.type){case"sharedString":s=o[parseInt(e.value,10)];break;case"boolean":s=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":s=e.value}return s&&t[e.xc]&&(s=function(e,t,o){const i=e.display||t;e.relTarget||e.location||o.generateNotSupportedWarning(Mb.BadlyFormattedHyperlink);const s=e.relTarget?e.relTarget:ct(Yo(e.location).sheetName);return nt(i,s)}(t[e.xc],s,i)),e.formula&&(s=e.formula.content),s}const US={fillColor:"#000000",textColor:"#ffffff",bold:!0},VS={bold:!0},zS={style:"thin",color:"#000000FF"};function BS(e,t){for(const o of t.sheets)for(const t of o.tables){const i=e.sheets.find((e=>e.name===o.sheetName));i&&t.autoFilter&&(i.filterTables||(i.filterTables=[]),i.filterTables.push({range:t.ref}))}!function(e,t){const o=ov(e.styles),i=ov(e.borders);for(let s of t.sheets)for(let t of s.tables){const n=e.sheets.find((e=>e.name===s.sheetName));if(!n)continue;const r=ii(t.ref);for(let e=0;e<t.headerRowCount;e++)HS(US,{...r,bottom:r.top+e},n.cells,o);for(let e=0;e<t.totalsRowCount;e++)HS(VS,{...r,top:r.bottom-e},n.cells,o);t.style?.showFirstColumn&&HS(VS,{...r,right:r.left},n.cells,o),t.style?.showLastColumn&&HS(VS,{...r,left:r.right},n.cells,o);for(let e=r.left;e<=r.right;e++)for(let o=r.top;o<=r.bottom;o++){const s=Zt(e,o),a=n.cells[s],l={left:e===r.left||t.style?.showColumnStripes?zS:void 0,right:e===r.right?zS:void 0,top:o===r.top||t.style?.showRowStripes||o>r.bottom-t.totalsRowCount?zS:void 0,bottom:o===r.bottom?zS:void 0},c=a?.border?{...i[a.border],...l}:l;let h=i.findIndex((e=>vt(e,c)));-1===h&&(h=i.length,i.push(c)),a?a.border=h:n.cells[s]={border:h}}}e.styles=tv(o),e.borders=tv(i)}(e,t),function(e,t){for(let o of e){const e=t.find((e=>e.sheetName===o.name)).tables;for(let t of e){const e=t.name+"[";for(let i of Ci(ii(t.ref))){const s=Zt(i.col,i.row),n=o.cells[s];if(n&&n.content&&n.content.startsWith("=")){let o;for(;-1!==(o=n.content.indexOf(e));){let i=n.content.slice(o+e.length),r=i.indexOf("]");i.startsWith("[")&&(r=i.indexOf("]",r+1),r=i.indexOf("]",r+1)),i=i.slice(0,r);const a=$S(i,t,s);n.content=n.content.slice(0,o)+a+n.content.slice(e.length+o+r+1)}}}}}}(e.sheets,t.sheets)}function HS(e,t,o,i){for(let s=t.left;s<=t.right;s++)for(let n=t.top;n<=t.bottom;n++){const t=Zt(s,n),r=o[t],a=r?.style?{...i[r.style],...e}:e;let l=i.findIndex((e=>vt(e,a)));-1===l&&(l=i.length,i.push(a)),r?r.style=l:o[t]={style:l}}}function $S(e,t,o){const i=e.split(","),s=ii(t.ref),n={...s};let r=!0;if(1===i.length){const e=t.cols.findIndex((e=>e.name===i[0]));n.left=n.right=e+s.left,t.headerRowCount&&(n.top+=t.headerRowCount),t.totalsRowCount&&(n.bottom-=1)}else{switch(i[0].slice(1,i[0].length-1)){case"#All":n.top=t.headerRowCount?s.top+t.headerRowCount:s.top,n.bottom=s.bottom;break;case"#Data":n.top=t.headerRowCount?s.top+t.headerRowCount:s.top,n.bottom=t.totalsRowCount?s.bottom+1:s.bottom;break;case"#This Row":n.top=n.bottom=qt(o).row;break;case"#Headers":n.top=n.bottom=s.top,t.headerRowCount||(r=!1);break;case"#Totals":n.top=n.bottom=s.bottom,t.totalsRowCount||(r=!1)}const e=i[1].slice(1,i[1].length-1),a=t.cols.findIndex((t=>t.name===e));n.left=n.right=a+s.left}return r?n.top!==n.bottom?ni(n):Zt(n.left,n.top):J}function WS(e,t,o){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:o}}function GS(e){return String(e).replace(/\&/g,"&").replace(/\</g,"<").replace(/\>/g,">").replace(/\"/g,""").replace(/\'/g,"'").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"")}function qS(e){return new hb(e.map((([e,t])=>`${e}="${GS(t)}"`)).join(" "))}function ZS(e,t="text/xml"){const o=(new DOMParser).parseFromString(e.toString(),t),i=o.querySelector("parsererror");if(i){const t=i.innerHTML,o=parseInt(t.split(":")[0],10),s=e.toString().trim().split("\n"),n=s.slice(Math.max(o-3,0),Math.min(o+2,s.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${n}`)}return o}function jS(e){if(e)return{style:e.style,color:{rgb:e.color}}}function YS(e,t){return KS`
|
|
1418
1418
|
<Override ContentType="${t}" PartName="${e}" />
|
|
1419
|
-
`}function XS(e){return new hb(e.join("\n"))}function KS(e,...t){let o=[e[0]];for(let i=0;i<t.length;i++){const s=t[i]instanceof hb?t[i]:GS(t[i]);o.push(s+e[i+1])}return new hb(pt(o))}function QS(e){return e.replace(/[a-z0-9]+:(?=[a-z0-9]+)/gi,"")}function JS(e){return e.replace(/([a-z0-9]+):(?=[a-z0-9]+)/gi,"$1\\:")}class eC{value;constructor(e){this.value=e}asString(){return iv(String(this.value))}asBool(){return"true"===this.value||"false"!==this.value&&Boolean(Number(this.value))}asNum(){return Number(this.value)}}class tC{rootFile;xlsxFileStructure;warningManager;relationships;currentFile=void 0;areNamespaceIgnored;constructor(e,t,o){this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=o,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(dt)}mapOnElements(e,t){const o=[],i=this.currentFile;let s;if(e.children){const t=this.querySelector(e.parent,e.query)?.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=i,o}catchErrorOnElement(e,t){const o=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([o,e.message].join("\n"))}extractAttr(e,t,o){const i=e.attributes[t];i||this.handleMissingValue(e,`attribute "${t}"`,o);const s=i?.value?i.value:o?.default;return void 0===s?void 0:new eC(s)}extractTextContent(e,t){if(void 0!==t?.default&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const o="preserve"===e?.attributes["xml:space"]?.value;let i=e?.textContent;return e&&null!==i||this.handleMissingValue(e,"text content",t),i&&(i=o?i:i.trim()),i?iv(i):t?.default}extractChildAttr(e,t,o,i){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}>`,i);const n=s?this.extractAttr(s,o,i)?.asString():i?.default;return void 0!==n?new eC(n):void 0}extractChildTextContent(e,t,o){if(void 0!==o?.default&&"string"!=typeof o.default)throw new Error("extractTextContent default value should be a string");let i=this.querySelector(e,t);return i||this.handleMissingValue(e,`child <${t}>`,o),i?this.extractTextContent(i,o):o?.default}handleMissingValue(e,t,o){if(o?.required){if(!o?.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 ${o.default}`)}}extractColor(e,t,o){if(!e)return o?{rgb:o}:void 0;const i=this.extractAttr(e,"theme")?.asString();let s;if(void 0!==i){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");s=this.getThemeColor(i,t.clrScheme)}else s=this.extractAttr(e,"rgb")?.asString();return{rgb:s,auto:this.extractAttr(e,"auto")?.asBool(),indexed:this.extractAttr(e,"indexed")?.asNum(),tint:this.extractAttr(e,"tint")?.asNum()}}getTargetXmlFile(e){if(!e)throw new Error("Undefined target file");let t=e.target;t=t.replace("../",""),t=t.replace("./","");const o=this.getListOfFiles().find((e=>e.file.fileName.endsWith(t)));if(!o||!o.file)throw new Error("Cannot find target file");return o}querySelector(e,t){return t=this.areNamespaceIgnored?QS(t):JS(t),e.querySelector(t)}querySelectorAll(e,t){return t=this.areNamespaceIgnored?QS(t):JS(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 oC extends tC{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:ub}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:ub}).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 iC extends tC{theme;constructor(e,t,o,i){super(e,t,o),this.theme=i}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},(e=>({sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),pivot:this.extractAttr(e,"pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)})));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:"extLst x14:conditionalFormatting"},(e=>({sqref:this.extractChildTextContent(e,"xm:sqref",{required:!0}).split(" "),pivot:this.extractAttr(e,"xm:pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)})))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:"cfRule, x14:cfRule"},(e=>{const o=this.extractAttr(e,"type",{required:!0}).asString();if("dataBar"===o)throw new Error("Databars conditional formats are not supported.");return{type:o,priority:this.extractAttr(e,"priority",{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:this.extractAttr(e,"dxfId")?.asNum(),stopIfTrue:this.extractAttr(e,"stopIfTrue")?.asBool(),aboveAverage:this.extractAttr(e,"aboveAverage")?.asBool(),percent:this.extractAttr(e,"percent")?.asBool(),bottom:this.extractAttr(e,"bottom")?.asBool(),operator:this.extractAttr(e,"operator")?.asString(),text:this.extractAttr(e,"text")?.asString(),timePeriod:this.extractAttr(e,"timePeriod")?.asString(),rank:this.extractAttr(e,"rank")?.asNum(),stdDev:this.extractAttr(e,"stdDev")?.asNum(),equalAverage:this.extractAttr(e,"equalAverage")?.asBool()}}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:"formula"},(e=>this.extractTextContent(e,{required:!0})))}extractCfColorScale(e,t){const o=this.querySelector(e,"colorScale");if(o)return{colors:this.mapOnElements({parent:o,query:"color"},(e=>this.extractColor(e,t,"ffffff"))),cfvos:this.extractCFVos(o)}}extractCfIconSet(e){const t=this.querySelector(e,"iconSet, x14:iconSet");if(t)return{iconSet:this.extractAttr(t,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(t,"showValue",{default:!0}).asBool(),percent:this.extractAttr(t,"percent",{default:!0}).asBool(),reverse:this.extractAttr(t,"reverse")?.asBool(),custom:this.extractAttr(t,"custom")?.asBool(),cfvos:this.extractCFVos(t),cfIcons:this.extractCfIcons(t)}}extractCfIcons(e){const t=this.mapOnElements({parent:e,query:"cfIcon, x14:cfIcon"},(e=>({iconSet:this.extractAttr(e,"iconSet",{required:!0}).asString(),iconId:this.extractAttr(e,"iconId",{required:!0}).asNum()})));return 0===t.length?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:"cfvo, x14:cfvo"},(e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),gte:this.extractAttr(e,"gte",{default:!0})?.asBool(),value:e.attributes.val?this.extractAttr(e,"val")?.asString():this.extractChildTextContent(e,"f, xm:f")})))}}class sC extends tC{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!Zb[t])throw new Error(`Unsupported chart type ${t}`);const o=this.mapOnElements({parent:e,query:"c:title a:t"},(e=>e.textContent||"")).join(""),i=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:o,type:Zb[t],dataSets:this.extractChartDatasets(this.querySelector(e,`c:${t}`)),labelRange:this.extractChildTextContent(e,"c:ser c:cat c:f"),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:qb[this.extractChildAttr(e,"c:legendPos","val",{default:"b"}).asString()],stacked:"stacked"===i,fontColor:"000000"}}))[0]}extractChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},(e=>({label:this.extractChildTextContent(e,"c:tx 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=QS(e.tagName);if(db.some((e=>e===t)))return t}throw new Error("Unknown chart type")}}class nC extends tC{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{if("twoCellAnchor"!==QS(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 o=this.querySelector(t,e);if(!o)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(o,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(o,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(o,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(o,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),o=this.getTargetXmlFile(this.relationships[t]),i=new sC(o,this.xlsxFileStructure,this.warningManager).extractChart();if(!i)throw new Error("Unable to extract chart definition");return i}}class rC extends tC{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 aC extends tC{getTable(){return this.mapOnElements({query:"table",parent:this.rootFile.file.xml},(e=>({displayName:this.extractAttr(e,"displayName",{required:!0}).asString(),name:this.extractAttr(e,"name")?.asString(),id:this.extractAttr(e,"id",{required:!0}).asString(),ref:this.extractAttr(e,"ref",{required:!0}).asString(),headerRowCount:this.extractAttr(e,"headerRowCount",{default:1}).asNum(),totalsRowCount:this.extractAttr(e,"totalsRowCount",{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)})))[0]}extractTableCols(e){return this.mapOnElements({query:"tableColumn",parent:e},(e=>({id:this.extractAttr(e,"id",{required:!0}).asString(),name:this.extractAttr(e,"name",{required:!0}).asString(),colFormula:this.extractChildTextContent(e,"calculatedColumnFormula")})))}extractTableStyleInfo(e){return this.mapOnElements({query:"tableStyleInfo",parent:e},(e=>({name:this.extractAttr(e,"name")?.asString(),showFirstColumn:this.extractAttr(e,"showFirstColumn")?.asBool(),showLastColumn:this.extractAttr(e,"showLastColumn")?.asBool(),showRowStripes:this.extractAttr(e,"showRowStripes")?.asBool(),showColumnStripes:this.extractAttr(e,"showColumnStripes")?.asBool()})))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:"autoFilter",parent:e},(e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,"ref",{required:!0}).asString()})))[0]}extractFilterColumns(e){return this.mapOnElements({query:"tableColumn",parent:e},(t=>({colId:this.extractAttr(e,"colId",{required:!0}).asNum(),hiddenButton:this.extractAttr(e,"hiddenButton",{default:!1}).asBool(),filters:this.extractSimpleFilter(t)})))}extractSimpleFilter(e){return this.mapOnElements({query:"filter",parent:e},(e=>({val:this.extractAttr(e,"val",{required:!0}).asString()})))}}class lC extends tC{theme;constructor(e,t,o,i){super(e,t,o),this.theme=i}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=ev(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=ev(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id,o=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(!o)throw new Error("Cannot find corresponding workbook sheet");return o}extractConditionalFormats(){return new iC(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},(e=>{const t=this.extractAttr(e,"r:id",{required:!0})?.asString(),o=this.getTargetXmlFile(this.relationships[t]);return new nC(o,this.xlsxFileStructure,this.warningManager).extractFigures()}))[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},(e=>{const t=this.extractAttr(e,"r:id",{required:!0})?.asString(),o=this.getTargetXmlFile(this.relationships[t]);return new aC(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 rC(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:wb.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:xb.toString()}).asNum()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},(e=>({width:this.extractAttr(e,"width")?.asNum(),customWidth:this.extractAttr(e,"customWidth")?.asBool(),bestFit:this.extractAttr(e,"bestFit")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),min:this.extractAttr(e,"min",{required:!0})?.asNum(),max:this.extractAttr(e,"max",{required:!0})?.asNum(),styleIndex:this.extractAttr(e,"style")?.asNum()})))}extractRows(e){return this.mapOnElements({parent:e,query:"sheetData row"},(e=>({index:this.extractAttr(e,"r",{required:!0})?.asNum(),cells:this.extractCells(e),height:this.extractAttr(e,"ht")?.asNum(),customHeight:this.extractAttr(e,"customHeight")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),styleIndex:this.extractAttr(e,"s")?.asNum()})))}extractCells(e){return this.mapOnElements({parent:e,query:"c"},(e=>({xc:this.extractAttr(e,"r",{required:!0})?.asString(),styleIndex:this.extractAttr(e,"s")?.asNum(),type:Ub[this.extractAttr(e,"t",{default:"n"})?.asString()],value:this.extractChildTextContent(e,"v"),formula:this.extractCellFormula(e)})))}extractCellFormula(e){const t=this.querySelector(e,"f");if(t)return{content:this.extractTextContent(t),sharedIndex:this.extractAttr(t,"si")?.asNum(),ref:this.extractAttr(t,"ref")?.asString()}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},(e=>{const t=this.extractAttr(e,"r:id")?.asString();return{xc:this.extractAttr(e,"ref",{required:!0})?.asString(),location:this.extractAttr(e,"location")?.asString(),display:this.extractAttr(e,"display")?.asString(),relTarget:t?this.relationships[t].target:void 0}}))}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),o={};for(let e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),i=this.extractTextContent(e,{required:!0});o[t]=i}const i=[];for(let e=0;e<Object.keys(o).length;e++)o[e]?i.push(o[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),i.push(""));return i}}class cC extends tC{theme;constructor(e,t,o){super(e.styles,e,t),this.theme=o}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},(e=>this.extractNumFormats(e)))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},(e=>this.extractFont(e)))}extractFont(e){const t=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),o=this.extractChildAttr(e,"sz","val",{default:Z.toString()}).asNum(),i=this.extractColor(this.querySelector(e,"color"),this.theme),s=this.querySelector(e,"i")||void 0,n=s&&"0"!==s.attributes.val?.value,r=this.querySelector(e,"b")||void 0,a=r&&"0"!==r.attributes.val?.value,l=this.querySelector(e,"strike")||void 0,c=l&&"0"!==l.attributes.val?.value,h=this.querySelector(e,"u")||void 0;return{name:t,size:o,color:i,italic:n,bold:a,underline:h&&"none"!==h.attributes.val?.value,strike:c}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},(e=>this.extractFill(e)))}extractFill(e){const t=e.children[0];return"patternFill"===t.tagName?{patternType:t.attributes.patternType?.value,bgColor:this.extractColor(this.querySelector(t,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(t,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(t,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},(e=>this.extractBorder(e)))}extractBorder(e){const t={left:this.extractSingleBorder(e,"left",this.theme),right:this.extractSingleBorder(e,"right",this.theme),top:this.extractSingleBorder(e,"top",this.theme),bottom:this.extractSingleBorder(e,"bottom",this.theme),diagonal:this.extractSingleBorder(e,"diagonal",this.theme)};return t.diagonal&&(t.diagonalUp=this.extractAttr(e,"diagonalUp")?.asBool(),t.diagonalDown=this.extractAttr(e,"diagonalDown")?.asBool()),t}extractSingleBorder(e,t,o){const i=this.querySelector(e,t);if(i&&i.attributes.style)return{style:this.extractAttr(i,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(i.children[0],o,"000000")}}extractAlignment(e){return{horizontal:this.extractAttr(e,"horizontal",{default:"general"}).asString(),vertical:this.extractAttr(e,"vertical",{default:"bottom"}).asString(),textRotation:this.extractAttr(e,"textRotation")?.asNum(),wrapText:this.extractAttr(e,"wrapText")?.asBool(),indent:this.extractAttr(e,"indent")?.asNum(),relativeIndent:this.extractAttr(e,"relativeIndent")?.asNum(),justifyLastLine:this.extractAttr(e,"justifyLastLine")?.asBool(),shrinkToFit:this.extractAttr(e,"shrinkToFit")?.asBool(),readingOrder:this.extractAttr(e,"readingOrder")?.asNum()}}getDxfs(){return this.mapOnElements({query:"dxf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"font"),o=this.querySelector(e,"fill"),i=this.querySelector(e,"border"),s=this.querySelector(e,"numFmt"),n=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:o?this.extractFill(o):void 0,numFmt:s?this.extractNumFormats(s):void 0,alignment:n?this.extractAlignment(n):void 0,border:i?this.extractBorder(i):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 hC extends tC{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})}))),o={};for(let e of t)o[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:o}}))}}function dC(e,t){const o=function(e,t){const o=t[Ob],i=o.querySelectorAll(`Override[ContentType="${e}"]`),s=[];for(let e of i){const t=e?.attributes.PartName.value;s.push(t.substring(1))}return s}(e,t);return function(e,t){const o=[];for(let i of e){const e=uC(i,t);o.push({file:{fileName:i,xml:t[i]},rels:e?{fileName:e,xml:t[e]}:void 0})}return o}(o,t)}function uC(e,t){if(e===Ob)return"_rels/.rels";let o="";const i=e.split("/");for(let e=0;e<i.length-1;e++)o+=i[e]+"/";return o+="_rels/",o+=i[i.length-1]+".rels",t[o]||(o=void 0),o}class gC{warningManager;xmls;constructor(e){this.warningManager=new Nb,this.xmls={};for(let t of Object.keys(e))(t.endsWith(".xml")||t.endsWith(".rels"))&&(this.xmls[t]=ZS(new hb(e[t])))}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new oC(e.theme,e,this.warningManager).getTheme():void 0,o=e.sharedStrings?new oC(e.sharedStrings,e,this.warningManager).getSharedStrings():[],i=e.sheets.sort(((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0}))).map((o=>new lC(o,e,this.warningManager,t).getSheet())),s=e.externalLinks.map((t=>new hC(t,e,this.warningManager).getExternalBook())),n=new cC(e,this.warningManager,t);return{fonts:n.getFonts(),fills:n.getFills(),borders:n.getBorders(),dxfs:n.getDxfs(),numFmts:n.getNumFormats(),styles:n.getStyles(),sheets:i,sharedStrings:o,externalBooks:s}}buildXlsxFileStructure(){const e={sheets:dC(bb.sheet,this.xmls),workbook:dC(bb.workbook,this.xmls)[0],styles:dC(bb.styles,this.xmls)[0],sharedStrings:dC(bb.sharedStrings,this.xmls)[0],theme:dC(bb.themes,this.xmls)[0],charts:dC(bb.chart,this.xmls),figures:dC(bb.drawing,this.xmls),tables:dC(bb.table,this.xmls),pivots:dC(bb.pivot,this.xmls),externalLinks:dC(bb.externalLink,this.xmls)};if(!e.workbook.rels)throw Error(n("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:12,sheets:FS(e,this.warningManager),styles:lv(e,this.warningManager),formats:hv(e,this.warningManager),borders:rv(e,this.warningManager),entities:{},revisionId:ee};return BS(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=Ct(e.styles[t])})),t}}function pC(e){const t=tS(e);let o=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&Po.test(e.value)){const t=e.value.trim();return o.includes(t)||o.push(t),`${he}${o.indexOf(t)}${he}`}return e.value}))),dependencies:o}}const mC=13,fC="Sheet1";function bC(e,t){if(!e)return wC();if(e["[Content_Types].xml"]){const o=new gC(e);if(e=o.convertXlsx(),t)for(let e of o.warningManager.warnings.sort())console.warn(e)}return"version"in e&&e.version<mC&&(e=function(e){for(let t=vC.findIndex((t=>t.from===e.version));t<vC.length;t++)e=vC[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,o=new ti;for(const i of e.sheets||[])for(const e of i.figures||[])t.has(e.id)&&(e.id+=o.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(wC(),e,{version:mC}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(EC(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(EC(fC,"Sheet1"));return e}(e),e}(e),e}const vC=[{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 o=t.cells[e];o.content&&o.content.startsWith("=")&&(o.formula=pC(o.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:o,...i}=t.figures[e].data,s=[];for(let e of o)if(e.labelCell){const t=ii(e.dataRange),o=e.labelCell+":"+Zt(t.right,t.bottom);s.push(o)}else s.push(e.dataRange);i.dataSetsHaveTitle=Boolean(o[0].labelCell),i.dataSets=s,t.figures[e].data=i}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){const t=[],o=new RegExp(ce,"g");for(let i of e.sheets||[]){if(!i.name)continue;const e=i.name,s=e.replace(o,"_");let n=1,r=s;for(;t.includes(r);)r=`${s}${n}`,n++;i.name=r,t.push(r);const a=t=>{if(void 0===t)return t;let o=t.replace(e,r),i=t;for(;i!==o;)i=o,o=i.replace(e,r);return i};for(let e in i.cells){const t=i.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(a))}for(let e of i.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(a),o=a(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:o}}for(let e of i.conditionalFormats||[]){e.ranges=e.ranges.map(a);for(const t of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===e.rule[t]?.type&&(e.rule[t].value=a(e.rule[t].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 o=t.cells[e];if(o.formula){let{text:e,dependencies:t}=o.formula;for(let[o,i]of Object.entries(t)){const t=`\\${he}${o}\\${he}`;e=e.replace(new RegExp(t,"g"),i)}o.content=e,delete o.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let o of e.sheets||[])for(let e in o.cells||[]){const i=o.cells[e];i.format&&(i.format=gt(i.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}},{description:"Fix datafilter duplication",from:12,to:12.5,applyMigration(e){for(let t of e.sheets||[]){let e=[];for(let o of t.filterTables||[]){const t=ii(o.range),i=e.findIndex((e=>gi(e,t)));-1!==i?e[i]=t:e.push(t)}t.filterTables=e.map((e=>({range:ni(e)})))}return e}},{description:"Change Border description structure",from:12.5,to:13,applyMigration(e){for(const t in e.borders){const o=e.borders[t];for(const e in o)Array.isArray(o[e])&&(o[e]={style:o[e][0],color:o[e][1]})}return e}}];function SC(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const o=[],i=[],s=e=>{if("CREATE_SHEET"===e.type)o.push(e.sheetId);else if("sheetId"in e&&!o.includes(e.sheetId))return{...e,sheetId:fC};return e};for(const e of t)"REMOTE_REVISION"===e.type?i.push({...e,commands:e.commands.map(s)}):i.push(e);return i}(e,t),t=CC(t,"SORT_CELLS"),t=function(e,t){const o=[],i={};for(const t of e.sheets||[])t.figures?.forEach((e=>{"chart"===e.tag&&(i[e.id]=e.data)}));for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const o of e.commands){let e=o;switch(o.type){case"CREATE_CHART":i[o.id]=o.definition;break;case"UPDATE_CHART":if(!i[o.id]){console.log(`Fix chart definition: chart with id ${o.id} not found.`);continue}const t={...i[o.id],...o.definition};e={...o,definition:t},i[o.id]=t}t.push(e)}o.push({...e,commands:t})}else o.push(e);return o}(e,t=CC(t,"SET_DECIMAL")),t}function CC(e,t){const o=[];for(const i of e)"REMOTE_REVISION"===i.type?o.push({...i,commands:i.commands.filter((e=>e.type!==t))}):o.push(i);return o}function EC(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[],filterTables:[],isVisible:!0}}function wC(e="Sheet1"){return{version:mC,sheets:[EC(fC,e)],entities:{},styles:{},formats:{},borders:{},revisionId:ee,uniqueFigureIds:!0}}function xC(e,t){return{...EC(e,t),charts:[],images:[]}}class yC{static getters=[];history;dispatch;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 o of e){let e=o.call(this,t);Array.isArray(e)||(e=[e]);const i=e.filter((e=>0!==e));if(i.length)return i}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}class IC extends yC{getters;range;uuidGenerator;constructor({getters:e,stateObserver:t,range:o,dispatch:i,uuidGenerator:s}){super(t,i),this.range=o,o.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=s}import(e){}export(e){}adaptRanges(e,t){}garbageCollectExternalResources(){}}function RC(e){return""===e?NaN:Number(e)}class TC{id;zone;filters;constructor(e){this.filters=[],this.zone=e;const t=new ti;this.id=t.uuidv4();for(const o of Ke(e.left,e.right+1)){const e={...this.zone,left:o,right:o};this.filters.push(new AC(t.uuidv4(),e))}}get contentZone(){if(this.zone.bottom!==this.zone.top)return{...this.zone,top:this.zone.top+1}}getFilterId(e){return this.filters.find((t=>t.col===e))?.id}clone(){return new TC(this.zone)}}class AC{id;zoneWithHeaders;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}}}function OC(e){return Object.entries(e).map((([e,t])=>t?MC(parseInt(e,10),t):void 0)).filter(dt).map((e=>Zt(e.left,e.top)+":"+Zt(e.right,e.bottom)))}function MC(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}class NC{getters;providers=[];constructor(e){this.getters=e}static getters=["getRangeString","getSelectionRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData"];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",o="COL"===e.dimension?"right":"bottom",i="COL"===e.dimension?"columns":"rows";const s=[...e.elements];s.sort(((e,t)=>t-e));const n=Qe(s);this.executeOnAllRanges((s=>{if(s.sheetId!==e.sheetId)return{changeType:"NONE"};let r=s,a="NONE";for(let e of n){const n=Tt(e),l=Rt(e);if(s.zone[t]<=n&&n<=s.zone[o]){const e=Math.min(s.zone[o],l)-n+1;a="RESIZE",r=this.createAdaptedRange(r,i,a,-e)}else if(s.zone[t]>=n&&s.zone[o]<=l)a="REMOVE",r=s.clone({...this.getInvalidRange()});else if(s.zone[t]<=l&&s.zone[o]>=l){const e=l-s.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,i,a,-e),r=this.createAdaptedRange(r,i,"MOVE",-(s.zone[t]-n))}else n<s.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,i,a,-(l-n+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",o="COL"===e.dimension?"right":"bottom",i="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((s=>{if(s.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(s.zone[t]<=e.base&&e.base<s.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(s,i,"RESIZE",e.quantity)};if(e.base<s.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(s,i,"MOVE",e.quantity)}}else{if(s.zone[t]<e.base&&e.base<=s.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(s,i,"RESIZE",e.quantity)};if(e.base<=s.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(s,i,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId!==e.sheetId)return{changeType:"NONE"};const o=this.getters.getSheetName(e.sheetId);return{changeType:"REMOVE",range:t=t.clone({...this.getInvalidRange(),invalidSheetName:o})}}),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 o=void 0,i=e.sheetId;return{changeType:"CHANGE",range:t.clone({sheetId:i,invalidSheetName:o})}}return{changeType:"NONE"}}));break;case"MOVE_RANGES":{const t=e.target[0];this.executeOnAllRanges((o=>{if(o.sheetId!==e.sheetId||!mi(o.zone,t))return{changeType:"NONE"};const i=e.targetSheetId,s=e.col-t.left,n=e.row-t.top,r=this.createAdaptedRange(o,"both","MOVE",[s,n]),a=e.sheetId!==i||r.prefixSheet;return{changeType:"MOVE",range:r.clone({sheetId:i,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const o=e(t);return"NONE"===o.changeType||si(o.range.zone)?o:{range:o.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,o,i){const s=Ei(e.unboundedZone,t,o,i);return e.clone({zone:s})}executeOnAllRanges(e,t){const o=this.verifyRangeRemoved(e);for(const e of this.providers)e(o,t)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,o,i){const s=e.map((e=>Xo.fromRange(e,this.getters)));return s.map((e=>{if(!si(e.zone))return e;const s=e.prefixSheet?e.sheetId:i,n={...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:o),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:o)};return e.clone({sheetId:s,zone:n}).orderZone()}))}getRangeFromSheetXC(e,t){if(!$o.test(t))return new Xo({sheetId:"",zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let o,i=t,s=!1;t.includes("!")&&(({xc:i,sheetName:o}=Yo(t)),o&&(s=!0));const n=oi(i),r=Xo.getRangeParts(i,n),a=o&&!this.getters.getSheetIdByName(o)?o:void 0,l=this.getters.getSheetIdByName(o)||e;return new Xo({prefixSheet:s,zone:n,sheetId:l,invalidSheetName:a,parts:r},this.getters.getSheetSize).orderZone()}getSelectionRangeString(e,t){const o=Xo.fromRange(e,this.getters),i=this.getters.expandZone(o.sheetId,o.zone),s=o.clone({zone:{...i,bottom:o.isFullCol?void 0:i.bottom,right:o.isFullRow?void 0:i.right}});return this.getRangeString(s,t)}getRangeString(e,t,o=!1){if(!e)return J;if(e.invalidXc)return e.invalidXc;if(!this.getters.tryGetSheet(e.sheetId))return J;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return J;if(e.zone.left<0||e.zone.top<0)return J;const i=Xo.fromRange(e,this.getters);let s=i.sheetId!==t||i.invalidSheetName||i.prefixSheet,n="";if(s&&(n=i.invalidSheetName?i.invalidSheetName:$e(this.getters.getSheetName(i.sheetId))),s&&!n)return J;let r=this.getRangePartString(i,0,o);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)&&(r+=":",r+=this.getRangePartString(i,1,o)),`${s?n+"!":""}${r}`}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 Xo(t,this.getters.getSheetSize)}getRangePartString(e,t,o=!1){const i=e.parts&&e.parts[t]?.colFixed?"$":"",s=Bt(0===t?e.zone.left:e.zone.right),n=e.parts&&e.parts[t]?.rowFixed?"$":"",r=String(0===t?e.zone.top+1:e.zone.bottom+1);let a="";return a=e.isFullCol&&!o?0===t&&e.unboundedZone.hasHeader?i+s+n+r:i+s:e.isFullRow&&!o?0===t&&e.unboundedZone.hasHeader?i+s+n+r:n+r:i+s+n+r,a}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:J}}}class _C extends yC{static layers=[];getters;ui;selection;constructor({getters:e,stateObserver:t,dispatch:o,uiActions:i,selection:s}){super(t,o),this.getters=e,this.ui=i,this.selection=s}drawGrid(e,t){}}const FC=Hg.mapping;class DC{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;offsetScrollbarX;offsetScrollbarY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,o,i,s,n){this.getters=e,this.sheetId=t,this.boundaries=o,this.viewportWidth=i.width,this.viewportHeight=i.height,this.offsetScrollbarX=n.x,this.offsetScrollbarY=n.y,this.canScrollVertically=s.canScrollVertically,this.canScrollHorizontally=s.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:o,size:i}=this.getters.getColDimensions(this.sheetId,e),{end:s,size:n}=this.getters.getRowDimensions(this.sheetId,t),r=this.searchHeaderIndex("COL",o-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,r),l=this.searchHeaderIndex("ROW",s-this.viewportHeight,0),c=this.getters.getRowSize(this.sheetId,l);let h=o-this.offsetCorrectionX;this.canScrollHorizontally&&(h+=Math.max(L,Math.min(a,this.viewportWidth-i)),h=Math.max(h,this.viewportWidth));let d=s-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(k+5,Math.min(c,this.viewportHeight-n)),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 o=this.getters.getMainCellPosition({sheetId:t,...e}),{col:i,row:s}=this.getters.getNextVisibleCellPosition(o);pi(i,this.boundaries.top,this.boundaries)&&this.adjustPositionX(i),pi(this.boundaries.left,s,this.boundaries)&&this.adjustPositionY(s)}adjustPositionX(e){const t=this.sheetId,{end:o}=this.getters.getColDimensions(t,e),i=this.getters.getNumberCols(t);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<o){let o=e;for(;this.getters.isColHidden(t,o)&&e<i;)o++;const s=this.getters.getColDimensions(t,o).end,n=this.searchHeaderIndex("COL",s-this.viewportWidth-this.offsetCorrectionX,this.boundaries.left,!0);this.offsetX=this.getters.getColDimensions(t,n).end-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX()}else if(this.left>e){let o=e;for(;this.getters.isColHidden(t,o)&&e>0;)o--;this.offsetX=this.getters.getColDimensions(t,o).start-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX()}}adjustPositionY(e){const t=this.sheetId,{end:o}=this.getters.getRowDimensions(t,e),i=this.getters.getNumberRows(t);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<o){let o=e;for(;this.getters.isRowHidden(t,o)&&e<i;)o++;const s=this.getters.getRowDimensions(t,o).end,n=this.searchHeaderIndex("ROW",s-this.viewportHeight-this.offsetCorrectionY,this.boundaries.top,!0);this.offsetY=this.getters.getRowDimensions(t,n).end-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY()}else if(this.top>e){let o=e;for(;this.getters.isRowHidden(t,o)&&e>0;)o--;this.offsetY=this.getters.getRowDimensions(t,o).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=di(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,o=0,i=!1){let s=0;const n=this.sheetId,r=this.getters.getNumberHeaders(n,e);for(let a=o;a<=r-1;a++){const o=i||"COL"!==e?a<this.top&&a>this.bottom:a<this.left&&a>this.right;if(!this.getters.isHeaderHidden(n,e,a)&&!o&&(s+="COL"===e?this.getters.getColSize(n,a):this.getters.getRowSize(n,a),s>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 LC{cells;getters;index=0;direction;constructor(e,t,o){this.cells=e,this.getters=t,this.direction=o}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:o,tooltip:i}=Ws.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:o,tooltip:i,origin:{col:e.data.col,row:e.data.row}}}}class kC{subscriptions={};on(e,t,o){if(!o)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:o})}trigger(e,t){const o=this.subscriptions[e]||[];for(let e=0,i=o.length;e<i;e++){const i=o[e];i.callback.call(i.owner,t)}}off(e,t){const o=this.subscriptions[e];o&&(this.subscriptions[e]=o.filter((e=>e.owner!==t)))}clear(){this.subscriptions={}}}function PC(e,t){return{...e,definition:oa(e.definition,t)}}function UC(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let o=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(let t of e)o>t&&o--}if("ADD_COLUMNS_ROWS"===t.type){o=o>("before"===t.position?t.base-1:t.base)?o+t.quantity:o}return o>0?{...e,quantity:o}:void 0}km.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],PC),km.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],PC),km.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const o=t.sheetId;if(e.targetSheetId===o||e.sheetId===o)return;return e})),km.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),km.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){if(e.name===t.name)return{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),km.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE","CREATE_FILTER_TABLE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const o=[];for(const i of e.target)for(const e of t.target)gi(i,e)||o.push({...i});if(o.length)return{...e,target:o};return})),km.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],UC),km.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],UC),km.addTransformation("CREATE_FILTER_TABLE",["CREATE_FILTER_TABLE","ADD_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;for(const o of e.target)for(const e of t.target)if(gi(e,o))return;return e}));const VC=[{match:function(e){return"sheetId"in e},fn:HC},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const o=HC(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const i=[];for(const o of e.target){const e=Hn(o,t);e&&i.push(e)}if(!i.length)return"IGNORE_COMMAND";return{...e,target:i}}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const o=HC(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const o="COL"===t.dimension?"col":"row";let i=e[o];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(i))return"IGNORE_COMMAND";for(let t of e)i>=t&&i--}"ADD_COLUMNS_ROWS"===t.type&&(i>t.base||i===t.base&&"before"===t.position)&&(i+=t.quantity);return{...e,[o]:i}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const o of t.target){if(!(e.col===o.left&&e.row===o.top)&&pi(e.col,e.row,o))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 o=HC(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const o="ADD_COLUMNS_ROWS"===e.type,i=o?"base":"elements";let s=o?[e[i]]:e[i];if("REMOVE_COLUMNS_ROWS"===t.type&&(s=s.map((e=>{if(t.elements.includes(e))return;const o=t.elements.sort(((e,t)=>t-e));for(let t of o)e>t&&e--;return e})).filter(dt)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;s=s.map((o=>o>e?o+t.quantity:o))}if(s.length){let t=s;return o&&(t=s[0]),{...e,[i]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}},{match:function(e){return"ranges"in e},fn:function(e,t){const o=[],i="DELETE_SHEET"===t.type&&t.sheetId;for(const s of e.ranges)if(s._sheetId!==t.sheetId)o.push({...s,_zone:s._zone});else{const e=Hn(s._zone,t);e&&i!==s._sheetId&&o.push({...s,_zone:e})}if(!o.length)return"IGNORE_COMMAND";return{...e,ranges:o}}}];function zC(e,t){const o=km.getTransformation(e.type,t.type);return o?o(e,t):function(e,t){for(const{match:o,fn:i}of VC)if(o(e)){const o=i(e,t);if("SKIP_TRANSFORMATION"===o)continue;if("IGNORE_COMMAND"===o)return;e=o}return e}(e,t)}function BC(e,t){let o=[...e];for(const e of t)o=o.map((t=>zC(t,e))).filter(dt);return o}function HC(e,t){const o="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===o?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class $C{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,o,i,s,n){this.rootCommand=i,this.timestamp=n,this.id=e,this.clientId=t,this._commands=[...o],this._changes=s?[...s]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class WC extends Error{}class GC extends kC{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;uuidGenerator=new ti;constructor(e,t,o=ee){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=o,this.debouncedMove=function(e,t,o){let i;return function(){const s=this,n=arguments,r=o&&!i;clearTimeout(i),i=setTimeout((function(){i=null,o||e.apply(s,n)}),t),r&&e.apply(s,n)}}(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,o){if(!t.length||!o.length||!this.canApplyOptimisticUpdate())return;const i=new $C(this.uuidGenerator.uuidv4(),this.clientId,t,e,o,Date.now());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 WC("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(dt))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}getLastLocalNonEmptyRevision(e){const t=this.revisions.getRevertedExecution();for(const o of t){if("SNAPSHOT"===o.rootCommand)return;if(o.rootCommand&&"REMOTE"!==o.rootCommand&&(!e.includes(o.rootCommand?.type)&&o.commands.length))return o}}_move(e){if(!this.clients[this.clientId])return;const t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;const o=t?"CLIENT_MOVED":"CLIENT_JOINED",i=this.getClient();this.clients[this.clientId]={...i,position:e},this.transportService.sendMessage({type:o,version:1,client:{...i,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:o,timestamp:i}=e,s=new $C(e.nextRevisionId,t,o,"REMOTE",void 0,i);if(s.clientId!==this.clientId){this.revisions.insert(s.id,s,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:BC(o,t)})}break;case"SNAPSHOT_CREATED":{const t=new $C(e.nextRevisionId,"server",[],"SNAPSHOT",void 0,Date.now());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 qC=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];var ZC;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(ZC||(ZC={}));class jC extends _C{inputHasSingleRange;static layers=[1];static getters=[];ranges=[];focusedRangeIndex=null;activeSheet;willAddNewRange=!1;constructor(e,t,o){if(o&&t.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");super(e),this.inputHasSingleRange=o,this.insertNewRange(0,t),this.activeSheet=this.getters.getActiveSheetId(),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}handleEvent(e){const t=ni(e.anchor.zone),o=this.activeSheet,i=this.getters.getActiveSheetId(),s=this.getters.getSheetName(i);this.add([i===o?t:`${$e(s)}!${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 o=e.value.replace(/^,+/,"").split(",").map((e=>e.trim()));this.setRange(t,o)}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:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),i=this.getters.expandZone(e.sheetIdTo,yi({col:t,row:o}));this.selection.resetAnchor(this,{cell:{col:t,row:o},zone:i})}}}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 o=Math.max(0,...this.ranges.map((e=>Number(e.id))));this.ranges.splice(e,0,...t.map(((e,t)=>({xc:e,id:o+t+1,color:Mt[(o+t)%Mt.length]}))))}setRange(e,t){const[,...o]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,o),o.length&&this.focus(e+o.length)}removeRange(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const o=this.cleanInputs([e]).filter((e=>this.getters.isRangeValid(e))).filter((e=>this.shouldBeHighlighted(this.activeSheet,e)));return o.map((e=>{const{sheetName:o}=Yo(e);return{zone:this.getters.getRangeFromSheetXC(this.activeSheet,e).zone,sheetId:o&&this.getters.getSheetIdByName(o)||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:o}=Yo(t),i=this.getters.getSheetIdByName(o),s=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(i===s||void 0===i&&s===e)}getIndex(e){const t=this.ranges.findIndex((t=>t.id===e));return t>=0?t:null}}const YC=[XC,function(e,t){return"target"in t&&Array.isArray(t.target)?{...Be(t),target:e.getSelectedZones()}:t},function(e,t){if(!("row"in t)||!("col"in t))return t;const{col:o,row:i}=e.getActivePosition();return{...Be(t),col:o,row:i}}];function XC(e,t){return"sheetId"in t?{...Be(t),sheetId:e.getActiveSheetId()}:t}const KC=new ti;function QC(e,t){const o=e.getSelectedZone();return{...XC(e,t),elements:"COL"===t.dimension?Ke(o.left,o.right+1):Ke(o.top,o.bottom+1)}}function JC(e,t){const o=e.getSelectedZone();return{...Be(t),zone:o}}function eE(e,t){const o=Be(t),i=e.getSelectedZone(),{top:s,bottom:n,left:r,right:a}=i;return"cols"in o?o.cols=Ke(r,a+1):"rows"in o&&(o.rows=Ke(s,n+1)),o}const tE=new zi;tE.add("UPDATE_CELL",iE),tE.add("CLEAR_CELL",iE),tE.add("DELETE_CONTENT",iE),tE.add("ADD_MERGE",iE),tE.add("REMOVE_MERGE",iE),tE.add("SET_FORMATTING",iE),tE.add("CLEAR_FORMATTING",iE),tE.add("SET_BORDER",iE),tE.add("CREATE_FILTER_TABLE",iE),tE.add("REMOVE_FILTER_TABLE",iE),tE.add("HIDE_SHEET",iE),tE.add("ADD_COLUMNS_ROWS",(function(e,t){const o=e.getActivePosition();return{...XC(e,t),base:"COL"===t.dimension?o.col:o.row}})),tE.add("REMOVE_COLUMNS_ROWS",QC),tE.add("HIDE_COLUMNS_ROWS",QC),tE.add("RESIZE_COLUMNS_ROWS",QC),tE.add("CREATE_SHEET",(function(e,t){const o=Be(t);o.sheetId=KC.uuidv4();const i=t.name||e.getSheet(e.getActiveSheetId()).name,s=i.match(/(.+?)\d*$/)?.[1]||i;return o.name=e.getNextSheetName(s),o})),tE.add("CREATE_FIGURE",(function(e,t){const o=XC(e,t);return o.figure.id=KC.uuidv4(),o})),tE.add("CREATE_CHART",(function(e,t){return{...XC(e,t),id:KC.uuidv4()}})),tE.add("CREATE_IMAGE",(function(e,t){return{...XC(e,t),figureId:KC.uuidv4()}}));const oE=new zi;function iE(e,t){let o=Be(t);for(const t of YC)o=t(e,o);return o}function sE(e,t){if(!t)return;if(!tE.contains(t.type))return;return tE.get(t.type)(e,t)}function nE(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return Ms(e.rootCommand)?sE(t,e.rootCommand):function(e,t,o){if(!oE.contains(t.type))return;return oE.get(t.type)(e,t,o)}(t,e.rootCommand,e.commands)}oE.add("STOP_EDITION",(function(e,t,o){return o.map((t=>sE(e,t))).filter(dt)})),oE.add("PASTE",(function(e,t){return{type:"REPEAT_PASTE",pasteOption:Be(t.pasteOption),target:e.getSelectedZones()}})),oE.add("INSERT_CELL",JC),oE.add("DELETE_CELL",JC),oE.add("AUTORESIZE_COLUMNS",eE),oE.add("AUTORESIZE_ROWS",eE),oE.add("SORT_CELLS",(function(e,t){const o=e.getSelectedZone();return{...XC(e,t),col:o.left,row:o.top,zone:o}})),oE.add("SUM_SELECTION",iE),oE.add("SET_DECIMAL",iE);class rE{getters;dispatch;selection;operation;sheetId;constructor(e,t,o,i){this.getters=t,this.dispatch=o,this.selection=i,this.operation=e,this.sheetId=t.getActiveSheetId()}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0}addMissingDimensions(e,t,o,i){const s=this.getters.getActiveSheetId(),n=t+i-this.getters.getNumberRows(s);n>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(s)-1,sheetId:s,quantity:n,position:"after"});const r=e+o-this.getters.getNumberCols(s);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(s)-1,sheetId:s,quantity:r,position:"after"})}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class aE extends rE{cells;copiedTables;zones;constructor(e,t,o,i,s){if(super(t,o,i,s),!e.length)return this.cells=[[]],this.zones=[],void(this.copiedTables=[]);const n=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===n.size&&1===r.size?function(e){return e.reduce(((e,t)=>{const o=e.length;for(let i=0;i<o;i++)if(gi(e[i],t))return e[i]=hi(e[i],t),e;return e[o]=t,e}),[])}(e):[e[e.length-1]],h=c.map((e=>Ci(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=o.getActiveSheetId();for(let e of u){let t=[];for(let i of d){const s={col:i,row:e,sheetId:p};t.push({cell:o.getCell(s),style:o.getCellComputedStyle(s),evaluatedCell:o.getEvaluatedCell(s),border:o.getCellBorder(s)||void 0,position:s})}g.push(t)}const m=[];for(const t of e)for(const e of this.getters.getFilterTablesInZone(p,t)){const t=[];for(const o of Ke(e.zone.left,e.zone.right+1))t.push(this.getters.getFilterValues({sheetId:p,col:o,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 o=this.getters.getActiveSheetId();if("CUT"===this.operation&&void 0!==t?.pasteOption)return 21;if(e.length>1&&(this.cells.length>1||this.cells[0].length>1))return 20;const i=this.cells.length,s=this.cells[0].length;for(let t of this.getPasteZones(e))if(this.getters.doesIntersectMerge(o,t)&&(e.length>1||!this.getters.isSingleCellOrMerge(o,e[0])||i*s!=1))return 2;const{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(o);for(const t of this.getPasteZones(e))if(t.left<n&&t.right>=n||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 o=this.cells.length,i=this.cells[0].length,s="CUT"===this.operation;t?.selectTarget&&this.selectPastedZone(i,o,s,e)}pasteFromCopy(e,t){if(1===e.length){const o=this.cells.length,i=this.cells[0].length,s=this.pastedZones(e,i,o);for(const e of s)this.pasteZone(e.left,e.top,t)}else for(const o of e)for(let e=o.left;e<=o.right;e++)for(let i=o.top;i<=o.bottom;i++)this.pasteZone(e,i,t);void 0===t?.pasteOption&&this.pasteCopiedTables(e)}pasteFromCut(e,t){this.clearClippedZones();const o=e[0];this.pasteZone(o.left,o.top,t),this.dispatch("MOVE_RANGES",{target:this.zones,sheetId:this.sheetId,targetSheetId:this.getters.getActiveSheetId(),col:o.left,row:o.top});for(const e of this.copiedTables)this.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.sheetId,target:[e.zone]});this.pasteCopiedTables(e)}pastedZones(e,t,o){const i=e[0],s=Math.max(1,Math.floor((i.right+1-i.left)/t)),n=Math.max(1,Math.floor((i.bottom+1-i.top)/o)),r=[];for(let e=0;e<s;e++)for(let s=0;s<n;s++){const n=i.top+s*o,a=i.left+e*t;r.push({left:a,top:n,bottom:n+o-1,right:a+t-1})}return r}getPasteZones(e){const t=this.cells;if(!t.length||!t[0].length)return e;const o=[],i=t.length,s=t[0].length,n=e[e.length-1],r=n.left,a=n.top,l=Math.max(1,Math.floor((n.right+1-r)/s)),c=Math.max(1,Math.floor((n.bottom+1-a)/i));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)o.push({left:r,top:a,right:r-1+e*s,bottom:a-1+t*i});return o}selectPastedZone(e,t,o,i){const s=i[0],n=s.left,r=s.top;if(t>1||e>1||o){const s=this.pastedZones(i,e,t),a=o?s[0]:hi(...s);this.selection.selectZone({cell:{col:n,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,o){const i=this.cells.length,s=this.cells[0].length,n="onlyValue"!==o?.pasteOption&&o?.shouldPasteCF,r=this.getters.getActiveSheetId();this.addMissingDimensions(s,i,e,t);for(let a=0;a<i;a++){const i=this.cells[a];for(let l=0;l<s;l++){const s=i[l],c={col:e+l,row:t+a,sheetId:r};"CUT"!==this.operation&&this.pasteMergeIfExist(s.position,c),this.pasteCell(s,c,this.operation,o),n&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{originPosition:s.position,targetPosition:c,operation:this.operation})}}}pasteCell(e,t,o,i){const{sheetId:s,col:n,row:r}=t,a=this.getters.getEvaluatedCell(t);if("onlyValue"!==i?.pasteOption){const o=this.getters.getCellBorder(t),i=e.border,a={top:o?.top||i?.top,bottom:o?.bottom||i?.bottom,left:o?.left||i?.left,right:o?.right||i?.right};this.dispatch("SET_BORDER",{sheetId:s,col:n,row:r,border:a})}if(e.cell){if("onlyFormat"===i?.pasteOption)return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.evaluatedCell.format});if("onlyValue"===i?.pasteOption){const o=bo(e.evaluatedCell.value);return void this.dispatch("UPDATE_CELL",{...t,content:o})}let a=e.cell.content;if(e.cell.isFormula&&"COPY"===o){const t=n-e.position.col,i=r-e.position.row;a=this.getUpdatedContent(s,e.cell,t,i,o)}this.dispatch("UPDATE_CELL",{...t,content:a,style:e.cell.style||null,format:e.cell.format})}else a&&("onlyValue"===i?.pasteOption?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===i?.pasteOption?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,o,i,s){const n=this.getters.createAdaptedRanges(t.dependencies,o,i,e);return this.getters.buildFormulaContent(e,t,n)}pasteMergeIfExist(e,t){let{sheetId:o,col:i,row:s}=e;const{col:n,row:r}=this.getters.getMainCellPosition(e);if(n===i&&r===s){const n=this.getters.getMerge(e);if(!n)return;({sheetId:o,col:i,row:s}=t),this.dispatch("ADD_MERGE",{sheetId:o,force:!0,target:[{left:i,top:s,right:i+n.right-n.left,bottom:s+n.bottom-n.top}]})}}pasteCopiedTables(e){const t=this.getters.getActiveSheetId(),o=e[0],i=this.zones[0],s=[o.left-i.left,o.top-i.top];for(const e of this.copiedTables){const o=Ei(e.zone,"both","MOVE",s);this.dispatch("CREATE_FILTER_TABLE",{sheetId:t,target:[o]});for(const i of Ke(0,e.filtersValues.length))this.dispatch("UPDATE_FILTER",{sheetId:t,col:o.left+i,row:o.top,values:e.filtersValues[i]})}}getClipboardContent(){return{[Is.PlainText]:this.getPlainTextContent(),[Is.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 o of t){e+=`<td style="${Li(Fi(o.style))}">`+GS(this.getters.getCellText(o.position))+"</td>"}e+="</tr>"}return e+="</table>",e}isColRowDirtyingClipboard(e,t){if(!this.zones)return!1;for(let o of this.zones){if("COL"===t&&e<=o.right)return!0;if("ROW"===t&&e<=o.bottom)return!0}return!1}drawClipboard(e){const{ctx:t,thinLineWidth:o}=e;if(this.sheetId===this.getters.getActiveSheetId()&&this.zones&&this.zones.length){t.setLineDash([8,5]),t.strokeStyle=E,t.lineWidth=3.3*o;for(const e of this.zones){const{x:o,y:i,width:s,height:n}=this.getters.getVisibleRect(e);s>0&&n>0&&t.strokeRect(o,i,s,n)}}}}class lE{operation;getters;dispatch;sheetId;copiedFigure;copiedFigureContent;constructor(e,t,o){this.operation=e,this.getters=t,this.dispatch=o,this.sheetId=t.getActiveSheetId();const i=t.getSelectedFigureId();if(!i)throw new Error("No figure selected");const s=t.getFigure(this.sheetId,i);if(!s)throw new Error(`No figure for the given id: ${i}`);switch(this.copiedFigure={...s},s.tag){case"chart":this.copiedFigureContent=new cE(o,t,this.sheetId,i);break;case"image":this.copiedFigureContent=new hE(o,t,this.sheetId,i);break;default:throw new Error(`Unknow tag '${s.tag}' for the given figure id: ${i}`)}}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0===e.length?74:void 0!==t?.pasteOption?22:0}paste(e){const t=this.getters.getActiveSheetId(),{width:o,height:i}=this.copiedFigure,s=this.getters.getNumberCols(t),n=this.getters.getNumberRows(t),r=this.getters.getColDimensions(t,e[0].left).start,a=this.getters.getRowDimensions(t,e[0].top).start,l=this.getters.getColDimensions(t,s-1).end,c=this.getters.getRowDimensions(t,n-1).end,h={x:l<o?0:Math.min(r,l-o),y:c<i?0:Math.min(a,c-i)},d=(new ti).uuidv4();this.copiedFigureContent.paste(t,d,h,{height:i,width:o}),"CUT"===this.operation&&this.dispatch("DELETE_FIGURE",{sheetId:this.copiedFigureContent.sheetId,id:this.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{id:d})}getClipboardContent(){return{[Is.PlainText]:"\t"}}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class cE{dispatch;sheetId;copiedChart;constructor(e,t,o,i){this.dispatch=e,this.sheetId=o;const s=t.getChart(i);if(!s)throw new Error(`No chart for the given id: ${i}`);this.copiedChart=s.copyInSheetId(o)}paste(e,t,o,i){const s=this.copiedChart.copyInSheetId(e);this.dispatch("CREATE_CHART",{id:t,sheetId:e,position:o,size:i,definition:s.getDefinition()})}}class hE{dispatch;sheetId;copiedImage;constructor(e,t,o,i){this.dispatch=e,this.sheetId=o;const s=t.getImage(i);this.copiedImage=Be(s)}paste(e,t,o,i){const s=Be(this.copiedImage);this.dispatch("CREATE_IMAGE",{figureId:t,sheetId:e,position:o,size:i,definition:s})}}class dE extends rE{values;constructor(e,t,o,i){super("COPY",t,o,i),this.values=e.replace(/\r/g,"").split("\n").map((e=>e.split("\t")))}isPasteAllowed(e,t){const o=this.getters.getActiveSheetId(),i=this.getPasteZone(e);return this.getters.doesIntersectMerge(o,i)?2:0}paste(e){const t=this.values,o=this.getPasteZone(e),{left:i,top:s}=o,{numberOfCols:n,numberOfRows:r}=vi(o),a=this.getters.getActiveSheetId();this.addMissingDimensions(n,r,i,s);for(let e=0;e<t.length;e++)for(let o=0;o<t[e].length;o++)this.dispatch("UPDATE_CELL",{row:s+e,col:i+o,content:t[e][o],sheetId:a});const l={left:i,top:s,right:i+n-1,bottom:s+r-1};this.selection.selectZone({cell:{col:i,row:s},zone:l})}getClipboardContent(){return{[Is.PlainText]:this.values.map((e=>e.join("\t"))).join("\n")}}getPasteZone(e){const t=this.values.length,o=Math.max(...this.values.map((e=>e.length))),{left:i,top:s}=e[0];return{top:s,left:i,bottom:s+t-1,right:i+o-1}}}function uE(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:o}=Yo(e.value),[i,s]=t.split(":"),n=o?`${$e(o)}!`:"",r=gE(i),a=s?`:${gE(s)}`:"";return{...e,value:n+r+a}}function gE(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=pE(e,"colrow");break;case"colrow":e=pE(e,"row");break;case"row":e=pE(e,"col");break;case"col":e=pE(e,"none")}return e}function pE(e,t){let o;switch(e=e.replace(/\$/g,""),t){case"col":return"$"+e;case"row":return o=e.search(/[0-9]/),e.slice(0,o)+"$"+e.slice(o);case"colrow":return o=e.search(/[0-9]/),-1===o||0===o?"$"+e:"$"+(e=e.slice(0,o)+"$"+e.slice(o));case"none":return e}}const mE=n("The cell you are trying to edit has been deleted.");const fE=[{name:n("Sum"),types:[ys.number],compute:e=>tc.compute([e])},{name:n("Avg"),types:[ys.number],compute:e=>uc.compute([e])},{name:n("Min"),types:[ys.number],compute:e=>Oc.compute([e])},{name:n("Max"),types:[ys.number],compute:e=>Ic.compute([e])},{name:n("Count"),types:[ys.number,ys.text,ys.boolean,ys.error],compute:e=>Cc.compute([e])},{name:n("Count Numbers"),types:[ys.number,ys.text,ys.boolean,ys.error],compute:e=>Sc.compute([e])}];const bE=(new zi).add("sheet",class extends IC{static 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","checkZonesExistInSheet","getCommandZones","checkElementsIncludeAllNonFrozenHeaders"];sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(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 Tt(e.elements)<0||Rt(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){for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let t of e.sheets){const e=t.name||s("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:o,rowNumber:i}=this.getImportedSheetSize(t),n={id:t.id,name:e,numberOfCols:o,rows:ei(i),areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0}};this.orderedSheetIds.push(n.id),this.sheets[n.id]=n}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(dt).map((e=>{const t=this.sheets[e],o={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)&&(o.panes=t.panes),o}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e){const t=He(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,o){return"COL"===t?o>=0&&o<this.getNumberCols(e):o>=0&&o<this.getNumberRows(e)}getRow(e,t){const o=this.getSheet(e).rows[t];if(!o)throw new Error(`Row ${o} not found.`);return o}getCell({sheetId:e,col:t,row:o}){const i=this.tryGetSheet(e)?.rows[o]?.cells[t];if(void 0!==i)return this.getters.getCellById(i)}getColsZone(e,t,o){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:o}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(dt)}getRowsZone(e,t,o){return{top:t,bottom:o,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 o=this.orderedSheetIds.map(this.getSheetName.bind(this));let i=`${e}${t}`;for(;o.includes(i);)i=`${e}${t}`,t++;return i}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,o){const i={...this.getPaneDivisions(e)};"COL"===o?i.xSplit=t:"ROW"===o&&(i.ySplit=t),this.history.update("sheets",e,"panes",i)}checkElementsIncludeAllNonFrozenHeaders(e,t,o){const i=this.getters.getPaneDivisions(e),s="ROW"===t?i.ySplit:i.xSplit,n=this.getters.getNumberHeaders(e,t);if(!s)return!1;return St(o,Ke(s,n))}isEmpty(e,t){return Ci(t).map((({col:t,row:o})=>this.getCell({sheetId:e,col:t,row:o}))).every((e=>!e||""===e.content))}getCommandZones(e){const t=[];return"zone"in e&&t.push(e.zone),"target"in e&&t.push(...e.target),"ranges"in e&&t.push(...e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone))),"col"in e&&"row"in e&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(si))return 25;if(t.length){const o=this.getSheetZone(e);return t.every((e=>mi(e,o)))?0:18}return 0}updateCellPosition(e){const{sheetId:t,cellId:o,col:i,row:s}=e;o?this.setNewPosition(o,t,i,s):this.clearPosition(t,i,s)}setNewPosition(e,t,o,i){const s=this.cellPosition[e];s&&this.clearPosition(t,s.col,s.row),this.history.update("cellPosition",e,{row:i,col:o,sheetId:t}),this.history.update("sheets",t,"rows",i,"cells",o,e)}clearPosition(e,t,o){const i=this.sheets[e]?.rows[o].cells[t];i&&(this.history.update("cellPosition",i,void 0),this.history.update("sheets",e,"rows",o,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++){this.sheets[e].rows[i].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:i})}}createSheet(e,t,o,i,s){const n={id:e,name:t,numberOfCols:o,rows:ei(i),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},r=this.orderedSheetIds.slice();r.splice(s,0,n.id);const a=this.sheets;return this.history.update("orderedSheetIds",r),this.history.update("sheets",Object.assign({},a,{[n.id]:n})),n}moveSheet(e,t){const o=this.orderedSheetIds.slice(),i=o.findIndex((t=>t===e)),s=o.splice(i,1);let n=this.findIndexOfTargetSheet(i,t);o.splice(n,0,s[0]),this.history.update("orderedSheetIds",o)}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(n("There is not enough visible sheets"))}checkSheetName(e){const{orderedSheetIds:t,sheets:o}=this,i=e.name&&e.name.trim().toLowerCase();return t.find((e=>o[e]?.name.toLowerCase()===i))?11:ce.test(i)?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 o of t)if(o.top<e.quantity&&e.quantity<=o.bottom)return 66;return 0}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let o of t)if(o.left<e.quantity&&e.quantity<=o.right)return 66;return 0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const o=e.name;this.history.update("sheets",e.id,"name",t.trim());const i=Object.assign({},this.sheetIdsMapName);i[t]=e.id,delete i[o],this.history.update("sheetIdsMapName",i)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t){const o=this.getSheet(e),i=this.getDuplicateSheetName(o.name),s=Be(o);s.id=t,s.name=i;for(let e=0;e<=s.numberOfCols;e++)for(let t=0;t<=s.rows.length;t++)s.rows[t]&&(s.rows[t].cells[e]=void 0);const n=this.orderedSheetIds.slice(),r=n.indexOf(e);n.splice(r+1,0,s.id),this.history.update("orderedSheetIds",n),this.history.update("sheets",Object.assign({},this.sheets,{[s.id]:s}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:o}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:s.id,col:e,row:o,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIdsMapName);a[s.name]=s.id,this.history.update("sheetIdsMapName",a)}getDuplicateSheetName(e){let t=1;const o=this.orderedSheetIds.map(this.getSheetName.bind(this)),i=n("Copy of %s",e);let s=i.toString();for(;o.includes(s);)s=`${i} (${t})`,t++;return s}deleteSheet(e){const t=e.name,o=Object.assign({},this.sheets);delete o[e.id],this.history.update("sheets",o);const i=this.orderedSheetIds.slice(),s=i.indexOf(e.id);i.splice(s,1),this.history.update("orderedSheetIds",i);const n=Object.assign({},this.sheetIdsMapName);delete n[t],this.history.update("sheetIdsMapName",n)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let o of t)this.moveCellOnColumnsDeletion(e,o);const o=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",o-t.length);const i=t.filter((t=>t<e.panes.xSplit)).length;i&&this.setPaneDivisions(e.id,e.panes.xSplit-i,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(let o of Qe(t)){const t=o[o.length-1],i=o[0];this.moveCellOnRowsDeletion(e,t,i),this.updateRowsStructureOnDeletion(e,t,i)}const o=t.filter((t=>t<e.panes.ySplit)).length;o&&this.setPaneDivisions(e.id,e.panes.ySplit-o,"ROW")}addColumns(e,t,o,i){const s="before"===o?t:t+1;this.moveCellsOnAddition(e,s,i,"columns");const n=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",n+i),s<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+i,"COL")}addRows(e,t,o,i){const s="before"===o?t:t+1;this.addEmptyRows(e,i),this.moveCellsOnAddition(e,s,i,"rows"),s<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+i,"ROW")}moveCellOnColumnsDeletion(e,t){for(let o=0;o<e.rows.length;o++){const i=e.rows[o];for(let s in i.cells){const n=Number(s),r=i.cells[s];r&&(n===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:n,row:o}),n>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:n-1,row:o}))}}}moveCellsOnAddition(e,t,o,i){const s=[];for(let n=0;n<e.rows.length;n++){const r=e.rows[n];if("rows"!==i||n>=t)for(let a in r.cells){const l=Number(a),c=r.cells[a];c&&("rows"===i||l>=t)&&s.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c,col:l+("columns"===i?o:0),row:n+("rows"===i?o:0)})}}for(let e of s.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,o){const i=o-t+1;for(let s=0;s<e.rows.length;s++){const n=e.rows[s];if(s>=t&&s<=o)for(let t in n.cells){const o=Number(t);n.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:o,row:s})}if(s>o)for(let t in n.cells){const o=Number(t),r=n.cells[t];r&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:o,row:s-i})}}}updateRowsStructureOnDeletion(e,t,o){const i=[],s=e.rows.map((e=>e.cells)).reverse();for(let n in e.rows){const e=Number(n);e>=t&&e<=o||i.push({cells:s.pop()})}this.history.update("sheets",e.id,"rows",i)}addEmptyRows(e,t){const o=e.rows.slice();for(let e=0;e<t;e++)o.push({cells:{}});this.history.update("sheets",e.id,"rows",o)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(qt);let o=e.rowNumber,i=e.colNumber;for(let{col:e,row:s}of t)o=Math.max(o,s+1),i=Math.max(i,e+1);return{rowNumber:o,colNumber:i}}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}checkZonesAreInSheet(e){return"sheetId"in e?this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):0}}).add("header visibility",class extends IC{static getters=["checkElementsIncludeAllVisibleHeaders","getHiddenColsGroups","getHiddenRowsGroups","isRowHiddenByUser","isColHiddenByUser"];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),o="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=o?67:Tt(e.elements)<0||Rt(e.elements)>o?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,Be(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 o of[...e.elements].sort(((e,t)=>t-e)))t.splice(o,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]],o=bt(e.position,e.base);t.splice(o,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,o){return St(o,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=[[]],o=this.hiddenHeaders[e].COL;for(let e=0;e<o.length;e++){o[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=[[]],o=this.hiddenHeaders[e].ROW;for(let e=0;e<o.length;e++){o[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 Ke(0,this.hiddenHeaders[e][t].length).filter((o=>!this.hiddenHeaders[e][t][o]))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=Boolean(t.rows[e]?.isHidden);for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=Boolean(t.cols[e]?.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let o of e.sheets){void 0===o.rows&&(o.rows={});for(let e=0;e<this.getters.getNumberRows(o.id);e++)(t||this.hiddenHeaders[o.id].ROW[e])&&(void 0===o.rows[e]&&(o.rows[e]={}),o.rows[e].isHidden=this.hiddenHeaders[o.id].ROW[e]);void 0===o.cols&&(o.cols={});for(let e=0;e<this.getters.getNumberCols(o.id);e++)(t||this.hiddenHeaders[o.id].COL[e])&&(void 0===o.cols[e]&&(o.cols[e]={}),o.cols[e].isHidden=this.hiddenHeaders[o.id].COL[e])}}}).add("filters",class extends IC{static getters=["doesZonesContainFilter","getFilter","getFilters","getFilterTable","getFilterTables","getFilterTablesInZone","getFilterId"];tables={};allowDispatch(e){switch(e.type){case"CREATE_FILTER_TABLE":if(!Ti(...e.target))return 82;const t=hi(...e.target),o=()=>this.getFilterTables(e.sheetId).some((e=>gi(e.zone,t)))?79:0,i=()=>{const o=this.getters.getMergesInZone(e.sheetId,t);for(let e of o)if(gi(t,e))return 81;return 0};return this.checkValidations(e,o,i);case"ADD_MERGE":for(let t of e.target)for(let o of this.getFilterTables(e.sheetId))if(gi(o.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 o={};for(const t of Object.values(this.tables[e.sheetId]||{}))if(t){const e=Be(t);o[e.id]=e}this.history.update("tables",e.sheetIdTo,o);break;case"ADD_COLUMNS_ROWS":this.onAddColumnsRows(e);break;case"REMOVE_COLUMNS_ROWS":this.onDeleteColumnsRows(e);break;case"CREATE_FILTER_TABLE":{const t=hi(...e.target),o=this.createFilterTable(t);this.history.update("tables",e.sheetId,o.id,o);break}case"REMOVE_FILTER_TABLE":{const t={};for(const o of this.getFilterTables(e.sheetId))e.target.every((e=>!di(e,o.zone)))&&(t[o.id]=o);this.history.update("tables",e.sheetId,t);break}case"UPDATE_CELL":{const t=e.sheetId;for(let o of this.getFilterTables(t))this.canUpdateCellCmdExtendTable(e,o)&&this.extendTableDown(t,o);break}}}getFilters(e){return this.getFilterTables(e).map((e=>e.filters)).flat()}getFilterTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(dt):[]}getFilter(e){return this.getFilterTable(e)?.filters.find((t=>t.col===e.col))}getFilterId(e){return this.getFilter(e)?.id}getFilterTable({sheetId:e,col:t,row:o}){return this.getFilterTables(e).find((e=>pi(t,o,e.zone)))}getFilterTablesInZone(e,t){return this.getFilterTables(e).filter((e=>mi(e.zone,t)))}doesZonesContainFilter(e,t){for(const o of t)for(const t of this.getFilterTables(e))if(di(o,t.zone))return!0;return!1}onAddColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const o=ri(t.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),i=[];for(const o of t.filters){const t=ri(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);i.push(new AC(o.id,t))}if(i.length<vi(o).numberOfCols){for(let e=o.left;e<=o.right;e++)i.find((t=>t.col===e))||i.push(new AC(this.uuidGenerator.uuidv4(),{...o,left:e,right:e}));i.sort(((e,t)=>e.col-t.col))}this.history.update("tables",e.sheetId,t.id,"zone",o),this.history.update("tables",e.sheetId,t.id,"filters",i)}}onDeleteColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){if("ROW"===e.dimension&&e.elements.includes(t.zone.top)){const o={...this.tables[e.sheetId]};delete o[t.id],this.history.update("tables",e.sheetId,o);continue}const o=ci(t.zone,"COL"===e.dimension?"left":"top",e.elements);if(o){if(ni(o)!==ni(t.zone)){const i=[];for(const o of t.filters){const t=ci(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.elements);t&&i.push(new AC(o.id,t))}this.history.update("tables",e.sheetId,t.id,"zone",o),this.history.update("tables",e.sheetId,t.id,"filters",i)}}else{const o={...this.tables[e.sheetId]};delete o[t.id],this.history.update("tables",e.sheetId,o)}}}createFilterTable(e){return new TC(e)}extendTableDown(e,t){const o={...t.zone,bottom:t.zone.bottom+1};this.history.update("tables",e,t.id,"zone",o);for(let o=0;o<t.filters.length;o++){const i=t.filters[o],s={...i.zoneWithHeaders,bottom:i.zoneWithHeaders.bottom+1};this.history.update("tables",e,t.id,"filters",o,"zoneWithHeaders",s)}}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:o,row:i},s){if(!e)return;const n=s.zone;if(!(n.bottom+1===i&&o>=n.left&&o<=n.right))return!1;for(const e of Ke(n.left,n.right+1)){const o={sheetId:t,col:e,row:i},s=this.getters.getCell(o)?.content;if(s)return!1;if(this.getters.getFilter(o))return!1;if(this.getters.isInMerge(o))return!1}return!0}import(e){for(const t of e.sheets)for(const e of t.filterTables||[]){const o=this.createFilterTable(ii(e.range));this.history.update("tables",t.id,o.id,o)}}export(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))t.filterTables.push({range:ni(e.zone)})}exportForExcel(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))1!==vi(e.zone).numberOfRows&&t.filterTables.push({range:ni(e.zone),filters:[]})}}).add("cell",class extends IC{static getters=["zoneToXC","getCells","getFormulaCellContent","getCellStyle","buildFormulaContent","getCellById"];nextId=1;cells={};adaptRanges(e,t){for(const o of Object.keys(this.cells))for(const i of Object.values(this.cells[o]||{}))if(i.isFormula)for(const s of i.dependencies)if(!t||s.sheetId===t){const t=e(s);"NONE"!==t.changeType&&this.history.update("cells",o,i.id,"dependencies",i.dependencies.indexOf(s),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case"CLEAR_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);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,o){for(let i of t)for(let t=i.top;t<=i.bottom;t++)for(let s=i.left;s<=i.right;s++)this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,format:o})}clearFormatting(e,t){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:null,format:""})}handleAddColumnsRows(e,t){let o,i;"before"===e.position?(o=Ke(e.base,e.base+e.quantity),i=e.base+e.quantity):(o=Ke(e.base+1,e.base+e.quantity+1),i=e.base),t(e.sheetId,i,o)}import(e){for(let t of e.sheets)for(let o in t.cells){const i=t.cells[o],{col:s,row:n}=qt(o);if(i?.content||i?.format||i?.style){const o=this.importCell(t.id,i,e.styles,e.formats);this.history.update("cells",t.id,o.id,o),this.dispatch("UPDATE_CELL_POSITION",{cellId:o.id,col:s,row:n,sheetId:t.id})}}}export(e){const t={},o={};for(let i of e.sheets){const e={},s=Object.keys(this.cells[i.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const i of s){const s=this.getters.getCell(i);e[Zt(i.col,i.row)]={style:s.style?gt(s.style,t):void 0,format:s.format?gt(s.format,o):void 0,content:s.content||void 0}}i.cells=e}e.styles=t,e.formats=o}importCell(e,t,o,i){const s=t.style&&o[t.style]||void 0,n=t.format&&i[t.format]||void 0,r=this.getNextUid();return this.createCell(r,t?.content||"",n,s,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,o,i=!1){const s=o||t.dependencies;let n=0;return pt(t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=s[n++];return this.getters.getRangeString(t,e,i)}return t.value})))}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,o=[{colFixed:!1,rowFixed:!1}]){const i=Zt((t=this.getters.expandZone(e,t)).left,t.top,o[0]),s=Zt(t.right,t.bottom,o.length>1?o[1]:o[0]),n=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),r=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=n.col===r.col&&n.row===r.row;return i==s||a?i:i+":"+s}setStyle(e,t,o){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let s=i.top;s<=i.bottom;s++){const i=this.getters.getCell({sheetId:e,col:t,row:s});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:s,style:o?{...i?.style,...o}:void 0})}}copyColumnStyle(e,t,o){for(let i=0;i<this.getters.getNumberRows(e);i++){const s=this.getFormat(e,t,i);if(s.style||s.format)for(let t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,...s})}}copyRowStyle(e,t,o){for(let i=0;i<this.getters.getNumberCols(e);i++){const s=this.getFormat(e,i,t);if(s.style||s.format)for(let t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:i,row:t,...s})}}getFormat(e,t,o){const i={},s=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),n=this.getters.getCell(s);return n&&(n.style&&(i.style=n.style),n.format&&(i.format=n.format)),i}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,o,i){const s=this.getters.getCell({sheetId:e,col:t,row:o}),n="content"in i||"formula"in i,r=n?It(i?.content):s?.content||"";let a;a=void 0!==i.style?i.style||void 0:s?s.style:void 0;const l="format"in i?i.format:s&&s.format;if((n&&!r&&!i.formula||!n&&(!s||""===s.content))&&!a&&!l)return void(s&&(this.history.update("cells",e,s.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:o,sheetId:e})));const c=s?.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:o,sheetId:e})}createCell(e,t,o,i,s){if(!t.startsWith("="))return this.createLiteralCell(e,t,o,i);try{return this.createFormulaCell(e,t,o,i,s)}catch(s){return this.createErrorFormula(e,t,o,i,s)}}createLiteralCell(e,t,o,i){return{id:e,content:t,style:i,format:o||Oo(t),isFormula:!1}}createFormulaCell(e,t,o,i,s){const n=rS(t);return n.dependencies.length?this.createFormulaCellWithDependencies(e,n,o,i,s):{id:e,content:t,style:i,format:o,isFormula:!0,compiledFormula:n,dependencies:[]}}createFormulaCellWithDependencies(e,t,o,i,s){const n=t.dependencies.map((e=>this.getters.getRangeFromSheetXC(s,e))),r=this.buildFormulaContent.bind(this);return{id:e,get content(){return r(s,{dependencies:this.dependencies,compiledFormula:this.compiledFormula})},style:i,format:o,isFormula:!0,compiledFormula:t,dependencies:n}}createErrorFormula(e,t,o,i,s){return{id:e,content:t,style:i,format:o,isFormula:!0,compiledFormula:{dependencies:[],tokens:xv(t),execute:function(){throw s}},dependencies:[]}}checkCellOutOfSheet(e){const{sheetId:t,col:o,row:i}=e;if(!this.getters.tryGetSheet(t))return 27;return pi(o,i,this.getters.getSheetZone(t))?0:18}checkUselessClearCell(e){const t=this.getters.getCell(e);return t&&(t.content||t.style||t.format)?0:94}checkUselessUpdateCell(e){const t=this.getters.getCell(e),o="style"in e,i="format"in e;return("content"in e||"formula"in e)&&t?.content!==e.content||o&&!vt(t?.style,e.style)||i&&t?.format!==e.format?0:94}}).add("merge",class extends IC{static getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge"];nextId=1;merges={};mergeCellMap={};allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return 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 o of Object.values(t).filter(dt))this.addMerge(e.sheetIdTo,o.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 o=t?[t]:Object.keys(this.merges);for(const t of o)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(dt)}getMerge({sheetId:e,col:t,row:o}){const i=this.mergeCellMap[e],s=i?t in i&&i[t]?.[o]:void 0;return s?this.getMergeById(e,s):void 0}getMergesInZone(e,t){const o=this.mergeCellMap[e];if(!o)return[];const i=new Set;for(const{col:e,row:s}of Ci(t)){const t=o[e]?.[s];t&&i.add(t)}return Array.from(i).map((t=>this.getMergeById(e,t))).filter(dt)}doesIntersectMerge(e,t){for(const o of this.getMerges(e))if(gi(t,o))return!0;return!1}doesColumnsHaveCommonMerges(e,t,o){const i=this.getters.getSheet(e);for(let s=0;s<this.getters.getNumberRows(e);s++)if(this.isInSameMerge(i.id,t,s,o,s))return!0;return!1}doesRowsHaveCommonMerges(e,t,o){const i=this.getters.getSheet(e);for(let s=0;s<=this.getters.getNumberCols(e);s++)if(this.isInSameMerge(i.id,s,t,s,o))return!0;return!1}expandZone(e,t){let{left:o,right:i,top:s,bottom:n}=t,r={left:o,right:i,top:s,bottom:n};for(let t in this.merges[e]){const o=this.getMergeById(e,parseInt(t));o&&gi(o,r)&&(r=hi(o,r))}return ui(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,o,i,s){const n=this.getMerge({sheetId:e,col:t,row:o}),r=this.getMerge({sheetId:e,col:i,row:s});return!(!n||!r)&&ui(n,r)}isInMerge({sheetId:e,col:t,row:o}){const i=this.mergeCellMap[e];return!!i&&(t in i&&Boolean(i[t]?.[o]))}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:o}=this.getMerge(e);return{sheetId:e.sheetId,col:o,row:t}}isMergeHidden(e,t){const o=this.getters.getHiddenColsGroups(e),i=this.getters.getHiddenRowsGroups(e);for(let e of o)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of i)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const o=this.getMerge({sheetId:e,col:t.left,row:t.top});if(o)return ui(t,o);const{numberOfCols:i,numberOfRows:s}=vi(t);return 1===i&&1===s}isMergeDestructive(e,t){let{left:o,right:i,top:s,bottom:n}=t;i=We(i,0,this.getters.getNumberCols(e)-1),n=We(n,0,this.getters.getNumberRows(e)-1);for(let t=s;t<=n;t++)for(let n=o;n<=i;n++)if(n!==o||t!==s){const o=this.getters.getCell({sheetId:e,col:n,row:t});if(o&&""!==o.content)return!0}return!1}getMergeById(e,t){const o=this.merges[e]?.[t];return void 0!==o?MC(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 o of e)if(t!==o&&gi(t,o))return 66;return 0}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;const{xSplit:o,ySplit:i}=this.getters.getPaneDivisions(e);for(const e of t)if(e.left<o&&e.right>=o||e.top<i&&e.bottom>=i)return 76;return 0}checkMergedContentUpdate(e){const{col:t,row:o,content:i}=e;if(void 0===i)return 0;const{col:s,row:n}=this.getMainCellPosition(e);return s===t&&n===o?0:4}checkMergeExists(e){const{sheetId:t,target:o}=e;for(const e of o){const{left:o,top:i}=e,s=this.getMerge({sheetId:t,col:o,row:i});if(void 0===s||!ui(e,s))return 5}return 0}addMerge(e,t){let{left:o,right:i,top:s,bottom:n}=t;i=We(i,0,this.getters.getNumberCols(e)-1),n=We(n,0,this.getters.getNumberRows(e)-1);if(Zt(o,s)===Zt(i,n))return;const r=this.getters.getCell({sheetId:e,col:o,row:s});let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,ni({left:o,top:s,right:i,bottom:n})));let l=new Set;for(let t=s;t<=n;t++)for(let n=o;n<=i;n++){n===o&&t===s||this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,style:r?r.style:null,content:""});const i=this.getMerge({sheetId:e,col:n,row:t});i&&l.add(i.id),this.history.update("mergeCellMap",e,n,t,a)}for(let t of l){const{top:o,bottom:i,left:s,right:n}=this.getMergeById(e,t);for(let t=o;t<=i;t++)for(let o=s;o<=n;o++){const i={sheetId:e,col:o,row:t},s=this.getMerge(i);s&&s.id===a||(this.history.update("mergeCellMap",e,o,t,void 0),this.dispatch("CLEAR_CELL",i))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:o,top:i,bottom:s,right:n}=t,r=this.getMerge({sheetId:e,col:o,row:i});if(void 0!==r&&ui(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=i;t<=s;t++)for(let i=o;i<=n;i++)this.history.update("mergeCellMap",e,i,t,void 0)}}applyRangeChangeOnSheet(e,t){const o=Object.entries(this.merges[e]||{});for(const[i,s]of o)if(s){const o=s.zone,n=t(s);switch(n.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,o);break;default:const{numberOfCols:t,numberOfRows:s}=vi(n.range.zone);1===t&&1===s?this.removeMerge(e,o):this.history.update("merges",e,parseInt(i,10),n.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:o,row:i}of Ci(t))this.history.update("mergeCellMap",e,o,i,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 o of t)this.addMerge(e,ii(o))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...OC(e))}}exportForExcel(e){this.export(e)}}).add("headerSize",class extends IC{static getters=["getRowSize","getColSize"];sizes={};handle(e){switch(e.type){case"CREATE_SHEET":{const t=this.computeSheetSizes(e.sheetId),o={COL:t.COL.map((e=>({manualSize:void 0,computedSize:mt(e)}))),ROW:t.ROW.map((e=>({manualSize:void 0,computedSize:mt(e)})))};this.history.update("sizes",e.sheetId,o);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,Be(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const t={...this.sizes};delete t[e.sheetId],this.history.update("sizes",t);break;case"REMOVE_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];for(let o of[...e.elements].sort(((e,t)=>t-e)))t.splice(o,1);const o=Tt(e.elements);t=t.map(((t,i)=>"ROW"===e.dimension&&i>=o?{manualSize:t.manualSize,computedSize:mt((()=>this.getRowTallestCellSize(e.sheetId,i)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];const o=bt(e.position,e.base),i=t[e.base],s=Ke(0,e.quantity).map((()=>({manualSize:i.manualSize,computedSize:mt(i.computedSize())})));t.splice(o,0,...s),t=t.map(((t,o)=>"ROW"===e.dimension&&o>e.base+e.quantity?{manualSize:t.manualSize,computedSize:mt((()=>this.getRowTallestCellSize(e.sheetId,o)))}: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 o=this.getRowTallestCellSize(e.sheetId,t);this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:mt(o)})}else this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:mt(e.size||L)});break;case"UPDATE_CELL":const o=this.sizes[e.sheetId]?.ROW?.[e.row];if(o&&!o.manualSize){const{sheetId:t,row:o}=e;this.history.update("sizes",t,"ROW",o,"computedSize",mt((()=>this.getRowTallestCellSize(t,o))))}break;case"ADD_MERGE":case"REMOVE_MERGE":for(let t of e.target)for(let o of Ke(t.top,t.bottom+1)){const t=this.getRowTallestCellSize(e.sheetId,o);t!==this.getRowSize(e.sheetId,o)&&this.history.update("sizes",e.sheetId,"ROW",o,"computedSize",mt(t))}}}getColSize(e,t){return this.getHeaderSize(e,"COL",t)}getRowSize(e,t){return this.getHeaderSize(e,"ROW",t)}getHeaderSize(e,t,o){return Math.round(this.sizes[e]?.[t][o]?.manualSize||this.sizes[e]?.[t][o]?.computedSize()||this.getDefaultHeaderSize(t))}computeSheetSizes(e){const t={COL:[],ROW:[]};for(let o of Ke(0,this.getters.getNumberCols(e)))t.COL.push(this.getHeaderSize(e,"COL",o));for(let o of Ke(0,this.getters.getNumberRows(e))){let i=this.sizes[e]?.ROW?.[o].manualSize;if(!i){i=this.getRowTallestCellSize(e,o)}t.ROW.push(i)}return t}getDefaultHeaderSize(e){return"COL"===e?L:k}getCellHeight(e){const t=this.getters.getMerge(e);if(t&&t.bottom!==t.top)return k;return function(e){return e&&e.content?Ge(Xe(e.style),e.isFormula?1:e.content.split(me).length)+2*H:k}(this.getters.getCell(e))}getRowTallestCellSize(e,t){const o=this.getters.getRowCells(e,t);let i=0;for(let e=0;e<o.length;e++){const t=this.getters.getCellById(o[e]);if(!t)continue;const s=this.getters.getCellPosition(t.id),n=this.getCellHeight(s);n>i&&n>k&&(i=n)}return i<=k?k:i}import(e){for(let t of e.sheets){const e={COL:[],ROW:[]};for(let[o,i]of Object.entries(t.rows))i.size&&(e.ROW[o]=i.size);for(let[o,i]of Object.entries(t.cols))i.size&&(e.COL[o]=i.size);const o=this.computeSheetSizes(t.id);this.sizes[t.id]={COL:o.COL.map(((t,o)=>({manualSize:e.COL[o],computedSize:mt(t)}))),ROW:o.ROW.map(((t,o)=>({manualSize:e.ROW[o],computedSize:mt(t)})))}}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let o of e.sheets){void 0===o.rows&&(o.rows={});for(let e of Ke(0,this.getters.getNumberRows(o.id)))(t||this.sizes[o.id].ROW[e]?.manualSize)&&(o.rows[e]={...o.rows[e],size:this.getRowSize(o.id,e)});void 0===o.cols&&(o.cols={});for(let e of Ke(0,this.getters.getNumberCols(o.id)))(t||this.sizes[o.id].COL[e]?.manualSize)&&(o.cols[e]={...o.cols[e],size:this.getColSize(o.id,e)})}}}).add("borders",class extends IC{static getters=["getCellBorder","getBordersColors"];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 o=t.slice().map((e=>e?.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,o)}break;case"DELETE_SHEET":const o={...this.borders};delete o[e.sheetId],this.history.update("borders",o);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_ZONE_BORDERS":if(e.border){const t=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));this.setBorders(e.sheetId,t,e.border.position,""===e.border.color?void 0:{style:e.border.style||X,color:e.border.color||K})}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":for(let t of[...e.elements].sort(((e,t)=>t-e)))"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,o;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,o=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,o)}handleAddRows(e){let t,o;"before"===e.position?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,o=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,o)}getCellBorder({sheetId:e,col:t,row:o}){const i={top:this.borders[e]?.[t]?.[o]?.horizontal,bottom:this.borders[e]?.[t]?.[o+1]?.horizontal,left:this.borders[e]?.[t]?.[o]?.vertical,right:this.borders[e]?.[t+1]?.[o]?.vertical};return i.bottom||i.left||i.right||i.top?i:null}getBordersColors(e){const t=[],o=this.borders[e];if(o)for(const e of o.filter(dt))for(const o of e)o?.horizontal&&t.push(o.horizontal.color),o?.vertical&&t.push(o.vertical.color);return t}ensureColumnBorderContinuity(e,t,o){const i=Ke(t+1,o);for(let s=0;s<this.getters.getNumberRows(e);s++){const n=this.getCellBorder({sheetId:e,col:t,row:s}),r=this.getCellBorder({sheetId:e,col:o,row:s});if(n&&r){const t=this.getCommonSides(n,r);for(let o of i)this.addBorder(e,o,s,t)}}}ensureRowBorderContinuity(e,t,o){const i=Ke(t+1,o);for(let s=0;s<this.getters.getNumberCols(e);s++){const n=this.getCellBorder({sheetId:e,col:s,row:t}),r=this.getCellBorder({sheetId:e,col:s,row:o});if(n&&r){const t=this.getCommonSides(n,r);for(let o of i)this.addBorder(e,s,o,t)}}}getCommonSides(e,t){const o={};for(let i of["top","bottom","left","right"])e[i]&&e[i]===t[i]&&(o[i]=e[i]);return o}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsRange(e){return this.borders[e]?Ke(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,o,{moveFirstLeftBorder:i}={}){this.borders[e]&&(o<0&&this.moveBordersOfColumn(e,t,o,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((s=>{(s===t&&i||s!==t)&&this.moveBordersOfColumn(e,s,o,"vertical"),this.moveBordersOfColumn(e,s,o,"horizontal")})))}shiftBordersVertically(e,t,o,{moveFirstTopBorder:i}={}){this.borders[e]&&(o<0&&this.moveBordersOfRow(e,t,o,"horizontal",{destructive:!1}),this.getRowsRange(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((s=>{(s===t&&i||s!==t)&&this.moveBordersOfRow(e,s,o,"horizontal"),this.moveBordersOfRow(e,s,o,"vertical")})))}moveBordersOfRow(e,t,o,i,{destructive:s}={destructive:!0}){const n=this.borders[e];n&&this.getColumnsWithBorders(e).forEach((r=>{const a=n[r]?.[t+o]?.[i],l=n[r]?.[t]?.[i];this.history.update("borders",e,r,t+o,i,s?l:l||a),this.history.update("borders",e,r,t,i,void 0)}))}moveBordersOfColumn(e,t,o,i,{destructive:s}={destructive:!0}){const n=this.borders[e];n&&this.getRowsRange(e).forEach((r=>{const a=n[t+o]?.[r]?.[i],l=n[t]?.[r]?.[i];this.history.update("borders",e,t+o,r,i,s?l:l||a),this.history.update("borders",e,t,r,i,void 0)}))}setBorder(e,t,o,i,s=!0){!s&&this.borders?.[e]?.[t]?.[o]?.vertical||this.history.update("borders",e,t,o,"vertical",i?.left),!s&&this.borders?.[e]?.[t]?.[o]?.horizontal||this.history.update("borders",e,t,o,"horizontal",i?.top),!s&&this.borders?.[e]?.[t+1]?.[o]?.vertical||this.history.update("borders",e,t+1,o,"vertical",i?.right),!s&&this.borders?.[e]?.[t]?.[o+1]?.horizontal||this.history.update("borders",e,t,o+1,"horizontal",i?.bottom)}clearBorders(e,t){for(let o of t){for(let t=o.top;t<=o.bottom;t++){this.history.update("borders",e,o.right+1,t,"vertical",void 0);for(let i=o.left;i<=o.right;i++)this.history.update("borders",e,i,t,void 0)}for(let t=o.left;t<=o.right;t++)this.history.update("borders",e,t,o.bottom+1,"horizontal",void 0)}}addBorder(e,t,o,i){this.setBorder(e,t,o,{...this.getCellBorder({sheetId:e,col:t,row:o}),...i})}setBorders(e,t,o,i){if("clear"===o)return this.clearBorders(e,t);for(let s of t){if("h"===o||"hv"===o||"all"===o)for(let t=s.top+1;t<=s.bottom;t++)for(let o=s.left;o<=s.right;o++)this.addBorder(e,o,t,{top:i});if("v"===o||"hv"===o||"all"===o)for(let t=s.top;t<=s.bottom;t++)for(let o=s.left+1;o<=s.right;o++)this.addBorder(e,o,t,{left:i});if("left"===o||"all"===o||"external"===o)for(let t=s.top;t<=s.bottom;t++)this.addBorder(e,s.left,t,{left:i});if("right"===o||"all"===o||"external"===o)for(let t=s.top;t<=s.bottom;t++)this.addBorder(e,s.right+1,t,{left:i});if("top"===o||"all"===o||"external"===o)for(let t=s.left;t<=s.right;t++)this.addBorder(e,t,s.top,{top:i});if("bottom"===o||"all"===o||"external"===o)for(let t=s.left;t<=s.right;t++)this.addBorder(e,t,s.bottom+1,{top:i})}}addBordersToMerge(e,t){const{left:o,right:i,top:s,bottom:n}=t,r=this.getCellBorder({sheetId:e,col:o,row:s}),a=this.getCellBorder({sheetId:e,col:i,row:n});this.clearBorders(e,[t]),r?.top&&this.setBorders(e,[{...t,bottom:s}],"top",r.top),r?.left&&this.setBorders(e,[{...t,right:o}],"left",r.left),a?.bottom?this.setBorders(e,[{...t,top:n}],"bottom",a.bottom):r?.bottom&&this.setBorders(e,[{...t,top:n}],"bottom",r.bottom),a?.right?this.setBorders(e,[{...t,left:i}],"right",a.right):r?.right&&this.setBorders(e,[{...t,left:i}],"right",r.right)}checkBordersUnchanged(e){const t=this.getCellBorder(e),o=!(e.border?.bottom||e.border?.left||e.border?.right||e.border?.top);return!t&&o||vt(t,e.border)?94:0}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(const o in t.cells){const i=t.cells[o];if(i?.border){const s=e.borders[i.border],{col:n,row:r}=qt(o);this.setBorder(t.id,n,r,s,!1)}}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,ii(e))}export(e){let t=0;const o={};function i(e){for(let[t,i]of Object.entries(o))if(vt(i,e))return parseInt(t,10);return o[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let o=0;o<t.rowNumber;o++){const s=this.getCellBorder({sheetId:t.id,col:e,row:o});if(s){const n=Zt(e,o),r=t.cells[n],a=i(s);r?r.border=a:t.cells[n]={border:a}}}e.borders=o}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends IC{static getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];cfRules={};loopThroughRangesOfSheet(e,t){for(const o of this.cfRules[e])for(const i of o.ranges){const s=t(i);switch(s.changeType){case"REMOVE":let t=o.ranges.slice();t.splice(o.ranges.indexOf(i),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",t):this.removeConditionalFormatting(o.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",o.ranges.indexOf(i),s.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 o={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(o,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){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,{useFixedReference:!0}))))}getConditionalFormats(e){return this.cfRules[e]?.map((t=>this.mapToConditionalFormat(e,t)))||[]}getRulesSelection(e,t){const o=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{o.add(e)}))})),Array.from(o)}getRulesByZone(e,t){const o=new Set;for(let i=t.top;i<=t.bottom;i++)for(let s=t.left;s<=t.right;s++){this.getRulesByCell(e,s,i).forEach((e=>{o.add(e.id)}))}return o}getRulesByCell(e,t,o){const i=[];for(let s of this.cfRules[e])for(let e of s.ranges)pi(t,o,e.zone)&&i.push(s);return new Set(i.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t,o={useFixedReference:!1}){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e,o.useFixedReference)))}}mapToConditionalFormatInternal(e,t){const o={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return o}addConditionalFormatting(e,t){const o=this.cfRules[t].slice(),i=o.findIndex((t=>t.id===e.id)),s=this.mapToConditionalFormatInternal(t,e);i>-1?o.splice(i,1,s):o.push(s),this.history.update("cfRules",t,o)}checkValidReordering(e,t,o){if(!this.cfRules[o])return 27;const i=this.cfRules[o].findIndex((t=>t.id===e));if(-1===i)return 72;const s="up"===t?i-1:i+1;return s<0||s>=this.cfRules[o].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 o=>{if(t.includes(o.operator)){const t=[],i=e=>void 0===e||""===e;return e>=1&&i(o.values[0])&&t.push(52),e>=2&&i(o.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{rS(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,o=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(o)?49:0}checkMinBiggerThanMax(e){const t=e.minimum.value,o=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&RC(t)>=RC(o)?48:0}checkMidBiggerThanMax(e){const t=e.midpoint?.value,o=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&RC(t)>=RC(o)?50:0}checkMinBiggerThanMid(e){const t=e.minimum.value,o=e.midpoint?.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&RC(t)>=RC(o)?51:0}removeConditionalFormatting(e,t){const o=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==o){const e=this.cfRules[t].slice();e.splice(o,1),this.history.update("cfRules",t,e)}}reorderConditionalFormatting(e,t,o){const i=this.cfRules[o].findIndex((t=>t.id===e)),s="up"===t?i-1:i+1;if(!(s<0||s>=this.cfRules[o].length)&&-1!==i&&-1!==s){const e=[...this.cfRules[o]],t=e[i];e[i]=e[s],e[s]=t,this.history.update("cfRules",o,e)}}}).add("figures",class extends IC{static getters=["getFigures","getFigure","getFigureSheetId"];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}}beforeHandle(e){if("DELETE_SHEET"===e.type)this.getters.getFigures(e.sheetId).forEach((t=>{this.dispatch("DELETE_FIGURE",{id:t.id,sheetId:e.sheetId})}))}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:o,...i}=e,s=i;this.updateFigure(o,s);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId);break;case"REMOVE_COLUMNS_ROWS":this.onRowColDelete(e.sheetId,e.dimension)}}onRowColDelete(e,t){"ROW"===t?this.onRowDeletion(e):this.onColDeletion(e)}onRowDeletion(e){const t=this.getters.getNumberRows(e);let o=0;for(let i=0;i<t;i++)o+=this.getters.getRowSize(e,i);const i=this.getters.getFigures(e);for(const t of i){const i=Math.min(t.y,o-t.height);i!==t.y&&this.dispatch("UPDATE_FIGURE",{sheetId:e,id:t.id,y:i})}}onColDeletion(e){const t=this.getters.getNumberCols(e);let o=0;for(let i=0;i<t;i++)o+=this.getters.getColSize(e,i);const i=this.getters.getFigures(e);for(const t of i){const i=Math.min(t.x,o-t.width);i!==t.x&&this.dispatch("UPDATE_FIGURE",{sheetId:e,id:t.id,x:i})}}updateFigure(e,t){if("id"in t)for(const[o,i]of Object.entries(t))switch(o){case"x":case"y":void 0!==i&&this.history.update("figures",e,t.id,o,Math.max(i,0));break;case"width":case"height":void 0!==i&&this.history.update("figures",e,t.id,o,i)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){return void 0===this.figures[e]?.[t]?71:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>t?.[e]))?83:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(dt)}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>void 0!==this.figures[t]?.[e]))}import(e){for(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 o=void 0;t.figures.push({...e,data:o})}}exportForExcel(e){this.export(e)}}).add("chart",class extends IC{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];charts={};createChart=function(e){const t=$r.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(o,i,s){const n=t.find((e=>e.match(i.type)));if(!n)throw new Error(`No builder for this chart: ${i.type}`);return n.createChart(i,s,e)}}(this.getters);validateChartDefinition=e=>function(e,t){const o=$r.getAll().find((e=>e.match(t.type)));if(!o)throw new Error("Unknown chart type.");return o.validateChartDefinition(e,t)}(this,e.definition);adaptRanges(e){for(const[t,o]of Object.entries(this.charts))this.history.update("charts",t,o?.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){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 t=this.getters.getFigures(e.sheetId);for(const o of t)if("chart"===o.tag){const t=o.id.split(ie).pop(),i=`${e.sheetIdTo}${ie}${t}`,s=this.charts[o.id]?.copyForSheetId(e.sheetIdTo);s&&this.dispatch("CREATE_CHART",{id:i,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){return this.charts[e]?.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){const t=this.charts[e]?.type;if(!t)throw new Error("Chart not defined.");return t}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter((([,t])=>t?.sheetId===e)).map((([e])=>e))}getChartDefinition(e){const t=this.charts[e]?.getDefinition();if(!t)throw new Error(`There is no chart with the given figureId: ${e}`);return t}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){if(e.sheets)for(let t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(let t of e){const e=t;if(e&&"chart"===e.tag){const t=this.charts[e.id]?.getDefinition();t&&(e.data=t,o.push(e))}else o.push(e)}t.figures=o}}exportForExcel(e){for(let t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(let t of e)if(t&&"chart"===t.tag){const e=this.charts[t.id]?.getDefinitionForExcel();e&&o.push({...t,data:e})}t.charts=o}}addFigure(e,t,o={x:0,y:0},i={width:536,height:335}){if(this.getters.getFigure(t,e))return;const s={id:e,x:o.x,y:o.y,width:i.width,height:i.height,tag:"chart"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:s})}addChart(e,t){const o=this.getters.getFigureSheetId(e);o&&this.history.update("charts",e,this.createChart(e,t,o))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?85:0}checkChartExists(e){return this.getters.getFigureSheetId(e.id)?0:86}}).add("image",class extends IC{static getters=["getImage","getImagePath","getImageSize"];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?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 o of t)if("image"===o.tag){const t=o.id.split(ie).pop(),i=`${e.sheetIdTo}${ie}${t}`,s=this.getImage(o.id);if(s){const t={width:o.width,height:o.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:i,position:{x:o.x,y:o.y},size:t,definition:Be(s)})}}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(){const e=new Set(this.getAllImages().map((e=>e.path)));for(const t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,o,i){const s={id:e,x:o.x,y:o.y,width:i.width,height:i.height,tag:"image"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:s})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter((e=>"image"===e.tag));for(const o of e)this.history.update("images",t.id,o.id,o.data),this.syncedImages.add(o.data.path)}}export(e){for(const t of e.sheets){const e=t.figures.filter((e=>"image"===e.tag));for(const o of e)o.data=this.images[t.id]?.[o.id]}}exportForExcel(e){for(const t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(const t of e)if("image"===t?.tag){const e=this.getImage(t.id);e&&o.push({...t,data:Be(e)})}t.images=o}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(dt));return e}}),vE=(new zi).add("ui_sheet",class extends _C{static getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getColDimensions","getRowDimensions","getColRowOffset"];ctx=document.createElement("canvas").getContext("2d");allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){const o=this.getColMaxWidth(e.sheetId,t);0!==o&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:o,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),o=this.getters.getCellComputedStyle(e),i=t.split(me);let s=Math.max(...i.map((e=>this.getTextWidth(e,o))));this.getters.getConditionalIcon(e)&&(s+=function(e){return Xe(e)+2*z}(this.getters.getCellStyle(e)));if(this.getters.isFilterHeader(e)&&(s+=20),s>0&&(s+=2*$,"wrap"===this.getters.getCellStyle(e).wrapping)){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,s)}return s}getTextWidth(e,t){return qe(this.ctx,e,t)}getCellText(e,t=!1){const o=this.getters.getCell(e);return t&&o?.isFormula?o.content:this.getters.getEvaluatedCell(e).formattedValue}getCellMultiLineText(e,t){const o=this.getters.getCellStyle(e),i=this.getters.getCellText(e,this.getters.shouldShowFormulas()),s=[];for(const e of i.split("\n")){const i=e.split(" ");if(!t){s.push(e);continue}let n="",r=t;for(let e of i){const i=this.splitWordToSpecificWidth(this.ctx,e,t,o),a=i.pop(),l=qe(this.ctx,a,o);if(i.length)""!==n&&(s.push(n),n="",r=t),i.forEach((e=>{s.push(e)})),n=a,r=t-l;else{const e=""===n?a:" "+a,i=qe(this.ctx,e,o);i<=r?(n+=e,r-=i):(s.push(n),n=a,r=t-l)}}""!==n&&s.push(n)}return s}getColDimensions(e,t){const o=this.getColRowOffset("COL",0,t,e),i=this.getters.getColSize(e,t);return{start:o,size:i,end:o+(this.getters.isColHidden(e,t)?0:i)}}getRowDimensions(e,t){const o=this.getColRowOffset("ROW",0,t,e),i=this.getters.getRowSize(e,t);return{start:o,size:i,end:o+(this.getters.isRowHidden(e,t)?0:i)}}getColRowOffset(e,t,o,i=this.getters.getActiveSheetId()){if(o<t)return-this.getColRowOffset(e,o,t);let s=0;for(let n=t;n<o;n++)this.getters.isHeaderHidden(i,e,n)||(s+="COL"===e?this.getters.getColSize(i,n):this.getters.getRowSize(i,n));return s}getColMaxWidth(e,t){const o=Ci(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,Rt(o))}splitWordToSpecificWidth(e,t,o,i){if(qe(e,t,i)<=o)return[t];const s=[];let n="";for(let r of t){qe(e,n+r,i)>o?(s.push(n),n=r):n+=r}return s.push(n),s}checkSheetExists(e){return"sheetId"in e&&void 0===this.getters.tryGetSheet(e.sheetId)?27:0}checkZonesAreInSheet(e){const t="sheetId"in e?e.sheetId:this.getters.tryGetActiveSheetId(),o=this.getters.getCommandZones(e);return!t&&o.length>0?93:t&&o.length>0?this.getters.checkZonesExistInSheet(t,o):0}}).add("header_visibility_ui",class extends _C{static getters=["getNextVisibleCellPosition","findVisibleHeader","findLastVisibleColRowIndex","findFirstVisibleColRowIndex","isRowHidden","isColHidden","isHeaderHidden"];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,o){return"COL"===t?this.isColHidden(e,o):this.isRowHidden(e,o)}getNextVisibleCellPosition({sheetId:e,col:t,row:o}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",o,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,o,i){if(o<=i)for(let s=o;s<=i;s++)if(this.getters.doesHeaderExist(e,t,s)&&!this.isHeaderHidden(e,t,s))return s;if(o>i)for(let s=o;s>=i;s--)if(this.getters.doesHeaderExist(e,t,s)&&!this.isHeaderHidden(e,t,s))return s}findLastVisibleColRowIndex(e,t,{last:o,first:i}){return Ke(o,i,-1).find((o=>!this.isHeaderHidden(e,t,o)))||i}findFirstVisibleColRowIndex(e,t){const o=this.getters.getNumberHeaders(e,t);for(let i=0;i<o;i++){if("COL"===t&&!this.isColHidden(e,i))return i;if("ROW"===t&&!this.isRowHidden(e,i))return i}}exportForExcel(e){for(const t of e.sheets)for(const[e,o]of Object.entries(t.rows)){const i=this.isRowHidden(t.id,Number(e));o.isHidden=i}}}).add("ui_options",class extends _C{static getters=["shouldShowFormulas"];showFormulas=!1;handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}).add("selectionInputManager",class extends _C{config;static layers=[1];static getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];inputs={};focusedInputId=null;get currentInput(){return this.focusedInputId?this.inputs[this.focusedInputId]:null}constructor(e){super(e),this.config=e}allowDispatch(e){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 t=this.currentInput?.getIndex(e.rangeId);if(this.focusedInputId===e.id&&this.currentInput?.focusedRangeIndex===t)return 29;break;case"ADD_EMPTY_RANGE":const o=this.inputs[e.id];if(o.inputHasSingleRange&&1===o.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){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:yi({col:0,row:0})},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}break;case"FOCUS_RANGE":case"CHANGE_RANGE":const t=this.inputs[e.id],o=t.ranges.find((t=>t.id===e.rangeId));if(o){const i=this.getters.getActiveSheetId(),s=this.getters.getRangeFromSheetXC(i,o?.xc||"A1").zone;this.selection.capture(t,{cell:{col:s.left,row:s.top},zone:s},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}}this.currentInput?.handle(e)}getSelectionInput(e){return this.inputs[e]?this.inputs[e].ranges.map(((t,o)=>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===o}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:o}=Yo(e);return null!==t.match($o)&&(!o||void 0!==this.getters.getSheetIdByName(o))}getSelectionInputValue(e){return this.inputs[e].getSelectionInputValue()}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].getSelectionInputHighlights():[]}initInput(e,t,o=!1){if(this.inputs[e]=new jC(this.config,t,o),0===t.length){const t=this.inputs[e],o={zone:yi({col:0,row:0}),cell:{col:0,row:0}};this.selection.capture(t,o,{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e}}unfocus(){this.selection.release(this.currentInput),this.focusedInputId=null}}).add("highlight",class extends _C{static layers=[1];static getters=["getHighlights"];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:o}=vi(e.zone),i=t*o==1?this.getters.expandZone(e.sheetId,e.zone):e.zone;return{...e,zone:i}}))}drawGrid(e){const{ctx:t,thinLineWidth:o}=e,i=this.getters.getActiveSheetId(),s=3*o;t.lineWidth=s;const n=this.getHighlights();for(let e of n.filter(((e,t)=>n.findIndex((t=>ui(t.zone,e.zone)&&t.sheetId===i))===t))){const{x:o,y:i,width:n,height:r}=this.getters.getVisibleRect(e.zone);n>0&&r>0&&(t.strokeStyle=e.color,t.strokeRect(o+s/2,i+s/2,n-s,r-s),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(o+s,i+s,n-2*s,r-2*s))}}}).add("grid renderer",class extends _C{static layers=[0,7];static getters=["getColDimensionsInViewport","getRowDimensionsInViewport"];boxes=[];getColDimensionsInViewport(e,t){const o=Tt(this.getters.getSheetViewVisibleCols()),i=this.getters.getColRowOffsetInViewport("COL",o,t),s=this.getters.getColSize(e,t);return{start:i,size:s,end:i+(this.getters.isColHidden(e,t)?0:s)}}getRowDimensionsInViewport(e,t){const o=Tt(this.getters.getSheetViewVisibleRows()),i=this.getters.getColRowOffsetInViewport("ROW",o,t),s=this.getters.getRowSize(e,t);return{start:i,size:s,end:i+(this.getters.isRowHidden(e,t)?0:s)}}getHeaderOffset(e,t,o){let i=this.getters.getColRowOffsetInViewport(e,t,o);return this.getters.isDashboard()||(i+="ROW"===e?F:D),i}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:o}=e,{width:i,height:s}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,i+m,s+m);const n=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),r=n?.1*o:0;if(n)for(const e of this.boxes)t.strokeStyle="#E2E3E3",t.lineWidth=o,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 o=e.style;o.fillColor&&"#ffffff"!==o.fillColor&&(t.fillStyle=o.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){const{ctx:t,thinLineWidth:o}=e;for(const e of this.boxes)if(e.content&&e.isOverflow){const i=e.content.align||"left";let s,n;const r=e.y+o/2,a=e.height-o,l=Math.min(e.clipRect?.width||1/0,e.content.width);"left"===i?(s=e.x+o/2,n=l-2*o):"right"===i?(s=e.x+e.width-o/2,n=2*o-l):(s=(e.clipRect?.x||e.x+e.width/2-e.content.width/2)+o/2,n=l-2*o),t.fillStyle="#ffffff",t.fillRect(s,r,n,a)}}drawBorders(e){const{ctx:t}=e;for(let e of this.boxes){const t=e.border;if(t){const{x:i,y:s,width:n,height:r}=e;t.left&&o(t.left,i,s,i,s+r),t.top&&o(t.top,i,s,i+n,s),t.right&&o(t.right,i+n,s,i+n,s+r),t.bottom&&o(t.bottom,i,s+r,i+n,s+r)}}function o({style:e,color:o},i,s,n,r){switch(t.strokeStyle=o,e){case"medium":t.lineWidth=2,s+=(i+=s===r?-.5:.5)===(n+=s===r?1.5:.5)?-.5:.5,r+=i===n?1.5:.5;break;case"thick":t.lineWidth=3,s===r&&(i--,n++),i===n&&(s--,r++);break;case"dashed":t.lineWidth=1,t.setLineDash([1,3]);break;case"dotted":t.lineWidth=1,s===r&&(i+=.5,n+=.5),i===n&&(s+=.5,r+=.5),t.setLineDash([1,1]);break;default:t.lineWidth=1}t.beginPath(),t.moveTo(i,s),t.lineTo(n,r),t.stroke(),t.lineWidth=1,t.setLineDash([])}}drawTexts(e){const{ctx:t,thinLineWidth:o}=e;let i;t.textBaseline="top";for(let e of this.boxes)if(e.content){const s=e.style||{},n=e.content.align||"left",r=Ye(s);r!==i&&(i=r,t.font=r),t.fillStyle=s.textColor||"#000";let a=e.x;if(a+="left"===n?B+(e.image?e.image.size+z:0):"right"===n?e.width-B-(e.isFilterHeader?20:0):e.width/2,t.textAlign=n,e.clipRect){t.save(),t.beginPath();const{x:o,y:i,width:s,height:n}=e.clipRect;t.rect(o,i,s,n),t.clip()}const l=Xe(s),c=e.content.textLines.length;let h=this.computeTextYCoordinate(e,l,c);for(let i of e.content.textLines){if(t.fillText(i,Math.round(a),Math.round(h)),s.strikethrough||s.underline){const e=qe(t,i,s);let r=a;"right"===n?r-=e:"center"===n&&(r-=e/2),s.strikethrough&&t.fillRect(r,h+l/2,e,2.6*o),s.underline&&t.fillRect(r,h+l+1,e,1.3*o)}h+=B+l}e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const o=e.image.image;if(e.image.clipIcon){t.save(),t.beginPath();const{x:o,y:i,width:s,height:n}=e.image.clipIcon;t.rect(o,i,s,n),t.clip()}const i=e.image.size,s=this.computeTextYCoordinate(e,i);t.drawImage(o,e.x+z,s,i,i),e.image.clipIcon&&t.restore()}}computeTextYCoordinate(e,t,o=1){const i=e.y+1,s=Ge(t,o),n=e.height>s+2*B,r=e.verticalAlign||Y;if(n){if("middle"===r)return i+(e.height-s)/2;if("bottom"===r)return i+e.height-s-B}return i+B}drawHeaders(e){const{ctx:t,thinLineWidth:o}=e,i=this.getters.getSheetViewVisibleCols(),s=i[0],n=i[i.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 o of e)for(let e of Ke(o.left,o.right+1))t.add(e);return t}(d),g=function(e){const t=new Set;for(let o of e)for(let e of Ke(o.top,o.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 ${j}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=o,t.strokeStyle="#333";for(let e=s;e<=n;e++){const o={left:e,right:e,top:0,bottom:f-1},{x:i,width:s}=this.getters.getVisibleRect(o),n=this.getters.doesZonesContainFilter(p,[o]),r=E.has(e),a=u.has(e);t.fillStyle=r?n?T:S:a?n?O:v:n?A:b,t.fillRect(i,0,s,F)}for(let e=a;e<=l;e++){const o={top:e,bottom:e,left:0,right:m-1},{y:i,height:s}=this.getters.getVisibleRect(o),n=this.getters.doesZonesContainFilter(p,[o]),r=w.has(e),a=g.has(e);t.fillStyle=r?n?T:S:a?n?O:v:n?A:b,t.fillRect(0,i,D,s)}t.beginPath(),t.moveTo(D,0),t.lineTo(D,h),t.moveTo(0,F),t.lineTo(c,F),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(const e of i){const o=this.getters.getColSize(p,e),i=Bt(e);t.fillStyle=E.has(e)?"#fff":C;let n=this.getHeaderOffset("COL",s,e);t.fillText(i,n+o/2,13),t.moveTo(n+o,0),t.lineTo(n+o,F)}for(const e of r){const o=this.getters.getRowSize(p,e);t.fillStyle=w.has(e)?"#fff":C;let i=this.getHeaderOffset("ROW",a,e);t.fillText(String(e+1),24,i+o/2),t.moveTo(0,i+o),t.lineTo(D,i+o)}t.stroke()}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:o}=e,{x:i,y:s}=this.getters.getMainViewportCoordinates(),n=this.getters.isDashboard()?0:D,r=this.getters.isDashboard()?0:F;t.lineWidth=6*o,t.strokeStyle="#BCBCBC",t.beginPath(),i&&(t.moveTo(n+i,0),t.lineTo(n+i,r)),s&&(t.moveTo(0,r+s),t.lineTo(n,r+s)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:o}=e,{x:i,y:s}=this.getters.getMainViewportCoordinates(),n=this.getters.getSheetViewVisibleCols(),r=n[0],a=n[n.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:r,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:D,u=this.getters.isDashboard()?0:F;t.lineWidth=6*o,t.strokeStyle="#DADFE8",t.beginPath(),i&&(t.moveTo(d+i,u),t.lineTo(d+i,h.height+u)),s&&(t.moveTo(d,u+s),t.lineTo(h.width+d,u+s)),t.stroke()}findNextEmptyCol(e,t,o){const i=this.getters.getActiveSheetId();let s=e;for(;s<t;){const e={sheetId:i,col:s+1,row:o},t=this.getters.getEvaluatedCell(e),n=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==ys.empty||this.getters.isInMerge(e)||n?.left)return s;s++}return s}findPreviousEmptyCol(e,t,o){const i=this.getters.getActiveSheetId();let s=e;for(;s>t;){const e={sheetId:i,col:s-1,row:o},t=this.getters.getEvaluatedCell(e),n=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==ys.empty||this.getters.isInMerge(e)||n?.right)return s;s--}return s}computeCellAlignment(e,t){if(this.getters.getCell(e)?.isFormula&&this.getters.shouldShowFormulas())return"left";const{align:o}=this.getters.getCellStyle(e),i=this.getters.getEvaluatedCell(e);return t&&i.type===ys.number?"center"!==o?"left":o:o||i.defaultAlign}createZoneBox(e,t,o){const{left:i,right:s}=o,n=t.left,r=t.top,a={sheetId:e,col:n,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===ys.empty)return f;const b=this.getters.getConditionalIcon(a),v=Xe(f.style),S=b?z+v:0;b&&(f.image={type:"icon",size:v,clipIcon:{x:f.x,y:f.y,width:Math.min(S,g),height:p},image:sf[b].img}),f.isFilterHeader=this.getters.isFilterHeader(a);const C=f.isFilterHeader?19:0,E=this.getters.getCellComputedStyle(a),w=E.wrapping||"overflow",x="wrap"!==w||h?void 0:g-2*B,y=this.getters.getCellMultiLineText(a,x),I=Math.max(...y.map((e=>this.getters.getTextWidth(e,E)+B))),R=S+I+C,T=this.computeCellAlignment(a,R>g);f.content={textLines:y,width:"overflow"===w?I:g,align:T},c.type===ys.error&&c.error.logLevel>l.silent&&(f.error=c.error.message);const A=R>g||v>p;if(b||f.isFilterHeader)f.clipRect={x:f.x+S,y:f.y,width:Math.max(0,g-S-C),height:p};else if(A&&"overflow"===w){let e,o;switch(this.getters.isInMerge(a)?(e=this.getters.getMerge(a).right,o=n):(e=this.findNextEmptyCol(n,s,r),o=this.findPreviousEmptyCol(n,i,r),f.isOverflow=!0),T){case"left":{const o=yi({col:e,row:r}),{x:i,y:s,width:n,height:a}=this.getters.getVisibleRect(hi(t,o));(n<R||v>a||y.length>1)&&(f.clipRect={x:i,y:s,width:n,height:a});break}case"right":{const e=yi({col:o,row:r}),{x:i,y:s,width:n,height:a}=this.getters.getVisibleRect(hi(t,e));(n<R||v>a||y.length>1)&&(f.clipRect={x:i,y:s,width:n,height:a});break}case"center":{const i={...t,left:o,right:e},{x:s,y:n,height:r,width:a}=this.getters.getVisibleRect(i),l=R/2,c=f.x+f.width/2;if(s+a<c+l||s>c-l||v>r||y.length>1){const e=s>c-l?s:c-l,t=s+a-e;f.clipRect={x:e,y:n,width:t,height:r}}break}}}else("clip"===w||"wrap"===w||y.length>1)&&(f.clipRect={x:f.x,y:f.y,width:g,height:p});return f}getGridBoxes(){const e=[],t=this.getters.getSheetViewVisibleCols(),o=t[0],i=t[t.length-1],s=this.getters.getSheetViewVisibleRows(),n={left:o,right:i,top:s[0],bottom:s[s.length-1]},r=this.getters.getActiveSheetId();for(const o of s)for(const i of t){const t={sheetId:r,col:i,row:o};this.getters.isInMerge(t)||e.push(this.createZoneBox(r,yi(t),n))}for(const t of this.getters.getMerges(r))if(!this.getters.isMergeHidden(r,t)&&gi(t,n)){const o=this.createZoneBox(r,t,n),i=this.getters.getCellBorder({sheetId:r,col:t.right,row:t.bottom});o.border={...o.border,bottom:i?i.bottom:void 0,right:i?i.right:void 0},o.isMerge=!0,e.push(o)}return e}}).add("autofill",class extends _C{static layers=[5];static getters=["getAutofillTooltip"];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case"AUTOFILL_SELECT":const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:We(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:We(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:46;case"AUTOFILL_AUTO":const o=this.getters.getSelectedZone();return o.top===o.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(),o=this.autofillZone;switch(this.direction){case"down":for(let i=t.left;i<=t.right;i++){const s=[];for(let e=t.top;e<=t.bottom;e++)s.push(Zt(i,e));const n=this.createGenerator(s);for(let t=o.top;t<=o.bottom;t++)this.computeNewCell(n,i,t,e)}break;case"up":for(let i=t.left;i<=t.right;i++){const s=[];for(let e=t.bottom;e>=t.top;e--)s.push(Zt(i,e));const n=this.createGenerator(s);for(let t=o.bottom;t>=o.top;t--)this.computeNewCell(n,i,t,e)}break;case"left":for(let i=t.top;i<=t.bottom;i++){const s=[];for(let e=t.right;e>=t.left;e--)s.push(Zt(e,i));const n=this.createGenerator(s);for(let t=o.right;t>=o.left;t--)this.computeNewCell(n,t,i,e)}break;case"right":for(let i=t.top;i<=t.bottom;i++){const s=[];for(let e=t.left;e<=t.right;e++)s.push(Zt(e,i));const n=this.createGenerator(s);for(let t=o.left;t<=o.right;t++)this.computeNewCell(n,t,i,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 o=this.getters.getSelectedZone();if(pi(e,t,o))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,o.top-1,o.left,o.right),this.steps=o.top-t;break;case"down":this.saveZone(o.bottom+1,t,o.left,o.right),this.steps=t-o.bottom;break;case"left":this.saveZone(o.top,o.bottom,e,o.left-1),this.steps=o.left-e;break;case"right":this.saveZone(o.top,o.bottom,o.right+1,e),this.steps=e-o.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let o=e.left,i=e.bottom;if(o>0){let e={sheetId:t,col:o-1,row:i};for(;this.getters.getCell(e)?.content;)i+=1,e={sheetId:t,col:o-1,row:i}}if(i===e.bottom&&(o=e.right,o<=this.getters.getNumberCols(t))){let e={sheetId:t,col:o+1,row:i};for(;this.getters.getCell(e)?.content;)i+=1,e={sheetId:t,col:o+1,row:i}}i!==e.bottom&&(this.select(e.left,i-1),this.autofill(!0))}computeNewCell(e,t,o,i){const{cellData:s,tooltip:n,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=s;this.tooltip=n,i&&this.dispatch("AUTOFILL_CELL",{originCol:r.col,originRow:r.row,col:t,row:o,content:a,style:l,border:c,format:h})}getRule(e,t){const o=Gs.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((o=>o.condition(e,t)));return o&&o.generateRule(e,t)}createGenerator(e){const t=[],o=[],i=this.getters.getActiveSheetId();for(let t of e){const{col:e,row:s}=qt(t),n=this.getters.getCell({sheetId:i,col:e,row:s});o.push({col:e,row:s,cell:n,sheetId:i})}const s=o.map((e=>e.cell));for(let e of o){let o={type:"COPY_MODIFIER"};if(e&&e.cell){o=this.getRule(e.cell,s)||o}const i=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:i},rule:o})}return new LC(t,this.getters,this.direction)}saveZone(e,t,o,i){this.autofillZone={top:e,bottom:t,left:o,right:i}}getDirection(e,t){const o=this.getters.getSelectedZone(),i={up:{number:o.top-t,value:"up"},down:{number:t-o.bottom,value:"down"},left:{number:o.left-e,value:"left"},right:{number:e-o.right,value:"right"}};if(1===Object.values(i).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(i).find((e=>e.number>0?1:0)).value;const s=i.up.number>0?"up":"down",n=i.left.number>0?"left":"right";return Math.abs(i[s].number)>=Math.abs(i[n].number)?i[s].value:i[n].value}autoFillMerge(e,t,o,i){const s=this.getters.getActiveSheetId(),n={sheetId:s,col:o,row:i},r={sheetId:s,col:e,row:t};if(this.getters.isInMerge(n)&&!this.getters.isInMerge(r)){const e=this.getters.getMerge(n);e&&this.dispatch("REMOVE_MERGE",{sheetId:s,target:[e]})}const a=this.getters.getMerge(r);a?.topLeft.col===e&&a?.topLeft.row===t&&this.dispatch("ADD_MERGE",{sheetId:s,target:[{top:i,bottom:i+a.bottom-a.top,left:o,right:o+a.right-a.left}]})}drawGrid(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:o}=e,{x:i,y:s,width:n,height:r}=this.getters.getVisibleRect(this.autofillZone);n>0&&r>0&&(t.strokeStyle="black",t.lineWidth=o,t.setLineDash([3]),t.strokeRect(i,s,n,r),t.setLineDash([]))}}).add("find_and_replace",class extends _C{static layers=[3];static getters=["getSearchMatches","getCurrentSelectedMatchIndex"];searchMatches=[];selectedMatchIndex=null;currentSearchRegex=null;searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1};toSearch="";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(ZC.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(ZC.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(ZC.current)}updateRegex(){let e=ze(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),o=[];if(this.toSearch)for(const i of Object.values(t)){const{col:t,row:s}=this.getters.getCellPosition(i.id),n=this.getters.isColHidden(e,t),r=this.getters.isRowHidden(e,s);if(!n&&!r&&(i&&this.currentSearchRegex&&this.currentSearchRegex.test(this.getSearchableString({sheetId:e,col:t,row:s})))){const e={col:t,row:s,selected:!1};o.push(e)}}return o.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 o;o=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,o=(o%t.length+t.length)%t.length,this.selectedMatchIndex=o,this.selection.selectCell(t[o].col,t[o].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 o=this.getters.getActiveSheetId(),i=this.getters.getCell({sheetId:o,...e}),{col:s,row:n}=e;if(i?.isFormula&&!this.searchOptions.searchFormulas)return;const r=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),a=this.getSearchableString({sheetId:o,col:s,row:n}).replace(r,t);this.dispatch("UPDATE_CELL",{sheetId:o,col:s,row:n,content:a})}replace(e){if(null===this.selectedMatchIndex)return;const t=this.searchMatches[this.selectedMatchIndex];this.replaceMatch(t,e),this.selectNextCell(ZC.next)}replaceAll(e){const t=this.searchMatches.length;for(let o=0;o<t;o++)this.replaceMatch(this.searchMatches[o],e)}getSearchableString(e){const t=this.getters.getCell(e);return this.searchOptions.searchFormulas&&t?.isFormula?t.content:this.getters.getEvaluatedCell(e).formattedValue}drawGrid(e){const{ctx:t}=e,o=this.getters.getActiveSheetId();for(const e of this.searchMatches){const i=this.getters.getMerge({sheetId:o,col:e.col,row:e.row}),s=i?i.left:e.col,n=i?i.right:e.col,r=i?i.top:e.row,a=i?i.bottom:e.row,{x:l,y:c,width:h,height:d}=this.getters.getVisibleRect({top:r,left:s,right:n,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)))}}}).add("sort",class extends _C{static getters=["getContiguousZone"];allowDispatch(e){if("SORT_CELLS"===e.type){if(!pi(e.col,e.row,e.zone))throw new Error(n("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 Ci(t).some((({col:t,row:o})=>!this.getters.isInMerge({sheetId:e,col:t,row:o})))?64:0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const o=this.getters.getMerges(e).filter((e=>gi(e,t))),i=vi(o[0]);let[s,n]=[i.numberOfCols,i.numberOfRows];return o.every((e=>{let[t,o]=[e.right-e.left+1,e.bottom-e.top+1];return t===s&&o===n}))?0:64}expand(e,t){const{left:o,right:i,top:s,bottom:n}=this.getters.expandZone(e,t);return{left:Math.max(0,o),right:Math.min(this.getters.getNumberCols(e)-1,i),top:Math.max(0,s),bottom:Math.min(this.getters.getNumberRows(e)-1,n)}}checkExpandedValues(e,t){const o=this.expand(e,t);let i;if(this.getters.doesIntersectMerge(e,o)){const{left:t,right:s,top:n,bottom:r}=o;for(let o=t;o<=s;o++)for(let t=n;t<=r;t++){const{col:s,row:n}=this.getters.getMainCellPosition({sheetId:e,col:o,row:t});if(i=this.getters.getEvaluatedCell({sheetId:e,col:s,row:n}),i.formattedValue)return!0}}else for(let t of this.getters.getEvaluatedCellsInZone(e,o))if(t.formattedValue)return!0;return!1}getContiguousZone(e,t){let o,{top:i,bottom:s,left:n,right:r}=t,a=!1;for(;!a;)a=!0,i>0&&(o=this.checkExpandedValues(e,{left:n-1,right:r+1,top:i-1,bottom:i-1}),o&&(a=!1,i--)),n>0&&(o=this.checkExpandedValues(e,{left:n-1,right:n-1,top:i-1,bottom:s+1}),o&&(a=!1,n--)),r<this.getters.getNumberCols(e)-1&&(o=this.checkExpandedValues(e,{left:r+1,right:r+1,top:i-1,bottom:s+1}),o&&(a=!1,r++)),s<this.getters.getNumberRows(e)-1&&(o=this.checkExpandedValues(e,{left:n-1,right:r+1,top:s+1,bottom:s+1}),o&&(a=!1,s++));return{left:n,right:r,top:i,bottom:s}}hasHeader(e,t){if(1===t[0].length)return!1;let o=t.map((t=>t.map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).type))));return o[0][0]===ys.empty&&(o=o.slice(1)),!o.some((e=>e[0]===ys.empty))&&!!o.some((e=>e[1]!==ys.empty&&e[0]!==e[1]))}sortZone(e,t,o,i,s){const[n,r]=this.mainCellsSteps(e,o);let a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},o),c=this.mainCells(e,o);!s.sortHeaders&&this.hasHeader(e,c)&&(l.top+=r),c=this.mainCells(e,l);const h=function(e,t,o){const i=e.map(((e,t)=>({index:t,type:e.type,value:e.value})));let s=i.filter((e=>e.type===ys.empty)),n=i.filter((e=>e.type!==ys.empty));o&&(n.push(...s.map((e=>({...e,type:ys.number,value:0})))),s=[]);const r="descending"===t?-1:1;return n.sort(((e,t)=>{let o=sa.indexOf(e.type)-sa.indexOf(t.type);return 0===o&&(o=e.type===ys.text||e.type===ys.error?e.value.localeCompare(t.value):e.value-t.value),r*o})).concat(s)}(c[a-l.left].map((e=>this.getters.getEvaluatedCell(e))),i,Boolean(s.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:o,row:i,sheetId:s}=c[e][d[t]];const a=this.getters.getCell({sheetId:s,col:o,row:i});let h=l.left+e*n,u=l.top+t*r,g={sheetId:s,col:h,row:u,content:""};if(a){let e=a.content;if(a.isFormula){const t=u-this.getters.getCellPosition(a.id).row,o=this.getters.createAdaptedRanges(a.dependencies,0,t,s);e=this.getters.buildFormulaContent(s,a,o)}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 o=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[o?o.right-o.left+1:1,o?o.bottom-o.top+1:1]}mainCells(e,t){const[o,i]=this.mainCellsSteps(e,t),s=[],n=Ke(t.left,t.right+1,o),r=Ke(t.top,t.bottom+1,i);for(const t of n){const o=[];s.push(o);for(const i of r)o.push({sheetId:e,col:t,row:i})}return s}}).add("automatic_sum",class extends _C{static getters=["getAutomaticSums"];handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:o}=this.getters.getSelection();for(const i of t){const t=this.getAutomaticSums(e,i,o.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,o){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,o):this.sumData(e,t)}sumData(e,t){const o=this.dimensionsToSum(e,t),i=this.sumDimensions(e,t,o).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return o.has("ROW")&&o.has("COL")&&i.push(this.sumTotal(t)),i}sumAdjacentData(e,t,o){const{col:i,row:s}=pi(o.col,o.row,t)?o:{col:t.left,row:t.top},n=this.findAdjacentData(e,i,s);return n?this.getters.isSingleCellOrMerge(e,t)||Si(hi(n,t))?[{position:{col:i,row:s},zone:n}]:this.sumDimensions(e,hi(n,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,o){const i=this.getters.getSheet(e),s=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),n=this.findSuitableZoneToSum(i,s.col,s.row);if(n)return this.getters.expandZone(e,n)}findSuitableZoneToSum(e,t,o){const i=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:o-1}),s=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:o});if(this.isNumber(s)&&!this.isNumber(i))return this.findHorizontalZone(e,t,o);const n=this.findVerticalZone(e,t,o);if(this.isZoneValid(n))return n;const r=this.findHorizontalZone(e,t,o);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,o){const i={top:0,bottom:o-1,left:t,right:t},s=this.reduceZoneStart(e,i,i.bottom);return{...i,top:s}}findHorizontalZone(e,t,o){const i={top:o,bottom:o,left:0,right:t-1},s=this.reduceZoneStart(e,i,i.right);return{...i,left:s}}reduceZoneStart(e,t,o){const i=this.getters.getEvaluatedCellsInZone(e.id,t),s=Ke(o,-1,-1),n=Rt(s.filter((e=>i[e]&&!i[e].isAutoSummable))),r=Qe(s.filter((e=>this.isNumber(i[e]))))[0]||[];return Rt(r)<n?1/0:Tt(r)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===ys.number&&!(e.format&&xo(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){const o=new Set;return Si(t)?(o.add(1===vi(t).numberOfCols?"COL":"ROW"),o):(this.lastColIsEmpty(e,t)&&o.add("ROW"),this.lastRowIsEmpty(e,t)&&o.add("COL"),0===o.size&&o.add("COL"),o)}sumDimensions(e,t,o){return[...o.has("COL")?this.sumColumns(t,e):[],...o.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:o}=e;return{position:{col:o,row:t},zone:{...e,top:t,right:o-1}}}sumColumns(e,t){const o=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,o.bottom-1)},Ci(o).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const o=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,o.right-1)},Ci(o).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const o of t){const{col:t,row:i}=o.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,content:`=SUM(${this.getters.zoneToXC(e,o.zone)})`})}}nextEmptyRow(e,t){let o=t.bottom+1;const{left:i,right:s}=t;for(;!this.getters.isEmpty(e,{bottom:o,top:o,left:i,right:s});)o++;return{...t,top:o,bottom:o}}nextEmptyCol(e,t){let o=t.right+1;const{top:i,bottom:s}=t;for(;!this.getters.isEmpty(e,{left:o,right:o,top:i,bottom:s});)o++;return{...t,left:o,right:o}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}).add("format",class extends _C{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,o){for(const i of t)for(const t of Ci(i)){const i=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==i){const s=No(i,o);this.dispatch("SET_FORMATTING",{sheetId:e,target:[yi(t)],format:s})}}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==ys.number||e.format&&xo(e.format)))return e.format||Ao(e.value)}}}).add("split_to_columns",class extends _C{static getters=["getAutomaticSeparator"];allowDispatch(e){return"SPLIT_TEXT_INTO_COLUMNS"===e.type?this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e):0}handle(e){if("SPLIT_TEXT_INTO_COLUMNS"===e.type)this.splitIntoColumns(e)}getAutomaticSeparator(){const e=this.getters.getSelectedCells();for(const t of e)if(t.value&&t.type===ys.text){const e=this.getAutoSeparatorForString(t.value);if(e)return e}return" "}getAutoSeparatorForString(e){const t=[me,";",","," ","."];for(const o of t)if(e.includes(o))return o}splitIntoColumns({separator:e,addNewColumns:t}){const o=this.getters.getSelectedZone(),i=this.getters.getActiveSheetId(),s=this.getSplittedCols(o,e);t&&this.addColsToAvoidCollisions(o,s),this.removeMergesInSplitZone(o,s),this.addColumnsToNotOverflowSheet(o,s);for(let e=0;e<s.length;e++){const t=o.top+e,n=s[e],r=o.left,a=this.getters.getCell({sheetId:i,col:r,row:t});if(1!==n.length||n[0]!==a?.content)for(const[e,o]of n.entries())this.dispatch("UPDATE_CELL",{sheetId:i,col:r+e,row:t,content:o,format:"",style:a?.style||null})}}getSplittedCols(e,t){if(!t)throw new Error("Separator cannot be empty");const o=this.getters.getActiveSheetId(),i=[];for(const s of Ke(e.top,e.bottom+1)){const n=this.getters.getEvaluatedCell({sheetId:o,col:e.left,row:s}).formattedValue;i.push(this.splitAndRemoveTrailingEmpty(n,t))}return i}splitAndRemoveTrailingEmpty(e,t){const o=e.split(t);for(;o.length>1&&""===o[o.length-1];)o.pop();return o}willSplittedColsOverwriteContent(e,t){const o=this.getters.getActiveSheetId();for(const i of Ke(e.top,e.bottom+1)){const s=t[i-e.top];for(let t=1;t<s.length;t++){const s=this.getters.getCell({sheetId:o,col:e.left+t,row:i});if(s&&s.content)return!0}}return!1}removeMergesInSplitZone(e,t){const o=this.getters.getActiveSheetId(),i=Math.max(...t.map((e=>e.length))),s={...e,right:e.left+i-1},n=this.getters.getMergesInZone(o,s);this.dispatch("REMOVE_MERGE",{sheetId:o,target:n})}addColsToAvoidCollisions(e,t){const o=this.getters.getActiveSheetId();let i=0;for(const s of Ke(e.top,e.bottom+1)){const n={sheetId:o,col:e.left,row:s},r=t[s-e.top],a=this.getColsToAddToAvoidCollision(n,r);i=Math.max(i,a)}i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:e.left,sheetId:o,quantity:i,position:"after"})}getColsToAddToAvoidCollision(e,t){const o=t.length;for(let t=1;t<o;t++){const i=e.col+t,s=this.getters.getCell({...e,col:i});if(s&&s.content)return o-t}return 0}addColumnsToNotOverflowSheet(e,t){const o=this.getters.getActiveSheetId(),i=Math.max(...t.map((e=>e.length-1))),s=this.getters.getNumberCols(o)-1;e.left+i>s&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:s,sheetId:o,quantity:e.left+i-s,position:"after"})}checkSingleColSelected(){return this.getters.isSingleColSelected()?0:89}checkNonEmptySelector(e){return""===e.separator?90:0}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return 0;const t=this.getters.getSelectedZones()[0],o=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,o)?91:0}checkSeparatorInSelection({separator:e}){const t=this.getters.getSelectedCells();for(const o of t)if(o.formattedValue.includes(e))return 0;return 92}}).add("cell_popovers",class extends _C{static getters=["getCellPopover","getPersistentPopoverTypeAtPosition","hasOpenedPopover"];persistentPopover;allowDispatch(e){if("OPEN_CELL_POPOVER"===e.type){try{Vn.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}){const o=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=Vn.get(this.persistentPopover.type).onOpen?.(e,this.getters);return t?.isOpen?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}if(void 0===e||void 0===t||!this.getters.isVisibleInViewport({sheetId:o,col:e,row:t}))return{isOpen:!1};const i=this.getters.getMainCellPosition({sheetId:o,col:e,row:t}),s=Vn.getAll().map((e=>e.onHover?.(i,this.getters))).find((e=>e?.isOpen));return s?.isOpen?{...s,anchorRect:this.computePopoverAnchorRect(i)}:{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 o=this.getters.getActiveSheetId(),i=this.getters.getMerge({sheetId:o,col:e,row:t});return i?this.getters.getVisibleRect(i):this.getters.getVisibleRect(yi({col:e,row:t}))}}).add("collaborative",class extends _C{static getters=["getClientsToDisplay","getClient","getConnectedClients","isFullySynchronized"];static layers=[6];availableColors=new Set(qC);colors={};session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}chooseNewColor(){0===this.availableColors.size&&(this.availableColors=new Set(qC));const e=(t=[...this.availableColors.values()])[Math.floor(Math.random()*t.length)];var t;return this.availableColors.delete(e),e}getClient(){return this.session.getClient()}getConnectedClients(){return this.session.getConnectedClients()}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof WC)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const o of this.getters.getConnectedClients())if(o.id!==this.getters.getClient().id&&o.position&&o.position.sheetId===e&&this.isPositionValid(o.position)){const e=o.position;this.colors[o.id]||(this.colors[o.id]=this.chooseNewColor());const i=this.colors[o.id];t.push({...o,position:e,color:i})}return t}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,i=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:s,col:n}=e.position,r=this.getters.expandZone(i,{top:s,bottom:s,left:n,right:n}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);if(c<=0||h<=0)continue;const d=e.color,u=`${d}10`;t.fillStyle=u,t.lineWidth=4*o,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 ${Z+1}px ${j}`}}}).add("history",class extends _C{static getters=["canUndo","canRedo"];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on("new-local-state-update",this,this.onNewLocalStateUpdate),this.session.on("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}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();if(t)"UNDO"===e?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t));else{const e=this.getPossibleRevisionToRepeat();if(!e)return;const t=nE(e,this.getters);if(!t)return;if(!Array.isArray(t))return void this.dispatch(t.type,t);for(const e of t)this.dispatch(e.type,e)}}canUndo(){return this.undoStack.length>0}canRedo(){if(this.redoStack.length>0)return!0;const e=this.getPossibleRevisionToRepeat();return!(!(t=e)||!t.rootCommand||"object"!=typeof t.rootCommand)&&(Ms(t.rootCommand)?tE.contains(t.rootCommand.type):oE.contains(t.rootCommand.type));var t}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()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision(["REQUEST_REDO"])}}),SE=(new zi).add("selection",class extends _C{static layers=[6];static getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getSelectedCells","getStatisticFnResults","getAggregate","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSelected","isSingleColSelected","getElementsFromSelection","tryGetActiveSheetId","isGridSelectionActive"];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;activeSheet=null;constructor(e){super(e),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 o=[];switch(e.mode){case"overrideSelection":o=[t.zone];break;case"updateAnchor":o=[...this.gridSelection.zones];const i=o.findIndex((t=>ui(t,e.previousAnchor.zone)));i>=0&&(o[i]=t.zone);break;case"newAnchor":o=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,o),this.selection.resetDefaultAnchor(this,Be(this.gridSelection.anchor));const{col:i,row:s}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:i,row:s}),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:o,row:i}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(o,i),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:Be(this.gridSelection)},e.sheetIdTo in this.sheetsData)Object.assign(this,this.sheetsData[e.sheetIdTo]),this.selection.resetDefaultAnchor(this,Be(this.gridSelection.anchor));else{const{col:t,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0});this.selectCell(t,o)}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:o,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:i})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:o,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:i})}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 s=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of s)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:Be(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:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:o})}const n=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(n,e))),this.gridSelection.anchor.zone=this.getters.expandZone(n,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null}this.selection.resetDefaultAnchor(this,Be(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}tryGetActiveSheetId(){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 o=t.left;o<=t.right;o++)e.add(o);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(let o of this.gridSelection.zones)if(0===o.left&&o.right===this.getters.getNumberCols(t)-1)for(let t=o.top;t<=o.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 Be(this.gridSelection.zones)}getSelectedZone(){return Be(this.gridSelection.anchor.zone)}getSelection(){return Be(this.gridSelection)}getSelectedCells(){const e=this.getters.getActiveSheetId(),t=[];for(const o of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,o));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{const t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}getStatisticFnResults(){const e=this.getters.getActiveSheetId(),t=new Set;for(const o of this.gridSelection.zones)for(const{col:i,row:s}of Ci(o)){if(this.getters.isRowHidden(e,s)||this.getters.isColHidden(e,i))continue;const o=this.getters.getEvaluatedCell({sheetId:e,col:i,row:s});o.type!==ys.empty&&t.add(o)}let o=new Set,i=[];for(let e of t)o.add(e.type),i.push(e.value);let s={};for(let e of fE){let t;e.types.some((e=>o.has(e)))&&(t=e.compute(i)),s[e.name]=t}return s}getAggregate(){let e=0,t=0;const o=this.getters.getActiveSheetId(),i=this.gridSelection.zones.map(Ci).flat();for(const{col:s,row:n}of i){const i=this.getters.getEvaluatedCell({sheetId:o,col:s,row:n});i.type===ys.number&&(t++,e+=i.value)}return t<2?null:bo(e)}isSelected(e){return!!this.getters.getSelectedZones().find((t=>ui(t,e)))}isSingleColSelected(){const e=this.getters.getSelectedZones();return 1===e.length&&e[0].left===e[0].right}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let o=[];const i="COL"===e?"left":"top",s="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[s]-e[i]+1},((t,o)=>e[i]+o));o=o.concat(t)}return[...new Set(o)].sort()}setSelectionMixin(e,t){const{anchor:o,zones:i}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=o,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,o)=>t===o.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(i)}selectCell(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.expandZone(o,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:i,cell:{col:e,row:t}},[i])}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){const t=this.getters.getSheetIds(),o=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[o]})}onColumnsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,i=li(o,"left",[...e.elements]);let s={left:t.col,right:t.col,top:t.row,bottom:t.row};s=li(s,"left",[...e.elements]);const n={cell:{col:s.left,row:s.top},zone:i},r=this.gridSelection.zones.map((t=>li(t,"left",[...e.elements])));this.setSelectionMixin(n,r)}onRowsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,i=li(o,"top",[...e.elements]);let s={left:t.col,right:t.col,top:t.row,bottom:t.row};s=li(s,"top",[...e.elements]);const n={cell:{col:s.left,row:s.top},zone:i},r=this.gridSelection.zones.map((t=>li(t,"top",[...e.elements])));this.setSelectionMixin(n,r)}onAddElements(e){const t="COL"===e.dimension?"left":"top",o=ai(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),i=this.gridSelection.zones.map((o=>ai(o,t,e.base,e.position,e.quantity))),s={cell:{col:o.left,row:o.top},zone:o};this.setSelectionMixin(s,i)}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 o="COL"===e.dimension,i=e.elements[0],s=e.elements[t-1],n=e.base<i,r=n&&o?t:0,a=n&&!o?t:0,l=[{left:o?i+r:0,right:o?s+r:this.getters.getNumberCols(e.sheetId)-1,top:o?0:i+a,bottom:o?this.getters.getNumberRows(e.sheetId)-1:s+a}],c=new aE(l,"CUT",this.getters,this.dispatch,this.selection),h=n?e.base:e.base+1,d=[{left:o?h:0,right:o?h+t-1:this.getters.getNumberCols(e.sheetId)-1,top:o?0:h,bottom:o?this.getters.getNumberRows(e.sheetId)-1:h+t-1}];c.paste(d,{selectTarget:!0});const u=n?e.elements.map((e=>e+t)):e.elements;let g=e.base;for(const t of u){const o="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:o,elements:[g]}),g+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:u})}isMoveElementAllowed(e){const t="COL"===e.dimension,o=e.elements[0],i=e.elements[e.elements.length-1],s=e.sheetId,n=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(n(s,o-1,o)||n(s,i,i+1)||n(s,e.base-1,e.base))return 2;const r=[e.base,...e.elements],a=t?this.getters.getNumberCols(s):this.getters.getNumberRows(s);return r.some((e=>e<0||e>=a))?87:0}clipSelection(e,t){const o=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:We(e.left,0,o),right:We(e.right,0,o),top:We(e.top,0,i),bottom:We(e.bottom,0,i)}))),anchor:{cell:{col:We(t.anchor.cell.col,0,o),row:We(t.anchor.cell.row,0,i)},zone:{left:We(t.anchor.zone.left,0,o),right:We(t.anchor.zone.right,0,o),top:We(t.anchor.zone.top,0,i),bottom:We(t.anchor.zone.bottom,0,i)}}}}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,i=this.getSelectedZones();t.fillStyle="#f3f7fe";const s=1===i.length&&i[0].left===i[0].right&&i[0].top===i[0].bottom;t.fillStyle=s?"#f3f7fe":"#e9f0ff",t.strokeStyle=E,t.lineWidth=1.5*o;for(const e of i){const{x:o,y:i,width:s,height:n}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(o,i,s,n),t.globalCompositeOperation="source-over",t.strokeRect(o,i,s,n)}t.globalCompositeOperation="source-over";const n=this.getActivePosition();let r;t.strokeStyle=E,t.lineWidth=3*o,r=this.getters.isInMerge(n)?this.getters.getMerge(n):yi(n);const{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);c>0&&h>0&&t.strokeRect(a,l,c,h)}}).add("clipboard",class extends _C{static layers=[2];static getters=["getClipboardContent","getClipboardTextContent","isCutOperation","isPaintingFormat"];status="invisible";state;lastPasteState;_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 o=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);return this.state.isPasteAllowed(e.target,{pasteOption:o});case"PASTE_FROM_OS_CLIPBOARD":return new dE(e.text,this.getters,this.dispatch,this.selection).isPasteAllowed(e.target);case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(o)}case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(o)}}return 0}handle(e){switch(e.type){case"COPY":case"CUT":const t=this.getters.getSelectedZones();this.state=this.getClipboardState(t,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const o=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1,this.state.paste(e.target,{pasteOption:o,shouldPasteCF:!0,selectTarget:!0}),"CUT"===this.state.operation&&(this.state=void 0),this.lastPasteState=this.state,this.status="invisible";break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!si(t[0])){for(const{col:t,row:o}of Ci(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:o,sheetId:this.getters.getActiveSheetId()});break}this.getClipboardStateForCopyCells(t,"CUT").paste(o);break}case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension);this.getClipboardStateForCopyCells(t,"CUT").paste(o);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==this.state?.operation||e.sheetId!==this.state?.sheetId)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"!==this.state?.operation||e.sheetId!==this.state?.sheetId)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":this.state=new dE(e.text,this.getters,this.dispatch,this.selection),this.state.paste(e.target),this.lastPasteState=this.state,this.status="invisible";break;case"REPEAT_PASTE":this.lastPasteState?.paste(e.target,{pasteOption:e.pasteOption,shouldPasteCF:!0,selectTarget:!0});break;case"ACTIVATE_PAINT_FORMAT":{const e=this.getters.getSelectedZones();this.state=this.getClipboardStateForCopyCells(e,"COPY"),this._isPaintingFormat=!0,this.status="visible";break}default:Ms(e)&&(this.status="invisible")}}getClipboardContent(){return this.state?.getClipboardContent()||{[Is.PlainText]:"\t"}}getClipboardTextContent(){return this.state?.getClipboardContent()[Is.PlainText]||"\t"}isCutOperation(){return!!this.state&&"CUT"===this.state.operation}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const o=this.getters.getActiveSheetId();let i;return i="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(o)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1},{cut:[i],paste:[e]}}getInsertCellsTargets(e,t){const o=this.getters.getActiveSheetId();let i,s;return"COL"===t?(i={...e,right:this.getters.getNumberCols(o)-1},s={...e,left:e.right+1,right:e.right+1}):(i={...e,bottom:this.getters.getNumberRows(o)-1},s={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1}),{cut:[i],paste:[s]}}getClipboardStateForCopyCells(e,t){return new aE(e,t,this.getters,this.dispatch,this.selection)}getClipboardState(e,t){return this.getters.getSelectedFigureId()?new lE(t,this.getters,this.dispatch):new aE(e,t,this.getters,this.dispatch,this.selection)}drawGrid(e){"visible"===this.status&&this.state&&this.state.drawClipboard(e)}}).add("edition",class extends _C{static getters=["getEditionMode","isSelectingForComposer","showSelectionIndicator","getCurrentContent","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights","getCurrentEditedCell"];col=0;row=0;mode="inactive";sheetId="";currentContent="";currentTokens=[];selectionStart=0;selectionEnd=0;selectionInitialStart=0;initialContent="";previousRef="";previousRange=void 0;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),o=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((e=>{const{xc:o,sheetName:i}=Yo(e.value),s=i||this.getters.getSheetName(this.sheetId),n=this.getters.getActiveSheetId();if(this.getters.getSheetName(n)!==s)return!1;const r=this.getters.getRangeFromSheetXC(n,o);return ui(this.getters.expandZone(n,r.zone),t.zone)}));this.previousRef=o.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=o.start;break;case"CHANGE_HIGHLIGHT":const i=this.getters.getRangeFromRangeData(e.range),s=this.getRangeReference(i,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(s),this.previousRef=s,this.selectionStart=this.currentContent.length,this.selectionEnd=this.currentContent.length;break;case"ACTIVATE_SHEET":if(this.currentContent.startsWith("=")||(this.cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){const t=this.getters.getActivePosition(),{col:o,row:i}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),s=this.getters.expandZone(e.sheetIdTo,yi({col:o,row:i}));this.selection.resetAnchor(this,{cell:{col:o,row:i},zone:s})}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:mE}));break;case"CYCLE_EDITION_REFERENCES":this.cycleReferences()}}getEditionMode(){return this.mode}getCurrentContent(){return"inactive"===this.mode?this.getComposerContent(this.getters.getActivePosition()):this.currentContent}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((o=>o.start<=e&&o.end>=t))}cycleReferences(){const e=this.getTokensInSelection(),t=e.filter((e=>"REFERENCE"===e.type));if(0===t.length)return;const o=e.map(uE).map((e=>e.value)).join(""),i=this.currentContent,s=e[0].start,n=e[e.length-1].end,r=i.slice(0,s)+o+i.slice(n),a=r.length-i.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,o){return t>=0&&t<=e&&o>=0&&o<=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:mE});const{top:t,left:o}=li({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=o,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:mE});const{top:t,left:o}=li({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=o,this.row=t}onAddElements(e){const{top:t,left:o}=ai({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=o,this.row=t}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=yi({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){const o=this.getters.getActiveCell();e&&o.format?.includes("%")&&so(e)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const{col:i,row:s,sheetId:n}=this.getters.getActivePosition();this.col=i,this.sheetId=n,this.row=s,this.initialContent=this.getComposerContent({sheetId:n,col:i,row:s}),this.mode="editing",this.setContent(e||this.initialContent,t),this.colorIndexByRange={};const r=yi({col:this.col,row:this.row});this.selection.capture(this,{cell:{col:this.col,row:this.row},zone:r},{handleEvent:this.handleEvent.bind(this),release:()=>{this.stopEdition()}})}stopEdition(){if("inactive"!==this.mode){this.cancelEditionAndActivateSheet();const e=this.col,t=this.row;let o=this.currentContent;if(!(this.initialContent!==o))return;if(o){const i=this.getters.getActiveSheetId(),s=this.getters.getEvaluatedCell({sheetId:i,col:this.col,row:this.row});if(o.startsWith("=")){const e=this.currentTokens.filter((e=>"LEFT_PAREN"===e.type)).length,t=this.currentTokens.filter((e=>"RIGHT_PAREN"===e.type)).length,i=e-t;i>0&&(o+=pt(new Array(i).fill(")")))}else s.link&&(o=nt(o,s.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,col:e,row:t,content:o})}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(t?.isFormula)return t.content;const{format:o,value:i,type:s,formattedValue:n}=this.getters.getEvaluatedCell(e);switch(s){case ys.text:case ys.empty:return i;case ys.boolean:return n;case ys.error:return t?.content||"";case ys.number:return o&&xo(o)?n:this.numberComposerContent(i,o)}}numberComposerContent(e,t){return t?.includes("%")?100*e+"%":function(e){const{integerDigits:t,decimalDigits:o}=Co(e,20);return o?`${t}.${o}`:t}(e)}cancelEdition(){"inactive"!==this.mode&&(this.mode="inactive",this.selection.release(this))}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,o){const i=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(i||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?aS(e):[],this.currentTokens.length>100&&o&&this.ui.notifyUI({type:"ERROR",text:n("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),o=this.getZoneReference(e);this.canStartComposerRangeSelection()?(this.insertText(o,t),this.selectionInitialStart=t):(this.insertText(","+o,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 o=this.getters.getActiveSheetId();let i=this.getters.zoneToXC(o,e,t);if(this.getters.getCurrentEditedCell()?.sheetId!==this.getters.getActiveSheetId()){i=`${$e(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${i}`}return i}getRangeReference(e,t=[{colFixed:!1,rowFixed:!1}]){let o=[...t];1===t.length&&Ri(e.zone)>1?o.push({...t[0]}):2===t.length&&1===Ri(e.zone)&&o.pop();const i=e.clone({parts:o});return this.getters.getSelectionRangeString(i,this.getters.getCurrentEditedCell()?.sheetId||this.getters.getActiveSheetId())}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),o=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,o)}replaceText(e,t,o){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(o,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const o=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),i=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:o,selection:{start:i,end:i}})}updateRangeColor(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return;const e=this.getters.getCurrentEditedCell()?.sheetId||this.getters.getActiveSheetId(),t=this.getReferencedRanges().map((t=>this.getters.getRangeString(t,e))),o={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(o[e]=this.colorIndexByRange[e]);const i=new Set(Object.values(o));let s=0;const n=()=>{for(;i.has(s);)s++;return i.add(s),s};for(const e of t){const t=e in o?o[e]:n();o[e]=t}this.colorIndexByRange=o}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=this.getters.getCurrentEditedCell()?.sheetId||this.getters.getActiveSheetId(),t=e=>{const t=this.colorIndexByRange[e];return Mt[t%Mt.length]};return this.getReferencedRanges().map((o=>{const i=this.getters.getRangeString(o,e);return{zone:o.zone,color:t(i),sheetId:o.sheetId}}))}getReferencedRanges(){const e=this.getters.getCurrentEditedCell()?.sheetId||this.getters.getActiveSheetId();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 o=t,i=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(i.type)||Ev.includes(i.value);){if("SPACE"!==i.type||o<1)return!1;o--,i=this.currentTokens[o]}for(o=t+1,i=this.currentTokens[o];i&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(i.type);){if("SPACE"!==i.type)return!1;o++,i=this.currentTokens[o]}return!0}return!1}getTokensInSelection(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return this.currentTokens.filter((o=>o.start<=e&&o.end>=e||o.start>=e&&o.start<t))}}),CE=(new zi).add("evaluation",class extends _C{static getters=["evaluateFormula","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getColEvaluatedCells","getEvaluatedCellsInZone"];isUpToDate=!1;evaluatedCells={};evalContext;lazyEvaluation;constructor(e){super(e),this.evalContext=e.custom,this.lazyEvaluation=e.lazyEvaluation}handle(e){switch(Rs.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 o=rS(e),i=this.getCompilationParameters((e=>this.getEvaluatedCell(this.getters.getCellPosition(e.id)))),s=[];for(let e of o.dependencies)s.push(this.getters.getRangeFromSheetXC(t,e));return o.execute(s,...i).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:o}){return void 0===this.getters.getCell({sheetId:e,col:t,row:o})?Us(""):this.evaluatedCells[e]?.[t]?.[o]?.()||Us("")}getEvaluatedCells(e){const t=this.getters.getCells(e)||{},o={};for(let e of Object.keys(t)){const t=this.getters.getCellPosition(e);o[e]=this.getEvaluatedCell(t)}return o}getColEvaluatedCells(e,t){return Object.values(this.evaluatedCells[e]?.[t]||[]).filter(dt).map((e=>e()))}getEvaluatedCellsInZone(e,t){return Ci(t).map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o})))}setEvaluatedCell(e,t){const{col:o,row:i,sheetId:s}=this.getters.getCellPosition(e);this.evaluatedCells[s]||(this.evaluatedCells[s]={}),this.evaluatedCells[s][o]||(this.evaluatedCells[s][o]={}),this.evaluatedCells[s][o][i]=t,this.lazyEvaluation||this.evaluatedCells[s][o][i]()}*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=>{const t=e.id,{col:s,row:n,sheetId:r}=this.getters.getCellPosition(t),a=this.evaluatedCells[r]?.[s]?.[n];return a||mt((()=>{try{switch(e.isFormula){case!0:return i(e);case!1:return ks(e.content,e.format)}}catch(t){return o(t,e)}}))},o=(e,t)=>{e instanceof Error||(e=new Error(e));const o=e?.errorType||a.GenericError,i=s[2].__lastFnCalled||"",n=new c(o,e.message.replace("[[FUNCTION_NAME]]",i),void 0!==e.logLevel?e.logLevel:l.error);return Hs(t.content,n)},i=t=>{const o=t.id;if(e.has(o))throw new d;s[2].__originCellXC=()=>{const e=s[2].getters.getCellPosition(o);return Zt(e.col,e.row)},e.add(o);const i=t.compiledFormula.execute(t.dependencies,...s);if(e.delete(o),Array.isArray(i.value))throw new Error(n("This formula depends on invalid values"));return Us(i.value,t.format||i.format)},s=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(FC),this.evalContext,{getters:this.getters}),o=this.getters;const i=t=>{const o=e(t);if(o.type===ys.error)throw o.error;return o},s={};function r(e){if(!si(e.zone))throw new u;if(e.invalidSheetName)throw new Error(n("Invalid sheet name: %s",e.invalidSheetName))}return[function(e,t,s,a){if(r(e),t)return{value:ni(e.zone)};if(e.zone.bottom!==e.zone.top||e.zone.left!==e.zone.right)throw new Error(a?n("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",s.toString(),a.toString()):n("Function %s expects its parameters to be single values or single cell references, not ranges.",s.toString()));return function(e){let t;if(!o.tryGetSheet(e.sheetId))throw new Error(n("Invalid sheet name"));return t=o.getCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}),t&&""!==t.content?i(t):{value:null,format:t?.format}}(e)},function(e){r(e);const n=e.sheetId,a=o.getSheetZone(n),l=di(e.zone,a);if(!l)return[[]];const{top:c,left:h,bottom:d,right:u}=l,g=`${n}-${c}-${h}-${d}-${u}`;if(g in s)return s[g];const p=new Array(u-h+1);for(let o=h;o<=u;o++){const s=new Array(d-c+1);for(let n=c;n<=d;n++){const r=t.getters.getCell({sheetId:e.sheetId,col:o,row:n});s[n-c]=r?i(r):void 0}p[o-h]=s}return s[g]=p,p},t]}exportForExcel(e){for(let t of e.sheets)for(const e in t.cells){const o={sheetId:t.id,...qt(e)},i=this.getters.getCell(o);if(i){const s=t.cells[e],n=this.getEvaluatedCell(o);s.value=n.value,s.isFormula=i.isFormula&&!this.isBadExpression(i.content),i.format!==n.format&&(s.computedFormat=n.format),i.isFormula&&i.dependencies.length&&(s.content=this.getters.buildFormulaContent(t.id,i,i.dependencies,!0))}}}isBadExpression(e){try{return rS(e),!1}catch(e){return!0}}}).add("evaluation_filter",class extends _C{static getters=["getCellBorderWithFilterBorder","getFilterHeaders","getFilterValues","isFilterHeader","isRowFiltered","isFilterActive"];filterValues={};hiddenRows=new Set;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 o of this.getters.getFilters(e.sheetIdTo)){const i=o.zoneWithHeaders;t[o.id]=this.getFilterValues({sheetId:e.sheetId,col:i.left,row:i.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:o,row:i}=e;let s;for(let e of this.getters.getFilterTables(t)){const n=e.zone;if(pi(o,i,n)){const e=this.intersectZoneWithViewport(t,n);s={top:i===e.top?Q:void 0,bottom:i===e.bottom?Q:void 0,left:o===e.left?Q:void 0,right:o===e.right?Q:void 0}}}const n=this.getters.getCellBorder(e),r={...s,...Ct(n||{})};return ut(r)?null:r}getFilterHeaders(e){const t=[];for(let o of this.getters.getFilterTables(e)){const i=o.zone;if(!i)continue;const s=i.top;for(let o=i.left;o<=i.right;o++)this.getters.isColHidden(e,o)||this.getters.isRowHidden(e,s)||t.push({col:o,row:s})}return t}getFilterValues(e){const t=this.getters.getFilterId(e),o=e.sheetId;return t&&this.filterValues[o]&&this.filterValues[o][t]||[]}isFilterHeader({sheetId:e,col:t,row:o}){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===o))}isFilterActive(e){const t=this.getters.getFilterId(e),o=e.sheetId;return Boolean(t&&this.filterValues[o]?.[t]?.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:o,sheetId:i}){const s=this.getters.getFilterId({sheetId:i,col:e,row:t});s&&(this.filterValues[i]||(this.filterValues[i]={}),this.filterValues[i][s]=o)}updateHiddenRows(){const e=this.getters.getActiveSheetId(),t=this.getters.getFilters(e).sort(((e,t)=>e.zoneWithHeaders.top-t.zoneWithHeaders.top)),o=new Set;for(let i of t){if(this.getters.isRowHiddenByUser(e,i.zoneWithHeaders.top))continue;if(o.has(i.zoneWithHeaders.top))continue;const t=this.filterValues[e]?.[i.id]?.map(Et);if(t&&i.filteredZone)for(let s=i.filteredZone.top;s<=i.filteredZone.bottom;s++){const n=this.getCellValueAsString(e,i.col,s);t.includes(n)&&o.add(s)}}this.hiddenRows=o}getCellValueAsString(e,t,o){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets){const e=t.id;for(const o of t.filterTables){const i=ii(o.range),s=[],n=[];for(const o of Ke(0,vi(i).numberOfCols)){const r={sheetId:t.id,col:i.left+o,row:i.top},a=this.getFilterValues(r),l=this.getters.getFilter(r);if(!l)continue;const c=l.filteredZone?Ci(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)));s.push({colId:o,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(o,d,n);n.push(u),t.cells[Zt(h.col,h.row)]={...t.cells[Zt(h.col,h.row)],content:u,value:u,isFormula:!1}}o.filters=s}}}getUniqueColNameForExcel(e,t,o){t||(t=`Column${e}`);let i=t,s=2;for(;o.includes(i);)i=t+String(s),s++;return i}}).add("evaluation_chart",class extends _C{static getters=["getChartRuntime","getStyleOfSingleCellChart"];charts={};createRuntimeChart=function(e){const t=$r.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(o){const i=t.find((e=>e.match(o.type)));if(!i)throw new Error("No runtime builder for this chart.");return i.getChartRuntime(o,e)}}(this.getters);handle(e){if(Rs.has(e.type)||Ts.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:er(e)};if(!t)return{background:w,fontColor:er(w)};const o=t.zone.left,i=t.zone.top,s=t.sheetId,n=this.getters.getCellComputedStyle({sheetId:s,col:o,row:i}),r=n.fillColor||w;return{background:r,fontColor:n.textColor||er(r)}}}).add("evaluation_cf",class extends _C{static getters=["getConditionalIcon","getCellComputedStyle"];isStale=!0;computedStyles={};computedIcons={};uuidGenerator=new ti;handle(e){switch((Ts.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 o=this.getters.getActiveSheetId(),i=this.getters.getRulesByCell(o,e.originCol,e.originRow);for(const t of i)this.adaptRules(o,t,[Zt(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.originPosition,e.targetPosition,e.operation)}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getCellComputedStyle(e){const{sheetId:t,col:o,row:i}=e,s=this.getters.getCell(e),n=this.computedStyles[t],r=n&&n[o]?.[i],a={...s?.style,...r};return this.getters.getEvaluatedCell(e).link&&!a.textColor&&(a.textColor=R),this.getters.isFilterHeader(e)&&(a.bold=!0),a}getConditionalIcon({col:e,row:t}){const o=this.getters.getActiveSheetId(),i=this.computedIcons[o];return i&&i[e]?.[t]}computeStyles(){const e=this.getters.getActiveSheetId();this.computedStyles[e]={},this.computedIcons[e]={};const t=this.computedStyles[e];for(let o of this.getters.getConditionalFormats(e).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 i of o.ranges){const s=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=s.top;i<=s.bottom;i++)for(let n=s.left;n<=s.right;n++){const s=this.rulePredicate[o.rule.type];let r=this.getters.getEvaluatedCell({sheetId:e,col:n,row:i});s&&s(r,o.rule)&&(t[n]||(t[n]=[]),t[n][i]=Object.assign(t[n]?.[i]||{},o.rule.style))}}}}parsePoint(e,t,o){const i=this.getters.getActiveSheetId(),s=this.getters.getEvaluatedCellsInZone(i,this.getters.getRangeFromSheetXC(i,e).zone).filter((e=>e.type===ys.number)).map((e=>e.value));switch(t.type){case"value":return"max"===o?Rt(s):Tt(s);case"number":return Number(t.value);case"percentage":const e=Tt(s);return e+(Rt(s)-e)*Number(t.value)/100;case"percentile":return ao(s,Number(t.value)/100,!0);case"formula":const i=t.value&&this.getters.evaluateFormula(t.value);return"number"==typeof i?i:null;default:return null}}applyIcon(e,t){const o=this.parsePoint(e,t.lowerInflectionPoint),i=this.parsePoint(e,t.upperInflectionPoint);if(null===o||null===i||o>i)return;const s=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(s,e).zone,r=this.computedIcons[s],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=n.top;e<=n.bottom;e++)for(let l=n.left;l<=n.right;l++){const n=this.getters.getEvaluatedCell({sheetId:s,col:l,row:e});if(n.type!==ys.number)continue;const c=this.computeIcon(n.value,i,t.upperInflectionPoint.operator,o,t.lowerInflectionPoint.operator,a);r[l]||(r[l]=[]),r[l][e]=c}}computeIcon(e,t,o,i,s,n){return"ge"===o&&e>=t||"gt"===o&&e>t?n[0]:"ge"===s&&e>=i||"gt"===s&&e>i?n[1]:n[2]}applyColorScale(e,t){const o=this.parsePoint(e,t.minimum,"min"),i=t.midpoint?this.parsePoint(e,t.midpoint):null,s=this.parsePoint(e,t.maximum,"max");if(null===o||null===s||o>=s||i&&(o>=i||i>=s))return;const n=this.getters.getActiveSheetId(),r=this.getters.getRangeFromSheetXC(n,e).zone,a=this.computedStyles[n],l=[];t.midpoint&&i?(l.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,i,t.minimum.color,t.midpoint.color)}),l.push({minValue:i,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(i,s,t.midpoint.color,t.maximum.color)})):l.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,s,t.minimum.color,t.maximum.color)});for(let e=r.top;e<=r.bottom;e++)for(let t=r.left;t<=r.right;t++){const r=this.getters.getEvaluatedCell({sheetId:n,col:t,row:e});if(r.type===ys.number){const n=We(r.value,o,s);let c;c=2===l.length&&i?n<=i?this.colorCell(n,l[0].minValue,l[0].minColor,l[0].colorDiffUnit):this.colorCell(n,l[1].minValue,l[1].minColor,l[1].colorDiffUnit):this.colorCell(n,l[0].minValue,l[0].minColor,l[0].colorDiffUnit),a[t]||(a[t]=[]),a[t][e]=a[t]?.[e]||{},a[t][e].fillColor=Nt(c)}}}computeColorDiffUnits(e,t,o,i){const s=t-e;return[((o>>16)%256-(i>>16)%256)/s,((o>>8)%256-(i>>8)%256)/s,(o%256-i%256)/s]}colorCell(e,t,o,i){const[s,n,r]=i;return Math.round((o>>16)%256-s*(e-t))<<16|Math.round((o>>8)%256-n*(e-t))<<8|Math.round(o%256-r*(e-t))}rulePredicate={CellIsRule:(e,t)=>{if(e.type===ys.error)return!1;const o=t.values.map(Ps);switch(t.operator){case"IsEmpty":return""===e.value.toString().trim();case"IsNotEmpty":return""!==e.value.toString().trim();case"BeginsWith":return""!==o[0]&&e.value.toString().startsWith(o[0].toString());case"EndsWith":return""!==o[0]&&e.value.toString().endsWith(o[0].toString());case"Between":return e.value>=o[0]&&e.value<=o[1];case"NotBetween":return!(e.value>=o[0]&&e.value<=o[1]);case"ContainsText":return e.value.toString().indexOf(o[0].toString())>-1;case"NotContains":return!e.value||-1==e.value.toString().indexOf(o[0].toString());case"GreaterThan":return e.value>o[0];case"GreaterThanOrEqual":return e.value>=o[0];case"LessThan":return e.value<o[0];case"LessThanOrEqual":return e.value<=o[0];case"NotEqual":return""!==o[0]&&e.value!==o[0];case"Equal":return""===o[0]||e.value===o[0];default:console.warn(n("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}};adaptRules(e,t,o,i){if(0===o.length&&0===i.length)return;const s=this.getters.getConditionalFormats(e),n=s.findIndex((e=>e.id===t.id));let r=[];n>-1&&(r=s[n].ranges),r=r.concat(o);const a=fi(r,i);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,o){const i=Zt(t.col,t.row);for(let s of this.getters.getConditionalFormats(e.sheetId))for(let n of s.ranges)if(pi(e.col,e.row,this.getters.getRangeFromSheetXC(e.sheetId,n).zone)){const n=s,r=[];if("CUT"===o&&r.push(Zt(e.col,e.row)),e.sheetId===t.sheetId)this.adaptRules(e.sheetId,n,[i],r);else{this.adaptRules(e.sheetId,n,[],r);const o=this.getCFToCopyTo(t.sheetId,n);this.adaptRules(t.sheetId,o,[i],[])}}}getCFToCopyTo(e,t){const o=this.getters.getConditionalFormats(e).find((e=>e.stopIfTrue===t.stopIfTrue&&vt(e.rule,t.rule)));return o||{...t,id:this.uuidGenerator.uuidv4(),ranges:[]}}}).add("viewport",class extends _C{static getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getActiveSheetDOMScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio","isPositionVisible"];viewports={};sheetViewWidth=pe();sheetViewHeight=pe();gridOffsetX=0;gridOffsetY=0;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":const t=this.getters.getActiveSheetId();let{col:o,row:i}=wi(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const s=e.previousAnchor.zone,n=e.anchor.zone,{top:r,bottom:a,left:l,right:c}=this.getMainInternalViewport(t);s.left===n.left&&s.right===n.right&&(o=l>o||o>c?l:o),s.top===n.top&&s.bottom===n.bottom&&(i=r>i||i>a?r:i)}o=Math.min(o,this.getters.getNumberCols(t)-1),i=Math.min(i,this.getters.getNumberRows(t)-1),this.refreshViewport(t,{col:o,row:i})}}handle(e){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 t=this.getters.getActiveSheetId(),{top:o,viewportHeight:i,offsetCorrectionY:s}=this.getMainInternalViewport(t),n=this.getters.getRowDimensions(t,o);this.shiftVertically(n.start+i-s);break;case"SHIFT_VIEWPORT_UP":{const e=this.getters.getActiveSheetId(),{top:t,viewportHeight:o,offsetCorrectionY:i}=this.getMainInternalViewport(e),s=this.getters.getRowDimensions(e,t);this.shiftVertically(s.end-i-o);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!==e.style?.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:r,row:a}=this.getters.getActivePosition();this.refreshViewport(this.getters.getActiveSheetId(),{col:r,row:a})}}finalize(){for(const e of this.sheetsWithDirtyViewports)this.resetViewports(e);this.sheetsWithDirtyViewports=new Set,this.setViewports()}setViewports(){const e=this.getters.getSheetIds();for(const t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getColIndex(e))))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getRowIndex(e))))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}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=>Ke(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=>Ke(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:o,ySplit:i}=this.getters.getPaneDivisions(e);let{width:s,height:n}=t.getMaxSize();return{x:this.getters.getColDimensions(e,o).start,y:this.getters.getRowDimensions(e,i).start,width:s,height:n}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:o}=this.getMainViewportRect(),i=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-i.viewportWidth+1),maxOffsetY:Math.max(0,o-i.viewportHeight+1)}}getColRowOffsetInViewport(e,t,o){const i=this.getters.getActiveSheetId(),s=this.getters.getSheetViewVisibleCols(),n=this.getters.getSheetViewVisibleRows();if(o<t)return-this.getColRowOffsetInViewport(e,o,t);let r=0;const a="COL"===e?s:n;for(let s=t;s<o;s++)a.includes(s)&&(r+="COL"===e?this.getters.getColSize(i,s):this.getters.getRowSize(i,s));return r}isVisibleInViewport({sheetId:e,col:t,row:o}){return this.getSubViewports(e).some((e=>e.isVisible(t,o)))}getEdgeScrollCol(e,t,o){let i=!1,s=0,n=0;const{xSplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(i=!0,n=Kt(e-a),s=1):e<l&&o>=l&&c>0?(i=!0,n=Kt(l-e),s=-1):r&&t<l&&e>l&&(i=!0,n=Kt(e),s="reset"),{canEdgeScroll:i,direction:s,delay:n}}getEdgeScrollRow(e,t,o){let i=!1,s=0,n=0;const{ySplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(i=!0,n=Kt(e-a),s=1):e<l&&o>=l&&c>0?(i=!0,n=Kt(l-e),s=-1):r&&t<l&&e>l&&(i=!0,n=Kt(e),s="reset"),{canEdgeScroll:i,direction:s,delay:n}}getVisibleRect(e){const t=this.getters.getActiveSheetId(),o=this.getSubViewports(t).map((t=>t.getRect(e))).filter(dt);if(0===o.length)return{x:0,y:0,width:0,height:0};const i=Math.min(...o.map((e=>e.x))),s=Math.min(...o.map((e=>e.y))),n=Math.max(...o.map((e=>e.x+e.width)))-i,r=Math.max(...o.map((e=>e.y+e.height)))-s;return{x:i+this.gridOffsetX,y:s+this.gridOffsetY,width:n,height:r}}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,o).start}}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(dt)}checkPositiveDimension(e){return e.width<0||e.height<0?69:0}checkValuesAreDifferent(e){const{height:t,width:o}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===o&&e.height===t?77:0}checkScrollingDirection({offsetX:e,offsetY:t}){const o=this.getMainInternalViewport(this.getters.getActiveSheetId());return!o.canScrollHorizontally&&e>0||!o.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 o=this.getSubViewports(e);Object.values(o).forEach((e=>{e.adjustPosition(t)}))}}resizeSheetView(e,t,o=0,i=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=o,this.gridOffsetY=i,this.recomputeViewports()}recomputeViewports(){for(let e of Object.keys(this.viewports))this.resetViewports(e)}setSheetViewOffset(e,t){const o=this.getters.getActiveSheetId(),{maxOffsetX:i,maxOffsetY:s}=this.getMaximumSheetOffset();Object.values(this.getSubViewports(o)).forEach((o=>o.setViewportOffset(We(e,0,i),We(t,0,s))))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetScrollbarX||0,y:this.viewports[e]?.bottomRight.offsetScrollbarY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),i=this.getters.getNumberCols(e),s=this.getters.getNumberRows(e),n=this.getters.getColRowOffset("COL",0,t,e),r=this.getters.getColRowOffset("ROW",0,o,e),{xRatio:a,yRatio:l}=this.getFrozenSheetViewRatio(e),c=a<1,h=l<1,d=this.getViewportOffset(e),u={topLeft:o&&t&&new DC(this.getters,e,{left:0,right:t-1,top:0,bottom:o-1},{width:n,height:r},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:o&&new DC(this.getters,e,{left:t,right:i-1,top:0,bottom:o-1},{width:this.sheetViewWidth-n,height:r},{canScrollHorizontally:c,canScrollVertically:!1},{x:c?d.x:0,y:0})||void 0,bottomLeft:t&&new DC(this.getters,e,{left:0,right:t-1,top:o,bottom:s-1},{width:n,height:this.sheetViewHeight-r},{canScrollHorizontally:!1,canScrollVertically:h},{x:0,y:h?d.y:0})||void 0,bottomRight:new DC(this.getters,e,{left:t,right:i-1,top:o,bottom:s-1},{width:this.sheetViewWidth-n,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 t=this.getters.getActiveSheetId(),{top:o}=this.getMainInternalViewport(t),{scrollX:i}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(i,e);const{anchor:s}=this.getters.getSelection();if(s.cell.row>=this.getters.getPaneDivisions(t).ySplit){const e=this.getMainInternalViewport(t).top-o;this.selection.selectCell(s.cell.col,s.cell.row+e)}}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],o=this.getters.getFigures(e),{scrollX:i,scrollY:s}=this.getActiveSheetScrollInfo(),{x:n,y:r}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of o)e.x>=n&&(e.x+e.width<=n+i||e.x>=a+i+n)||e.y>=r&&(e.y+e.height<=r+s||e.y>=l+s+r)||t.push(e);return t}isPositionVisible(e){const{scrollX:t,scrollY:o}=this.getters.getActiveSheetScrollInfo(),{x:i,y:s}=this.getters.getMainViewportCoordinates(),{width:n,height:r}=this.getters.getSheetViewDimension();return!(e.x>=i&&(e.x<i+t||e.x>n+t+i))&&!(e.y>=s&&(e.y<s+o||e.y>r+o+s))}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),i=this.getters.getColDimensions(e,t).start,s=this.getters.getRowDimensions(e,o).start;return{xRatio:i/(this.sheetViewWidth+this.gridOffsetX),yRatio:s/(this.sheetViewHeight+this.gridOffsetY)}}}).add("custom_colors",class extends _C{customColors=new Set;shouldUpdateColors=!1;static getters=["getCustomColors"];handle(e){switch(e.type){case"UPDATE_CELL":case"UPDATE_CHART":case"CREATE_CHART":case"ADD_CONDITIONAL_FORMAT":case"SET_BORDER":case"SET_ZONE_BORDERS":case"SET_FORMATTING":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())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getChartColors(t));return function(e){const t=[{leadColor:Lt(255,0,0),colors:[]},{leadColor:Lt(255,128,0),colors:[]},{leadColor:Lt(128,128,0),colors:[]},{leadColor:Lt(128,255,0),colors:[]},{leadColor:Lt(0,255,0),colors:[]},{leadColor:Lt(0,255,128),colors:[]},{leadColor:Lt(0,255,255),colors:[]},{leadColor:Lt(0,127,255),colors:[]},{leadColor:Lt(0,0,255),colors:[]},{leadColor:Lt(127,0,255),colors:[]},{leadColor:Lt(128,0,128),colors:[]},{leadColor:Lt(255,0,128),colors:[]}];for(const o of e.map(Ut)){let e=500,i=0;t.forEach(((t,s)=>{const n=(r=o,a=t.leadColor,Math.sqrt(Math.pow(r.r-a.r,2)+Math.pow(r.g-a.g,2)+Math.pow(r.b-a.b,2)));var r,a;e>n&&(e=n,i=s)})),t[i].colors.push(o)}return t.map((e=>e.colors.sort(((e,t)=>zt(e).s-zt(t).s)))).flat().map(Pt)}([...new Set([...new Set([...e,...this.customColors])].filter(Ft).map(_t))]).filter((e=>!_.includes(e)))}getColorsFromCells(e){const t=Object.values(this.getters.getCells(e)),o=new Set;for(const e of t)e.style?.textColor&&o.add(e.style.textColor),e.style?.fillColor&&o.add(e.style.fillColor);for(const t of this.getters.getBordersColors(e))o.add(t);return[...o]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),o=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(o.push(t.style.textColor),o.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(o.push(Nt(t.minimum.color)),o.push(t.midpoint?Nt(t.midpoint.color):void 0),o.push(Nt(t.maximum.color)))}return o.filter(dt)}getChartColors(e){const t=this.getters.getChartIds(e).map((e=>this.getters.getChart(e)));let o=new Set;for(let e of t){if(void 0===e)continue;const t=e.getDefinition().background;switch(void 0!==t&&o.add(t),e.type){case"gauge":const t=e.sectionRule.colors;o.add(t.lowerColor),o.add(t.middleColor),o.add(t.upperColor);break;case"scorecard":const i=e;o.add(i.baselineColorDown),o.add(i.baselineColorUp)}}return[...o]}tryToAddColor(e){const t=_t(e);e&&!_.includes(t)&&this.customColors.add(t)}}),EE=new zi;EE.add("link",{condition:(e,t)=>!!t.model.getters.getEvaluatedCell(e).link,execute:(e,t)=>Zi(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});class wE{fileStore;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 o=document.createElement("input");o.setAttribute("type","file"),o.setAttribute("accept","image/*"),o.addEventListener("change",(async()=>{null===o.files||1!=o.files.length?t():e(o.files[0])})),o.click()}))}getImageSize(e){return new Promise(((t,o)=>{const i=new Image;i.src=e,i.addEventListener("load",(()=>{const e={width:i.width,height:i.height};t(e)})),i.addEventListener("error",o)}))}}class xE{focusableElement=void 0;setFocusableElement(e){this.focusableElement=e}focus(){this.focusableElement?.focus()}}const yE=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];Ni`
|
|
1419
|
+
`}function XS(e){return new hb(e.join("\n"))}function KS(e,...t){let o=[e[0]];for(let i=0;i<t.length;i++){const s=t[i]instanceof hb?t[i]:GS(t[i]);o.push(s+e[i+1])}return new hb(pt(o))}function QS(e){return e.replace(/[a-z0-9]+:(?=[a-z0-9]+)/gi,"")}function JS(e){return e.replace(/([a-z0-9]+):(?=[a-z0-9]+)/gi,"$1\\:")}class eC{value;constructor(e){this.value=e}asString(){return iv(String(this.value))}asBool(){return"true"===this.value||"false"!==this.value&&Boolean(Number(this.value))}asNum(){return Number(this.value)}}class tC{rootFile;xlsxFileStructure;warningManager;relationships;currentFile=void 0;areNamespaceIgnored;constructor(e,t,o){this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=o,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(dt)}mapOnElements(e,t){const o=[],i=this.currentFile;let s;if(e.children){const t=this.querySelector(e.parent,e.query)?.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=i,o}catchErrorOnElement(e,t){const o=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([o,e.message].join("\n"))}extractAttr(e,t,o){const i=e.attributes[t];i||this.handleMissingValue(e,`attribute "${t}"`,o);const s=i?.value?i.value:o?.default;return void 0===s?void 0:new eC(s)}extractTextContent(e,t){if(void 0!==t?.default&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const o="preserve"===e?.attributes["xml:space"]?.value;let i=e?.textContent;return e&&null!==i||this.handleMissingValue(e,"text content",t),i&&(i=o?i:i.trim()),i?iv(i):t?.default}extractChildAttr(e,t,o,i){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}>`,i);const n=s?this.extractAttr(s,o,i)?.asString():i?.default;return void 0!==n?new eC(n):void 0}extractChildTextContent(e,t,o){if(void 0!==o?.default&&"string"!=typeof o.default)throw new Error("extractTextContent default value should be a string");let i=this.querySelector(e,t);return i||this.handleMissingValue(e,`child <${t}>`,o),i?this.extractTextContent(i,o):o?.default}handleMissingValue(e,t,o){if(o?.required){if(!o?.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 ${o.default}`)}}extractColor(e,t,o){if(!e)return o?{rgb:o}:void 0;const i=this.extractAttr(e,"theme")?.asString();let s;if(void 0!==i){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");s=this.getThemeColor(i,t.clrScheme)}else s=this.extractAttr(e,"rgb")?.asString();return{rgb:s,auto:this.extractAttr(e,"auto")?.asBool(),indexed:this.extractAttr(e,"indexed")?.asNum(),tint:this.extractAttr(e,"tint")?.asNum()}}getTargetXmlFile(e){if(!e)throw new Error("Undefined target file");let t=e.target;t=t.replace("../",""),t=t.replace("./","");const o=this.getListOfFiles().find((e=>e.file.fileName.endsWith(t)));if(!o||!o.file)throw new Error("Cannot find target file");return o}querySelector(e,t){return t=this.areNamespaceIgnored?QS(t):JS(t),e.querySelector(t)}querySelectorAll(e,t){return t=this.areNamespaceIgnored?QS(t):JS(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 oC extends tC{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:ub}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:ub}).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 iC extends tC{theme;constructor(e,t,o,i){super(e,t,o),this.theme=i}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},(e=>({sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),pivot:this.extractAttr(e,"pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)})));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:"extLst x14:conditionalFormatting"},(e=>({sqref:this.extractChildTextContent(e,"xm:sqref",{required:!0}).split(" "),pivot:this.extractAttr(e,"xm:pivot")?.asBool(),cfRules:this.extractCFRules(e,this.theme)})))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:"cfRule, x14:cfRule"},(e=>{const o=this.extractAttr(e,"type",{required:!0}).asString();if("dataBar"===o)throw new Error("Databars conditional formats are not supported.");return{type:o,priority:this.extractAttr(e,"priority",{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:this.extractAttr(e,"dxfId")?.asNum(),stopIfTrue:this.extractAttr(e,"stopIfTrue")?.asBool(),aboveAverage:this.extractAttr(e,"aboveAverage")?.asBool(),percent:this.extractAttr(e,"percent")?.asBool(),bottom:this.extractAttr(e,"bottom")?.asBool(),operator:this.extractAttr(e,"operator")?.asString(),text:this.extractAttr(e,"text")?.asString(),timePeriod:this.extractAttr(e,"timePeriod")?.asString(),rank:this.extractAttr(e,"rank")?.asNum(),stdDev:this.extractAttr(e,"stdDev")?.asNum(),equalAverage:this.extractAttr(e,"equalAverage")?.asBool()}}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:"formula"},(e=>this.extractTextContent(e,{required:!0})))}extractCfColorScale(e,t){const o=this.querySelector(e,"colorScale");if(o)return{colors:this.mapOnElements({parent:o,query:"color"},(e=>this.extractColor(e,t,"ffffff"))),cfvos:this.extractCFVos(o)}}extractCfIconSet(e){const t=this.querySelector(e,"iconSet, x14:iconSet");if(t)return{iconSet:this.extractAttr(t,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(t,"showValue",{default:!0}).asBool(),percent:this.extractAttr(t,"percent",{default:!0}).asBool(),reverse:this.extractAttr(t,"reverse")?.asBool(),custom:this.extractAttr(t,"custom")?.asBool(),cfvos:this.extractCFVos(t),cfIcons:this.extractCfIcons(t)}}extractCfIcons(e){const t=this.mapOnElements({parent:e,query:"cfIcon, x14:cfIcon"},(e=>({iconSet:this.extractAttr(e,"iconSet",{required:!0}).asString(),iconId:this.extractAttr(e,"iconId",{required:!0}).asNum()})));return 0===t.length?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:"cfvo, x14:cfvo"},(e=>({type:this.extractAttr(e,"type",{required:!0}).asString(),gte:this.extractAttr(e,"gte",{default:!0})?.asBool(),value:e.attributes.val?this.extractAttr(e,"val")?.asString():this.extractChildTextContent(e,"f, xm:f")})))}}class sC extends tC{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!Zb[t])throw new Error(`Unsupported chart type ${t}`);const o=this.mapOnElements({parent:e,query:"c:title a:t"},(e=>e.textContent||"")).join(""),i=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:o,type:Zb[t],dataSets:this.extractChartDatasets(this.querySelector(e,`c:${t}`)),labelRange:this.extractChildTextContent(e,"c:ser c:cat c:f"),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:qb[this.extractChildAttr(e,"c:legendPos","val",{default:"b"}).asString()],stacked:"stacked"===i,fontColor:"000000"}}))[0]}extractChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},(e=>({label:this.extractChildTextContent(e,"c:tx 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=QS(e.tagName);if(db.some((e=>e===t)))return t}throw new Error("Unknown chart type")}}class nC extends tC{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{if("twoCellAnchor"!==QS(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 o=this.querySelector(t,e);if(!o)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(o,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(o,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(o,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(o,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),o=this.getTargetXmlFile(this.relationships[t]),i=new sC(o,this.xlsxFileStructure,this.warningManager).extractChart();if(!i)throw new Error("Unable to extract chart definition");return i}}class rC extends tC{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 aC extends tC{getTable(){return this.mapOnElements({query:"table",parent:this.rootFile.file.xml},(e=>({displayName:this.extractAttr(e,"displayName",{required:!0}).asString(),name:this.extractAttr(e,"name")?.asString(),id:this.extractAttr(e,"id",{required:!0}).asString(),ref:this.extractAttr(e,"ref",{required:!0}).asString(),headerRowCount:this.extractAttr(e,"headerRowCount",{default:1}).asNum(),totalsRowCount:this.extractAttr(e,"totalsRowCount",{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)})))[0]}extractTableCols(e){return this.mapOnElements({query:"tableColumn",parent:e},(e=>({id:this.extractAttr(e,"id",{required:!0}).asString(),name:this.extractAttr(e,"name",{required:!0}).asString(),colFormula:this.extractChildTextContent(e,"calculatedColumnFormula")})))}extractTableStyleInfo(e){return this.mapOnElements({query:"tableStyleInfo",parent:e},(e=>({name:this.extractAttr(e,"name")?.asString(),showFirstColumn:this.extractAttr(e,"showFirstColumn")?.asBool(),showLastColumn:this.extractAttr(e,"showLastColumn")?.asBool(),showRowStripes:this.extractAttr(e,"showRowStripes")?.asBool(),showColumnStripes:this.extractAttr(e,"showColumnStripes")?.asBool()})))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:"autoFilter",parent:e},(e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,"ref",{required:!0}).asString()})))[0]}extractFilterColumns(e){return this.mapOnElements({query:"tableColumn",parent:e},(t=>({colId:this.extractAttr(e,"colId",{required:!0}).asNum(),hiddenButton:this.extractAttr(e,"hiddenButton",{default:!1}).asBool(),filters:this.extractSimpleFilter(t)})))}extractSimpleFilter(e){return this.mapOnElements({query:"filter",parent:e},(e=>({val:this.extractAttr(e,"val",{required:!0}).asString()})))}}class lC extends tC{theme;constructor(e,t,o,i){super(e,t,o),this.theme=i}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=ev(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=ev(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id,o=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(!o)throw new Error("Cannot find corresponding workbook sheet");return o}extractConditionalFormats(){return new iC(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},(e=>{const t=this.extractAttr(e,"r:id",{required:!0})?.asString(),o=this.getTargetXmlFile(this.relationships[t]);return new nC(o,this.xlsxFileStructure,this.warningManager).extractFigures()}))[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},(e=>{const t=this.extractAttr(e,"r:id",{required:!0})?.asString(),o=this.getTargetXmlFile(this.relationships[t]);return new aC(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 rC(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:wb.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:xb.toString()}).asNum()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},(e=>({width:this.extractAttr(e,"width")?.asNum(),customWidth:this.extractAttr(e,"customWidth")?.asBool(),bestFit:this.extractAttr(e,"bestFit")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),min:this.extractAttr(e,"min",{required:!0})?.asNum(),max:this.extractAttr(e,"max",{required:!0})?.asNum(),styleIndex:this.extractAttr(e,"style")?.asNum()})))}extractRows(e){return this.mapOnElements({parent:e,query:"sheetData row"},(e=>({index:this.extractAttr(e,"r",{required:!0})?.asNum(),cells:this.extractCells(e),height:this.extractAttr(e,"ht")?.asNum(),customHeight:this.extractAttr(e,"customHeight")?.asBool(),hidden:this.extractAttr(e,"hidden")?.asBool(),styleIndex:this.extractAttr(e,"s")?.asNum()})))}extractCells(e){return this.mapOnElements({parent:e,query:"c"},(e=>({xc:this.extractAttr(e,"r",{required:!0})?.asString(),styleIndex:this.extractAttr(e,"s")?.asNum(),type:Ub[this.extractAttr(e,"t",{default:"n"})?.asString()],value:this.extractChildTextContent(e,"v"),formula:this.extractCellFormula(e)})))}extractCellFormula(e){const t=this.querySelector(e,"f");if(t)return{content:this.extractTextContent(t),sharedIndex:this.extractAttr(t,"si")?.asNum(),ref:this.extractAttr(t,"ref")?.asString()}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},(e=>{const t=this.extractAttr(e,"r:id")?.asString();return{xc:this.extractAttr(e,"ref",{required:!0})?.asString(),location:this.extractAttr(e,"location")?.asString(),display:this.extractAttr(e,"display")?.asString(),relTarget:t?this.relationships[t].target:void 0}}))}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),o={};for(let e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),i=this.extractTextContent(e,{required:!0});o[t]=i}const i=[];for(let e=0;e<Object.keys(o).length;e++)o[e]?i.push(o[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),i.push(""));return i}}class cC extends tC{theme;constructor(e,t,o){super(e.styles,e,t),this.theme=o}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},(e=>this.extractNumFormats(e)))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},(e=>this.extractFont(e)))}extractFont(e){const t=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),o=this.extractChildAttr(e,"sz","val",{default:Z.toString()}).asNum(),i=this.extractColor(this.querySelector(e,"color"),this.theme),s=this.querySelector(e,"i")||void 0,n=s&&"0"!==s.attributes.val?.value,r=this.querySelector(e,"b")||void 0,a=r&&"0"!==r.attributes.val?.value,l=this.querySelector(e,"strike")||void 0,c=l&&"0"!==l.attributes.val?.value,h=this.querySelector(e,"u")||void 0;return{name:t,size:o,color:i,italic:n,bold:a,underline:h&&"none"!==h.attributes.val?.value,strike:c}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},(e=>this.extractFill(e)))}extractFill(e){const t=e.children[0];return"patternFill"===t.tagName?{patternType:t.attributes.patternType?.value,bgColor:this.extractColor(this.querySelector(t,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(t,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(t,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},(e=>this.extractBorder(e)))}extractBorder(e){const t={left:this.extractSingleBorder(e,"left",this.theme),right:this.extractSingleBorder(e,"right",this.theme),top:this.extractSingleBorder(e,"top",this.theme),bottom:this.extractSingleBorder(e,"bottom",this.theme),diagonal:this.extractSingleBorder(e,"diagonal",this.theme)};return t.diagonal&&(t.diagonalUp=this.extractAttr(e,"diagonalUp")?.asBool(),t.diagonalDown=this.extractAttr(e,"diagonalDown")?.asBool()),t}extractSingleBorder(e,t,o){const i=this.querySelector(e,t);if(i&&i.attributes.style)return{style:this.extractAttr(i,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(i.children[0],o,"000000")}}extractAlignment(e){return{horizontal:this.extractAttr(e,"horizontal",{default:"general"}).asString(),vertical:this.extractAttr(e,"vertical",{default:"bottom"}).asString(),textRotation:this.extractAttr(e,"textRotation")?.asNum(),wrapText:this.extractAttr(e,"wrapText")?.asBool(),indent:this.extractAttr(e,"indent")?.asNum(),relativeIndent:this.extractAttr(e,"relativeIndent")?.asNum(),justifyLastLine:this.extractAttr(e,"justifyLastLine")?.asBool(),shrinkToFit:this.extractAttr(e,"shrinkToFit")?.asBool(),readingOrder:this.extractAttr(e,"readingOrder")?.asNum()}}getDxfs(){return this.mapOnElements({query:"dxf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"font"),o=this.querySelector(e,"fill"),i=this.querySelector(e,"border"),s=this.querySelector(e,"numFmt"),n=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:o?this.extractFill(o):void 0,numFmt:s?this.extractNumFormats(s):void 0,alignment:n?this.extractAlignment(n):void 0,border:i?this.extractBorder(i):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 hC extends tC{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})}))),o={};for(let e of t)o[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:o}}))}}function dC(e,t){const o=function(e,t){const o=t[Ob],i=o.querySelectorAll(`Override[ContentType="${e}"]`),s=[];for(let e of i){const t=e?.attributes.PartName.value;s.push(t.substring(1))}return s}(e,t);return function(e,t){const o=[];for(let i of e){const e=uC(i,t);o.push({file:{fileName:i,xml:t[i]},rels:e?{fileName:e,xml:t[e]}:void 0})}return o}(o,t)}function uC(e,t){if(e===Ob)return"_rels/.rels";let o="";const i=e.split("/");for(let e=0;e<i.length-1;e++)o+=i[e]+"/";return o+="_rels/",o+=i[i.length-1]+".rels",t[o]||(o=void 0),o}class gC{warningManager;xmls;constructor(e){this.warningManager=new Nb,this.xmls={};for(let t of Object.keys(e))(t.endsWith(".xml")||t.endsWith(".rels"))&&(this.xmls[t]=ZS(new hb(e[t])))}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new oC(e.theme,e,this.warningManager).getTheme():void 0,o=e.sharedStrings?new oC(e.sharedStrings,e,this.warningManager).getSharedStrings():[],i=e.sheets.sort(((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0}))).map((o=>new lC(o,e,this.warningManager,t).getSheet())),s=e.externalLinks.map((t=>new hC(t,e,this.warningManager).getExternalBook())),n=new cC(e,this.warningManager,t);return{fonts:n.getFonts(),fills:n.getFills(),borders:n.getBorders(),dxfs:n.getDxfs(),numFmts:n.getNumFormats(),styles:n.getStyles(),sheets:i,sharedStrings:o,externalBooks:s}}buildXlsxFileStructure(){const e={sheets:dC(bb.sheet,this.xmls),workbook:dC(bb.workbook,this.xmls)[0],styles:dC(bb.styles,this.xmls)[0],sharedStrings:dC(bb.sharedStrings,this.xmls)[0],theme:dC(bb.themes,this.xmls)[0],charts:dC(bb.chart,this.xmls),figures:dC(bb.drawing,this.xmls),tables:dC(bb.table,this.xmls),pivots:dC(bb.pivot,this.xmls),externalLinks:dC(bb.externalLink,this.xmls)};if(!e.workbook.rels)throw Error(n("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:12,sheets:FS(e,this.warningManager),styles:lv(e,this.warningManager),formats:hv(e,this.warningManager),borders:rv(e,this.warningManager),entities:{},revisionId:ee};return BS(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=Ct(e.styles[t])})),t}}function pC(e){const t=tS(e);let o=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&ko.test(e.value)){const t=e.value.trim();return o.includes(t)||o.push(t),`${he}${o.indexOf(t)}${he}`}return e.value}))),dependencies:o}}const mC=13,fC="Sheet1";function bC(e,t){if(!e)return wC();if(e["[Content_Types].xml"]){const o=new gC(e);if(e=o.convertXlsx(),t)for(let e of o.warningManager.warnings.sort())console.warn(e)}return"version"in e&&e.version<mC&&(e=function(e){for(let t=vC.findIndex((t=>t.from===e.version));t<vC.length;t++)e=vC[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,o=new ti;for(const i of e.sheets||[])for(const e of i.figures||[])t.has(e.id)&&(e.id+=o.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(wC(),e,{version:mC}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(EC(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(EC(fC,"Sheet1"));return e}(e),e}(e),e}const vC=[{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 o=t.cells[e];o.content&&o.content.startsWith("=")&&(o.formula=pC(o.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:o,...i}=t.figures[e].data,s=[];for(let e of o)if(e.labelCell){const t=ii(e.dataRange),o=e.labelCell+":"+Zt(t.right,t.bottom);s.push(o)}else s.push(e.dataRange);i.dataSetsHaveTitle=Boolean(o[0].labelCell),i.dataSets=s,t.figures[e].data=i}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){const t=[],o=new RegExp(ce,"g");for(let i of e.sheets||[]){if(!i.name)continue;const e=i.name,s=e.replace(o,"_");let n=1,r=s;for(;t.includes(r);)r=`${s}${n}`,n++;i.name=r,t.push(r);const a=t=>{if(void 0===t)return t;let o=t.replace(e,r),i=t;for(;i!==o;)i=o,o=i.replace(e,r);return i};for(let e in i.cells){const t=i.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(a))}for(let e of i.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(a),o=a(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:o}}for(let e of i.conditionalFormats||[]){e.ranges=e.ranges.map(a);for(const t of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===e.rule[t]?.type&&(e.rule[t].value=a(e.rule[t].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 o=t.cells[e];if(o.formula){let{text:e,dependencies:t}=o.formula;for(let[o,i]of Object.entries(t)){const t=`\\${he}${o}\\${he}`;e=e.replace(new RegExp(t,"g"),i)}o.content=e,delete o.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let o of e.sheets||[])for(let e in o.cells||[]){const i=o.cells[e];i.format&&(i.format=gt(i.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}},{description:"Fix datafilter duplication",from:12,to:12.5,applyMigration(e){for(let t of e.sheets||[]){let e=[];for(let o of t.filterTables||[]){const t=ii(o.range),i=e.findIndex((e=>gi(e,t)));-1!==i?e[i]=t:e.push(t)}t.filterTables=e.map((e=>({range:ni(e)})))}return e}},{description:"Change Border description structure",from:12.5,to:13,applyMigration(e){for(const t in e.borders){const o=e.borders[t];for(const e in o)Array.isArray(o[e])&&(o[e]={style:o[e][0],color:o[e][1]})}return e}}];function SC(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const o=[],i=[],s=e=>{if("CREATE_SHEET"===e.type)o.push(e.sheetId);else if("sheetId"in e&&!o.includes(e.sheetId))return{...e,sheetId:fC};return e};for(const e of t)"REMOTE_REVISION"===e.type?i.push({...e,commands:e.commands.map(s)}):i.push(e);return i}(e,t),t=CC(t,"SORT_CELLS"),t=function(e,t){const o=[],i={};for(const t of e.sheets||[])t.figures?.forEach((e=>{"chart"===e.tag&&(i[e.id]=e.data)}));for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const o of e.commands){let e=o;switch(o.type){case"CREATE_CHART":i[o.id]=o.definition;break;case"UPDATE_CHART":if(!i[o.id]){console.log(`Fix chart definition: chart with id ${o.id} not found.`);continue}const t={...i[o.id],...o.definition};e={...o,definition:t},i[o.id]=t}t.push(e)}o.push({...e,commands:t})}else o.push(e);return o}(e,t=CC(t,"SET_DECIMAL")),t}function CC(e,t){const o=[];for(const i of e)"REMOTE_REVISION"===i.type?o.push({...i,commands:i.commands.filter((e=>e.type!==t))}):o.push(i);return o}function EC(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[],filterTables:[],isVisible:!0}}function wC(e="Sheet1"){return{version:mC,sheets:[EC(fC,e)],entities:{},styles:{},formats:{},borders:{},revisionId:ee,uniqueFigureIds:!0}}function xC(e,t){return{...EC(e,t),charts:[],images:[]}}class yC{static getters=[];history;dispatch;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 o of e){let e=o.call(this,t);Array.isArray(e)||(e=[e]);const i=e.filter((e=>0!==e));if(i.length)return i}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}class IC extends yC{getters;range;uuidGenerator;constructor({getters:e,stateObserver:t,range:o,dispatch:i,uuidGenerator:s}){super(t,i),this.range=o,o.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=s}import(e){}export(e){}adaptRanges(e,t){}garbageCollectExternalResources(){}}function RC(e){return""===e?NaN:Number(e)}class TC{id;zone;filters;constructor(e){this.filters=[],this.zone=e;const t=new ti;this.id=t.uuidv4();for(const o of Ke(e.left,e.right+1)){const e={...this.zone,left:o,right:o};this.filters.push(new AC(t.uuidv4(),e))}}get contentZone(){if(this.zone.bottom!==this.zone.top)return{...this.zone,top:this.zone.top+1}}getFilterId(e){return this.filters.find((t=>t.col===e))?.id}clone(){return new TC(this.zone)}}class AC{id;zoneWithHeaders;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}}}function OC(e){return Object.entries(e).map((([e,t])=>t?MC(parseInt(e,10),t):void 0)).filter(dt).map((e=>Zt(e.left,e.top)+":"+Zt(e.right,e.bottom)))}function MC(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}class NC{getters;providers=[];constructor(e){this.getters=e}static getters=["getRangeString","getSelectionRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData"];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",o="COL"===e.dimension?"right":"bottom",i="COL"===e.dimension?"columns":"rows";const s=[...e.elements];s.sort(((e,t)=>t-e));const n=Qe(s);this.executeOnAllRanges((s=>{if(s.sheetId!==e.sheetId)return{changeType:"NONE"};let r=s,a="NONE";for(let e of n){const n=Tt(e),l=Rt(e);if(s.zone[t]<=n&&n<=s.zone[o]){const e=Math.min(s.zone[o],l)-n+1;a="RESIZE",r=this.createAdaptedRange(r,i,a,-e)}else if(s.zone[t]>=n&&s.zone[o]<=l)a="REMOVE",r=s.clone({...this.getInvalidRange()});else if(s.zone[t]<=l&&s.zone[o]>=l){const e=l-s.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,i,a,-e),r=this.createAdaptedRange(r,i,"MOVE",-(s.zone[t]-n))}else n<s.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,i,a,-(l-n+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",o="COL"===e.dimension?"right":"bottom",i="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((s=>{if(s.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(s.zone[t]<=e.base&&e.base<s.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(s,i,"RESIZE",e.quantity)};if(e.base<s.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(s,i,"MOVE",e.quantity)}}else{if(s.zone[t]<e.base&&e.base<=s.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(s,i,"RESIZE",e.quantity)};if(e.base<=s.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(s,i,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId!==e.sheetId)return{changeType:"NONE"};const o=this.getters.getSheetName(e.sheetId);return{changeType:"REMOVE",range:t=t.clone({...this.getInvalidRange(),invalidSheetName:o})}}),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 o=void 0,i=e.sheetId;return{changeType:"CHANGE",range:t.clone({sheetId:i,invalidSheetName:o})}}return{changeType:"NONE"}}));break;case"MOVE_RANGES":{const t=e.target[0];this.executeOnAllRanges((o=>{if(o.sheetId!==e.sheetId||!mi(o.zone,t))return{changeType:"NONE"};const i=e.targetSheetId,s=e.col-t.left,n=e.row-t.top,r=this.createAdaptedRange(o,"both","MOVE",[s,n]),a=e.sheetId!==i||r.prefixSheet;return{changeType:"MOVE",range:r.clone({sheetId:i,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const o=e(t);return"NONE"===o.changeType||si(o.range.zone)?o:{range:o.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,o,i){const s=Ei(e.unboundedZone,t,o,i);return e.clone({zone:s})}executeOnAllRanges(e,t){const o=this.verifyRangeRemoved(e);for(const e of this.providers)e(o,t)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,o,i){const s=e.map((e=>Xo.fromRange(e,this.getters)));return s.map((e=>{if(!si(e.zone))return e;const s=e.prefixSheet?e.sheetId:i,n={...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:o),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:o)};return e.clone({sheetId:s,zone:n}).orderZone()}))}getRangeFromSheetXC(e,t){if(!$o.test(t))return new Xo({sheetId:"",zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let o,i=t,s=!1;t.includes("!")&&(({xc:i,sheetName:o}=Yo(t)),o&&(s=!0));const n=oi(i),r=Xo.getRangeParts(i,n),a=o&&!this.getters.getSheetIdByName(o)?o:void 0,l=this.getters.getSheetIdByName(o)||e;return new Xo({prefixSheet:s,zone:n,sheetId:l,invalidSheetName:a,parts:r},this.getters.getSheetSize).orderZone()}getSelectionRangeString(e,t){const o=Xo.fromRange(e,this.getters),i=this.getters.expandZone(o.sheetId,o.zone),s=o.clone({zone:{...i,bottom:o.isFullCol?void 0:i.bottom,right:o.isFullRow?void 0:i.right}});return this.getRangeString(s,t)}getRangeString(e,t,o=!1){if(!e)return J;if(e.invalidXc)return e.invalidXc;if(!this.getters.tryGetSheet(e.sheetId))return J;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return J;if(e.zone.left<0||e.zone.top<0)return J;const i=Xo.fromRange(e,this.getters);let s=i.sheetId!==t||i.invalidSheetName||i.prefixSheet,n="";if(s&&(n=i.invalidSheetName?i.invalidSheetName:$e(this.getters.getSheetName(i.sheetId))),s&&!n)return J;let r=this.getRangePartString(i,0,o);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)&&(r+=":",r+=this.getRangePartString(i,1,o)),`${s?n+"!":""}${r}`}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 Xo(t,this.getters.getSheetSize)}getRangePartString(e,t,o=!1){const i=e.parts&&e.parts[t]?.colFixed?"$":"",s=Bt(0===t?e.zone.left:e.zone.right),n=e.parts&&e.parts[t]?.rowFixed?"$":"",r=String(0===t?e.zone.top+1:e.zone.bottom+1);let a="";return a=e.isFullCol&&!o?0===t&&e.unboundedZone.hasHeader?i+s+n+r:i+s:e.isFullRow&&!o?0===t&&e.unboundedZone.hasHeader?i+s+n+r:n+r:i+s+n+r,a}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:J}}}class _C extends yC{static layers=[];getters;ui;selection;constructor({getters:e,stateObserver:t,dispatch:o,uiActions:i,selection:s}){super(t,o),this.getters=e,this.ui=i,this.selection=s}drawGrid(e,t){}}const FC=Hg.mapping;class DC{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;offsetScrollbarX;offsetScrollbarY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,o,i,s,n){this.getters=e,this.sheetId=t,this.boundaries=o,this.viewportWidth=i.width,this.viewportHeight=i.height,this.offsetScrollbarX=n.x,this.offsetScrollbarY=n.y,this.canScrollVertically=s.canScrollVertically,this.canScrollHorizontally=s.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:o,size:i}=this.getters.getColDimensions(this.sheetId,e),{end:s,size:n}=this.getters.getRowDimensions(this.sheetId,t),r=this.searchHeaderIndex("COL",o-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,r),l=this.searchHeaderIndex("ROW",s-this.viewportHeight,0),c=this.getters.getRowSize(this.sheetId,l);let h=o-this.offsetCorrectionX;this.canScrollHorizontally&&(h+=Math.max(L,Math.min(a,this.viewportWidth-i)),h=Math.max(h,this.viewportWidth));let d=s-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(P+5,Math.min(c,this.viewportHeight-n)),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 o=this.getters.getMainCellPosition({sheetId:t,...e}),{col:i,row:s}=this.getters.getNextVisibleCellPosition(o);pi(i,this.boundaries.top,this.boundaries)&&this.adjustPositionX(i),pi(this.boundaries.left,s,this.boundaries)&&this.adjustPositionY(s)}adjustPositionX(e){const t=this.sheetId,{end:o}=this.getters.getColDimensions(t,e),i=this.getters.getNumberCols(t);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<o){let o=e;for(;this.getters.isColHidden(t,o)&&e<i;)o++;const s=this.getters.getColDimensions(t,o).end,n=this.searchHeaderIndex("COL",s-this.viewportWidth-this.offsetCorrectionX,this.boundaries.left,!0);this.offsetX=this.getters.getColDimensions(t,n).end-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX()}else if(this.left>e){let o=e;for(;this.getters.isColHidden(t,o)&&e>0;)o--;this.offsetX=this.getters.getColDimensions(t,o).start-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX()}}adjustPositionY(e){const t=this.sheetId,{end:o}=this.getters.getRowDimensions(t,e),i=this.getters.getNumberRows(t);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<o){let o=e;for(;this.getters.isRowHidden(t,o)&&e<i;)o++;const s=this.getters.getRowDimensions(t,o).end,n=this.searchHeaderIndex("ROW",s-this.viewportHeight-this.offsetCorrectionY,this.boundaries.top,!0);this.offsetY=this.getters.getRowDimensions(t,n).end-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY()}else if(this.top>e){let o=e;for(;this.getters.isRowHidden(t,o)&&e>0;)o--;this.offsetY=this.getters.getRowDimensions(t,o).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=di(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,o=0,i=!1){let s=0;const n=this.sheetId,r=this.getters.getNumberHeaders(n,e);for(let a=o;a<=r-1;a++){const o=i||"COL"!==e?a<this.top&&a>this.bottom:a<this.left&&a>this.right;if(!this.getters.isHeaderHidden(n,e,a)&&!o&&(s+="COL"===e?this.getters.getColSize(n,a):this.getters.getRowSize(n,a),s>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 LC{cells;getters;index=0;direction;constructor(e,t,o){this.cells=e,this.getters=t,this.direction=o}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:o,tooltip:i}=Ws.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:o,tooltip:i,origin:{col:e.data.col,row:e.data.row}}}}class PC{subscriptions={};on(e,t,o){if(!o)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:o})}trigger(e,t){const o=this.subscriptions[e]||[];for(let e=0,i=o.length;e<i;e++){const i=o[e];i.callback.call(i.owner,t)}}off(e,t){const o=this.subscriptions[e];o&&(this.subscriptions[e]=o.filter((e=>e.owner!==t)))}clear(){this.subscriptions={}}}function kC(e,t){return{...e,definition:oa(e.definition,t)}}function UC(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let o=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(let t of e)o>t&&o--}if("ADD_COLUMNS_ROWS"===t.type){o=o>("before"===t.position?t.base-1:t.base)?o+t.quantity:o}return o>0?{...e,quantity:o}:void 0}Pm.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],kC),Pm.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],kC),Pm.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const o=t.sheetId;if(e.targetSheetId===o||e.sheetId===o)return;return e})),Pm.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),Pm.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){if(e.name===t.name)return{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),Pm.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE","CREATE_FILTER_TABLE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const o=[];for(const i of e.target)for(const e of t.target)gi(i,e)||o.push({...i});if(o.length)return{...e,target:o};return})),Pm.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],UC),Pm.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],UC),Pm.addTransformation("CREATE_FILTER_TABLE",["CREATE_FILTER_TABLE","ADD_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;for(const o of e.target)for(const e of t.target)if(gi(e,o))return;return e}));const VC=[{match:function(e){return"sheetId"in e},fn:HC},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const o=HC(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const i=[];for(const o of e.target){const e=Hn(o,t);e&&i.push(e)}if(!i.length)return"IGNORE_COMMAND";return{...e,target:i}}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const o=HC(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const o="COL"===t.dimension?"col":"row";let i=e[o];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(i))return"IGNORE_COMMAND";for(let t of e)i>=t&&i--}"ADD_COLUMNS_ROWS"===t.type&&(i>t.base||i===t.base&&"before"===t.position)&&(i+=t.quantity);return{...e,[o]:i}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const o of t.target){if(!(e.col===o.left&&e.row===o.top)&&pi(e.col,e.row,o))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 o=HC(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const o="ADD_COLUMNS_ROWS"===e.type,i=o?"base":"elements";let s=o?[e[i]]:e[i];if("REMOVE_COLUMNS_ROWS"===t.type&&(s=s.map((e=>{if(t.elements.includes(e))return;const o=t.elements.sort(((e,t)=>t-e));for(let t of o)e>t&&e--;return e})).filter(dt)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;s=s.map((o=>o>e?o+t.quantity:o))}if(s.length){let t=s;return o&&(t=s[0]),{...e,[i]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}},{match:function(e){return"ranges"in e},fn:function(e,t){const o=[],i="DELETE_SHEET"===t.type&&t.sheetId;for(const s of e.ranges)if(s._sheetId!==t.sheetId)o.push({...s,_zone:s._zone});else{const e=Hn(s._zone,t);e&&i!==s._sheetId&&o.push({...s,_zone:e})}if(!o.length)return"IGNORE_COMMAND";return{...e,ranges:o}}}];function zC(e,t){const o=Pm.getTransformation(e.type,t.type);return o?o(e,t):function(e,t){for(const{match:o,fn:i}of VC)if(o(e)){const o=i(e,t);if("SKIP_TRANSFORMATION"===o)continue;if("IGNORE_COMMAND"===o)return;e=o}return e}(e,t)}function BC(e,t){let o=[...e];for(const e of t)o=o.map((t=>zC(t,e))).filter(dt);return o}function HC(e,t){const o="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===o?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class $C{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,o,i,s,n){this.rootCommand=i,this.timestamp=n,this.id=e,this.clientId=t,this._commands=[...o],this._changes=s?[...s]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class WC extends Error{}class GC extends PC{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;uuidGenerator=new ti;constructor(e,t,o=ee){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=o,this.debouncedMove=function(e,t,o){let i;return function(){const s=this,n=arguments,r=o&&!i;clearTimeout(i),i=setTimeout((function(){i=null,o||e.apply(s,n)}),t),r&&e.apply(s,n)}}(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,o){if(!t.length||!o.length||!this.canApplyOptimisticUpdate())return;const i=new $C(this.uuidGenerator.uuidv4(),this.clientId,t,e,o,Date.now());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 WC("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(dt))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}getLastLocalNonEmptyRevision(e){const t=this.revisions.getRevertedExecution();for(const o of t){if("SNAPSHOT"===o.rootCommand)return;if(o.rootCommand&&"REMOTE"!==o.rootCommand&&(!e.includes(o.rootCommand?.type)&&o.commands.length))return o}}_move(e){if(!this.clients[this.clientId])return;const t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;const o=t?"CLIENT_MOVED":"CLIENT_JOINED",i=this.getClient();this.clients[this.clientId]={...i,position:e},this.transportService.sendMessage({type:o,version:1,client:{...i,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:o,timestamp:i}=e,s=new $C(e.nextRevisionId,t,o,"REMOTE",void 0,i);if(s.clientId!==this.clientId){this.revisions.insert(s.id,s,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:BC(o,t)})}break;case"SNAPSHOT_CREATED":{const t=new $C(e.nextRevisionId,"server",[],"SNAPSHOT",void 0,Date.now());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 qC=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];var ZC;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(ZC||(ZC={}));class jC extends _C{inputHasSingleRange;static layers=[1];static getters=[];ranges=[];focusedRangeIndex=null;activeSheet;willAddNewRange=!1;constructor(e,t,o){if(o&&t.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");super(e),this.inputHasSingleRange=o,this.insertNewRange(0,t),this.activeSheet=this.getters.getActiveSheetId(),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}handleEvent(e){const t=ni(e.anchor.zone),o=this.activeSheet,i=this.getters.getActiveSheetId(),s=this.getters.getSheetName(i);this.add([i===o?t:`${$e(s)}!${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 o=e.value.replace(/^,+/,"").split(",").map((e=>e.trim()));this.setRange(t,o)}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:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),i=this.getters.expandZone(e.sheetIdTo,yi({col:t,row:o}));this.selection.resetAnchor(this,{cell:{col:t,row:o},zone:i})}}}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 o=Math.max(0,...this.ranges.map((e=>Number(e.id))));this.ranges.splice(e,0,...t.map(((e,t)=>({xc:e,id:o+t+1,color:Mt[(o+t)%Mt.length]}))))}setRange(e,t){const[,...o]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,o),o.length&&this.focus(e+o.length)}removeRange(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const o=this.cleanInputs([e]).filter((e=>this.getters.isRangeValid(e))).filter((e=>this.shouldBeHighlighted(this.activeSheet,e)));return o.map((e=>{const{sheetName:o}=Yo(e);return{zone:this.getters.getRangeFromSheetXC(this.activeSheet,e).zone,sheetId:o&&this.getters.getSheetIdByName(o)||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:o}=Yo(t),i=this.getters.getSheetIdByName(o),s=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(i===s||void 0===i&&s===e)}getIndex(e){const t=this.ranges.findIndex((t=>t.id===e));return t>=0?t:null}}const YC=[XC,function(e,t){return"target"in t&&Array.isArray(t.target)?{...Be(t),target:e.getSelectedZones()}:t},function(e,t){if(!("row"in t)||!("col"in t))return t;const{col:o,row:i}=e.getActivePosition();return{...Be(t),col:o,row:i}}];function XC(e,t){return"sheetId"in t?{...Be(t),sheetId:e.getActiveSheetId()}:t}const KC=new ti;function QC(e,t){const o=e.getSelectedZone();return{...XC(e,t),elements:"COL"===t.dimension?Ke(o.left,o.right+1):Ke(o.top,o.bottom+1)}}function JC(e,t){const o=e.getSelectedZone();return{...Be(t),zone:o}}function eE(e,t){const o=Be(t),i=e.getSelectedZone(),{top:s,bottom:n,left:r,right:a}=i;return"cols"in o?o.cols=Ke(r,a+1):"rows"in o&&(o.rows=Ke(s,n+1)),o}const tE=new zi;tE.add("UPDATE_CELL",iE),tE.add("CLEAR_CELL",iE),tE.add("DELETE_CONTENT",iE),tE.add("ADD_MERGE",iE),tE.add("REMOVE_MERGE",iE),tE.add("SET_FORMATTING",iE),tE.add("CLEAR_FORMATTING",iE),tE.add("SET_BORDER",iE),tE.add("CREATE_FILTER_TABLE",iE),tE.add("REMOVE_FILTER_TABLE",iE),tE.add("HIDE_SHEET",iE),tE.add("ADD_COLUMNS_ROWS",(function(e,t){const o=e.getActivePosition();return{...XC(e,t),base:"COL"===t.dimension?o.col:o.row}})),tE.add("REMOVE_COLUMNS_ROWS",QC),tE.add("HIDE_COLUMNS_ROWS",QC),tE.add("RESIZE_COLUMNS_ROWS",QC),tE.add("CREATE_SHEET",(function(e,t){const o=Be(t);o.sheetId=KC.uuidv4();const i=t.name||e.getSheet(e.getActiveSheetId()).name,s=i.match(/(.+?)\d*$/)?.[1]||i;return o.name=e.getNextSheetName(s),o})),tE.add("CREATE_FIGURE",(function(e,t){const o=XC(e,t);return o.figure.id=KC.uuidv4(),o})),tE.add("CREATE_CHART",(function(e,t){return{...XC(e,t),id:KC.uuidv4()}})),tE.add("CREATE_IMAGE",(function(e,t){return{...XC(e,t),figureId:KC.uuidv4()}}));const oE=new zi;function iE(e,t){let o=Be(t);for(const t of YC)o=t(e,o);return o}function sE(e,t){if(!t)return;if(!tE.contains(t.type))return;return tE.get(t.type)(e,t)}function nE(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return Ms(e.rootCommand)?sE(t,e.rootCommand):function(e,t,o){if(!oE.contains(t.type))return;return oE.get(t.type)(e,t,o)}(t,e.rootCommand,e.commands)}oE.add("STOP_EDITION",(function(e,t,o){return o.map((t=>sE(e,t))).filter(dt)})),oE.add("PASTE",(function(e,t){return{type:"REPEAT_PASTE",pasteOption:Be(t.pasteOption),target:e.getSelectedZones()}})),oE.add("INSERT_CELL",JC),oE.add("DELETE_CELL",JC),oE.add("AUTORESIZE_COLUMNS",eE),oE.add("AUTORESIZE_ROWS",eE),oE.add("SORT_CELLS",(function(e,t){const o=e.getSelectedZone();return{...XC(e,t),col:o.left,row:o.top,zone:o}})),oE.add("SUM_SELECTION",iE),oE.add("SET_DECIMAL",iE);class rE{getters;dispatch;selection;operation;sheetId;constructor(e,t,o,i){this.getters=t,this.dispatch=o,this.selection=i,this.operation=e,this.sheetId=t.getActiveSheetId()}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0}addMissingDimensions(e,t,o,i){const s=this.getters.getActiveSheetId(),n=t+i-this.getters.getNumberRows(s);n>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(s)-1,sheetId:s,quantity:n,position:"after"});const r=e+o-this.getters.getNumberCols(s);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(s)-1,sheetId:s,quantity:r,position:"after"})}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class aE extends rE{cells;copiedTables;zones;constructor(e,t,o,i,s){if(super(t,o,i,s),!e.length)return this.cells=[[]],this.zones=[],void(this.copiedTables=[]);const n=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===n.size&&1===r.size?function(e){return e.reduce(((e,t)=>{const o=e.length;for(let i=0;i<o;i++)if(gi(e[i],t))return e[i]=hi(e[i],t),e;return e[o]=t,e}),[])}(e):[e[e.length-1]],h=c.map((e=>Ci(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=o.getActiveSheetId();for(let e of u){let t=[];for(let i of d){const s={col:i,row:e,sheetId:p};t.push({cell:o.getCell(s),style:o.getCellComputedStyle(s),evaluatedCell:o.getEvaluatedCell(s),border:o.getCellBorder(s)||void 0,position:s})}g.push(t)}const m=[];for(const t of e)for(const e of this.getters.getFilterTablesInZone(p,t)){const t=[];for(const o of Ke(e.zone.left,e.zone.right+1))t.push(this.getters.getFilterValues({sheetId:p,col:o,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 o=this.getters.getActiveSheetId();if("CUT"===this.operation&&void 0!==t?.pasteOption)return 21;if(e.length>1&&(this.cells.length>1||this.cells[0].length>1))return 20;const i=this.cells.length,s=this.cells[0].length;for(let t of this.getPasteZones(e))if(this.getters.doesIntersectMerge(o,t)&&(e.length>1||!this.getters.isSingleCellOrMerge(o,e[0])||i*s!=1))return 2;const{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(o);for(const t of this.getPasteZones(e))if(t.left<n&&t.right>=n||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 o=this.cells.length,i=this.cells[0].length,s="CUT"===this.operation;t?.selectTarget&&this.selectPastedZone(i,o,s,e)}pasteFromCopy(e,t){if(1===e.length){const o=this.cells.length,i=this.cells[0].length,s=this.pastedZones(e,i,o);for(const e of s)this.pasteZone(e.left,e.top,t)}else for(const o of e)for(let e=o.left;e<=o.right;e++)for(let i=o.top;i<=o.bottom;i++)this.pasteZone(e,i,t);void 0===t?.pasteOption&&this.pasteCopiedTables(e)}pasteFromCut(e,t){this.clearClippedZones();const o=e[0];this.pasteZone(o.left,o.top,t),this.dispatch("MOVE_RANGES",{target:this.zones,sheetId:this.sheetId,targetSheetId:this.getters.getActiveSheetId(),col:o.left,row:o.top});for(const e of this.copiedTables)this.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.sheetId,target:[e.zone]});this.pasteCopiedTables(e)}pastedZones(e,t,o){const i=e[0],s=Math.max(1,Math.floor((i.right+1-i.left)/t)),n=Math.max(1,Math.floor((i.bottom+1-i.top)/o)),r=[];for(let e=0;e<s;e++)for(let s=0;s<n;s++){const n=i.top+s*o,a=i.left+e*t;r.push({left:a,top:n,bottom:n+o-1,right:a+t-1})}return r}getPasteZones(e){const t=this.cells;if(!t.length||!t[0].length)return e;const o=[],i=t.length,s=t[0].length,n=e[e.length-1],r=n.left,a=n.top,l=Math.max(1,Math.floor((n.right+1-r)/s)),c=Math.max(1,Math.floor((n.bottom+1-a)/i));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)o.push({left:r,top:a,right:r-1+e*s,bottom:a-1+t*i});return o}selectPastedZone(e,t,o,i){const s=i[0],n=s.left,r=s.top;if(t>1||e>1||o){const s=this.pastedZones(i,e,t),a=o?s[0]:hi(...s);this.selection.selectZone({cell:{col:n,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,o){const i=this.cells.length,s=this.cells[0].length,n="onlyValue"!==o?.pasteOption&&o?.shouldPasteCF,r=this.getters.getActiveSheetId();this.addMissingDimensions(s,i,e,t);for(let a=0;a<i;a++){const i=this.cells[a];for(let l=0;l<s;l++){const s=i[l],c={col:e+l,row:t+a,sheetId:r};"CUT"!==this.operation&&this.pasteMergeIfExist(s.position,c),this.pasteCell(s,c,this.operation,o),n&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{originPosition:s.position,targetPosition:c,operation:this.operation})}}}pasteCell(e,t,o,i){const{sheetId:s,col:n,row:r}=t,a=this.getters.getEvaluatedCell(t);if("onlyValue"!==i?.pasteOption){const o=this.getters.getCellBorder(t),i=e.border,a={top:o?.top||i?.top,bottom:o?.bottom||i?.bottom,left:o?.left||i?.left,right:o?.right||i?.right};this.dispatch("SET_BORDER",{sheetId:s,col:n,row:r,border:a})}if(e.cell){if("onlyFormat"===i?.pasteOption)return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.evaluatedCell.format});if("onlyValue"===i?.pasteOption){const o=bo(e.evaluatedCell.value);return void this.dispatch("UPDATE_CELL",{...t,content:o})}let a=e.cell.content;if(e.cell.isFormula&&"COPY"===o){const t=n-e.position.col,i=r-e.position.row;a=this.getUpdatedContent(s,e.cell,t,i,o)}this.dispatch("UPDATE_CELL",{...t,content:a,style:e.cell.style||null,format:e.cell.format})}else a&&("onlyValue"===i?.pasteOption?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===i?.pasteOption?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,o,i,s){const n=this.getters.createAdaptedRanges(t.dependencies,o,i,e);return this.getters.buildFormulaContent(e,t,n)}pasteMergeIfExist(e,t){let{sheetId:o,col:i,row:s}=e;const{col:n,row:r}=this.getters.getMainCellPosition(e);if(n===i&&r===s){const n=this.getters.getMerge(e);if(!n)return;({sheetId:o,col:i,row:s}=t),this.dispatch("ADD_MERGE",{sheetId:o,force:!0,target:[{left:i,top:s,right:i+n.right-n.left,bottom:s+n.bottom-n.top}]})}}pasteCopiedTables(e){const t=this.getters.getActiveSheetId(),o=e[0],i=this.zones[0],s=[o.left-i.left,o.top-i.top];for(const e of this.copiedTables){const o=Ei(e.zone,"both","MOVE",s);this.dispatch("CREATE_FILTER_TABLE",{sheetId:t,target:[o]});for(const i of Ke(0,e.filtersValues.length))this.dispatch("UPDATE_FILTER",{sheetId:t,col:o.left+i,row:o.top,values:e.filtersValues[i]})}}getClipboardContent(){return{[Is.PlainText]:this.getPlainTextContent(),[Is.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 o of t){e+=`<td style="${Li(Fi(o.style))}">`+GS(this.getters.getCellText(o.position))+"</td>"}e+="</tr>"}return e+="</table>",e}isColRowDirtyingClipboard(e,t){if(!this.zones)return!1;for(let o of this.zones){if("COL"===t&&e<=o.right)return!0;if("ROW"===t&&e<=o.bottom)return!0}return!1}drawClipboard(e){const{ctx:t,thinLineWidth:o}=e;if(this.sheetId===this.getters.getActiveSheetId()&&this.zones&&this.zones.length){t.setLineDash([8,5]),t.strokeStyle=E,t.lineWidth=3.3*o;for(const e of this.zones){const{x:o,y:i,width:s,height:n}=this.getters.getVisibleRect(e);s>0&&n>0&&t.strokeRect(o,i,s,n)}}}}class lE{operation;getters;dispatch;sheetId;copiedFigure;copiedFigureContent;constructor(e,t,o){this.operation=e,this.getters=t,this.dispatch=o,this.sheetId=t.getActiveSheetId();const i=t.getSelectedFigureId();if(!i)throw new Error("No figure selected");const s=t.getFigure(this.sheetId,i);if(!s)throw new Error(`No figure for the given id: ${i}`);switch(this.copiedFigure={...s},s.tag){case"chart":this.copiedFigureContent=new cE(o,t,this.sheetId,i);break;case"image":this.copiedFigureContent=new hE(o,t,this.sheetId,i);break;default:throw new Error(`Unknow tag '${s.tag}' for the given figure id: ${i}`)}}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0===e.length?74:void 0!==t?.pasteOption?22:0}paste(e){const t=this.getters.getActiveSheetId(),{width:o,height:i}=this.copiedFigure,s=this.getters.getNumberCols(t),n=this.getters.getNumberRows(t),r=this.getters.getColDimensions(t,e[0].left).start,a=this.getters.getRowDimensions(t,e[0].top).start,l=this.getters.getColDimensions(t,s-1).end,c=this.getters.getRowDimensions(t,n-1).end,h={x:l<o?0:Math.min(r,l-o),y:c<i?0:Math.min(a,c-i)},d=(new ti).uuidv4();this.copiedFigureContent.paste(t,d,h,{height:i,width:o}),"CUT"===this.operation&&this.dispatch("DELETE_FIGURE",{sheetId:this.copiedFigureContent.sheetId,id:this.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{id:d})}getClipboardContent(){return{[Is.PlainText]:"\t"}}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class cE{dispatch;sheetId;copiedChart;constructor(e,t,o,i){this.dispatch=e,this.sheetId=o;const s=t.getChart(i);if(!s)throw new Error(`No chart for the given id: ${i}`);this.copiedChart=s.copyInSheetId(o)}paste(e,t,o,i){const s=this.copiedChart.copyInSheetId(e);this.dispatch("CREATE_CHART",{id:t,sheetId:e,position:o,size:i,definition:s.getDefinition()})}}class hE{dispatch;sheetId;copiedImage;constructor(e,t,o,i){this.dispatch=e,this.sheetId=o;const s=t.getImage(i);this.copiedImage=Be(s)}paste(e,t,o,i){const s=Be(this.copiedImage);this.dispatch("CREATE_IMAGE",{figureId:t,sheetId:e,position:o,size:i,definition:s})}}class dE extends rE{values;constructor(e,t,o,i){super("COPY",t,o,i),this.values=e.replace(/\r/g,"").split("\n").map((e=>e.split("\t")))}isPasteAllowed(e,t){const o=this.getters.getActiveSheetId(),i=this.getPasteZone(e);return this.getters.doesIntersectMerge(o,i)?2:0}paste(e){const t=this.values,o=this.getPasteZone(e),{left:i,top:s}=o,{numberOfCols:n,numberOfRows:r}=vi(o),a=this.getters.getActiveSheetId();this.addMissingDimensions(n,r,i,s);for(let e=0;e<t.length;e++)for(let o=0;o<t[e].length;o++)this.dispatch("UPDATE_CELL",{row:s+e,col:i+o,content:t[e][o],sheetId:a});const l={left:i,top:s,right:i+n-1,bottom:s+r-1};this.selection.selectZone({cell:{col:i,row:s},zone:l})}getClipboardContent(){return{[Is.PlainText]:this.values.map((e=>e.join("\t"))).join("\n")}}getPasteZone(e){const t=this.values.length,o=Math.max(...this.values.map((e=>e.length))),{left:i,top:s}=e[0];return{top:s,left:i,bottom:s+t-1,right:i+o-1}}}function uE(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:o}=Yo(e.value),[i,s]=t.split(":"),n=o?`${$e(o)}!`:"",r=gE(i),a=s?`:${gE(s)}`:"";return{...e,value:n+r+a}}function gE(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=pE(e,"colrow");break;case"colrow":e=pE(e,"row");break;case"row":e=pE(e,"col");break;case"col":e=pE(e,"none")}return e}function pE(e,t){let o;switch(e=e.replace(/\$/g,""),t){case"col":return"$"+e;case"row":return o=e.search(/[0-9]/),e.slice(0,o)+"$"+e.slice(o);case"colrow":return o=e.search(/[0-9]/),-1===o||0===o?"$"+e:"$"+(e=e.slice(0,o)+"$"+e.slice(o));case"none":return e}}const mE=n("The cell you are trying to edit has been deleted.");const fE=[{name:n("Sum"),types:[ys.number],compute:e=>tc.compute([e])},{name:n("Avg"),types:[ys.number],compute:e=>uc.compute([e])},{name:n("Min"),types:[ys.number],compute:e=>Oc.compute([e])},{name:n("Max"),types:[ys.number],compute:e=>Ic.compute([e])},{name:n("Count"),types:[ys.number,ys.text,ys.boolean,ys.error],compute:e=>Cc.compute([e])},{name:n("Count Numbers"),types:[ys.number,ys.text,ys.boolean,ys.error],compute:e=>Sc.compute([e])}];const bE=(new zi).add("sheet",class extends IC{static 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","checkZonesExistInSheet","getCommandZones","checkElementsIncludeAllNonFrozenHeaders"];sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(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 Tt(e.elements)<0||Rt(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){for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let t of e.sheets){const e=t.name||s("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:o,rowNumber:i}=this.getImportedSheetSize(t),n={id:t.id,name:e,numberOfCols:o,rows:ei(i),areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0}};this.orderedSheetIds.push(n.id),this.sheets[n.id]=n}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(dt).map((e=>{const t=this.sheets[e],o={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)&&(o.panes=t.panes),o}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e){const t=He(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,o){return"COL"===t?o>=0&&o<this.getNumberCols(e):o>=0&&o<this.getNumberRows(e)}getRow(e,t){const o=this.getSheet(e).rows[t];if(!o)throw new Error(`Row ${o} not found.`);return o}getCell({sheetId:e,col:t,row:o}){const i=this.tryGetSheet(e)?.rows[o]?.cells[t];if(void 0!==i)return this.getters.getCellById(i)}getColsZone(e,t,o){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:o}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(dt)}getRowsZone(e,t,o){return{top:t,bottom:o,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 o=this.orderedSheetIds.map(this.getSheetName.bind(this));let i=`${e}${t}`;for(;o.includes(i);)i=`${e}${t}`,t++;return i}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,o){const i={...this.getPaneDivisions(e)};"COL"===o?i.xSplit=t:"ROW"===o&&(i.ySplit=t),this.history.update("sheets",e,"panes",i)}checkElementsIncludeAllNonFrozenHeaders(e,t,o){const i=this.getters.getPaneDivisions(e),s="ROW"===t?i.ySplit:i.xSplit,n=this.getters.getNumberHeaders(e,t);if(!s)return!1;return St(o,Ke(s,n))}isEmpty(e,t){return Ci(t).map((({col:t,row:o})=>this.getCell({sheetId:e,col:t,row:o}))).every((e=>!e||""===e.content))}getCommandZones(e){const t=[];return"zone"in e&&t.push(e.zone),"target"in e&&t.push(...e.target),"ranges"in e&&t.push(...e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone))),"col"in e&&"row"in e&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(si))return 25;if(t.length){const o=this.getSheetZone(e);return t.every((e=>mi(e,o)))?0:18}return 0}updateCellPosition(e){const{sheetId:t,cellId:o,col:i,row:s}=e;o?this.setNewPosition(o,t,i,s):this.clearPosition(t,i,s)}setNewPosition(e,t,o,i){const s=this.cellPosition[e];s&&this.clearPosition(t,s.col,s.row),this.history.update("cellPosition",e,{row:i,col:o,sheetId:t}),this.history.update("sheets",t,"rows",i,"cells",o,e)}clearPosition(e,t,o){const i=this.sheets[e]?.rows[o].cells[t];i&&(this.history.update("cellPosition",i,void 0),this.history.update("sheets",e,"rows",o,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++){this.sheets[e].rows[i].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:i})}}createSheet(e,t,o,i,s){const n={id:e,name:t,numberOfCols:o,rows:ei(i),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},r=this.orderedSheetIds.slice();r.splice(s,0,n.id);const a=this.sheets;return this.history.update("orderedSheetIds",r),this.history.update("sheets",Object.assign({},a,{[n.id]:n})),n}moveSheet(e,t){const o=this.orderedSheetIds.slice(),i=o.findIndex((t=>t===e)),s=o.splice(i,1);let n=this.findIndexOfTargetSheet(i,t);o.splice(n,0,s[0]),this.history.update("orderedSheetIds",o)}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(n("There is not enough visible sheets"))}checkSheetName(e){const{orderedSheetIds:t,sheets:o}=this,i=e.name&&e.name.trim().toLowerCase();return t.find((e=>o[e]?.name.toLowerCase()===i))?11:ce.test(i)?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 o of t)if(o.top<e.quantity&&e.quantity<=o.bottom)return 66;return 0}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let o of t)if(o.left<e.quantity&&e.quantity<=o.right)return 66;return 0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const o=e.name;this.history.update("sheets",e.id,"name",t.trim());const i=Object.assign({},this.sheetIdsMapName);i[t]=e.id,delete i[o],this.history.update("sheetIdsMapName",i)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t){const o=this.getSheet(e),i=this.getDuplicateSheetName(o.name),s=Be(o);s.id=t,s.name=i;for(let e=0;e<=s.numberOfCols;e++)for(let t=0;t<=s.rows.length;t++)s.rows[t]&&(s.rows[t].cells[e]=void 0);const n=this.orderedSheetIds.slice(),r=n.indexOf(e);n.splice(r+1,0,s.id),this.history.update("orderedSheetIds",n),this.history.update("sheets",Object.assign({},this.sheets,{[s.id]:s}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:o}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:s.id,col:e,row:o,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIdsMapName);a[s.name]=s.id,this.history.update("sheetIdsMapName",a)}getDuplicateSheetName(e){let t=1;const o=this.orderedSheetIds.map(this.getSheetName.bind(this)),i=n("Copy of %s",e);let s=i.toString();for(;o.includes(s);)s=`${i} (${t})`,t++;return s}deleteSheet(e){const t=e.name,o=Object.assign({},this.sheets);delete o[e.id],this.history.update("sheets",o);const i=this.orderedSheetIds.slice(),s=i.indexOf(e.id);i.splice(s,1),this.history.update("orderedSheetIds",i);const n=Object.assign({},this.sheetIdsMapName);delete n[t],this.history.update("sheetIdsMapName",n)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let o of t)this.moveCellOnColumnsDeletion(e,o);const o=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",o-t.length);const i=t.filter((t=>t<e.panes.xSplit)).length;i&&this.setPaneDivisions(e.id,e.panes.xSplit-i,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(let o of Qe(t)){const t=o[o.length-1],i=o[0];this.moveCellOnRowsDeletion(e,t,i),this.updateRowsStructureOnDeletion(e,t,i)}const o=t.filter((t=>t<e.panes.ySplit)).length;o&&this.setPaneDivisions(e.id,e.panes.ySplit-o,"ROW")}addColumns(e,t,o,i){const s="before"===o?t:t+1;this.moveCellsOnAddition(e,s,i,"columns");const n=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",n+i),s<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+i,"COL")}addRows(e,t,o,i){const s="before"===o?t:t+1;this.addEmptyRows(e,i),this.moveCellsOnAddition(e,s,i,"rows"),s<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+i,"ROW")}moveCellOnColumnsDeletion(e,t){for(let o=0;o<e.rows.length;o++){const i=e.rows[o];for(let s in i.cells){const n=Number(s),r=i.cells[s];r&&(n===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:n,row:o}),n>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:n-1,row:o}))}}}moveCellsOnAddition(e,t,o,i){const s=[];for(let n=0;n<e.rows.length;n++){const r=e.rows[n];if("rows"!==i||n>=t)for(let a in r.cells){const l=Number(a),c=r.cells[a];c&&("rows"===i||l>=t)&&s.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c,col:l+("columns"===i?o:0),row:n+("rows"===i?o:0)})}}for(let e of s.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,o){const i=o-t+1;for(let s=0;s<e.rows.length;s++){const n=e.rows[s];if(s>=t&&s<=o)for(let t in n.cells){const o=Number(t);n.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:o,row:s})}if(s>o)for(let t in n.cells){const o=Number(t),r=n.cells[t];r&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:o,row:s-i})}}}updateRowsStructureOnDeletion(e,t,o){const i=[],s=e.rows.map((e=>e.cells)).reverse();for(let n in e.rows){const e=Number(n);e>=t&&e<=o||i.push({cells:s.pop()})}this.history.update("sheets",e.id,"rows",i)}addEmptyRows(e,t){const o=e.rows.slice();for(let e=0;e<t;e++)o.push({cells:{}});this.history.update("sheets",e.id,"rows",o)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(qt);let o=e.rowNumber,i=e.colNumber;for(let{col:e,row:s}of t)o=Math.max(o,s+1),i=Math.max(i,e+1);return{rowNumber:o,colNumber:i}}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}checkZonesAreInSheet(e){return"sheetId"in e?this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):0}}).add("header visibility",class extends IC{static getters=["checkElementsIncludeAllVisibleHeaders","getHiddenColsGroups","getHiddenRowsGroups","isRowHiddenByUser","isColHiddenByUser"];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),o="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=o?67:Tt(e.elements)<0||Rt(e.elements)>o?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,Be(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 o of[...e.elements].sort(((e,t)=>t-e)))t.splice(o,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]],o=bt(e.position,e.base);t.splice(o,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,o){return St(o,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=[[]],o=this.hiddenHeaders[e].COL;for(let e=0;e<o.length;e++){o[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=[[]],o=this.hiddenHeaders[e].ROW;for(let e=0;e<o.length;e++){o[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 Ke(0,this.hiddenHeaders[e][t].length).filter((o=>!this.hiddenHeaders[e][t][o]))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=Boolean(t.rows[e]?.isHidden);for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=Boolean(t.cols[e]?.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let o of e.sheets){void 0===o.rows&&(o.rows={});for(let e=0;e<this.getters.getNumberRows(o.id);e++)(t||this.hiddenHeaders[o.id].ROW[e])&&(void 0===o.rows[e]&&(o.rows[e]={}),o.rows[e].isHidden=this.hiddenHeaders[o.id].ROW[e]);void 0===o.cols&&(o.cols={});for(let e=0;e<this.getters.getNumberCols(o.id);e++)(t||this.hiddenHeaders[o.id].COL[e])&&(void 0===o.cols[e]&&(o.cols[e]={}),o.cols[e].isHidden=this.hiddenHeaders[o.id].COL[e])}}}).add("filters",class extends IC{static getters=["doesZonesContainFilter","getFilter","getFilters","getFilterTable","getFilterTables","getFilterTablesInZone","getFilterId"];tables={};allowDispatch(e){switch(e.type){case"CREATE_FILTER_TABLE":if(!Ti(...e.target))return 82;const t=hi(...e.target),o=()=>this.getFilterTables(e.sheetId).some((e=>gi(e.zone,t)))?79:0,i=()=>{const o=this.getters.getMergesInZone(e.sheetId,t);for(let e of o)if(gi(t,e))return 81;return 0};return this.checkValidations(e,o,i);case"ADD_MERGE":for(let t of e.target)for(let o of this.getFilterTables(e.sheetId))if(gi(o.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 o={};for(const t of Object.values(this.tables[e.sheetId]||{}))if(t){const e=Be(t);o[e.id]=e}this.history.update("tables",e.sheetIdTo,o);break;case"ADD_COLUMNS_ROWS":this.onAddColumnsRows(e);break;case"REMOVE_COLUMNS_ROWS":this.onDeleteColumnsRows(e);break;case"CREATE_FILTER_TABLE":{const t=hi(...e.target),o=this.createFilterTable(t);this.history.update("tables",e.sheetId,o.id,o);break}case"REMOVE_FILTER_TABLE":{const t={};for(const o of this.getFilterTables(e.sheetId))e.target.every((e=>!di(e,o.zone)))&&(t[o.id]=o);this.history.update("tables",e.sheetId,t);break}case"UPDATE_CELL":{const t=e.sheetId;for(let o of this.getFilterTables(t))this.canUpdateCellCmdExtendTable(e,o)&&this.extendTableDown(t,o);break}}}getFilters(e){return this.getFilterTables(e).map((e=>e.filters)).flat()}getFilterTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(dt):[]}getFilter(e){return this.getFilterTable(e)?.filters.find((t=>t.col===e.col))}getFilterId(e){return this.getFilter(e)?.id}getFilterTable({sheetId:e,col:t,row:o}){return this.getFilterTables(e).find((e=>pi(t,o,e.zone)))}getFilterTablesInZone(e,t){return this.getFilterTables(e).filter((e=>mi(e.zone,t)))}doesZonesContainFilter(e,t){for(const o of t)for(const t of this.getFilterTables(e))if(di(o,t.zone))return!0;return!1}onAddColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const o=ri(t.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),i=[];for(const o of t.filters){const t=ri(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);i.push(new AC(o.id,t))}if(i.length<vi(o).numberOfCols){for(let e=o.left;e<=o.right;e++)i.find((t=>t.col===e))||i.push(new AC(this.uuidGenerator.uuidv4(),{...o,left:e,right:e}));i.sort(((e,t)=>e.col-t.col))}this.history.update("tables",e.sheetId,t.id,"zone",o),this.history.update("tables",e.sheetId,t.id,"filters",i)}}onDeleteColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){if("ROW"===e.dimension&&e.elements.includes(t.zone.top)){const o={...this.tables[e.sheetId]};delete o[t.id],this.history.update("tables",e.sheetId,o);continue}const o=ci(t.zone,"COL"===e.dimension?"left":"top",e.elements);if(o){if(ni(o)!==ni(t.zone)){const i=[];for(const o of t.filters){const t=ci(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.elements);t&&i.push(new AC(o.id,t))}this.history.update("tables",e.sheetId,t.id,"zone",o),this.history.update("tables",e.sheetId,t.id,"filters",i)}}else{const o={...this.tables[e.sheetId]};delete o[t.id],this.history.update("tables",e.sheetId,o)}}}createFilterTable(e){return new TC(e)}extendTableDown(e,t){const o={...t.zone,bottom:t.zone.bottom+1};this.history.update("tables",e,t.id,"zone",o);for(let o=0;o<t.filters.length;o++){const i=t.filters[o],s={...i.zoneWithHeaders,bottom:i.zoneWithHeaders.bottom+1};this.history.update("tables",e,t.id,"filters",o,"zoneWithHeaders",s)}}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:o,row:i},s){if(!e)return;const n=s.zone;if(!(n.bottom+1===i&&o>=n.left&&o<=n.right))return!1;for(const e of Ke(n.left,n.right+1)){const o={sheetId:t,col:e,row:i},s=this.getters.getCell(o)?.content;if(s)return!1;if(this.getters.getFilter(o))return!1;if(this.getters.isInMerge(o))return!1}return!0}import(e){for(const t of e.sheets)for(const e of t.filterTables||[]){const o=this.createFilterTable(ii(e.range));this.history.update("tables",t.id,o.id,o)}}export(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))t.filterTables.push({range:ni(e.zone)})}exportForExcel(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))1!==vi(e.zone).numberOfRows&&t.filterTables.push({range:ni(e.zone),filters:[]})}}).add("cell",class extends IC{static getters=["zoneToXC","getCells","getFormulaCellContent","getCellStyle","buildFormulaContent","getCellById"];nextId=1;cells={};adaptRanges(e,t){for(const o of Object.keys(this.cells))for(const i of Object.values(this.cells[o]||{}))if(i.isFormula)for(const s of i.dependencies)if(!t||s.sheetId===t){const t=e(s);"NONE"!==t.changeType&&this.history.update("cells",o,i.id,"dependencies",i.dependencies.indexOf(s),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case"CLEAR_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);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,o){for(let i of t)for(let t=i.top;t<=i.bottom;t++)for(let s=i.left;s<=i.right;s++)this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,format:o})}clearFormatting(e,t){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:null,format:""})}handleAddColumnsRows(e,t){let o,i;"before"===e.position?(o=Ke(e.base,e.base+e.quantity),i=e.base+e.quantity):(o=Ke(e.base+1,e.base+e.quantity+1),i=e.base),t(e.sheetId,i,o)}import(e){for(let t of e.sheets)for(let o in t.cells){const i=t.cells[o],{col:s,row:n}=qt(o);if(i?.content||i?.format||i?.style){const o=this.importCell(t.id,i,e.styles,e.formats);this.history.update("cells",t.id,o.id,o),this.dispatch("UPDATE_CELL_POSITION",{cellId:o.id,col:s,row:n,sheetId:t.id})}}}export(e){const t={},o={};for(let i of e.sheets){const e={},s=Object.keys(this.cells[i.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const i of s){const s=this.getters.getCell(i);e[Zt(i.col,i.row)]={style:s.style?gt(s.style,t):void 0,format:s.format?gt(s.format,o):void 0,content:s.content||void 0}}i.cells=e}e.styles=t,e.formats=o}importCell(e,t,o,i){const s=t.style&&o[t.style]||void 0,n=t.format&&i[t.format]||void 0,r=this.getNextUid();return this.createCell(r,t?.content||"",n,s,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,o,i=!1){const s=o||t.dependencies;let n=0;return pt(t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=s[n++];return this.getters.getRangeString(t,e,i)}return t.value})))}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,o=[{colFixed:!1,rowFixed:!1}]){const i=Zt((t=this.getters.expandZone(e,t)).left,t.top,o[0]),s=Zt(t.right,t.bottom,o.length>1?o[1]:o[0]),n=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),r=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=n.col===r.col&&n.row===r.row;return i==s||a?i:i+":"+s}setStyle(e,t,o){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let s=i.top;s<=i.bottom;s++){const i=this.getters.getCell({sheetId:e,col:t,row:s});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:s,style:o?{...i?.style,...o}:void 0})}}copyColumnStyle(e,t,o){for(let i=0;i<this.getters.getNumberRows(e);i++){const s=this.getFormat(e,t,i);if(s.style||s.format)for(let t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,...s})}}copyRowStyle(e,t,o){for(let i=0;i<this.getters.getNumberCols(e);i++){const s=this.getFormat(e,i,t);if(s.style||s.format)for(let t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:i,row:t,...s})}}getFormat(e,t,o){const i={},s=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),n=this.getters.getCell(s);return n&&(n.style&&(i.style=n.style),n.format&&(i.format=n.format)),i}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,o,i){const s=this.getters.getCell({sheetId:e,col:t,row:o}),n="content"in i||"formula"in i,r=n?It(i?.content):s?.content||"";let a;a=void 0!==i.style?i.style||void 0:s?s.style:void 0;const l="format"in i?i.format:s&&s.format;if((n&&!r&&!i.formula||!n&&(!s||""===s.content))&&!a&&!l)return void(s&&(this.history.update("cells",e,s.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:o,sheetId:e})));const c=s?.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:o,sheetId:e})}createCell(e,t,o,i,s){if(!t.startsWith("="))return this.createLiteralCell(e,t,o,i);try{return this.createFormulaCell(e,t,o,i,s)}catch(s){return this.createErrorFormula(e,t,o,i,s)}}createLiteralCell(e,t,o,i){return{id:e,content:t,style:i,format:o||Oo(t),isFormula:!1}}createFormulaCell(e,t,o,i,s){const n=rS(t);return n.dependencies.length?this.createFormulaCellWithDependencies(e,n,o,i,s):{id:e,content:t,style:i,format:o,isFormula:!0,compiledFormula:n,dependencies:[]}}createFormulaCellWithDependencies(e,t,o,i,s){const n=t.dependencies.map((e=>this.getters.getRangeFromSheetXC(s,e))),r=this.buildFormulaContent.bind(this);return{id:e,get content(){return r(s,{dependencies:this.dependencies,compiledFormula:this.compiledFormula})},style:i,format:o,isFormula:!0,compiledFormula:t,dependencies:n}}createErrorFormula(e,t,o,i,s){return{id:e,content:t,style:i,format:o,isFormula:!0,compiledFormula:{dependencies:[],tokens:xv(t),execute:function(){throw s}},dependencies:[]}}checkCellOutOfSheet(e){const{sheetId:t,col:o,row:i}=e;if(!this.getters.tryGetSheet(t))return 27;return pi(o,i,this.getters.getSheetZone(t))?0:18}checkUselessClearCell(e){const t=this.getters.getCell(e);return t&&(t.content||t.style||t.format)?0:94}checkUselessUpdateCell(e){const t=this.getters.getCell(e),o="style"in e,i="format"in e;return("content"in e||"formula"in e)&&t?.content!==e.content||o&&!vt(t?.style,e.style)||i&&t?.format!==e.format?0:94}}).add("merge",class extends IC{static getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge"];nextId=1;merges={};mergeCellMap={};allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return 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 o of Object.values(t).filter(dt))this.addMerge(e.sheetIdTo,o.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 o=t?[t]:Object.keys(this.merges);for(const t of o)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(dt)}getMerge({sheetId:e,col:t,row:o}){const i=this.mergeCellMap[e],s=i?t in i&&i[t]?.[o]:void 0;return s?this.getMergeById(e,s):void 0}getMergesInZone(e,t){const o=this.mergeCellMap[e];if(!o)return[];const i=new Set;for(const{col:e,row:s}of Ci(t)){const t=o[e]?.[s];t&&i.add(t)}return Array.from(i).map((t=>this.getMergeById(e,t))).filter(dt)}doesIntersectMerge(e,t){for(const o of this.getMerges(e))if(gi(t,o))return!0;return!1}doesColumnsHaveCommonMerges(e,t,o){const i=this.getters.getSheet(e);for(let s=0;s<this.getters.getNumberRows(e);s++)if(this.isInSameMerge(i.id,t,s,o,s))return!0;return!1}doesRowsHaveCommonMerges(e,t,o){const i=this.getters.getSheet(e);for(let s=0;s<=this.getters.getNumberCols(e);s++)if(this.isInSameMerge(i.id,s,t,s,o))return!0;return!1}expandZone(e,t){let{left:o,right:i,top:s,bottom:n}=t,r={left:o,right:i,top:s,bottom:n};for(let t in this.merges[e]){const o=this.getMergeById(e,parseInt(t));o&&gi(o,r)&&(r=hi(o,r))}return ui(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,o,i,s){const n=this.getMerge({sheetId:e,col:t,row:o}),r=this.getMerge({sheetId:e,col:i,row:s});return!(!n||!r)&&ui(n,r)}isInMerge({sheetId:e,col:t,row:o}){const i=this.mergeCellMap[e];return!!i&&(t in i&&Boolean(i[t]?.[o]))}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:o}=this.getMerge(e);return{sheetId:e.sheetId,col:o,row:t}}isMergeHidden(e,t){const o=this.getters.getHiddenColsGroups(e),i=this.getters.getHiddenRowsGroups(e);for(let e of o)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of i)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const o=this.getMerge({sheetId:e,col:t.left,row:t.top});if(o)return ui(t,o);const{numberOfCols:i,numberOfRows:s}=vi(t);return 1===i&&1===s}isMergeDestructive(e,t){let{left:o,right:i,top:s,bottom:n}=t;i=We(i,0,this.getters.getNumberCols(e)-1),n=We(n,0,this.getters.getNumberRows(e)-1);for(let t=s;t<=n;t++)for(let n=o;n<=i;n++)if(n!==o||t!==s){const o=this.getters.getCell({sheetId:e,col:n,row:t});if(o&&""!==o.content)return!0}return!1}getMergeById(e,t){const o=this.merges[e]?.[t];return void 0!==o?MC(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 o of e)if(t!==o&&gi(t,o))return 66;return 0}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;const{xSplit:o,ySplit:i}=this.getters.getPaneDivisions(e);for(const e of t)if(e.left<o&&e.right>=o||e.top<i&&e.bottom>=i)return 76;return 0}checkMergedContentUpdate(e){const{col:t,row:o,content:i}=e;if(void 0===i)return 0;const{col:s,row:n}=this.getMainCellPosition(e);return s===t&&n===o?0:4}checkMergeExists(e){const{sheetId:t,target:o}=e;for(const e of o){const{left:o,top:i}=e,s=this.getMerge({sheetId:t,col:o,row:i});if(void 0===s||!ui(e,s))return 5}return 0}addMerge(e,t){let{left:o,right:i,top:s,bottom:n}=t;i=We(i,0,this.getters.getNumberCols(e)-1),n=We(n,0,this.getters.getNumberRows(e)-1);if(Zt(o,s)===Zt(i,n))return;const r=this.getters.getCell({sheetId:e,col:o,row:s});let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,ni({left:o,top:s,right:i,bottom:n})));let l=new Set;for(let t=s;t<=n;t++)for(let n=o;n<=i;n++){n===o&&t===s||this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,style:r?r.style:null,content:""});const i=this.getMerge({sheetId:e,col:n,row:t});i&&l.add(i.id),this.history.update("mergeCellMap",e,n,t,a)}for(let t of l){const{top:o,bottom:i,left:s,right:n}=this.getMergeById(e,t);for(let t=o;t<=i;t++)for(let o=s;o<=n;o++){const i={sheetId:e,col:o,row:t},s=this.getMerge(i);s&&s.id===a||(this.history.update("mergeCellMap",e,o,t,void 0),this.dispatch("CLEAR_CELL",i))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:o,top:i,bottom:s,right:n}=t,r=this.getMerge({sheetId:e,col:o,row:i});if(void 0!==r&&ui(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=i;t<=s;t++)for(let i=o;i<=n;i++)this.history.update("mergeCellMap",e,i,t,void 0)}}applyRangeChangeOnSheet(e,t){const o=Object.entries(this.merges[e]||{});for(const[i,s]of o)if(s){const o=s.zone,n=t(s);switch(n.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,o);break;default:const{numberOfCols:t,numberOfRows:s}=vi(n.range.zone);1===t&&1===s?this.removeMerge(e,o):this.history.update("merges",e,parseInt(i,10),n.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:o,row:i}of Ci(t))this.history.update("mergeCellMap",e,o,i,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 o of t)this.addMerge(e,ii(o))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...OC(e))}}exportForExcel(e){this.export(e)}}).add("headerSize",class extends IC{static getters=["getRowSize","getColSize"];sizes={};handle(e){switch(e.type){case"CREATE_SHEET":{const t=this.computeSheetSizes(e.sheetId),o={COL:t.COL.map((e=>({manualSize:void 0,computedSize:mt(e)}))),ROW:t.ROW.map((e=>({manualSize:void 0,computedSize:mt(e)})))};this.history.update("sizes",e.sheetId,o);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,Be(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const t={...this.sizes};delete t[e.sheetId],this.history.update("sizes",t);break;case"REMOVE_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];for(let o of[...e.elements].sort(((e,t)=>t-e)))t.splice(o,1);const o=Tt(e.elements);t=t.map(((t,i)=>"ROW"===e.dimension&&i>=o?{manualSize:t.manualSize,computedSize:mt((()=>this.getRowTallestCellSize(e.sheetId,i)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];const o=bt(e.position,e.base),i=t[e.base],s=Ke(0,e.quantity).map((()=>({manualSize:i.manualSize,computedSize:mt(i.computedSize())})));t.splice(o,0,...s),t=t.map(((t,o)=>"ROW"===e.dimension&&o>e.base+e.quantity?{manualSize:t.manualSize,computedSize:mt((()=>this.getRowTallestCellSize(e.sheetId,o)))}: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 o=this.getRowTallestCellSize(e.sheetId,t);this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:mt(o)})}else this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:mt(e.size||L)});break;case"UPDATE_CELL":const o=this.sizes[e.sheetId]?.ROW?.[e.row];if(o&&!o.manualSize){const{sheetId:t,row:o}=e;this.history.update("sizes",t,"ROW",o,"computedSize",mt((()=>this.getRowTallestCellSize(t,o))))}break;case"ADD_MERGE":case"REMOVE_MERGE":for(let t of e.target)for(let o of Ke(t.top,t.bottom+1)){const t=this.getRowTallestCellSize(e.sheetId,o);t!==this.getRowSize(e.sheetId,o)&&this.history.update("sizes",e.sheetId,"ROW",o,"computedSize",mt(t))}}}getColSize(e,t){return this.getHeaderSize(e,"COL",t)}getRowSize(e,t){return this.getHeaderSize(e,"ROW",t)}getHeaderSize(e,t,o){return Math.round(this.sizes[e]?.[t][o]?.manualSize||this.sizes[e]?.[t][o]?.computedSize()||this.getDefaultHeaderSize(t))}computeSheetSizes(e){const t={COL:[],ROW:[]};for(let o of Ke(0,this.getters.getNumberCols(e)))t.COL.push(this.getHeaderSize(e,"COL",o));for(let o of Ke(0,this.getters.getNumberRows(e))){let i=this.sizes[e]?.ROW?.[o].manualSize;if(!i){i=this.getRowTallestCellSize(e,o)}t.ROW.push(i)}return t}getDefaultHeaderSize(e){return"COL"===e?L:P}getCellHeight(e){const t=this.getters.getMerge(e);if(t&&t.bottom!==t.top)return P;return function(e){return e&&e.content?Ge(Xe(e.style),e.isFormula?1:e.content.split(me).length)+2*H:P}(this.getters.getCell(e))}getRowTallestCellSize(e,t){const o=this.getters.getRowCells(e,t);let i=0;for(let e=0;e<o.length;e++){const t=this.getters.getCellById(o[e]);if(!t)continue;const s=this.getters.getCellPosition(t.id),n=this.getCellHeight(s);n>i&&n>P&&(i=n)}return i<=P?P:i}import(e){for(let t of e.sheets){const e={COL:[],ROW:[]};for(let[o,i]of Object.entries(t.rows))i.size&&(e.ROW[o]=i.size);for(let[o,i]of Object.entries(t.cols))i.size&&(e.COL[o]=i.size);const o=this.computeSheetSizes(t.id);this.sizes[t.id]={COL:o.COL.map(((t,o)=>({manualSize:e.COL[o],computedSize:mt(t)}))),ROW:o.ROW.map(((t,o)=>({manualSize:e.ROW[o],computedSize:mt(t)})))}}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let o of e.sheets){void 0===o.rows&&(o.rows={});for(let e of Ke(0,this.getters.getNumberRows(o.id)))(t||this.sizes[o.id].ROW[e]?.manualSize)&&(o.rows[e]={...o.rows[e],size:this.getRowSize(o.id,e)});void 0===o.cols&&(o.cols={});for(let e of Ke(0,this.getters.getNumberCols(o.id)))(t||this.sizes[o.id].COL[e]?.manualSize)&&(o.cols[e]={...o.cols[e],size:this.getColSize(o.id,e)})}}}).add("borders",class extends IC{static getters=["getCellBorder","getBordersColors"];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 o=t.slice().map((e=>e?.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,o)}break;case"DELETE_SHEET":const o={...this.borders};delete o[e.sheetId],this.history.update("borders",o);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_ZONE_BORDERS":if(e.border){const t=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));this.setBorders(e.sheetId,t,e.border.position,""===e.border.color?void 0:{style:e.border.style||X,color:e.border.color||K})}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":for(let t of[...e.elements].sort(((e,t)=>t-e)))"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,o;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,o=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,o)}handleAddRows(e){let t,o;"before"===e.position?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,o=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,o)}getCellBorder({sheetId:e,col:t,row:o}){const i={top:this.borders[e]?.[t]?.[o]?.horizontal,bottom:this.borders[e]?.[t]?.[o+1]?.horizontal,left:this.borders[e]?.[t]?.[o]?.vertical,right:this.borders[e]?.[t+1]?.[o]?.vertical};return i.bottom||i.left||i.right||i.top?i:null}getBordersColors(e){const t=[],o=this.borders[e];if(o)for(const e of o.filter(dt))for(const o of e)o?.horizontal&&t.push(o.horizontal.color),o?.vertical&&t.push(o.vertical.color);return t}ensureColumnBorderContinuity(e,t,o){const i=Ke(t+1,o);for(let s=0;s<this.getters.getNumberRows(e);s++){const n=this.getCellBorder({sheetId:e,col:t,row:s}),r=this.getCellBorder({sheetId:e,col:o,row:s});if(n&&r){const t=this.getCommonSides(n,r);for(let o of i)this.addBorder(e,o,s,t)}}}ensureRowBorderContinuity(e,t,o){const i=Ke(t+1,o);for(let s=0;s<this.getters.getNumberCols(e);s++){const n=this.getCellBorder({sheetId:e,col:s,row:t}),r=this.getCellBorder({sheetId:e,col:s,row:o});if(n&&r){const t=this.getCommonSides(n,r);for(let o of i)this.addBorder(e,s,o,t)}}}getCommonSides(e,t){const o={};for(let i of["top","bottom","left","right"])e[i]&&e[i]===t[i]&&(o[i]=e[i]);return o}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsRange(e){return this.borders[e]?Ke(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,o,{moveFirstLeftBorder:i}={}){this.borders[e]&&(o<0&&this.moveBordersOfColumn(e,t,o,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((s=>{(s===t&&i||s!==t)&&this.moveBordersOfColumn(e,s,o,"vertical"),this.moveBordersOfColumn(e,s,o,"horizontal")})))}shiftBordersVertically(e,t,o,{moveFirstTopBorder:i}={}){this.borders[e]&&(o<0&&this.moveBordersOfRow(e,t,o,"horizontal",{destructive:!1}),this.getRowsRange(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((s=>{(s===t&&i||s!==t)&&this.moveBordersOfRow(e,s,o,"horizontal"),this.moveBordersOfRow(e,s,o,"vertical")})))}moveBordersOfRow(e,t,o,i,{destructive:s}={destructive:!0}){const n=this.borders[e];n&&this.getColumnsWithBorders(e).forEach((r=>{const a=n[r]?.[t+o]?.[i],l=n[r]?.[t]?.[i];this.history.update("borders",e,r,t+o,i,s?l:l||a),this.history.update("borders",e,r,t,i,void 0)}))}moveBordersOfColumn(e,t,o,i,{destructive:s}={destructive:!0}){const n=this.borders[e];n&&this.getRowsRange(e).forEach((r=>{const a=n[t+o]?.[r]?.[i],l=n[t]?.[r]?.[i];this.history.update("borders",e,t+o,r,i,s?l:l||a),this.history.update("borders",e,t,r,i,void 0)}))}setBorder(e,t,o,i,s=!0){!s&&this.borders?.[e]?.[t]?.[o]?.vertical||this.history.update("borders",e,t,o,"vertical",i?.left),!s&&this.borders?.[e]?.[t]?.[o]?.horizontal||this.history.update("borders",e,t,o,"horizontal",i?.top),!s&&this.borders?.[e]?.[t+1]?.[o]?.vertical||this.history.update("borders",e,t+1,o,"vertical",i?.right),!s&&this.borders?.[e]?.[t]?.[o+1]?.horizontal||this.history.update("borders",e,t,o+1,"horizontal",i?.bottom)}clearBorders(e,t){for(let o of t){for(let t=o.top;t<=o.bottom;t++){this.history.update("borders",e,o.right+1,t,"vertical",void 0);for(let i=o.left;i<=o.right;i++)this.history.update("borders",e,i,t,void 0)}for(let t=o.left;t<=o.right;t++)this.history.update("borders",e,t,o.bottom+1,"horizontal",void 0)}}addBorder(e,t,o,i){this.setBorder(e,t,o,{...this.getCellBorder({sheetId:e,col:t,row:o}),...i})}setBorders(e,t,o,i){if("clear"===o)return this.clearBorders(e,t);for(let s of t){if("h"===o||"hv"===o||"all"===o)for(let t=s.top+1;t<=s.bottom;t++)for(let o=s.left;o<=s.right;o++)this.addBorder(e,o,t,{top:i});if("v"===o||"hv"===o||"all"===o)for(let t=s.top;t<=s.bottom;t++)for(let o=s.left+1;o<=s.right;o++)this.addBorder(e,o,t,{left:i});if("left"===o||"all"===o||"external"===o)for(let t=s.top;t<=s.bottom;t++)this.addBorder(e,s.left,t,{left:i});if("right"===o||"all"===o||"external"===o)for(let t=s.top;t<=s.bottom;t++)this.addBorder(e,s.right+1,t,{left:i});if("top"===o||"all"===o||"external"===o)for(let t=s.left;t<=s.right;t++)this.addBorder(e,t,s.top,{top:i});if("bottom"===o||"all"===o||"external"===o)for(let t=s.left;t<=s.right;t++)this.addBorder(e,t,s.bottom+1,{top:i})}}addBordersToMerge(e,t){const{left:o,right:i,top:s,bottom:n}=t,r=this.getCellBorder({sheetId:e,col:o,row:s}),a=this.getCellBorder({sheetId:e,col:i,row:n});this.clearBorders(e,[t]),r?.top&&this.setBorders(e,[{...t,bottom:s}],"top",r.top),r?.left&&this.setBorders(e,[{...t,right:o}],"left",r.left),a?.bottom?this.setBorders(e,[{...t,top:n}],"bottom",a.bottom):r?.bottom&&this.setBorders(e,[{...t,top:n}],"bottom",r.bottom),a?.right?this.setBorders(e,[{...t,left:i}],"right",a.right):r?.right&&this.setBorders(e,[{...t,left:i}],"right",r.right)}checkBordersUnchanged(e){const t=this.getCellBorder(e),o=!(e.border?.bottom||e.border?.left||e.border?.right||e.border?.top);return!t&&o||vt(t,e.border)?94:0}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(const o in t.cells){const i=t.cells[o];if(i?.border){const s=e.borders[i.border],{col:n,row:r}=qt(o);this.setBorder(t.id,n,r,s,!1)}}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,ii(e))}export(e){let t=0;const o={};function i(e){for(let[t,i]of Object.entries(o))if(vt(i,e))return parseInt(t,10);return o[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let o=0;o<t.rowNumber;o++){const s=this.getCellBorder({sheetId:t.id,col:e,row:o});if(s){const n=Zt(e,o),r=t.cells[n],a=i(s);r?r.border=a:t.cells[n]={border:a}}}e.borders=o}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends IC{static getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];cfRules={};loopThroughRangesOfSheet(e,t){for(const o of this.cfRules[e])for(const i of o.ranges){const s=t(i);switch(s.changeType){case"REMOVE":let t=o.ranges.slice();t.splice(o.ranges.indexOf(i),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",t):this.removeConditionalFormatting(o.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",o.ranges.indexOf(i),s.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 o={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(o,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){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,{useFixedReference:!0}))))}getConditionalFormats(e){return this.cfRules[e]?.map((t=>this.mapToConditionalFormat(e,t)))||[]}getRulesSelection(e,t){const o=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{o.add(e)}))})),Array.from(o)}getRulesByZone(e,t){const o=new Set;for(let i=t.top;i<=t.bottom;i++)for(let s=t.left;s<=t.right;s++){this.getRulesByCell(e,s,i).forEach((e=>{o.add(e.id)}))}return o}getRulesByCell(e,t,o){const i=[];for(let s of this.cfRules[e])for(let e of s.ranges)pi(t,o,e.zone)&&i.push(s);return new Set(i.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t,o={useFixedReference:!1}){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e,o.useFixedReference)))}}mapToConditionalFormatInternal(e,t){const o={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return o}addConditionalFormatting(e,t){const o=this.cfRules[t].slice(),i=o.findIndex((t=>t.id===e.id)),s=this.mapToConditionalFormatInternal(t,e);i>-1?o.splice(i,1,s):o.push(s),this.history.update("cfRules",t,o)}checkValidReordering(e,t,o){if(!this.cfRules[o])return 27;const i=this.cfRules[o].findIndex((t=>t.id===e));if(-1===i)return 72;const s="up"===t?i-1:i+1;return s<0||s>=this.cfRules[o].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 o=>{if(t.includes(o.operator)){const t=[],i=e=>void 0===e||""===e;return e>=1&&i(o.values[0])&&t.push(52),e>=2&&i(o.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{rS(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,o=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(o)?49:0}checkMinBiggerThanMax(e){const t=e.minimum.value,o=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&RC(t)>=RC(o)?48:0}checkMidBiggerThanMax(e){const t=e.midpoint?.value,o=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&RC(t)>=RC(o)?50:0}checkMinBiggerThanMid(e){const t=e.minimum.value,o=e.midpoint?.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&RC(t)>=RC(o)?51:0}removeConditionalFormatting(e,t){const o=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==o){const e=this.cfRules[t].slice();e.splice(o,1),this.history.update("cfRules",t,e)}}reorderConditionalFormatting(e,t,o){const i=this.cfRules[o].findIndex((t=>t.id===e)),s="up"===t?i-1:i+1;if(!(s<0||s>=this.cfRules[o].length)&&-1!==i&&-1!==s){const e=[...this.cfRules[o]],t=e[i];e[i]=e[s],e[s]=t,this.history.update("cfRules",o,e)}}}).add("figures",class extends IC{static getters=["getFigures","getFigure","getFigureSheetId"];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}}beforeHandle(e){if("DELETE_SHEET"===e.type)this.getters.getFigures(e.sheetId).forEach((t=>{this.dispatch("DELETE_FIGURE",{id:t.id,sheetId:e.sheetId})}))}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:o,...i}=e,s=i;this.updateFigure(o,s);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId);break;case"REMOVE_COLUMNS_ROWS":this.onRowColDelete(e.sheetId,e.dimension)}}onRowColDelete(e,t){"ROW"===t?this.onRowDeletion(e):this.onColDeletion(e)}onRowDeletion(e){const t=this.getters.getNumberRows(e);let o=0;for(let i=0;i<t;i++)o+=this.getters.getRowSize(e,i);const i=this.getters.getFigures(e);for(const t of i){const i=Math.min(t.y,o-t.height);i!==t.y&&this.dispatch("UPDATE_FIGURE",{sheetId:e,id:t.id,y:i})}}onColDeletion(e){const t=this.getters.getNumberCols(e);let o=0;for(let i=0;i<t;i++)o+=this.getters.getColSize(e,i);const i=this.getters.getFigures(e);for(const t of i){const i=Math.min(t.x,o-t.width);i!==t.x&&this.dispatch("UPDATE_FIGURE",{sheetId:e,id:t.id,x:i})}}updateFigure(e,t){if("id"in t)for(const[o,i]of Object.entries(t))switch(o){case"x":case"y":void 0!==i&&this.history.update("figures",e,t.id,o,Math.max(i,0));break;case"width":case"height":void 0!==i&&this.history.update("figures",e,t.id,o,i)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){return void 0===this.figures[e]?.[t]?71:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>t?.[e]))?83:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(dt)}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>void 0!==this.figures[t]?.[e]))}import(e){for(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 o=void 0;t.figures.push({...e,data:o})}}exportForExcel(e){this.export(e)}}).add("chart",class extends IC{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];charts={};createChart=function(e){const t=$r.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(o,i,s){const n=t.find((e=>e.match(i.type)));if(!n)throw new Error(`No builder for this chart: ${i.type}`);return n.createChart(i,s,e)}}(this.getters);validateChartDefinition=e=>function(e,t){const o=$r.getAll().find((e=>e.match(t.type)));if(!o)throw new Error("Unknown chart type.");return o.validateChartDefinition(e,t)}(this,e.definition);adaptRanges(e){for(const[t,o]of Object.entries(this.charts))this.history.update("charts",t,o?.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){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 t=this.getters.getFigures(e.sheetId);for(const o of t)if("chart"===o.tag){const t=o.id.split(ie).pop(),i=`${e.sheetIdTo}${ie}${t}`,s=this.charts[o.id]?.copyForSheetId(e.sheetIdTo);s&&this.dispatch("CREATE_CHART",{id:i,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){return this.charts[e]?.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){const t=this.charts[e]?.type;if(!t)throw new Error("Chart not defined.");return t}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter((([,t])=>t?.sheetId===e)).map((([e])=>e))}getChartDefinition(e){const t=this.charts[e]?.getDefinition();if(!t)throw new Error(`There is no chart with the given figureId: ${e}`);return t}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){if(e.sheets)for(let t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(let t of e){const e=t;if(e&&"chart"===e.tag){const t=this.charts[e.id]?.getDefinition();t&&(e.data=t,o.push(e))}else o.push(e)}t.figures=o}}exportForExcel(e){for(let t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(let t of e)if(t&&"chart"===t.tag){const e=this.charts[t.id]?.getDefinitionForExcel();e&&o.push({...t,data:e})}t.charts=o}}addFigure(e,t,o={x:0,y:0},i={width:536,height:335}){if(this.getters.getFigure(t,e))return;const s={id:e,x:o.x,y:o.y,width:i.width,height:i.height,tag:"chart"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:s})}addChart(e,t){const o=this.getters.getFigureSheetId(e);o&&this.history.update("charts",e,this.createChart(e,t,o))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?85:0}checkChartExists(e){return this.getters.getFigureSheetId(e.id)?0:86}}).add("image",class extends IC{static getters=["getImage","getImagePath","getImageSize"];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?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 o of t)if("image"===o.tag){const t=o.id.split(ie).pop(),i=`${e.sheetIdTo}${ie}${t}`,s=this.getImage(o.id);if(s){const t={width:o.width,height:o.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:i,position:{x:o.x,y:o.y},size:t,definition:Be(s)})}}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(){const e=new Set(this.getAllImages().map((e=>e.path)));for(const t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,o,i){const s={id:e,x:o.x,y:o.y,width:i.width,height:i.height,tag:"image"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:s})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter((e=>"image"===e.tag));for(const o of e)this.history.update("images",t.id,o.id,o.data),this.syncedImages.add(o.data.path)}}export(e){for(const t of e.sheets){const e=t.figures.filter((e=>"image"===e.tag));for(const o of e)o.data=this.images[t.id]?.[o.id]}}exportForExcel(e){for(const t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(const t of e)if("image"===t?.tag){const e=this.getImage(t.id);e&&o.push({...t,data:Be(e)})}t.images=o}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(dt));return e}}),vE=(new zi).add("ui_sheet",class extends _C{static getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getColDimensions","getRowDimensions","getColRowOffset"];ctx=document.createElement("canvas").getContext("2d");allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){const o=this.getColMaxWidth(e.sheetId,t);0!==o&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:o,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),o=this.getters.getCellComputedStyle(e),i=t.split(me);let s=Math.max(...i.map((e=>this.getTextWidth(e,o))));this.getters.getConditionalIcon(e)&&(s+=function(e){return Xe(e)+2*z}(this.getters.getCellStyle(e)));if(this.getters.isFilterHeader(e)&&(s+=20),s>0&&(s+=2*$,"wrap"===this.getters.getCellStyle(e).wrapping)){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,s)}return s}getTextWidth(e,t){return qe(this.ctx,e,t)}getCellText(e,t=!1){const o=this.getters.getCell(e);return t&&o?.isFormula?o.content:this.getters.getEvaluatedCell(e).formattedValue}getCellMultiLineText(e,t){const o=this.getters.getCellStyle(e),i=this.getters.getCellText(e,this.getters.shouldShowFormulas()),s=[];for(const e of i.split("\n")){const i=e.split(" ");if(!t){s.push(e);continue}let n="",r=t;for(let e of i){const i=this.splitWordToSpecificWidth(this.ctx,e,t,o),a=i.pop(),l=qe(this.ctx,a,o);if(i.length)""!==n&&(s.push(n),n="",r=t),i.forEach((e=>{s.push(e)})),n=a,r=t-l;else{const e=""===n?a:" "+a,i=qe(this.ctx,e,o);i<=r?(n+=e,r-=i):(s.push(n),n=a,r=t-l)}}""!==n&&s.push(n)}return s}getColDimensions(e,t){const o=this.getColRowOffset("COL",0,t,e),i=this.getters.getColSize(e,t);return{start:o,size:i,end:o+(this.getters.isColHidden(e,t)?0:i)}}getRowDimensions(e,t){const o=this.getColRowOffset("ROW",0,t,e),i=this.getters.getRowSize(e,t);return{start:o,size:i,end:o+(this.getters.isRowHidden(e,t)?0:i)}}getColRowOffset(e,t,o,i=this.getters.getActiveSheetId()){if(o<t)return-this.getColRowOffset(e,o,t);let s=0;for(let n=t;n<o;n++)this.getters.isHeaderHidden(i,e,n)||(s+="COL"===e?this.getters.getColSize(i,n):this.getters.getRowSize(i,n));return s}getColMaxWidth(e,t){const o=Ci(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,Rt(o))}splitWordToSpecificWidth(e,t,o,i){if(qe(e,t,i)<=o)return[t];const s=[];let n="";for(let r of t){qe(e,n+r,i)>o?(s.push(n),n=r):n+=r}return s.push(n),s}checkSheetExists(e){return"sheetId"in e&&void 0===this.getters.tryGetSheet(e.sheetId)?27:0}checkZonesAreInSheet(e){const t="sheetId"in e?e.sheetId:this.getters.tryGetActiveSheetId(),o=this.getters.getCommandZones(e);return!t&&o.length>0?93:t&&o.length>0?this.getters.checkZonesExistInSheet(t,o):0}}).add("header_visibility_ui",class extends _C{static getters=["getNextVisibleCellPosition","findVisibleHeader","findLastVisibleColRowIndex","findFirstVisibleColRowIndex","isRowHidden","isColHidden","isHeaderHidden"];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,o){return"COL"===t?this.isColHidden(e,o):this.isRowHidden(e,o)}getNextVisibleCellPosition({sheetId:e,col:t,row:o}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",o,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,o,i){if(o<=i)for(let s=o;s<=i;s++)if(this.getters.doesHeaderExist(e,t,s)&&!this.isHeaderHidden(e,t,s))return s;if(o>i)for(let s=o;s>=i;s--)if(this.getters.doesHeaderExist(e,t,s)&&!this.isHeaderHidden(e,t,s))return s}findLastVisibleColRowIndex(e,t,{last:o,first:i}){return Ke(o,i,-1).find((o=>!this.isHeaderHidden(e,t,o)))||i}findFirstVisibleColRowIndex(e,t){const o=this.getters.getNumberHeaders(e,t);for(let i=0;i<o;i++){if("COL"===t&&!this.isColHidden(e,i))return i;if("ROW"===t&&!this.isRowHidden(e,i))return i}}exportForExcel(e){for(const t of e.sheets)for(const[e,o]of Object.entries(t.rows)){const i=this.isRowHidden(t.id,Number(e));o.isHidden=i}}}).add("ui_options",class extends _C{static getters=["shouldShowFormulas"];showFormulas=!1;handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}).add("selectionInputManager",class extends _C{config;static layers=[1];static getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];inputs={};focusedInputId=null;get currentInput(){return this.focusedInputId?this.inputs[this.focusedInputId]:null}constructor(e){super(e),this.config=e}allowDispatch(e){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 t=this.currentInput?.getIndex(e.rangeId);if(this.focusedInputId===e.id&&this.currentInput?.focusedRangeIndex===t)return 29;break;case"ADD_EMPTY_RANGE":const o=this.inputs[e.id];if(o.inputHasSingleRange&&1===o.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){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:yi({col:0,row:0})},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}break;case"FOCUS_RANGE":case"CHANGE_RANGE":const t=this.inputs[e.id],o=t.ranges.find((t=>t.id===e.rangeId));if(o){const i=this.getters.getActiveSheetId(),s=this.getters.getRangeFromSheetXC(i,o?.xc||"A1").zone;this.selection.capture(t,{cell:{col:s.left,row:s.top},zone:s},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}}this.currentInput?.handle(e)}getSelectionInput(e){return this.inputs[e]?this.inputs[e].ranges.map(((t,o)=>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===o}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:o}=Yo(e);return null!==t.match($o)&&(!o||void 0!==this.getters.getSheetIdByName(o))}getSelectionInputValue(e){return this.inputs[e].getSelectionInputValue()}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].getSelectionInputHighlights():[]}initInput(e,t,o=!1){if(this.inputs[e]=new jC(this.config,t,o),0===t.length){const t=this.inputs[e],o={zone:yi({col:0,row:0}),cell:{col:0,row:0}};this.selection.capture(t,o,{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e}}unfocus(){this.selection.release(this.currentInput),this.focusedInputId=null}}).add("highlight",class extends _C{static layers=[1];static getters=["getHighlights"];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:o}=vi(e.zone),i=t*o==1?this.getters.expandZone(e.sheetId,e.zone):e.zone;return{...e,zone:i}}))}drawGrid(e){const{ctx:t,thinLineWidth:o}=e,i=this.getters.getActiveSheetId(),s=3*o;t.lineWidth=s;const n=this.getHighlights();for(let e of n.filter(((e,t)=>n.findIndex((t=>ui(t.zone,e.zone)&&t.sheetId===i))===t))){const{x:o,y:i,width:n,height:r}=this.getters.getVisibleRect(e.zone);n>0&&r>0&&(t.strokeStyle=e.color,t.strokeRect(o+s/2,i+s/2,n-s,r-s),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(o+s,i+s,n-2*s,r-2*s))}}}).add("grid renderer",class extends _C{static layers=[0,7];static getters=["getColDimensionsInViewport","getRowDimensionsInViewport"];boxes=[];getColDimensionsInViewport(e,t){const o=Tt(this.getters.getSheetViewVisibleCols()),i=this.getters.getColRowOffsetInViewport("COL",o,t),s=this.getters.getColSize(e,t);return{start:i,size:s,end:i+(this.getters.isColHidden(e,t)?0:s)}}getRowDimensionsInViewport(e,t){const o=Tt(this.getters.getSheetViewVisibleRows()),i=this.getters.getColRowOffsetInViewport("ROW",o,t),s=this.getters.getRowSize(e,t);return{start:i,size:s,end:i+(this.getters.isRowHidden(e,t)?0:s)}}getHeaderOffset(e,t,o){let i=this.getters.getColRowOffsetInViewport(e,t,o);return this.getters.isDashboard()||(i+="ROW"===e?F:D),i}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:o}=e,{width:i,height:s}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,i+m,s+m);const n=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),r=n?.1*o:0;if(n)for(const e of this.boxes)t.strokeStyle="#E2E3E3",t.lineWidth=o,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 o=e.style;o.fillColor&&"#ffffff"!==o.fillColor&&(t.fillStyle=o.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){const{ctx:t,thinLineWidth:o}=e;for(const e of this.boxes)if(e.content&&e.isOverflow){const i=e.content.align||"left";let s,n;const r=e.y+o/2,a=e.height-o,l=Math.min(e.clipRect?.width||1/0,e.content.width);"left"===i?(s=e.x+o/2,n=l-2*o):"right"===i?(s=e.x+e.width-o/2,n=2*o-l):(s=(e.clipRect?.x||e.x+e.width/2-e.content.width/2)+o/2,n=l-2*o),t.fillStyle="#ffffff",t.fillRect(s,r,n,a)}}drawBorders(e){const{ctx:t}=e;for(let e of this.boxes){const t=e.border;if(t){const{x:i,y:s,width:n,height:r}=e;t.left&&o(t.left,i,s,i,s+r),t.top&&o(t.top,i,s,i+n,s),t.right&&o(t.right,i+n,s,i+n,s+r),t.bottom&&o(t.bottom,i,s+r,i+n,s+r)}}function o({style:e,color:o},i,s,n,r){switch(t.strokeStyle=o,e){case"medium":t.lineWidth=2,s+=(i+=s===r?-.5:.5)===(n+=s===r?1.5:.5)?-.5:.5,r+=i===n?1.5:.5;break;case"thick":t.lineWidth=3,s===r&&(i--,n++),i===n&&(s--,r++);break;case"dashed":t.lineWidth=1,t.setLineDash([1,3]);break;case"dotted":t.lineWidth=1,s===r&&(i+=.5,n+=.5),i===n&&(s+=.5,r+=.5),t.setLineDash([1,1]);break;default:t.lineWidth=1}t.beginPath(),t.moveTo(i,s),t.lineTo(n,r),t.stroke(),t.lineWidth=1,t.setLineDash([])}}drawTexts(e){const{ctx:t,thinLineWidth:o}=e;let i;t.textBaseline="top";for(let e of this.boxes)if(e.content){const s=e.style||{},n=e.content.align||"left",r=Ye(s);r!==i&&(i=r,t.font=r),t.fillStyle=s.textColor||"#000";let a=e.x;if(a+="left"===n?B+(e.image?e.image.size+z:0):"right"===n?e.width-B-(e.isFilterHeader?20:0):e.width/2,t.textAlign=n,e.clipRect){t.save(),t.beginPath();const{x:o,y:i,width:s,height:n}=e.clipRect;t.rect(o,i,s,n),t.clip()}const l=Xe(s),c=e.content.textLines.length;let h=this.computeTextYCoordinate(e,l,c);for(let i of e.content.textLines){if(t.fillText(i,Math.round(a),Math.round(h)),s.strikethrough||s.underline){const e=qe(t,i,s);let r=a;"right"===n?r-=e:"center"===n&&(r-=e/2),s.strikethrough&&t.fillRect(r,h+l/2,e,2.6*o),s.underline&&t.fillRect(r,h+l+1,e,1.3*o)}h+=B+l}e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const o=e.image.image;if(e.image.clipIcon){t.save(),t.beginPath();const{x:o,y:i,width:s,height:n}=e.image.clipIcon;t.rect(o,i,s,n),t.clip()}const i=e.image.size,s=this.computeTextYCoordinate(e,i);t.drawImage(o,e.x+z,s,i,i),e.image.clipIcon&&t.restore()}}computeTextYCoordinate(e,t,o=1){const i=e.y+1,s=Ge(t,o),n=e.height>s+2*B,r=e.verticalAlign||Y;if(n){if("middle"===r)return i+(e.height-s)/2;if("bottom"===r)return i+e.height-s-B}return i+B}drawHeaders(e){const{ctx:t,thinLineWidth:o}=e,i=this.getters.getSheetViewVisibleCols(),s=i[0],n=i[i.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 o of e)for(let e of Ke(o.left,o.right+1))t.add(e);return t}(d),g=function(e){const t=new Set;for(let o of e)for(let e of Ke(o.top,o.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 ${j}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=o,t.strokeStyle="#333";for(let e=s;e<=n;e++){const o={left:e,right:e,top:0,bottom:f-1},{x:i,width:s}=this.getters.getVisibleRect(o),n=this.getters.doesZonesContainFilter(p,[o]),r=E.has(e),a=u.has(e);t.fillStyle=r?n?T:S:a?n?O:v:n?A:b,t.fillRect(i,0,s,F)}for(let e=a;e<=l;e++){const o={top:e,bottom:e,left:0,right:m-1},{y:i,height:s}=this.getters.getVisibleRect(o),n=this.getters.doesZonesContainFilter(p,[o]),r=w.has(e),a=g.has(e);t.fillStyle=r?n?T:S:a?n?O:v:n?A:b,t.fillRect(0,i,D,s)}t.beginPath(),t.moveTo(D,0),t.lineTo(D,h),t.moveTo(0,F),t.lineTo(c,F),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(const e of i){const o=this.getters.getColSize(p,e),i=Bt(e);t.fillStyle=E.has(e)?"#fff":C;let n=this.getHeaderOffset("COL",s,e);t.fillText(i,n+o/2,13),t.moveTo(n+o,0),t.lineTo(n+o,F)}for(const e of r){const o=this.getters.getRowSize(p,e);t.fillStyle=w.has(e)?"#fff":C;let i=this.getHeaderOffset("ROW",a,e);t.fillText(String(e+1),24,i+o/2),t.moveTo(0,i+o),t.lineTo(D,i+o)}t.stroke()}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:o}=e,{x:i,y:s}=this.getters.getMainViewportCoordinates(),n=this.getters.isDashboard()?0:D,r=this.getters.isDashboard()?0:F;t.lineWidth=6*o,t.strokeStyle="#BCBCBC",t.beginPath(),i&&(t.moveTo(n+i,0),t.lineTo(n+i,r)),s&&(t.moveTo(0,r+s),t.lineTo(n,r+s)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:o}=e,{x:i,y:s}=this.getters.getMainViewportCoordinates(),n=this.getters.getSheetViewVisibleCols(),r=n[0],a=n[n.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:r,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:D,u=this.getters.isDashboard()?0:F;t.lineWidth=6*o,t.strokeStyle="#DADFE8",t.beginPath(),i&&(t.moveTo(d+i,u),t.lineTo(d+i,h.height+u)),s&&(t.moveTo(d,u+s),t.lineTo(h.width+d,u+s)),t.stroke()}findNextEmptyCol(e,t,o){const i=this.getters.getActiveSheetId();let s=e;for(;s<t;){const e={sheetId:i,col:s+1,row:o},t=this.getters.getEvaluatedCell(e),n=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==ys.empty||this.getters.isInMerge(e)||n?.left)return s;s++}return s}findPreviousEmptyCol(e,t,o){const i=this.getters.getActiveSheetId();let s=e;for(;s>t;){const e={sheetId:i,col:s-1,row:o},t=this.getters.getEvaluatedCell(e),n=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==ys.empty||this.getters.isInMerge(e)||n?.right)return s;s--}return s}computeCellAlignment(e,t){if(this.getters.getCell(e)?.isFormula&&this.getters.shouldShowFormulas())return"left";const{align:o}=this.getters.getCellStyle(e),i=this.getters.getEvaluatedCell(e);return t&&i.type===ys.number?"center"!==o?"left":o:o||i.defaultAlign}createZoneBox(e,t,o){const{left:i,right:s}=o,n=t.left,r=t.top,a={sheetId:e,col:n,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===ys.empty)return f;const b=this.getters.getConditionalIcon(a),v=Xe(f.style),S=b?z+v:0;b&&(f.image={type:"icon",size:v,clipIcon:{x:f.x,y:f.y,width:Math.min(S,g),height:p},image:sf[b].img}),f.isFilterHeader=this.getters.isFilterHeader(a);const C=f.isFilterHeader?19:0,E=this.getters.getCellComputedStyle(a),w=E.wrapping||"overflow",x="wrap"!==w||h?void 0:g-2*B,y=this.getters.getCellMultiLineText(a,x),I=Math.max(...y.map((e=>this.getters.getTextWidth(e,E)+B))),R=S+I+C,T=this.computeCellAlignment(a,R>g);f.content={textLines:y,width:"overflow"===w?I:g,align:T},c.type===ys.error&&c.error.logLevel>l.silent&&(f.error=c.error.message);const A=R>g||v>p;if(b||f.isFilterHeader)f.clipRect={x:f.x+S,y:f.y,width:Math.max(0,g-S-C),height:p};else if(A&&"overflow"===w){let e,o;switch(this.getters.isInMerge(a)?(e=this.getters.getMerge(a).right,o=n):(e=this.findNextEmptyCol(n,s,r),o=this.findPreviousEmptyCol(n,i,r),f.isOverflow=!0),T){case"left":{const o=yi({col:e,row:r}),{x:i,y:s,width:n,height:a}=this.getters.getVisibleRect(hi(t,o));(n<R||v>a||y.length>1)&&(f.clipRect={x:i,y:s,width:n,height:a});break}case"right":{const e=yi({col:o,row:r}),{x:i,y:s,width:n,height:a}=this.getters.getVisibleRect(hi(t,e));(n<R||v>a||y.length>1)&&(f.clipRect={x:i,y:s,width:n,height:a});break}case"center":{const i={...t,left:o,right:e},{x:s,y:n,height:r,width:a}=this.getters.getVisibleRect(i),l=R/2,c=f.x+f.width/2;if(s+a<c+l||s>c-l||v>r||y.length>1){const e=s>c-l?s:c-l,t=s+a-e;f.clipRect={x:e,y:n,width:t,height:r}}break}}}else("clip"===w||"wrap"===w||y.length>1)&&(f.clipRect={x:f.x,y:f.y,width:g,height:p});return f}getGridBoxes(){const e=[],t=this.getters.getSheetViewVisibleCols(),o=t[0],i=t[t.length-1],s=this.getters.getSheetViewVisibleRows(),n={left:o,right:i,top:s[0],bottom:s[s.length-1]},r=this.getters.getActiveSheetId();for(const o of s)for(const i of t){const t={sheetId:r,col:i,row:o};this.getters.isInMerge(t)||e.push(this.createZoneBox(r,yi(t),n))}for(const t of this.getters.getMerges(r))if(!this.getters.isMergeHidden(r,t)&&gi(t,n)){const o=this.createZoneBox(r,t,n),i=this.getters.getCellBorder({sheetId:r,col:t.right,row:t.bottom});o.border={...o.border,bottom:i?i.bottom:void 0,right:i?i.right:void 0},o.isMerge=!0,e.push(o)}return e}}).add("autofill",class extends _C{static layers=[5];static getters=["getAutofillTooltip"];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case"AUTOFILL_SELECT":const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:We(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:We(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:46;case"AUTOFILL_AUTO":const o=this.getters.getSelectedZone();return o.top===o.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(),o=this.autofillZone;switch(this.direction){case"down":for(let i=t.left;i<=t.right;i++){const s=[];for(let e=t.top;e<=t.bottom;e++)s.push(Zt(i,e));const n=this.createGenerator(s);for(let t=o.top;t<=o.bottom;t++)this.computeNewCell(n,i,t,e)}break;case"up":for(let i=t.left;i<=t.right;i++){const s=[];for(let e=t.bottom;e>=t.top;e--)s.push(Zt(i,e));const n=this.createGenerator(s);for(let t=o.bottom;t>=o.top;t--)this.computeNewCell(n,i,t,e)}break;case"left":for(let i=t.top;i<=t.bottom;i++){const s=[];for(let e=t.right;e>=t.left;e--)s.push(Zt(e,i));const n=this.createGenerator(s);for(let t=o.right;t>=o.left;t--)this.computeNewCell(n,t,i,e)}break;case"right":for(let i=t.top;i<=t.bottom;i++){const s=[];for(let e=t.left;e<=t.right;e++)s.push(Zt(e,i));const n=this.createGenerator(s);for(let t=o.left;t<=o.right;t++)this.computeNewCell(n,t,i,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 o=this.getters.getSelectedZone();if(pi(e,t,o))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,o.top-1,o.left,o.right),this.steps=o.top-t;break;case"down":this.saveZone(o.bottom+1,t,o.left,o.right),this.steps=t-o.bottom;break;case"left":this.saveZone(o.top,o.bottom,e,o.left-1),this.steps=o.left-e;break;case"right":this.saveZone(o.top,o.bottom,o.right+1,e),this.steps=e-o.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let o=e.left,i=e.bottom;if(o>0){let e={sheetId:t,col:o-1,row:i};for(;this.getters.getCell(e)?.content;)i+=1,e={sheetId:t,col:o-1,row:i}}if(i===e.bottom&&(o=e.right,o<=this.getters.getNumberCols(t))){let e={sheetId:t,col:o+1,row:i};for(;this.getters.getCell(e)?.content;)i+=1,e={sheetId:t,col:o+1,row:i}}i!==e.bottom&&(this.select(e.left,i-1),this.autofill(!0))}computeNewCell(e,t,o,i){const{cellData:s,tooltip:n,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=s;this.tooltip=n,i&&this.dispatch("AUTOFILL_CELL",{originCol:r.col,originRow:r.row,col:t,row:o,content:a,style:l,border:c,format:h})}getRule(e,t){const o=Gs.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((o=>o.condition(e,t)));return o&&o.generateRule(e,t)}createGenerator(e){const t=[],o=[],i=this.getters.getActiveSheetId();for(let t of e){const{col:e,row:s}=qt(t),n=this.getters.getCell({sheetId:i,col:e,row:s});o.push({col:e,row:s,cell:n,sheetId:i})}const s=o.map((e=>e.cell));for(let e of o){let o={type:"COPY_MODIFIER"};if(e&&e.cell){o=this.getRule(e.cell,s)||o}const i=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:i},rule:o})}return new LC(t,this.getters,this.direction)}saveZone(e,t,o,i){this.autofillZone={top:e,bottom:t,left:o,right:i}}getDirection(e,t){const o=this.getters.getSelectedZone(),i={up:{number:o.top-t,value:"up"},down:{number:t-o.bottom,value:"down"},left:{number:o.left-e,value:"left"},right:{number:e-o.right,value:"right"}};if(1===Object.values(i).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(i).find((e=>e.number>0?1:0)).value;const s=i.up.number>0?"up":"down",n=i.left.number>0?"left":"right";return Math.abs(i[s].number)>=Math.abs(i[n].number)?i[s].value:i[n].value}autoFillMerge(e,t,o,i){const s=this.getters.getActiveSheetId(),n={sheetId:s,col:o,row:i},r={sheetId:s,col:e,row:t};if(this.getters.isInMerge(n)&&!this.getters.isInMerge(r)){const e=this.getters.getMerge(n);e&&this.dispatch("REMOVE_MERGE",{sheetId:s,target:[e]})}const a=this.getters.getMerge(r);a?.topLeft.col===e&&a?.topLeft.row===t&&this.dispatch("ADD_MERGE",{sheetId:s,target:[{top:i,bottom:i+a.bottom-a.top,left:o,right:o+a.right-a.left}]})}drawGrid(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:o}=e,{x:i,y:s,width:n,height:r}=this.getters.getVisibleRect(this.autofillZone);n>0&&r>0&&(t.strokeStyle="black",t.lineWidth=o,t.setLineDash([3]),t.strokeRect(i,s,n,r),t.setLineDash([]))}}).add("find_and_replace",class extends _C{static layers=[3];static getters=["getSearchMatches","getCurrentSelectedMatchIndex"];searchMatches=[];selectedMatchIndex=null;currentSearchRegex=null;searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1};toSearch="";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(ZC.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(ZC.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(ZC.current)}updateRegex(){let e=ze(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),o=[];if(this.toSearch)for(const i of Object.values(t)){const{col:t,row:s}=this.getters.getCellPosition(i.id),n=this.getters.isColHidden(e,t),r=this.getters.isRowHidden(e,s);if(!n&&!r&&(i&&this.currentSearchRegex&&this.currentSearchRegex.test(this.getSearchableString({sheetId:e,col:t,row:s})))){const e={col:t,row:s,selected:!1};o.push(e)}}return o.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 o;o=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,o=(o%t.length+t.length)%t.length,this.selectedMatchIndex=o,this.selection.selectCell(t[o].col,t[o].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 o=this.getters.getActiveSheetId(),i=this.getters.getCell({sheetId:o,...e}),{col:s,row:n}=e;if(i?.isFormula&&!this.searchOptions.searchFormulas)return;const r=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),a=this.getSearchableString({sheetId:o,col:s,row:n}).replace(r,t);this.dispatch("UPDATE_CELL",{sheetId:o,col:s,row:n,content:a})}replace(e){if(null===this.selectedMatchIndex)return;const t=this.searchMatches[this.selectedMatchIndex];this.replaceMatch(t,e),this.selectNextCell(ZC.next)}replaceAll(e){const t=this.searchMatches.length;for(let o=0;o<t;o++)this.replaceMatch(this.searchMatches[o],e)}getSearchableString(e){const t=this.getters.getCell(e);return this.searchOptions.searchFormulas&&t?.isFormula?t.content:this.getters.getEvaluatedCell(e).formattedValue}drawGrid(e){const{ctx:t}=e,o=this.getters.getActiveSheetId();for(const e of this.searchMatches){const i=this.getters.getMerge({sheetId:o,col:e.col,row:e.row}),s=i?i.left:e.col,n=i?i.right:e.col,r=i?i.top:e.row,a=i?i.bottom:e.row,{x:l,y:c,width:h,height:d}=this.getters.getVisibleRect({top:r,left:s,right:n,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)))}}}).add("sort",class extends _C{static getters=["getContiguousZone"];allowDispatch(e){if("SORT_CELLS"===e.type){if(!pi(e.col,e.row,e.zone))throw new Error(n("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 Ci(t).some((({col:t,row:o})=>!this.getters.isInMerge({sheetId:e,col:t,row:o})))?64:0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const o=this.getters.getMerges(e).filter((e=>gi(e,t))),i=vi(o[0]);let[s,n]=[i.numberOfCols,i.numberOfRows];return o.every((e=>{let[t,o]=[e.right-e.left+1,e.bottom-e.top+1];return t===s&&o===n}))?0:64}expand(e,t){const{left:o,right:i,top:s,bottom:n}=this.getters.expandZone(e,t);return{left:Math.max(0,o),right:Math.min(this.getters.getNumberCols(e)-1,i),top:Math.max(0,s),bottom:Math.min(this.getters.getNumberRows(e)-1,n)}}checkExpandedValues(e,t){const o=this.expand(e,t);let i;if(this.getters.doesIntersectMerge(e,o)){const{left:t,right:s,top:n,bottom:r}=o;for(let o=t;o<=s;o++)for(let t=n;t<=r;t++){const{col:s,row:n}=this.getters.getMainCellPosition({sheetId:e,col:o,row:t});if(i=this.getters.getEvaluatedCell({sheetId:e,col:s,row:n}),i.formattedValue)return!0}}else for(let t of this.getters.getEvaluatedCellsInZone(e,o))if(t.formattedValue)return!0;return!1}getContiguousZone(e,t){let o,{top:i,bottom:s,left:n,right:r}=t,a=!1;for(;!a;)a=!0,i>0&&(o=this.checkExpandedValues(e,{left:n-1,right:r+1,top:i-1,bottom:i-1}),o&&(a=!1,i--)),n>0&&(o=this.checkExpandedValues(e,{left:n-1,right:n-1,top:i-1,bottom:s+1}),o&&(a=!1,n--)),r<this.getters.getNumberCols(e)-1&&(o=this.checkExpandedValues(e,{left:r+1,right:r+1,top:i-1,bottom:s+1}),o&&(a=!1,r++)),s<this.getters.getNumberRows(e)-1&&(o=this.checkExpandedValues(e,{left:n-1,right:r+1,top:s+1,bottom:s+1}),o&&(a=!1,s++));return{left:n,right:r,top:i,bottom:s}}hasHeader(e,t){if(1===t[0].length)return!1;let o=t.map((t=>t.map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).type))));return o[0][0]===ys.empty&&(o=o.slice(1)),!o.some((e=>e[0]===ys.empty))&&!!o.some((e=>e[1]!==ys.empty&&e[0]!==e[1]))}sortZone(e,t,o,i,s){const[n,r]=this.mainCellsSteps(e,o);let a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},o),c=this.mainCells(e,o);!s.sortHeaders&&this.hasHeader(e,c)&&(l.top+=r),c=this.mainCells(e,l);const h=function(e,t,o){const i=e.map(((e,t)=>({index:t,type:e.type,value:e.value})));let s=i.filter((e=>e.type===ys.empty)),n=i.filter((e=>e.type!==ys.empty));o&&(n.push(...s.map((e=>({...e,type:ys.number,value:0})))),s=[]);const r="descending"===t?-1:1;return n.sort(((e,t)=>{let o=sa.indexOf(e.type)-sa.indexOf(t.type);return 0===o&&(o=e.type===ys.text||e.type===ys.error?e.value.localeCompare(t.value):e.value-t.value),r*o})).concat(s)}(c[a-l.left].map((e=>this.getters.getEvaluatedCell(e))),i,Boolean(s.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:o,row:i,sheetId:s}=c[e][d[t]];const a=this.getters.getCell({sheetId:s,col:o,row:i});let h=l.left+e*n,u=l.top+t*r,g={sheetId:s,col:h,row:u,content:""};if(a){let e=a.content;if(a.isFormula){const t=u-this.getters.getCellPosition(a.id).row,o=this.getters.createAdaptedRanges(a.dependencies,0,t,s);e=this.getters.buildFormulaContent(s,a,o)}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 o=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[o?o.right-o.left+1:1,o?o.bottom-o.top+1:1]}mainCells(e,t){const[o,i]=this.mainCellsSteps(e,t),s=[],n=Ke(t.left,t.right+1,o),r=Ke(t.top,t.bottom+1,i);for(const t of n){const o=[];s.push(o);for(const i of r)o.push({sheetId:e,col:t,row:i})}return s}}).add("automatic_sum",class extends _C{static getters=["getAutomaticSums"];handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:o}=this.getters.getSelection();for(const i of t){const t=this.getAutomaticSums(e,i,o.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,o){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,o):this.sumData(e,t)}sumData(e,t){const o=this.dimensionsToSum(e,t),i=this.sumDimensions(e,t,o).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return o.has("ROW")&&o.has("COL")&&i.push(this.sumTotal(t)),i}sumAdjacentData(e,t,o){const{col:i,row:s}=pi(o.col,o.row,t)?o:{col:t.left,row:t.top},n=this.findAdjacentData(e,i,s);return n?this.getters.isSingleCellOrMerge(e,t)||Si(hi(n,t))?[{position:{col:i,row:s},zone:n}]:this.sumDimensions(e,hi(n,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,o){const i=this.getters.getSheet(e),s=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),n=this.findSuitableZoneToSum(i,s.col,s.row);if(n)return this.getters.expandZone(e,n)}findSuitableZoneToSum(e,t,o){const i=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:o-1}),s=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:o});if(this.isNumber(s)&&!this.isNumber(i))return this.findHorizontalZone(e,t,o);const n=this.findVerticalZone(e,t,o);if(this.isZoneValid(n))return n;const r=this.findHorizontalZone(e,t,o);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,o){const i={top:0,bottom:o-1,left:t,right:t},s=this.reduceZoneStart(e,i,i.bottom);return{...i,top:s}}findHorizontalZone(e,t,o){const i={top:o,bottom:o,left:0,right:t-1},s=this.reduceZoneStart(e,i,i.right);return{...i,left:s}}reduceZoneStart(e,t,o){const i=this.getters.getEvaluatedCellsInZone(e.id,t),s=Ke(o,-1,-1),n=Rt(s.filter((e=>i[e]&&!i[e].isAutoSummable))),r=Qe(s.filter((e=>this.isNumber(i[e]))))[0]||[];return Rt(r)<n?1/0:Tt(r)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===ys.number&&!(e.format&&xo(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){const o=new Set;return Si(t)?(o.add(1===vi(t).numberOfCols?"COL":"ROW"),o):(this.lastColIsEmpty(e,t)&&o.add("ROW"),this.lastRowIsEmpty(e,t)&&o.add("COL"),0===o.size&&o.add("COL"),o)}sumDimensions(e,t,o){return[...o.has("COL")?this.sumColumns(t,e):[],...o.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:o}=e;return{position:{col:o,row:t},zone:{...e,top:t,right:o-1}}}sumColumns(e,t){const o=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,o.bottom-1)},Ci(o).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const o=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,o.right-1)},Ci(o).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const o of t){const{col:t,row:i}=o.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,content:`=SUM(${this.getters.zoneToXC(e,o.zone)})`})}}nextEmptyRow(e,t){let o=t.bottom+1;const{left:i,right:s}=t;for(;!this.getters.isEmpty(e,{bottom:o,top:o,left:i,right:s});)o++;return{...t,top:o,bottom:o}}nextEmptyCol(e,t){let o=t.right+1;const{top:i,bottom:s}=t;for(;!this.getters.isEmpty(e,{left:o,right:o,top:i,bottom:s});)o++;return{...t,left:o,right:o}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}).add("format",class extends _C{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,o){for(const i of t)for(const t of Ci(i)){const i=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==i){const s=No(i,o);this.dispatch("SET_FORMATTING",{sheetId:e,target:[yi(t)],format:s})}}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==ys.number||e.format&&xo(e.format)))return e.format||Ao(e.value)}}}).add("split_to_columns",class extends _C{static getters=["getAutomaticSeparator"];allowDispatch(e){return"SPLIT_TEXT_INTO_COLUMNS"===e.type?this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e):0}handle(e){if("SPLIT_TEXT_INTO_COLUMNS"===e.type)this.splitIntoColumns(e)}getAutomaticSeparator(){const e=this.getters.getSelectedCells();for(const t of e)if(t.value&&t.type===ys.text){const e=this.getAutoSeparatorForString(t.value);if(e)return e}return" "}getAutoSeparatorForString(e){const t=[me,";",","," ","."];for(const o of t)if(e.includes(o))return o}splitIntoColumns({separator:e,addNewColumns:t}){const o=this.getters.getSelectedZone(),i=this.getters.getActiveSheetId(),s=this.getSplittedCols(o,e);t&&this.addColsToAvoidCollisions(o,s),this.removeMergesInSplitZone(o,s),this.addColumnsToNotOverflowSheet(o,s);for(let e=0;e<s.length;e++){const t=o.top+e,n=s[e],r=o.left,a=this.getters.getCell({sheetId:i,col:r,row:t});if(1!==n.length||n[0]!==a?.content)for(const[e,o]of n.entries())this.dispatch("UPDATE_CELL",{sheetId:i,col:r+e,row:t,content:o,format:"",style:a?.style||null})}}getSplittedCols(e,t){if(!t)throw new Error("Separator cannot be empty");const o=this.getters.getActiveSheetId(),i=[];for(const s of Ke(e.top,e.bottom+1)){const n=this.getters.getEvaluatedCell({sheetId:o,col:e.left,row:s}).formattedValue;i.push(this.splitAndRemoveTrailingEmpty(n,t))}return i}splitAndRemoveTrailingEmpty(e,t){const o=e.split(t);for(;o.length>1&&""===o[o.length-1];)o.pop();return o}willSplittedColsOverwriteContent(e,t){const o=this.getters.getActiveSheetId();for(const i of Ke(e.top,e.bottom+1)){const s=t[i-e.top];for(let t=1;t<s.length;t++){const s=this.getters.getCell({sheetId:o,col:e.left+t,row:i});if(s&&s.content)return!0}}return!1}removeMergesInSplitZone(e,t){const o=this.getters.getActiveSheetId(),i=Math.max(...t.map((e=>e.length))),s={...e,right:e.left+i-1},n=this.getters.getMergesInZone(o,s);this.dispatch("REMOVE_MERGE",{sheetId:o,target:n})}addColsToAvoidCollisions(e,t){const o=this.getters.getActiveSheetId();let i=0;for(const s of Ke(e.top,e.bottom+1)){const n={sheetId:o,col:e.left,row:s},r=t[s-e.top],a=this.getColsToAddToAvoidCollision(n,r);i=Math.max(i,a)}i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:e.left,sheetId:o,quantity:i,position:"after"})}getColsToAddToAvoidCollision(e,t){const o=t.length;for(let t=1;t<o;t++){const i=e.col+t,s=this.getters.getCell({...e,col:i});if(s&&s.content)return o-t}return 0}addColumnsToNotOverflowSheet(e,t){const o=this.getters.getActiveSheetId(),i=Math.max(...t.map((e=>e.length-1))),s=this.getters.getNumberCols(o)-1;e.left+i>s&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:s,sheetId:o,quantity:e.left+i-s,position:"after"})}checkSingleColSelected(){return this.getters.isSingleColSelected()?0:89}checkNonEmptySelector(e){return""===e.separator?90:0}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return 0;const t=this.getters.getSelectedZones()[0],o=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,o)?91:0}checkSeparatorInSelection({separator:e}){const t=this.getters.getSelectedCells();for(const o of t)if(o.formattedValue.includes(e))return 0;return 92}}).add("cell_popovers",class extends _C{static getters=["getCellPopover","getPersistentPopoverTypeAtPosition","hasOpenedPopover"];persistentPopover;allowDispatch(e){if("OPEN_CELL_POPOVER"===e.type){try{Vn.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}){const o=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=Vn.get(this.persistentPopover.type).onOpen?.(e,this.getters);return t?.isOpen?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}if(void 0===e||void 0===t||!this.getters.isVisibleInViewport({sheetId:o,col:e,row:t}))return{isOpen:!1};const i=this.getters.getMainCellPosition({sheetId:o,col:e,row:t}),s=Vn.getAll().map((e=>e.onHover?.(i,this.getters))).find((e=>e?.isOpen));return s?.isOpen?{...s,anchorRect:this.computePopoverAnchorRect(i)}:{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 o=this.getters.getActiveSheetId(),i=this.getters.getMerge({sheetId:o,col:e,row:t});return i?this.getters.getVisibleRect(i):this.getters.getVisibleRect(yi({col:e,row:t}))}}).add("collaborative",class extends _C{static getters=["getClientsToDisplay","getClient","getConnectedClients","isFullySynchronized"];static layers=[6];availableColors=new Set(qC);colors={};session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}chooseNewColor(){0===this.availableColors.size&&(this.availableColors=new Set(qC));const e=(t=[...this.availableColors.values()])[Math.floor(Math.random()*t.length)];var t;return this.availableColors.delete(e),e}getClient(){return this.session.getClient()}getConnectedClients(){return this.session.getConnectedClients()}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof WC)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const o of this.getters.getConnectedClients())if(o.id!==this.getters.getClient().id&&o.position&&o.position.sheetId===e&&this.isPositionValid(o.position)){const e=o.position;this.colors[o.id]||(this.colors[o.id]=this.chooseNewColor());const i=this.colors[o.id];t.push({...o,position:e,color:i})}return t}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,i=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:s,col:n}=e.position,r=this.getters.expandZone(i,{top:s,bottom:s,left:n,right:n}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);if(c<=0||h<=0)continue;const d=e.color,u=`${d}10`;t.fillStyle=u,t.lineWidth=4*o,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 ${Z+1}px ${j}`}}}).add("history",class extends _C{static getters=["canUndo","canRedo"];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on("new-local-state-update",this,this.onNewLocalStateUpdate),this.session.on("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}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();if(t)"UNDO"===e?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t));else{const e=this.getPossibleRevisionToRepeat();if(!e)return;const t=nE(e,this.getters);if(!t)return;if(!Array.isArray(t))return void this.dispatch(t.type,t);for(const e of t)this.dispatch(e.type,e)}}canUndo(){return this.undoStack.length>0}canRedo(){if(this.redoStack.length>0)return!0;const e=this.getPossibleRevisionToRepeat();return!(!(t=e)||!t.rootCommand||"object"!=typeof t.rootCommand)&&(Ms(t.rootCommand)?tE.contains(t.rootCommand.type):oE.contains(t.rootCommand.type));var t}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()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision(["REQUEST_REDO"])}}),SE=(new zi).add("selection",class extends _C{static layers=[6];static getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getSelectedCells","getStatisticFnResults","getAggregate","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSelected","isSingleColSelected","getElementsFromSelection","tryGetActiveSheetId","isGridSelectionActive"];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;activeSheet=null;constructor(e){super(e),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 o=[];switch(e.mode){case"overrideSelection":o=[t.zone];break;case"updateAnchor":o=[...this.gridSelection.zones];const i=o.findIndex((t=>ui(t,e.previousAnchor.zone)));i>=0&&(o[i]=t.zone);break;case"newAnchor":o=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,o),this.selection.resetDefaultAnchor(this,Be(this.gridSelection.anchor));const{col:i,row:s}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:i,row:s}),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:o,row:i}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(o,i),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:Be(this.gridSelection)},e.sheetIdTo in this.sheetsData)Object.assign(this,this.sheetsData[e.sheetIdTo]),this.selection.resetDefaultAnchor(this,Be(this.gridSelection.anchor));else{const{col:t,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0});this.selectCell(t,o)}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:o,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:i})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:o,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:i})}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 s=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of s)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:Be(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:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:o})}const n=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(n,e))),this.gridSelection.anchor.zone=this.getters.expandZone(n,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null}this.selection.resetDefaultAnchor(this,Be(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}tryGetActiveSheetId(){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 o=t.left;o<=t.right;o++)e.add(o);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(let o of this.gridSelection.zones)if(0===o.left&&o.right===this.getters.getNumberCols(t)-1)for(let t=o.top;t<=o.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 Be(this.gridSelection.zones)}getSelectedZone(){return Be(this.gridSelection.anchor.zone)}getSelection(){return Be(this.gridSelection)}getSelectedCells(){const e=this.getters.getActiveSheetId(),t=[];for(const o of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,o));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{const t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}getStatisticFnResults(){const e=this.getters.getActiveSheetId(),t=new Set;for(const o of this.gridSelection.zones)for(const{col:i,row:s}of Ci(o)){if(this.getters.isRowHidden(e,s)||this.getters.isColHidden(e,i))continue;const o=this.getters.getEvaluatedCell({sheetId:e,col:i,row:s});o.type!==ys.empty&&t.add(o)}let o=new Set,i=[];for(let e of t)o.add(e.type),i.push(e.value);let s={};for(let e of fE){let t;e.types.some((e=>o.has(e)))&&(t=e.compute(i)),s[e.name]=t}return s}getAggregate(){let e=0,t=0;const o=this.getters.getActiveSheetId(),i=this.gridSelection.zones.map(Ci).flat();for(const{col:s,row:n}of i){const i=this.getters.getEvaluatedCell({sheetId:o,col:s,row:n});i.type===ys.number&&(t++,e+=i.value)}return t<2?null:bo(e)}isSelected(e){return!!this.getters.getSelectedZones().find((t=>ui(t,e)))}isSingleColSelected(){const e=this.getters.getSelectedZones();return 1===e.length&&e[0].left===e[0].right}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let o=[];const i="COL"===e?"left":"top",s="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[s]-e[i]+1},((t,o)=>e[i]+o));o=o.concat(t)}return[...new Set(o)].sort()}setSelectionMixin(e,t){const{anchor:o,zones:i}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=o,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,o)=>t===o.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(i)}selectCell(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.expandZone(o,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:i,cell:{col:e,row:t}},[i])}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){const t=this.getters.getSheetIds(),o=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[o]})}onColumnsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,i=li(o,"left",[...e.elements]);let s={left:t.col,right:t.col,top:t.row,bottom:t.row};s=li(s,"left",[...e.elements]);const n={cell:{col:s.left,row:s.top},zone:i},r=this.gridSelection.zones.map((t=>li(t,"left",[...e.elements])));this.setSelectionMixin(n,r)}onRowsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,i=li(o,"top",[...e.elements]);let s={left:t.col,right:t.col,top:t.row,bottom:t.row};s=li(s,"top",[...e.elements]);const n={cell:{col:s.left,row:s.top},zone:i},r=this.gridSelection.zones.map((t=>li(t,"top",[...e.elements])));this.setSelectionMixin(n,r)}onAddElements(e){const t="COL"===e.dimension?"left":"top",o=ai(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),i=this.gridSelection.zones.map((o=>ai(o,t,e.base,e.position,e.quantity))),s={cell:{col:o.left,row:o.top},zone:o};this.setSelectionMixin(s,i)}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 o="COL"===e.dimension,i=e.elements[0],s=e.elements[t-1],n=e.base<i,r=n&&o?t:0,a=n&&!o?t:0,l=[{left:o?i+r:0,right:o?s+r:this.getters.getNumberCols(e.sheetId)-1,top:o?0:i+a,bottom:o?this.getters.getNumberRows(e.sheetId)-1:s+a}],c=new aE(l,"CUT",this.getters,this.dispatch,this.selection),h=n?e.base:e.base+1,d=[{left:o?h:0,right:o?h+t-1:this.getters.getNumberCols(e.sheetId)-1,top:o?0:h,bottom:o?this.getters.getNumberRows(e.sheetId)-1:h+t-1}];c.paste(d,{selectTarget:!0});const u=n?e.elements.map((e=>e+t)):e.elements;let g=e.base;for(const t of u){const o="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:o,elements:[g]}),g+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:u})}isMoveElementAllowed(e){const t="COL"===e.dimension,o=e.elements[0],i=e.elements[e.elements.length-1],s=e.sheetId,n=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(n(s,o-1,o)||n(s,i,i+1)||n(s,e.base-1,e.base))return 2;const r=[e.base,...e.elements],a=t?this.getters.getNumberCols(s):this.getters.getNumberRows(s);return r.some((e=>e<0||e>=a))?87:0}clipSelection(e,t){const o=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:We(e.left,0,o),right:We(e.right,0,o),top:We(e.top,0,i),bottom:We(e.bottom,0,i)}))),anchor:{cell:{col:We(t.anchor.cell.col,0,o),row:We(t.anchor.cell.row,0,i)},zone:{left:We(t.anchor.zone.left,0,o),right:We(t.anchor.zone.right,0,o),top:We(t.anchor.zone.top,0,i),bottom:We(t.anchor.zone.bottom,0,i)}}}}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,i=this.getSelectedZones();t.fillStyle="#f3f7fe";const s=1===i.length&&i[0].left===i[0].right&&i[0].top===i[0].bottom;t.fillStyle=s?"#f3f7fe":"#e9f0ff",t.strokeStyle=E,t.lineWidth=1.5*o;for(const e of i){const{x:o,y:i,width:s,height:n}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(o,i,s,n),t.globalCompositeOperation="source-over",t.strokeRect(o,i,s,n)}t.globalCompositeOperation="source-over";const n=this.getActivePosition();let r;t.strokeStyle=E,t.lineWidth=3*o,r=this.getters.isInMerge(n)?this.getters.getMerge(n):yi(n);const{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);c>0&&h>0&&t.strokeRect(a,l,c,h)}}).add("clipboard",class extends _C{static layers=[2];static getters=["getClipboardContent","getClipboardTextContent","isCutOperation","isPaintingFormat"];status="invisible";state;lastPasteState;_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 o=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);return this.state.isPasteAllowed(e.target,{pasteOption:o});case"PASTE_FROM_OS_CLIPBOARD":return new dE(e.text,this.getters,this.dispatch,this.selection).isPasteAllowed(e.target);case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(o)}case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(o)}}return 0}handle(e){switch(e.type){case"COPY":case"CUT":const t=this.getters.getSelectedZones();this.state=this.getClipboardState(t,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const o=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1,this.state.paste(e.target,{pasteOption:o,shouldPasteCF:!0,selectTarget:!0}),"CUT"===this.state.operation&&(this.state=void 0),this.lastPasteState=this.state,this.status="invisible";break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!si(t[0])){for(const{col:t,row:o}of Ci(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:o,sheetId:this.getters.getActiveSheetId()});break}this.getClipboardStateForCopyCells(t,"CUT").paste(o);break}case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension);this.getClipboardStateForCopyCells(t,"CUT").paste(o);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==this.state?.operation||e.sheetId!==this.state?.sheetId)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"!==this.state?.operation||e.sheetId!==this.state?.sheetId)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":this.state=new dE(e.text,this.getters,this.dispatch,this.selection),this.state.paste(e.target),this.lastPasteState=this.state,this.status="invisible";break;case"REPEAT_PASTE":this.lastPasteState?.paste(e.target,{pasteOption:e.pasteOption,shouldPasteCF:!0,selectTarget:!0});break;case"ACTIVATE_PAINT_FORMAT":{const e=this.getters.getSelectedZones();this.state=this.getClipboardStateForCopyCells(e,"COPY"),this._isPaintingFormat=!0,this.status="visible";break}default:Ms(e)&&(this.status="invisible")}}getClipboardContent(){return this.state?.getClipboardContent()||{[Is.PlainText]:"\t"}}getClipboardTextContent(){return this.state?.getClipboardContent()[Is.PlainText]||"\t"}isCutOperation(){return!!this.state&&"CUT"===this.state.operation}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const o=this.getters.getActiveSheetId();let i;return i="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(o)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1},{cut:[i],paste:[e]}}getInsertCellsTargets(e,t){const o=this.getters.getActiveSheetId();let i,s;return"COL"===t?(i={...e,right:this.getters.getNumberCols(o)-1},s={...e,left:e.right+1,right:e.right+1}):(i={...e,bottom:this.getters.getNumberRows(o)-1},s={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1}),{cut:[i],paste:[s]}}getClipboardStateForCopyCells(e,t){return new aE(e,t,this.getters,this.dispatch,this.selection)}getClipboardState(e,t){return this.getters.getSelectedFigureId()?new lE(t,this.getters,this.dispatch):new aE(e,t,this.getters,this.dispatch,this.selection)}drawGrid(e){"visible"===this.status&&this.state&&this.state.drawClipboard(e)}}).add("edition",class extends _C{static getters=["getEditionMode","isSelectingForComposer","showSelectionIndicator","getCurrentContent","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights","getCurrentEditedCell"];col=0;row=0;mode="inactive";sheetId="";currentContent="";currentTokens=[];selectionStart=0;selectionEnd=0;selectionInitialStart=0;initialContent="";previousRef="";previousRange=void 0;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),o=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((e=>{const{xc:o,sheetName:i}=Yo(e.value),s=i||this.getters.getSheetName(this.sheetId),n=this.getters.getActiveSheetId();if(this.getters.getSheetName(n)!==s)return!1;const r=this.getters.getRangeFromSheetXC(n,o);return ui(this.getters.expandZone(n,r.zone),t.zone)}));this.previousRef=o.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=o.start;break;case"CHANGE_HIGHLIGHT":const i=this.getters.getRangeFromRangeData(e.range),s=this.getRangeReference(i,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(s),this.previousRef=s,this.selectionStart=this.currentContent.length,this.selectionEnd=this.currentContent.length;break;case"ACTIVATE_SHEET":if(this.currentContent.startsWith("=")||(this.cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){const t=this.getters.getActivePosition(),{col:o,row:i}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),s=this.getters.expandZone(e.sheetIdTo,yi({col:o,row:i}));this.selection.resetAnchor(this,{cell:{col:o,row:i},zone:s})}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:mE}));break;case"CYCLE_EDITION_REFERENCES":this.cycleReferences()}}getEditionMode(){return this.mode}getCurrentContent(){return"inactive"===this.mode?this.getComposerContent(this.getters.getActivePosition()):this.currentContent}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((o=>o.start<=e&&o.end>=t))}cycleReferences(){const e=this.getTokensInSelection(),t=e.filter((e=>"REFERENCE"===e.type));if(0===t.length)return;const o=e.map(uE).map((e=>e.value)).join(""),i=this.currentContent,s=e[0].start,n=e[e.length-1].end,r=i.slice(0,s)+o+i.slice(n),a=r.length-i.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,o){return t>=0&&t<=e&&o>=0&&o<=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:mE});const{top:t,left:o}=li({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=o,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:mE});const{top:t,left:o}=li({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=o,this.row=t}onAddElements(e){const{top:t,left:o}=ai({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=o,this.row=t}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=yi({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){const o=this.getters.getActiveCell();e&&o.format?.includes("%")&&so(e)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const{col:i,row:s,sheetId:n}=this.getters.getActivePosition();this.col=i,this.sheetId=n,this.row=s,this.initialContent=this.getComposerContent({sheetId:n,col:i,row:s}),this.mode="editing",this.setContent(e||this.initialContent,t),this.colorIndexByRange={};const r=yi({col:this.col,row:this.row});this.selection.capture(this,{cell:{col:this.col,row:this.row},zone:r},{handleEvent:this.handleEvent.bind(this),release:()=>{this.stopEdition()}})}stopEdition(){if("inactive"!==this.mode){this.cancelEditionAndActivateSheet();const e=this.col,t=this.row;let o=this.currentContent;if(!(this.initialContent!==o))return;if(o){const i=this.getters.getActiveSheetId(),s=this.getters.getEvaluatedCell({sheetId:i,col:this.col,row:this.row});if(o.startsWith("=")){const e=this.currentTokens.filter((e=>"LEFT_PAREN"===e.type)).length,t=this.currentTokens.filter((e=>"RIGHT_PAREN"===e.type)).length,i=e-t;i>0&&(o+=pt(new Array(i).fill(")")))}else s.link&&(o=nt(o,s.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,col:e,row:t,content:o})}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(t?.isFormula)return t.content;const{format:o,value:i,type:s,formattedValue:n}=this.getters.getEvaluatedCell(e);switch(s){case ys.text:case ys.empty:return i;case ys.boolean:return n;case ys.error:return t?.content||"";case ys.number:return o&&xo(o)?n:this.numberComposerContent(i,o)}}numberComposerContent(e,t){return t?.includes("%")?100*e+"%":function(e){const{integerDigits:t,decimalDigits:o}=Co(e,20);return o?`${t}.${o}`:t}(e)}cancelEdition(){"inactive"!==this.mode&&(this.mode="inactive",this.selection.release(this))}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,o){const i=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(i||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?aS(e):[],this.currentTokens.length>100&&o&&this.ui.notifyUI({type:"ERROR",text:n("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),o=this.getZoneReference(e);this.canStartComposerRangeSelection()?(this.insertText(o,t),this.selectionInitialStart=t):(this.insertText(","+o,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 o=this.getters.getActiveSheetId();let i=this.getters.zoneToXC(o,e,t);if(this.getters.getCurrentEditedCell()?.sheetId!==this.getters.getActiveSheetId()){i=`${$e(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${i}`}return i}getRangeReference(e,t=[{colFixed:!1,rowFixed:!1}]){let o=[...t];1===t.length&&Ri(e.zone)>1?o.push({...t[0]}):2===t.length&&1===Ri(e.zone)&&o.pop();const i=e.clone({parts:o});return this.getters.getSelectionRangeString(i,this.getters.getCurrentEditedCell()?.sheetId||this.getters.getActiveSheetId())}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),o=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,o)}replaceText(e,t,o){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(o,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const o=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),i=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:o,selection:{start:i,end:i}})}updateRangeColor(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return;const e=this.getters.getCurrentEditedCell()?.sheetId||this.getters.getActiveSheetId(),t=this.getReferencedRanges().map((t=>this.getters.getRangeString(t,e))),o={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(o[e]=this.colorIndexByRange[e]);const i=new Set(Object.values(o));let s=0;const n=()=>{for(;i.has(s);)s++;return i.add(s),s};for(const e of t){const t=e in o?o[e]:n();o[e]=t}this.colorIndexByRange=o}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=this.getters.getCurrentEditedCell()?.sheetId||this.getters.getActiveSheetId(),t=e=>{const t=this.colorIndexByRange[e];return Mt[t%Mt.length]};return this.getReferencedRanges().map((o=>{const i=this.getters.getRangeString(o,e);return{zone:o.zone,color:t(i),sheetId:o.sheetId}}))}getReferencedRanges(){const e=this.getters.getCurrentEditedCell()?.sheetId||this.getters.getActiveSheetId();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 o=t,i=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(i.type)||Ev.includes(i.value);){if("SPACE"!==i.type||o<1)return!1;o--,i=this.currentTokens[o]}for(o=t+1,i=this.currentTokens[o];i&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(i.type);){if("SPACE"!==i.type)return!1;o++,i=this.currentTokens[o]}return!0}return!1}getTokensInSelection(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return this.currentTokens.filter((o=>o.start<=e&&o.end>=e||o.start>=e&&o.start<t))}}),CE=(new zi).add("evaluation",class extends _C{static getters=["evaluateFormula","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getColEvaluatedCells","getEvaluatedCellsInZone"];isUpToDate=!1;evaluatedCells={};evalContext;lazyEvaluation;constructor(e){super(e),this.evalContext=e.custom,this.lazyEvaluation=e.lazyEvaluation}handle(e){switch(Rs.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 o=rS(e),i=this.getCompilationParameters((e=>this.getEvaluatedCell(this.getters.getCellPosition(e.id)))),s=[];for(let e of o.dependencies)s.push(this.getters.getRangeFromSheetXC(t,e));return o.execute(s,...i).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:o}){return void 0===this.getters.getCell({sheetId:e,col:t,row:o})?Us(""):this.evaluatedCells[e]?.[t]?.[o]?.()||Us("")}getEvaluatedCells(e){const t=this.getters.getCells(e)||{},o={};for(let e of Object.keys(t)){const t=this.getters.getCellPosition(e);o[e]=this.getEvaluatedCell(t)}return o}getColEvaluatedCells(e,t){return Object.values(this.evaluatedCells[e]?.[t]||[]).filter(dt).map((e=>e()))}getEvaluatedCellsInZone(e,t){return Ci(t).map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o})))}setEvaluatedCell(e,t){const{col:o,row:i,sheetId:s}=this.getters.getCellPosition(e);this.evaluatedCells[s]||(this.evaluatedCells[s]={}),this.evaluatedCells[s][o]||(this.evaluatedCells[s][o]={}),this.evaluatedCells[s][o][i]=t,this.lazyEvaluation||this.evaluatedCells[s][o][i]()}*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=>{const t=e.id,{col:s,row:n,sheetId:r}=this.getters.getCellPosition(t),a=this.evaluatedCells[r]?.[s]?.[n];return a||mt((()=>{try{switch(e.isFormula){case!0:return i(e);case!1:return Ps(e.content,e.format)}}catch(t){return o(t,e)}}))},o=(e,t)=>{e instanceof Error||(e=new Error(e));const o=e?.errorType||a.GenericError,i=s[2].__lastFnCalled||"",n=new c(o,e.message.replace("[[FUNCTION_NAME]]",i),void 0!==e.logLevel?e.logLevel:l.error);return Hs(t.content,n)},i=t=>{const o=t.id;if(e.has(o))throw new d;s[2].__originCellXC=()=>{const e=s[2].getters.getCellPosition(o);return Zt(e.col,e.row)},e.add(o);const i=t.compiledFormula.execute(t.dependencies,...s);if(e.delete(o),Array.isArray(i.value))throw new Error(n("This formula depends on invalid values"));return Us(i.value,t.format||i.format)},s=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(FC),this.evalContext,{getters:this.getters}),o=this.getters;const i=t=>{const o=e(t);if(o.type===ys.error)throw o.error;return o},s={};function r(e){if(!si(e.zone))throw new u;if(e.invalidSheetName)throw new Error(n("Invalid sheet name: %s",e.invalidSheetName))}return[function(e,t,s,a){if(r(e),t)return{value:ni(e.zone)};if(e.zone.bottom!==e.zone.top||e.zone.left!==e.zone.right)throw new Error(a?n("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",s.toString(),a.toString()):n("Function %s expects its parameters to be single values or single cell references, not ranges.",s.toString()));return function(e){let t;if(!o.tryGetSheet(e.sheetId))throw new Error(n("Invalid sheet name"));return t=o.getCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}),t&&""!==t.content?i(t):{value:null,format:t?.format}}(e)},function(e){r(e);const n=e.sheetId,a=o.getSheetZone(n),l=di(e.zone,a);if(!l)return[[]];const{top:c,left:h,bottom:d,right:u}=l,g=`${n}-${c}-${h}-${d}-${u}`;if(g in s)return s[g];const p=new Array(u-h+1);for(let o=h;o<=u;o++){const s=new Array(d-c+1);for(let n=c;n<=d;n++){const r=t.getters.getCell({sheetId:e.sheetId,col:o,row:n});s[n-c]=r?i(r):void 0}p[o-h]=s}return s[g]=p,p},t]}exportForExcel(e){for(let t of e.sheets)for(const e in t.cells){const o={sheetId:t.id,...qt(e)},i=this.getters.getCell(o);if(i){const s=t.cells[e],n=this.getEvaluatedCell(o);s.value=n.value,s.isFormula=i.isFormula&&!this.isBadExpression(i.content),i.format!==n.format&&(s.computedFormat=n.format),i.isFormula&&i.dependencies.length&&(s.content=this.getters.buildFormulaContent(t.id,i,i.dependencies,!0))}}}isBadExpression(e){try{return rS(e),!1}catch(e){return!0}}}).add("evaluation_filter",class extends _C{static getters=["getCellBorderWithFilterBorder","getFilterHeaders","getFilterValues","isFilterHeader","isRowFiltered","isFilterActive"];filterValues={};hiddenRows=new Set;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 o of this.getters.getFilters(e.sheetIdTo)){const i=o.zoneWithHeaders;t[o.id]=this.getFilterValues({sheetId:e.sheetId,col:i.left,row:i.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:o,row:i}=e;let s;for(let e of this.getters.getFilterTables(t)){const n=e.zone;if(pi(o,i,n)){const e=this.intersectZoneWithViewport(t,n);s={top:i===e.top?Q:void 0,bottom:i===e.bottom?Q:void 0,left:o===e.left?Q:void 0,right:o===e.right?Q:void 0}}}const n=this.getters.getCellBorder(e),r={...s,...Ct(n||{})};return ut(r)?null:r}getFilterHeaders(e){const t=[];for(let o of this.getters.getFilterTables(e)){const i=o.zone;if(!i)continue;const s=i.top;for(let o=i.left;o<=i.right;o++)this.getters.isColHidden(e,o)||this.getters.isRowHidden(e,s)||t.push({col:o,row:s})}return t}getFilterValues(e){const t=this.getters.getFilterId(e),o=e.sheetId;return t&&this.filterValues[o]&&this.filterValues[o][t]||[]}isFilterHeader({sheetId:e,col:t,row:o}){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===o))}isFilterActive(e){const t=this.getters.getFilterId(e),o=e.sheetId;return Boolean(t&&this.filterValues[o]?.[t]?.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:o,sheetId:i}){const s=this.getters.getFilterId({sheetId:i,col:e,row:t});s&&(this.filterValues[i]||(this.filterValues[i]={}),this.filterValues[i][s]=o)}updateHiddenRows(){const e=this.getters.getActiveSheetId(),t=this.getters.getFilters(e).sort(((e,t)=>e.zoneWithHeaders.top-t.zoneWithHeaders.top)),o=new Set;for(let i of t){if(this.getters.isRowHiddenByUser(e,i.zoneWithHeaders.top))continue;if(o.has(i.zoneWithHeaders.top))continue;const t=this.filterValues[e]?.[i.id]?.map(Et);if(t&&i.filteredZone)for(let s=i.filteredZone.top;s<=i.filteredZone.bottom;s++){const n=this.getCellValueAsString(e,i.col,s);t.includes(n)&&o.add(s)}}this.hiddenRows=o}getCellValueAsString(e,t,o){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets){const e=t.id;for(const o of t.filterTables){const i=ii(o.range),s=[],n=[];for(const o of Ke(0,vi(i).numberOfCols)){const r={sheetId:t.id,col:i.left+o,row:i.top},a=this.getFilterValues(r),l=this.getters.getFilter(r);if(!l)continue;const c=l.filteredZone?Ci(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)));s.push({colId:o,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(o,d,n);n.push(u),t.cells[Zt(h.col,h.row)]={...t.cells[Zt(h.col,h.row)],content:u,value:u,isFormula:!1}}o.filters=s}}}getUniqueColNameForExcel(e,t,o){t||(t=`Column${e}`);let i=t,s=2;for(;o.includes(i);)i=t+String(s),s++;return i}}).add("evaluation_chart",class extends _C{static getters=["getChartRuntime","getStyleOfSingleCellChart"];charts={};createRuntimeChart=function(e){const t=$r.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(o){const i=t.find((e=>e.match(o.type)));if(!i)throw new Error("No runtime builder for this chart.");return i.getChartRuntime(o,e)}}(this.getters);handle(e){if(Rs.has(e.type)||Ts.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:er(e)};if(!t)return{background:w,fontColor:er(w)};const o=t.zone.left,i=t.zone.top,s=t.sheetId,n=this.getters.getCellComputedStyle({sheetId:s,col:o,row:i}),r=n.fillColor||w;return{background:r,fontColor:n.textColor||er(r)}}}).add("evaluation_cf",class extends _C{static getters=["getConditionalIcon","getCellComputedStyle"];isStale=!0;computedStyles={};computedIcons={};uuidGenerator=new ti;handle(e){switch((Ts.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 o=this.getters.getActiveSheetId(),i=this.getters.getRulesByCell(o,e.originCol,e.originRow);for(const t of i)this.adaptRules(o,t,[Zt(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.originPosition,e.targetPosition,e.operation)}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getCellComputedStyle(e){const{sheetId:t,col:o,row:i}=e,s=this.getters.getCell(e),n=this.computedStyles[t],r=n&&n[o]?.[i],a={...s?.style,...r};return this.getters.getEvaluatedCell(e).link&&!a.textColor&&(a.textColor=R),this.getters.isFilterHeader(e)&&(a.bold=!0),a}getConditionalIcon({col:e,row:t}){const o=this.getters.getActiveSheetId(),i=this.computedIcons[o];return i&&i[e]?.[t]}computeStyles(){const e=this.getters.getActiveSheetId();this.computedStyles[e]={},this.computedIcons[e]={};const t=this.computedStyles[e];for(let o of this.getters.getConditionalFormats(e).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 i of o.ranges){const s=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=s.top;i<=s.bottom;i++)for(let n=s.left;n<=s.right;n++){const s=this.rulePredicate[o.rule.type];let r=this.getters.getEvaluatedCell({sheetId:e,col:n,row:i});s&&s(r,o.rule)&&(t[n]||(t[n]=[]),t[n][i]=Object.assign(t[n]?.[i]||{},o.rule.style))}}}}parsePoint(e,t,o){const i=this.getters.getActiveSheetId(),s=this.getters.getEvaluatedCellsInZone(i,this.getters.getRangeFromSheetXC(i,e).zone).filter((e=>e.type===ys.number)).map((e=>e.value));switch(t.type){case"value":return"max"===o?Rt(s):Tt(s);case"number":return Number(t.value);case"percentage":const e=Tt(s);return e+(Rt(s)-e)*Number(t.value)/100;case"percentile":return ao(s,Number(t.value)/100,!0);case"formula":const i=t.value&&this.getters.evaluateFormula(t.value);return"number"==typeof i?i:null;default:return null}}applyIcon(e,t){const o=this.parsePoint(e,t.lowerInflectionPoint),i=this.parsePoint(e,t.upperInflectionPoint);if(null===o||null===i||o>i)return;const s=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(s,e).zone,r=this.computedIcons[s],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=n.top;e<=n.bottom;e++)for(let l=n.left;l<=n.right;l++){const n=this.getters.getEvaluatedCell({sheetId:s,col:l,row:e});if(n.type!==ys.number)continue;const c=this.computeIcon(n.value,i,t.upperInflectionPoint.operator,o,t.lowerInflectionPoint.operator,a);r[l]||(r[l]=[]),r[l][e]=c}}computeIcon(e,t,o,i,s,n){return"ge"===o&&e>=t||"gt"===o&&e>t?n[0]:"ge"===s&&e>=i||"gt"===s&&e>i?n[1]:n[2]}applyColorScale(e,t){const o=this.parsePoint(e,t.minimum,"min"),i=t.midpoint?this.parsePoint(e,t.midpoint):null,s=this.parsePoint(e,t.maximum,"max");if(null===o||null===s||o>=s||i&&(o>=i||i>=s))return;const n=this.getters.getActiveSheetId(),r=this.getters.getRangeFromSheetXC(n,e).zone,a=this.computedStyles[n],l=[];t.midpoint&&i?(l.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,i,t.minimum.color,t.midpoint.color)}),l.push({minValue:i,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(i,s,t.midpoint.color,t.maximum.color)})):l.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,s,t.minimum.color,t.maximum.color)});for(let e=r.top;e<=r.bottom;e++)for(let t=r.left;t<=r.right;t++){const r=this.getters.getEvaluatedCell({sheetId:n,col:t,row:e});if(r.type===ys.number){const n=We(r.value,o,s);let c;c=2===l.length&&i?n<=i?this.colorCell(n,l[0].minValue,l[0].minColor,l[0].colorDiffUnit):this.colorCell(n,l[1].minValue,l[1].minColor,l[1].colorDiffUnit):this.colorCell(n,l[0].minValue,l[0].minColor,l[0].colorDiffUnit),a[t]||(a[t]=[]),a[t][e]=a[t]?.[e]||{},a[t][e].fillColor=Nt(c)}}}computeColorDiffUnits(e,t,o,i){const s=t-e;return[((o>>16)%256-(i>>16)%256)/s,((o>>8)%256-(i>>8)%256)/s,(o%256-i%256)/s]}colorCell(e,t,o,i){const[s,n,r]=i;return Math.round((o>>16)%256-s*(e-t))<<16|Math.round((o>>8)%256-n*(e-t))<<8|Math.round(o%256-r*(e-t))}rulePredicate={CellIsRule:(e,t)=>{if(e.type===ys.error)return!1;const o=t.values.map(ks);switch(t.operator){case"IsEmpty":return""===e.value.toString().trim();case"IsNotEmpty":return""!==e.value.toString().trim();case"BeginsWith":return""!==o[0]&&e.value.toString().startsWith(o[0].toString());case"EndsWith":return""!==o[0]&&e.value.toString().endsWith(o[0].toString());case"Between":return e.value>=o[0]&&e.value<=o[1];case"NotBetween":return!(e.value>=o[0]&&e.value<=o[1]);case"ContainsText":return e.value.toString().indexOf(o[0].toString())>-1;case"NotContains":return!e.value||-1==e.value.toString().indexOf(o[0].toString());case"GreaterThan":return e.value>o[0];case"GreaterThanOrEqual":return e.value>=o[0];case"LessThan":return e.value<o[0];case"LessThanOrEqual":return e.value<=o[0];case"NotEqual":return""!==o[0]&&e.value!==o[0];case"Equal":return""===o[0]||e.value===o[0];default:console.warn(n("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}};adaptRules(e,t,o,i){if(0===o.length&&0===i.length)return;const s=this.getters.getConditionalFormats(e),n=s.findIndex((e=>e.id===t.id));let r=[];n>-1&&(r=s[n].ranges),r=r.concat(o);const a=fi(r,i);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,o){const i=Zt(t.col,t.row);for(let s of this.getters.getConditionalFormats(e.sheetId))for(let n of s.ranges)if(pi(e.col,e.row,this.getters.getRangeFromSheetXC(e.sheetId,n).zone)){const n=s,r=[];if("CUT"===o&&r.push(Zt(e.col,e.row)),e.sheetId===t.sheetId)this.adaptRules(e.sheetId,n,[i],r);else{this.adaptRules(e.sheetId,n,[],r);const o=this.getCFToCopyTo(t.sheetId,n);this.adaptRules(t.sheetId,o,[i],[])}}}getCFToCopyTo(e,t){const o=this.getters.getConditionalFormats(e).find((e=>e.stopIfTrue===t.stopIfTrue&&vt(e.rule,t.rule)));return o||{...t,id:this.uuidGenerator.uuidv4(),ranges:[]}}}).add("viewport",class extends _C{static getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getActiveSheetDOMScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio","isPositionVisible"];viewports={};sheetViewWidth=pe();sheetViewHeight=pe();gridOffsetX=0;gridOffsetY=0;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":const t=this.getters.getActiveSheetId();let{col:o,row:i}=wi(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const s=e.previousAnchor.zone,n=e.anchor.zone,{top:r,bottom:a,left:l,right:c}=this.getMainInternalViewport(t);s.left===n.left&&s.right===n.right&&(o=l>o||o>c?l:o),s.top===n.top&&s.bottom===n.bottom&&(i=r>i||i>a?r:i)}o=Math.min(o,this.getters.getNumberCols(t)-1),i=Math.min(i,this.getters.getNumberRows(t)-1),this.refreshViewport(t,{col:o,row:i})}}handle(e){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 t=this.getters.getActiveSheetId(),{top:o,viewportHeight:i,offsetCorrectionY:s}=this.getMainInternalViewport(t),n=this.getters.getRowDimensions(t,o);this.shiftVertically(n.start+i-s);break;case"SHIFT_VIEWPORT_UP":{const e=this.getters.getActiveSheetId(),{top:t,viewportHeight:o,offsetCorrectionY:i}=this.getMainInternalViewport(e),s=this.getters.getRowDimensions(e,t);this.shiftVertically(s.end-i-o);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!==e.style?.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:r,row:a}=this.getters.getActivePosition();this.refreshViewport(this.getters.getActiveSheetId(),{col:r,row:a})}}finalize(){for(const e of this.sheetsWithDirtyViewports)this.resetViewports(e);this.sheetsWithDirtyViewports=new Set,this.setViewports()}setViewports(){const e=this.getters.getSheetIds();for(const t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getColIndex(e))))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getRowIndex(e))))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}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=>Ke(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=>Ke(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:o,ySplit:i}=this.getters.getPaneDivisions(e);let{width:s,height:n}=t.getMaxSize();return{x:this.getters.getColDimensions(e,o).start,y:this.getters.getRowDimensions(e,i).start,width:s,height:n}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:o}=this.getMainViewportRect(),i=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-i.viewportWidth+1),maxOffsetY:Math.max(0,o-i.viewportHeight+1)}}getColRowOffsetInViewport(e,t,o){const i=this.getters.getActiveSheetId(),s=this.getters.getSheetViewVisibleCols(),n=this.getters.getSheetViewVisibleRows();if(o<t)return-this.getColRowOffsetInViewport(e,o,t);let r=0;const a="COL"===e?s:n;for(let s=t;s<o;s++)a.includes(s)&&(r+="COL"===e?this.getters.getColSize(i,s):this.getters.getRowSize(i,s));return r}isVisibleInViewport({sheetId:e,col:t,row:o}){return this.getSubViewports(e).some((e=>e.isVisible(t,o)))}getEdgeScrollCol(e,t,o){let i=!1,s=0,n=0;const{xSplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(i=!0,n=Kt(e-a),s=1):e<l&&o>=l&&c>0?(i=!0,n=Kt(l-e),s=-1):r&&t<l&&e>l&&(i=!0,n=Kt(e),s="reset"),{canEdgeScroll:i,direction:s,delay:n}}getEdgeScrollRow(e,t,o){let i=!1,s=0,n=0;const{ySplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(i=!0,n=Kt(e-a),s=1):e<l&&o>=l&&c>0?(i=!0,n=Kt(l-e),s=-1):r&&t<l&&e>l&&(i=!0,n=Kt(e),s="reset"),{canEdgeScroll:i,direction:s,delay:n}}getVisibleRect(e){const t=this.getters.getActiveSheetId(),o=this.getSubViewports(t).map((t=>t.getRect(e))).filter(dt);if(0===o.length)return{x:0,y:0,width:0,height:0};const i=Math.min(...o.map((e=>e.x))),s=Math.min(...o.map((e=>e.y))),n=Math.max(...o.map((e=>e.x+e.width)))-i,r=Math.max(...o.map((e=>e.y+e.height)))-s;return{x:i+this.gridOffsetX,y:s+this.gridOffsetY,width:n,height:r}}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,o).start}}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(dt)}checkPositiveDimension(e){return e.width<0||e.height<0?69:0}checkValuesAreDifferent(e){const{height:t,width:o}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===o&&e.height===t?77:0}checkScrollingDirection({offsetX:e,offsetY:t}){const o=this.getMainInternalViewport(this.getters.getActiveSheetId());return!o.canScrollHorizontally&&e>0||!o.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 o=this.getSubViewports(e);Object.values(o).forEach((e=>{e.adjustPosition(t)}))}}resizeSheetView(e,t,o=0,i=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=o,this.gridOffsetY=i,this.recomputeViewports()}recomputeViewports(){for(let e of Object.keys(this.viewports))this.resetViewports(e)}setSheetViewOffset(e,t){const o=this.getters.getActiveSheetId(),{maxOffsetX:i,maxOffsetY:s}=this.getMaximumSheetOffset();Object.values(this.getSubViewports(o)).forEach((o=>o.setViewportOffset(We(e,0,i),We(t,0,s))))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetScrollbarX||0,y:this.viewports[e]?.bottomRight.offsetScrollbarY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),i=this.getters.getNumberCols(e),s=this.getters.getNumberRows(e),n=this.getters.getColRowOffset("COL",0,t,e),r=this.getters.getColRowOffset("ROW",0,o,e),{xRatio:a,yRatio:l}=this.getFrozenSheetViewRatio(e),c=a<1,h=l<1,d=this.getViewportOffset(e),u={topLeft:o&&t&&new DC(this.getters,e,{left:0,right:t-1,top:0,bottom:o-1},{width:n,height:r},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:o&&new DC(this.getters,e,{left:t,right:i-1,top:0,bottom:o-1},{width:this.sheetViewWidth-n,height:r},{canScrollHorizontally:c,canScrollVertically:!1},{x:c?d.x:0,y:0})||void 0,bottomLeft:t&&new DC(this.getters,e,{left:0,right:t-1,top:o,bottom:s-1},{width:n,height:this.sheetViewHeight-r},{canScrollHorizontally:!1,canScrollVertically:h},{x:0,y:h?d.y:0})||void 0,bottomRight:new DC(this.getters,e,{left:t,right:i-1,top:o,bottom:s-1},{width:this.sheetViewWidth-n,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 t=this.getters.getActiveSheetId(),{top:o}=this.getMainInternalViewport(t),{scrollX:i}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(i,e);const{anchor:s}=this.getters.getSelection();if(s.cell.row>=this.getters.getPaneDivisions(t).ySplit){const e=this.getMainInternalViewport(t).top-o;this.selection.selectCell(s.cell.col,s.cell.row+e)}}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],o=this.getters.getFigures(e),{scrollX:i,scrollY:s}=this.getActiveSheetScrollInfo(),{x:n,y:r}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of o)e.x>=n&&(e.x+e.width<=n+i||e.x>=a+i+n)||e.y>=r&&(e.y+e.height<=r+s||e.y>=l+s+r)||t.push(e);return t}isPositionVisible(e){const{scrollX:t,scrollY:o}=this.getters.getActiveSheetScrollInfo(),{x:i,y:s}=this.getters.getMainViewportCoordinates(),{width:n,height:r}=this.getters.getSheetViewDimension();return!(e.x>=i&&(e.x<i+t||e.x>n+t+i))&&!(e.y>=s&&(e.y<s+o||e.y>r+o+s))}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),i=this.getters.getColDimensions(e,t).start,s=this.getters.getRowDimensions(e,o).start;return{xRatio:i/(this.sheetViewWidth+this.gridOffsetX),yRatio:s/(this.sheetViewHeight+this.gridOffsetY)}}}).add("custom_colors",class extends _C{customColors=new Set;shouldUpdateColors=!1;static getters=["getCustomColors"];handle(e){switch(e.type){case"UPDATE_CELL":case"UPDATE_CHART":case"CREATE_CHART":case"ADD_CONDITIONAL_FORMAT":case"SET_BORDER":case"SET_ZONE_BORDERS":case"SET_FORMATTING":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())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getChartColors(t));return function(e){const t=[{leadColor:Lt(255,0,0),colors:[]},{leadColor:Lt(255,128,0),colors:[]},{leadColor:Lt(128,128,0),colors:[]},{leadColor:Lt(128,255,0),colors:[]},{leadColor:Lt(0,255,0),colors:[]},{leadColor:Lt(0,255,128),colors:[]},{leadColor:Lt(0,255,255),colors:[]},{leadColor:Lt(0,127,255),colors:[]},{leadColor:Lt(0,0,255),colors:[]},{leadColor:Lt(127,0,255),colors:[]},{leadColor:Lt(128,0,128),colors:[]},{leadColor:Lt(255,0,128),colors:[]}];for(const o of e.map(Ut)){let e=500,i=0;t.forEach(((t,s)=>{const n=(r=o,a=t.leadColor,Math.sqrt(Math.pow(r.r-a.r,2)+Math.pow(r.g-a.g,2)+Math.pow(r.b-a.b,2)));var r,a;e>n&&(e=n,i=s)})),t[i].colors.push(o)}return t.map((e=>e.colors.sort(((e,t)=>zt(e).s-zt(t).s)))).flat().map(kt)}([...new Set([...new Set([...e,...this.customColors])].filter(Ft).map(_t))]).filter((e=>!_.includes(e)))}getColorsFromCells(e){const t=Object.values(this.getters.getCells(e)),o=new Set;for(const e of t)e.style?.textColor&&o.add(e.style.textColor),e.style?.fillColor&&o.add(e.style.fillColor);for(const t of this.getters.getBordersColors(e))o.add(t);return[...o]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),o=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(o.push(t.style.textColor),o.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(o.push(Nt(t.minimum.color)),o.push(t.midpoint?Nt(t.midpoint.color):void 0),o.push(Nt(t.maximum.color)))}return o.filter(dt)}getChartColors(e){const t=this.getters.getChartIds(e).map((e=>this.getters.getChart(e)));let o=new Set;for(let e of t){if(void 0===e)continue;const t=e.getDefinition().background;switch(void 0!==t&&o.add(t),e.type){case"gauge":const t=e.sectionRule.colors;o.add(t.lowerColor),o.add(t.middleColor),o.add(t.upperColor);break;case"scorecard":const i=e;o.add(i.baselineColorDown),o.add(i.baselineColorUp)}}return[...o]}tryToAddColor(e){const t=_t(e);e&&!_.includes(t)&&this.customColors.add(t)}}),EE=new zi;EE.add("link",{condition:(e,t)=>!!t.model.getters.getEvaluatedCell(e).link,execute:(e,t)=>Zi(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});class wE{fileStore;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 o=document.createElement("input");o.setAttribute("type","file"),o.setAttribute("accept","image/*"),o.addEventListener("change",(async()=>{null===o.files||1!=o.files.length?t():e(o.files[0])})),o.click()}))}getImageSize(e){return new Promise(((t,o)=>{const i=new Image;i.src=e,i.addEventListener("load",(()=>{const e={width:i.width,height:i.height};t(e)})),i.addEventListener("error",o)}))}}class xE{focusableElement=void 0;setFocusableElement(e){this.focusableElement=e}focus(){this.focusableElement?.focus()}}const yE=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];Ni`
|
|
1420
1420
|
.o-ripple {
|
|
1421
1421
|
z-index: 1;
|
|
1422
1422
|
}
|
|
@@ -1783,7 +1783,7 @@
|
|
|
1783
1783
|
margin: 5px 0px 0px 0px !important;
|
|
1784
1784
|
height: 25px !important;
|
|
1785
1785
|
}
|
|
1786
|
-
`;class LE extends t.Component{static template="o-spreadsheet-BorderEditor";static components={ColorPickerWidget:Zm,Popover:vn};BORDER_POSITIONS=DE;lineStyleButtonRef=t.useRef("lineStyleButton");borderStyles=Fs;state=t.useState({activeTool:void 0});toggleDropdownTool(e){const t=this.state.activeTool===e;this.state.activeTool=t?void 0:e}closeDropdown(){this.state.activeTool=void 0}setBorderPosition(e){this.props.onBorderPositionPicked(e),this.closeDropdown()}setBorderColor(e){this.props.onBorderColorPicked(e),this.closeDropdown()}setBorderStyle(e){this.props.onBorderStylePicked(e),this.closeDropdown()}get lineStylePickerPopoverProps(){return{anchorRect:this.lineStylePickerAnchorRect,positioning:"BottomLeft",verticalOffset:0}}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"BottomLeft",verticalOffset:0}}get lineStylePickerAnchorRect(){const e=this.lineStyleButtonRef.el;if(null===e)return{x:0,y:0,width:0,height:0};const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}}LE.props={class:{type:String,optional:!0},currentBorderColor:{type:String,optional:!1},currentBorderStyle:{type:String,optional:!1},currentBorderPosition:{type:String,optional:!0},onBorderColorPicked:Function,onBorderStylePicked:Function,onBorderPositionPicked:Function,maxHeight:{type:Number,optional:!0},anchorRect:Object};class
|
|
1786
|
+
`;class LE extends t.Component{static template="o-spreadsheet-BorderEditor";static components={ColorPickerWidget:Zm,Popover:vn};BORDER_POSITIONS=DE;lineStyleButtonRef=t.useRef("lineStyleButton");borderStyles=Fs;state=t.useState({activeTool:void 0});toggleDropdownTool(e){const t=this.state.activeTool===e;this.state.activeTool=t?void 0:e}closeDropdown(){this.state.activeTool=void 0}setBorderPosition(e){this.props.onBorderPositionPicked(e),this.closeDropdown()}setBorderColor(e){this.props.onBorderColorPicked(e),this.closeDropdown()}setBorderStyle(e){this.props.onBorderStylePicked(e),this.closeDropdown()}get lineStylePickerPopoverProps(){return{anchorRect:this.lineStylePickerAnchorRect,positioning:"BottomLeft",verticalOffset:0}}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"BottomLeft",verticalOffset:0}}get lineStylePickerAnchorRect(){const e=this.lineStyleButtonRef.el;if(null===e)return{x:0,y:0,width:0,height:0};const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}}LE.props={class:{type:String,optional:!0},currentBorderColor:{type:String,optional:!1},currentBorderStyle:{type:String,optional:!1},currentBorderPosition:{type:String,optional:!0},onBorderColorPicked:Function,onBorderStylePicked:Function,onBorderPositionPicked:Function,maxHeight:{type:Number,optional:!0},anchorRect:Object};class PE extends t.Component{static template="o-spreadsheet-BorderEditorWidget";static components={BorderEditor:LE};borderEditorButtonRef=t.useRef("borderEditorButton");state=t.useState({currentColor:K,currentStyle:X,currentPosition:void 0});get borderEditorAnchorRect(){const e=this.borderEditorButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}onBorderPositionPicked(e){this.state.currentPosition=e,this.updateBorder()}onBorderColorPicked(e){this.state.currentColor=e,this.updateBorder()}onBorderStylePicked(e){this.state.currentStyle=e,this.updateBorder()}updateBorder(){void 0!==this.state.currentPosition&&this.env.model.dispatch("SET_ZONE_BORDERS",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),border:{position:this.state.currentPosition,color:this.state.currentColor,style:this.state.currentStyle}})}}PE.props={toggleBorderEditor:Function,showBorderEditor:Boolean,disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};Ni`
|
|
1787
1787
|
.o-topbar-composer {
|
|
1788
1788
|
height: fit-content;
|
|
1789
1789
|
margin-top: -1px;
|
|
@@ -1796,7 +1796,7 @@
|
|
|
1796
1796
|
top: 20%;
|
|
1797
1797
|
}
|
|
1798
1798
|
}
|
|
1799
|
-
`;class
|
|
1799
|
+
`;class kE extends t.Component{static template="o-spreadsheet-TopBarComposer";static components={Composer:Of};get composerStyle(){const e={padding:"5px 0px 5px 8px","max-height":"100px","line-height":"24px"};return e.height="inactive"===this.props.focus?"34px":"fit-content",Li(e)}get containerStyle(){return"inactive"===this.props.focus?Li({"border-color":M,"border-right":"none"}):Li({"border-color":E})}}kE.props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerContentFocused:Function},Ni`
|
|
1800
1800
|
.o-font-size-editor {
|
|
1801
1801
|
height: calc(100% - 4px);
|
|
1802
1802
|
input.o-font-size {
|
|
@@ -1905,7 +1905,7 @@
|
|
|
1905
1905
|
}
|
|
1906
1906
|
}
|
|
1907
1907
|
}
|
|
1908
|
-
`;class VE extends t.Component{static template="o-spreadsheet-TopBar";get dropdownStyle(){return`max-height:${this.props.dropdownMaxHeight}px`}static components={ColorPickerWidget:Zm,ColorPicker:qm,Menu:wn,TopBarComposer:
|
|
1908
|
+
`;class VE extends t.Component{static template="o-spreadsheet-TopBar";get dropdownStyle(){return`max-height:${this.props.dropdownMaxHeight}px`}static components={ColorPickerWidget:Zm,ColorPicker:qm,Menu:wn,TopBarComposer:kE,FontSizeEditor:UE,ActionButton:FE,BorderEditorWidget:PE};state=t.useState({menuState:{isOpen:!1,position:null,menuItems:[]},activeTool:"",fillColor:"#ffffff",textColor:"#000000"});isSelectingMenu=!1;openedEl=null;menus=[];EDIT=Ka;FORMAT=am;VIEW=Mm;formatNumberMenuItemSpec=Fm;isntToolbarMenu=!1;setup(){t.useExternalListener(window,"click",this.onExternalClick),t.onWillStart((()=>this.updateCellState())),t.onWillUpdateProps((()=>this.updateCellState()))}get topbarComponents(){return pf.getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.isntToolbarMenu&&this.openMenu(e,t)}toggleDropdownTool(e,t){const o=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=o?"":e,this.openedEl=o?null:t.target}toggleContextMenu(e,t){this.state.menuState.isOpen&&this.isntToolbarMenu?this.closeMenus():(this.openMenu(e,t),this.isntToolbarMenu=!0)}toggleToolbarContextMenu(e,t){if(this.state.menuState.isOpen&&!this.isntToolbarMenu)this.closeMenus();else{const o=Dn(e);this.openMenu(o,t),this.isntToolbarMenu=!1}}openMenu(e,t){const{left:o,top:i,height:s}=t.currentTarget.getBoundingClientRect();this.state.activeTool="",this.state.menuState.isOpen=!0,this.state.menuState.position={x:o,y:i+s},this.state.menuState.menuItems=e.children(this.env).sort(((e,t)=>e.sequence-t.sequence)),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.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.getCurrentStyle();this.state.fillColor=e.fillColor||"#ffffff",this.state.textColor=e.textColor||"#000000",this.menus=Lm.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){fa(this.env,{[e]:t}),this.onClick()}}VE.props={onClick:Function,focusComposer:String,onComposerContentFocused:Function,dropdownMaxHeight:Number};class zE{clipboard;constructor(e){this.clipboard=e}async write(e){try{this.clipboard?.write(this.getClipboardItems(e))}catch(e){}}async writeText(e){try{this.clipboard?.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"===e?.state?"permissionDenied":"notImplemented"}}}getClipboardItems(e){return[new ClipboardItem({[Is.PlainText]:this.getBlob(e,Is.PlainText),[Is.Html]:this.getBlob(e,Is.Html)})]}getBlob(e,t){return new Blob([e[t]||""],{type:t})}}const BE="#000";Ni`
|
|
1909
1909
|
.o-spreadsheet {
|
|
1910
1910
|
position: relative;
|
|
1911
1911
|
display: grid;
|
|
@@ -1996,8 +1996,8 @@
|
|
|
1996
1996
|
&.corner {
|
|
1997
1997
|
right: 0px;
|
|
1998
1998
|
bottom: 0px;
|
|
1999
|
-
height: ${
|
|
2000
|
-
width: ${
|
|
1999
|
+
height: ${k}px;
|
|
2000
|
+
width: ${k}px;
|
|
2001
2001
|
border-top: 1px solid #e2e3e3;
|
|
2002
2002
|
border-left: 1px solid #e2e3e3;
|
|
2003
2003
|
}
|
|
@@ -2310,7 +2310,7 @@
|
|
|
2310
2310
|
<autoFilter ${qS(t)}>
|
|
2311
2311
|
${XS(function(e){const t=[];for(const o of e.filters){const e=KS`
|
|
2312
2312
|
<filterColumn ${qS([["colId",o.colId]])}>
|
|
2313
|
-
${
|
|
2313
|
+
${Pw(o)}
|
|
2314
2314
|
</filterColumn>
|
|
2315
2315
|
`;t.push(e)}return t}(e))}
|
|
2316
2316
|
</autoFilter>
|
|
@@ -2322,19 +2322,19 @@
|
|
|
2322
2322
|
`}(e,o)}
|
|
2323
2323
|
${Dw}
|
|
2324
2324
|
</table>
|
|
2325
|
-
`;return ZS(i)}function
|
|
2325
|
+
`;return ZS(i)}function Pw(e){const t=e.displayedValues.map((e=>KS`<filter ${qS([["val",e]])}/>`));return KS`
|
|
2326
2326
|
<filters ${qS(e.displayBlanks?[["blank",1]]:[])}>
|
|
2327
2327
|
${XS(t)}
|
|
2328
2328
|
</filters>
|
|
2329
|
-
`}function
|
|
2329
|
+
`}function kw(e){if(!Object.values(e).length)return KS``;const t=[];for(let[o,i]of Object.entries(e)){const e=[["min",parseInt(o)+1],["max",parseInt(o)+1],["width",hS(i.size||L)],["customWidth",1],["hidden",i.isHidden?1:0]];t.push(KS`
|
|
2330
2330
|
<col ${qS(e)}/>
|
|
2331
2331
|
`)}return KS`
|
|
2332
2332
|
<cols>
|
|
2333
2333
|
${XS(t)}
|
|
2334
2334
|
</cols>
|
|
2335
|
-
`}function Uw(e,t,o){const i=[];for(let s=0;s<o.rowNumber;s++){const n=[["r",s+1]],r=o.rows[s]||{};n.push(["ht",cS(r.size||
|
|
2335
|
+
`}function Uw(e,t,o){const i=[];for(let s=0;s<o.rowNumber;s++){const n=[["r",s+1]],r=o.rows[s]||{};n.push(["ht",cS(r.size||P)],["customHeight",1],["hidden",r.isHidden?1:0]);const a=[];for(let i=0;i<o.colNumber;i++){const n=Zt(i,s),r=o.cells[n];if(r){const l=[["r",n]],c=uS(e,dS(r,t));l.push(["s",c]);let h=[],d=KS``;if(r.isFormula){const e=mw(r);if(!e)continue;({attrs:h,node:d}=e)}else if(r.content&&it(r.content)){const{label:t}=rt(r.content);({attrs:h,node:d}=fw(t,e.sharedStrings))}else if(r.content&&""!==r.content){const t=Vw(i,s,o);({attrs:h,node:d}=fw(r.content,e.sharedStrings,t))}l.push(...h),a.push(KS`<c ${qS(l)}>
|
|
2336
2336
|
${d}
|
|
2337
|
-
</c>`)}}(a.length||r.size!==
|
|
2337
|
+
</c>`)}}(a.length||r.size!==P||r.isHidden)&&i.push(KS`
|
|
2338
2338
|
<row ${qS(n)}>
|
|
2339
2339
|
${XS(a)}
|
|
2340
2340
|
</row>
|
|
@@ -2378,11 +2378,11 @@
|
|
|
2378
2378
|
${XS(i)}
|
|
2379
2379
|
</sheets>
|
|
2380
2380
|
</workbook>
|
|
2381
|
-
`),"xl/workbook.xml","workbook")}(e,o)),t.push(...function(e,t){const o=[];let i=1;for(const[s,n]of Object.entries(e.sheets)){const r=[["xmlns",pb.worksheet],["xmlns:r",Sb]],a=[["defaultRowHeight",cS(
|
|
2381
|
+
`),"xl/workbook.xml","workbook")}(e,o)),t.push(...function(e,t){const o=[];let i=1;for(const[s,n]of Object.entries(e.sheets)){const r=[["xmlns",pb.worksheet],["xmlns:r",Sb]],a=[["defaultRowHeight",cS(P)],["defaultColWidth",hS(L)]],l=Ww(n,s,i,t,o);i+=n.filterTables.length;let c=KS``;const h=[];for(const i of n.charts){const n=fS(i.id),r=gS(t.relsFiles,`xl/drawings/_rels/drawing${s}.xml.rels`,{target:`../charts/chart${n}.xml`,type:vb.chart});h.push(r),o.push(WS(rw(i,s,e),`xl/charts/chart${n}.xml`,"chart"))}for(const e of n.images){const i=e.data.mimetype;if(void 0===i)continue;const n=Qb[i];if(void 0===n)continue;let r=`image${vS(e.id)}.${n}`;const a=gS(t.relsFiles,`xl/drawings/_rels/drawing${s}.xml.rels`,{target:`../media/${r}`,type:vb.image});h.push(a),o.push({path:`xl/media/${r}`,imageSrc:e.data.path})}const d=[...n.charts,...n.images];if(d.length){const e=gS(t.relsFiles,`xl/worksheets/_rels/sheet${s}.xml.rels`,{target:`../drawings/drawing${s}.xml`,type:vb.drawing});o.push(WS(Rw(h,n,d),`xl/drawings/drawing${s}.xml`,"drawing")),c=KS`<drawing r:id="${e}" />`}const u=KS`
|
|
2382
2382
|
<worksheet ${qS(r)}>
|
|
2383
2383
|
${Hw(n)}
|
|
2384
2384
|
<sheetFormatPr ${qS(a)} />
|
|
2385
|
-
${
|
|
2385
|
+
${kw(n.cols)}
|
|
2386
2386
|
${Uw(t,e,n)}
|
|
2387
2387
|
${Bw(n.merges)}
|
|
2388
2388
|
${XS(Sw(t.dxfs,n.conditionalFormats))}
|
|
@@ -2492,4 +2492,4 @@
|
|
|
2492
2492
|
<tableParts count="${e.filterTables.length}">
|
|
2493
2493
|
${XS(a)}
|
|
2494
2494
|
</tableParts>
|
|
2495
|
-
`}var Gw;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(Gw||(Gw={}));function qw(e,t={}){const o=Be(t);return o.type=e,o}const Zw={},jw={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:F,HEADER_WIDTH:D,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:L,DEFAULT_CELL_HEIGHT:
|
|
2495
|
+
`}var Gw;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(Gw||(Gw={}));function qw(e,t={}){const o=Be(t);return o.type=e,o}const Zw={},jw={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:F,HEADER_WIDTH:D,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:L,DEFAULT_CELL_HEIGHT:P,SCROLLBAR_WIDTH:k},Yw={autofillModifiersRegistry:Ws,autofillRulesRegistry:Gs,cellMenuRegistry:fp,colMenuRegistry:Nm,linkMenuRegistry:Pn,functionRegistry:Hg,featurePluginRegistry:vE,statefulUIPluginRegistry:SE,coreViewsPluginRegistry:CE,corePluginRegistry:bE,rowMenuRegistry:Dm,sidePanelRegistry:gf,figureRegistry:Yr,chartSidePanelComponentRegistry:ef,chartComponentRegistry:Wr,chartRegistry:$r,topbarMenuRegistry:Lm,topbarComponentRegistry:pf,clickableCellRegistry:EE,otRegistry:Pm,inverseCommandRegistry:Jr,urlRegistry:Hi,cellPopoverRegistry:Vn,numberFormatMenuRegistry:_m,repeatLocalCommandTransformRegistry:oE,repeatCommandTransformRegistry:tE},Xw={arg:el,toBoolean:rs,toJsDate:as,toNumber:Qi,toString:os,toXC:Zt,toZone:ii,toCartesian:qt,numberToLetters:Bt,UuidGenerator:ti,formatValue:bo,computeTextWidth:qe,createEmptyWorkbookData:wC,createEmptySheet:EC,createEmptyExcelSheet:xC,getDefaultChartJsRuntime:br,chartFontColor:er,ChartColors:Jn,EvaluationError:c,CellErrorLevel:l,getFillingMode:Er,rgbaToHex:kt,colorToRGBA:Ut,positionToZone:yi,isDefined:dt,lazy:mt,genericRepeat:iE,deepEquals:vt},Kw={isMarkdownLink:it,parseMarkdownLink:rt,markdownLink:nt,openLink:Zi,urlRepresentation:qi},Qw={ChartPanel:tf,ChartFigure:qr,ChartJsComponent:Ai,Grid:cb,GridOverlay:Zf,ScorecardChart:ki,LineConfigPanel:Km,LineBarPieDesignPanel:jm,BarConfigPanel:Hm,LineBarPieConfigPanel:Bm,GaugeChartConfigPanel:Ym,GaugeChartDesignPanel:Xm,ScorecardChartConfigPanel:Qm,ScorecardChartDesignPanel:Jm,FigureComponent:mf};e.AbstractChart=Bn,e.CorePlugin=IC,e.DispatchResult=Ns,e.EvaluationError=c,e.Model=class extends PC{corePlugins=[];featurePlugins=[];statefulUIPlugins=[];coreViewsPlugins=[];range;session;isReplayingCommand=!1;renderers=[];status=0;config;corePluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},o={},i=[],s=new ti,n=!0){super(),i=SC(e,i);const r=bC(e,n);this.state=new iw,this.uuidGenerator=s,this.config=this.setupConfig(o),this.session=this.setupSession(r.revisionId),this.coreGetters={},this.range=new NC(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},this.uuidGenerator.setIsFastStrategy(!0),this.selection=new ow(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of bE.getAll())this.setupCorePlugin(e,r);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(i);for(let e of SE.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of CE.getAll()){const t=this.setupUiPlugin(e);this.coreViewsPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of vE.getAll()){const t=this.setupUiPlugin(e);this.featurePlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}this.uuidGenerator.setIsFastStrategy(!1),this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.joinSession(),o.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 o of e.getters){if(!(o in t))throw new Error(`Invalid getter name: ${o} for plugin ${t.constructor}`);if(o in this.getters)throw new Error(`Getter "${o}" is already defined.`);this.getters[o]=t[o].bind(t)}const o=e.layers.map((e=>[t,e]));return this.renderers.push(...o),this.renderers.sort(((e,t)=>e[1]-t[1])),t}setupCorePlugin(e,t){const o=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in o))throw new Error(`Invalid getter name: ${t} for plugin ${o.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=o[t].bind(o)}o.import(t),this.corePlugins.push(o),this.coreHandlers.push(o),this.handlers.push(o)}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 GC(JE({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{this.checkDispatchAllowed(e).isSuccessful&&(this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1)}}),this.config.transportService,e)}setupSessionEvents(){this.session.on("remote-revision-received",this,this.onRemoteRevisionReceived),this.session.on("revision-undone",this,(({commands:e})=>{this.dispatchFromCorePlugin("UNDO",{commands:e}),this.finalize()})),this.session.on("revision-redone",this,(({commands:e})=>{this.dispatchFromCorePlugin("REDO",{commands:e}),this.finalize()})),this.session.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.session.on("collaborative-event-received",this,(()=>{this.trigger("update")}))}setupConfig(e){const t=e.client||{id:this.uuidGenerator.uuidv4(),name:n("Anonymous").toString()},o=e.transportService||new WE;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:e.external||{},transportService:o,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,session:this.session}}checkDispatchAllowed(e){const t=Ms(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some((e=>0!==e))?new Ns(t.flat()):Ns.Success}checkDispatchAllowedCoreCommand(e){const t=this.corePlugins.map((t=>t.allowDispatch(e)));return t.push(this.range.allowDispatch(e)),t}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map((t=>t.allowDispatch(e)))}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0}canDispatch=(e,t)=>this.checkDispatchAllowed(qw(e,t));dispatch=(e,t)=>{const o=qw(e,t);let i=this.status;if(this.getters.isReadonly()&&(s=o,!As.has(s.type)))return new Ns(68);var s;if(!this.session.canApplyOptimisticUpdate())return new Ns(65);switch(i){case 0:const t=this.checkDispatchAllowed(o);if(!t.isSuccessful)return t;this.status=1;const{changes:i,commands:s}=this.state.recordChanges((()=>{Ms(o)&&this.state.addCommand(o),this.dispatchToHandlers(this.handlers,o),this.finalize()}));this.session.save(o,s,i),this.status=0,this.trigger("update");break;case 1:if(Ms(o)){const e=this.checkDispatchAllowed(o);if(!e.isSuccessful)return e;this.state.addCommand(o)}this.dispatchToHandlers(this.handlers,o);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(Ms(o))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,o)}return Ns.Success};dispatchFromCorePlugin=(e,t)=>{const o=qw(e,t),i=this.status;this.status=2;const s=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(s,o),this.status=i,Ns.Success};dispatchToHandlers(e,t){for(const o of e)o.beforeHandle(t);for(const o of e)o.handle(t)}drawGrid(e){for(let[t,o]of this.renderers)e.ctx.save(),t.drawGrid(e,o),e.ctx.restore()}exportData(){let e=wC();for(let t of this.handlers)t instanceof IC&&t.export(e);return e.revisionId=this.session.getRevisionId()||ee,e=Be(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={...wC(),sheets:[xC(fC,"Sheet1")]};for(let t of this.handlers)t instanceof yC&&t.exportForExcel(e);return e=Be(e),$w(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.Registry=zi,e.Revision=$C,e.SPREADSHEET_DIMENSIONS=jw,e.Spreadsheet=$E,e.UIPlugin=_C,e.__info__=Zw,e.addFunction=function(e,t){Hg.add(e,t)},e.astToFormula=Zv,e.compile=rS,e.components=Qw,e.convertAstNodes=qv,e.coreTypes=Os,e.findCellInNewZone=wi,e.functionCache=nS,e.helpers=Xw,e.invalidateEvaluationCommands=Rs,e.links=Kw,e.load=bC,e.parse=Wv,e.readonlyAllowedCommands=As,e.registries=Yw,e.setDefaultSheetViewSize=function(e){ge=e},e.setTranslationMethod=function(e){o=e},e.tokenize=xv,Object.defineProperty(e,"__esModule",{value:!0}),Zw.version="16.3.40",Zw.date="2024-07-02T10:32:45.187Z",Zw.hash="2851082"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|